# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-an-mcp-server-mid-session-the-post-negotiation-capability-drift-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-an-mcp-server-mid-session-the-post-negotiation-capability-drift-boundary.warrant.json
# Markdown SHA-256:   add9e30be724062b97ce3764f8abded0f4e5dc1515fdb0ae14136ead4443ca62
# Code AST SHA-256:   7b4c68ee6dc48d249b0dafb09a1de0ab76eea3ff34e3b7d025eba866734e5f2b
# Verified Classes:   CapabilityWarrantError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityWarrantError(RuntimeError):
    """Raised when a tools/call is attempted against a stale or unattested warrant."""


@dataclass(frozen=True)
class Warrant:
    server_identity: str
    schema_digest: str
    allowed_tools: frozenset


def _digest(tools_list_payload: dict) -> str:
    canonical = json.dumps(tools_list_payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def mint_warrant(attestation: dict, tools_list_payload: dict) -> Warrant:
    if not attestation.get("signature_verified"):
        raise CapabilityWarrantError("cannot mint warrant: attestation unverified")
    return Warrant(
        server_identity=attestation["identity"],
        schema_digest=_digest(tools_list_payload),
        allowed_tools=frozenset(t["name"] for t in tools_list_payload["tools"]),
    )


def authorize_call(
    warrant: Warrant,
    current_attestation: dict,
    current_tools_list_payload: dict,
    tool_name: str,
) -> None:
    """Enforce the dispatch-time invariant before any tools/call is emitted."""
    if warrant.server_identity != current_attestation.get("identity"):
        raise CapabilityWarrantError(
            f"server identity drifted: warrant={warrant.server_identity} "
            f"current={current_attestation.get('identity')}; re-attest required"
        )
    live_digest = _digest(current_tools_list_payload)
    if live_digest != warrant.schema_digest:
        raise CapabilityWarrantError(
            "tool surface digest mismatch since warrant mint; re-attest required"
        )
    if tool_name not in warrant.allowed_tools:
        # Fail closed: an unattested tool name must never reach the transport,
        # and must never trigger cross-tool fallback in the recovery loop.
        raise CapabilityWarrantError(
            f"tool {tool_name!r} not in attested allowlist; refusing dispatch"
        )


def dispatch(warrant, current_attestation, current_tools_list_payload, tool_name, args):
    authorize_call(warrant, current_attestation, current_tools_list_payload, tool_name)
    return {"tool": tool_name, "arguments": args}
