# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-mcp-tool-whose-attestation-chain-has-been-re-anchored-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-mcp-tool-whose-attestation-chain-has-been-re-anchored-mid-session.warrant.json
# Markdown SHA-256:   d22f6eacdade6125004ae03a669b23bd9f6c25e60e65619274a9a50848bb64f5
# Code AST SHA-256:   21e56379597ce53f5e613b307a7f4d0f61cff5fa3ce8d16413adedcc1d3d0ce3
# Verified Classes:   TrustAnchorDriftError, Warrant, PinnedTool, FederatedSession
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Dict, Optional


class TrustAnchorDriftError(RuntimeError):
    """Raised when a tool warrant is re-anchored to a root other than the
    one pinned at session initialize, without explicit re-negotiation."""


@dataclass(frozen=True)
class Warrant:
    tool: str
    schema_hash: str
    endpoint: str
    root_id: str          # identity of the signing trust root
    signature: bytes


@dataclass(frozen=True)
class PinnedTool:
    schema_hash: str
    endpoint: str


class FederatedSession:
    def __init__(self, pinned_root: str, verify: Callable[[Warrant, str], bool]):
        self.pinned_root = pinned_root
        self._verify = verify
        self._tools: Dict[str, PinnedTool] = {}

    def register_from_list(self, warrant: Warrant) -> None:
        if warrant.root_id != self.pinned_root:
            raise TrustAnchorDriftError(
                f"tools/list warrant for {warrant.tool!r} signed by "
                f"{warrant.root_id!r}, session pinned to {self.pinned_root!r}"
            )
        if not self._verify(warrant, self.pinned_root):
            raise TrustAnchorDriftError(
                f"tools/list warrant for {warrant.tool!r} failed signature check "
                f"against pinned root {self.pinned_root!r}"
            )
        self._tools[warrant.tool] = PinnedTool(warrant.schema_hash, warrant.endpoint)

    def admit_call(self, warrant: Warrant) -> None:
        cached = self._tools.get(warrant.tool)
        if cached is None:
            raise TrustAnchorDriftError(
                f"tools/call for unregistered tool {warrant.tool!r}"
            )
        # Continuity invariant: root must equal the session pin, even if the
        # signature would validate against some other trusted root.
        if warrant.root_id != self.pinned_root:
            raise TrustAnchorDriftError(
                f"tool {warrant.tool!r} re-anchored from {self.pinned_root!r} "
                f"to {warrant.root_id!r} mid-session; require re-initialize"
            )
        if not self._verify(warrant, self.pinned_root):
            raise TrustAnchorDriftError(
                f"tools/call warrant for {warrant.tool!r} failed signature check"
            )
        if warrant.schema_hash != cached.schema_hash:
            raise TrustAnchorDriftError(
                f"schema drift on {warrant.tool!r}: "
                f"{cached.schema_hash!r} -> {warrant.schema_hash!r}"
            )
        if warrant.endpoint != cached.endpoint:
            raise TrustAnchorDriftError(
                f"endpoint drift on {warrant.tool!r}: "
                f"{cached.endpoint!r} -> {warrant.endpoint!r}"
            )
        # Admissible: root, schema, and endpoint all continuous with discovery.
