# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-an-mcp-server-it-reconnected-to-over-http-without-re-verifying-the-attestation-bound-to-the-original-transport-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-an-mcp-server-it-reconnected-to-over-http-without-re-verifying-the-attestation-bound-to-the-original-transport-session.warrant.json
# Markdown SHA-256:   95282bafec6062ef809dd3657a9994c9c17fd7e51afd8969d6296be0d248b3c5
# Code AST SHA-256:   da504ceff4204a6248634a4efbb1c20bb8a0b0da780bc5e09465f449ab415465
# Verified Classes:   AttestationDriftError, Attestation, TransportState, ProvenanceGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class AttestationDriftError(RuntimeError):
    """Raised when a transport re-bind serves a schema that no longer matches the verified attestation."""


@dataclass
class Attestation:
    publisher_key_id: str
    schema_digest: str          # SHA-256 of the served tools/list schema at verification time
    endpoint_fingerprint: str   # resolved backend identity, not just origin


@dataclass
class TransportState:
    session_id: str
    transport_generation: int = 0
    current_schema_digest: str = ""
    current_endpoint_fingerprint: str = ""


@dataclass
class ProvenanceGuard:
    verified: Attestation
    transport: TransportState
    _bound_generation: int = field(default=-1)

    def on_connect(self, schema_bytes: bytes, endpoint_fingerprint: str) -> None:
        self.transport.transport_generation += 1
        self.transport.current_schema_digest = hashlib.sha256(schema_bytes).hexdigest()
        self.transport.current_endpoint_fingerprint = endpoint_fingerprint

    def assert_current(self) -> None:
        # Fail closed if the connection generation changed since the verdict was bound.
        if self.transport.transport_generation != self._bound_generation:
            if self.transport.current_schema_digest != self.verified.schema_digest:
                raise AttestationDriftError(
                    "transport re-bind serves schema digest "
                    f"{self.transport.current_schema_digest!r} but verified attestation covers "
                    f"{self.verified.schema_digest!r} (generation "
                    f"{self.transport.transport_generation}); refusing tool call"
                )
            if self.transport.current_endpoint_fingerprint != self.verified.endpoint_fingerprint:
                raise AttestationDriftError(
                    "endpoint fingerprint changed under cached TRUSTED verdict; re-verify required"
                )
            self._bound_generation = self.transport.transport_generation


def invoke_tool(guard: ProvenanceGuard, tool_name: str, args: dict) -> dict:
    guard.assert_current()
    # ... dispatch to transport only after fingerprint equality holds ...
    return {"tool": tool_name, "args": args, "status": "dispatched"}
