# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-mcp-tool-manifest-signatures-before-dispatch-and-what-breaks-when-it-verifies-after-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-mcp-tool-manifest-signatures-before-dispatch-and-what-breaks-when-it-verifies-after-handshake.warrant.json
# Markdown SHA-256:   72d1a5b2e7f8b81c2343fd78a055b56209ae12e33a05c540c6956de99f2ad57b
# Code AST SHA-256:   14dd6715b3bcfe614682fa548ba5865ad44071afc11c7ae90bb1fd5bbdc3b306
# Verified Classes:   ManifestAttestationError, VerifiedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestAttestationError(RuntimeError):
    """Raised when a tool call is composed against an unverified or drifted manifest."""


@dataclass(frozen=True)
class VerifiedManifest:
    server_id: str
    manifest_digest: str
    key_epoch: int
    declared_scope: frozenset
    declared_schemas: dict


def canonical_digest(manifest: dict) -> str:
    blob = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def admit_tool_for_dispatch(
    server_id: str,
    tool_name: str,
    in_context_schema: dict,
    requested_scope: str,
    verified: VerifiedManifest | None,
    verification_returned: bool,
    current_key_epoch: int,
) -> None:
    if not verification_returned:
        # The 340ms window: signature check enqueued but not yet returned.
        raise ManifestAttestationError(
            f"dispatch attempted for {server_id}/{tool_name} before verification returned"
        )
    if verified is None:
        raise ManifestAttestationError(
            f"no verified manifest for {server_id}; refusing to compose {tool_name}"
        )
    if verified.key_epoch != current_key_epoch:
        raise ManifestAttestationError(
            f"manifest for {server_id} signed under epoch {verified.key_epoch}, "
            f"server advertises epoch {current_key_epoch}; re-fetch and re-verify"
        )
    live_digest = canonical_digest(
        {"server_id": server_id, "tool": tool_name, "schema": in_context_schema}
    )
    attested_digest = canonical_digest(
        {
            "server_id": server_id,
            "tool": tool_name,
            "schema": verified.declared_schemas[tool_name],
        }
    )
    if live_digest != attested_digest:
        raise ManifestAttestationError(
            f"schema drift: in-context schema for {tool_name} does not match "
            f"verified manifest digest {verified.manifest_digest[:12]}"
        )
    if requested_scope not in verified.declared_scope:
        raise ManifestAttestationError(
            f"scope escalation: {requested_scope} not in attested scope "
            f"{sorted(verified.declared_scope)} for {server_id}"
        )
