# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-mutually-authenticated-mcp-peer-whose-capability-scope-has-silently-widened-between-handshake-and-first-to.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-mutually-authenticated-mcp-peer-whose-capability-scope-has-silently-widened-between-handshake-and-first-to.warrant.json
# Markdown SHA-256:   0aded605607257ea5cd8b34a322520ea7273de4e8a51243682a4baa25b3687bf
# Code AST SHA-256:   c938168a82ed732744798acd6cbd6110edc361bfc5e057879250dd9712517b07
# Verified Classes:   ScopeEpochMismatch, Attestation, ServerView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ScopeEpochMismatch(RuntimeError):
    """Raised when a peer's attested capability scope is not bound to the
    current policy epoch, or when the exercised capability exceeds the
    intersection of attested and currently-advertised scope."""
    pass


@dataclass(frozen=True)
class Attestation:
    peer_id: str
    scope_hash: str
    epoch: int
    nonce: str
    capabilities: frozenset


@dataclass(frozen=True)
class ServerView:
    supported_scope_hash: str
    epoch: int
    granted: frozenset


def verify_and_admit(
    attestation: Attestation,
    server: ServerView,
    required_cap: str,
    seen_nonces: set,
) -> None:
    # Condition 1: signature is assumed verified upstream by pinned key.
    # Condition 2: attestation must be bound to the CURRENT epoch.
    if attestation.epoch != server.epoch:
        raise ScopeEpochMismatch(
            f"epoch skew: attestation epoch {attestation.epoch} != "
            f"server epoch {server.epoch}; refusing tool call and "
            f"forcing re-handshake"
        )

    # Condition 2b: scope hash must match the server's advertised hash.
    expected = hashlib.sha256(
        ",".join(sorted(attestation.capabilities)).encode()
    ).hexdigest()[:16]
    if attestation.scope_hash != expected or \
       attestation.scope_hash != server.supported_scope_hash:
        raise ScopeEpochMismatch(
            f"scope_hash mismatch: attested {attestation.scope_hash} "
            f"!= server {server.supported_scope_hash}"
        )

    # Condition 3: exercised capability must lie in the INTERSECTION of
    # attested and currently-granted scope, never the union.
    effective = attestation.capabilities & server.granted
    if required_cap not in effective:
        raise ScopeEpochMismatch(
            f"capability {required_cap!r} not in effective scope "
            f"{sorted(effective)}; attested={sorted(attestation.capabilities)} "
            f"granted={sorted(server.granted)}"
        )

    # Condition 4: freshness — no replay of a prior attestation nonce.
    if attestation.nonce in seen_nonces:
        raise ScopeEpochMismatch(
            f"replayed attestation nonce {attestation.nonce!r}; "
            f"refusing to honor stale-scope grant"
        )
    seen_nonces.add(attestation.nonce)
