# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-whose-attestation-verifies-but-whose-capability-surface-has-drifted-the-mcp-supply-chain-toctou-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-tool-manifest-whose-attestation-verifies-but-whose-capability-surface-has-drifted-the-mcp-supply-chain-toctou-boundary.warrant.json
# Markdown SHA-256:   206cd4ba93dd3cd9131e33c80be705e3507579abe731a0b4a60c6d8779f5e9de
# Code AST SHA-256:   3f42d52ec5133c4df42a30d2e68022d3f97d72da0331baa32d41c151e4fb7504
# Verified Classes:   ManifestBindingError, AttestedManifest, LiveToolDescriptor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping, Optional

class ManifestBindingError(RuntimeError):
    """Raised when a live MCP tool surface cannot be bound to an attested manifest."""
    pass

@dataclass(frozen=True)
class AttestedManifest:
    server_id: str
    manifest_digest: str          # canonicalized digest over tools[]
    publisher_key_id: str
    tools: Mapping[str, dict]     # name -> {inputSchema, annotations}

@dataclass(frozen=True)
class LiveToolDescriptor:
    name: str
    input_schema: dict
    annotations: dict
    live_digest: Optional[str]    # digest the server claims for its current surface

def canonical_digest(tools: Mapping[str, dict]) -> str:
    # sorted keys, no whitespace, stable serialization — must match publisher's
    import hashlib, json
    payload = json.dumps(tools, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(payload).hexdigest()

def verify_dispatch(
    manifest: AttestedManifest,
    live: LiveToolDescriptor,
    trusted_keys: Mapping[str, bool],   # key_id -> currently trusted
    binding_dirty: bool,
) -> dict:
    if binding_dirty:
        raise ManifestBindingError(
            f"binding dirty for {manifest.server_id}; re-attestation required before dispatch"
        )
    if not trusted_keys.get(manifest.publisher_key_id, False):
        raise ManifestBindingError(
            f"publisher key {manifest.publisher_key_id} no longer trusted for {manifest.server_id}"
        )
    if live.live_digest is None:
        raise ManifestBindingError(
            f"server {manifest.server_id} exposes no manifest digest; cannot bind {live.name}"
        )
    if live.live_digest != manifest.manifest_digest:
        raise ManifestBindingError(
            f"digest drift on {manifest.server_id}/{live.name}: "
            f"attested={manifest.manifest_digest} live={live.live_digest}"
        )
    entry = manifest.tools.get(live.name)
    if entry is None:
        raise ManifestBindingError(
            f"tool {live.name} not present in attested manifest for {manifest.server_id}"
        )
    if entry["inputSchema"] != live.input_schema or entry["annotations"] != live.annotations:
        raise ManifestBindingError(
            f"schema/annotation drift on {manifest.server_id}/{live.name}: "
            f"name is not identity"
        )
    # policy must be derived from *this* entry, never a cached predecessor
    return {"server_id": manifest.server_id,
            "tool": live.name,
            "manifest_digest": manifest.manifest_digest,
            "annotations": entry["annotations"]}
