# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-signed-mcp-manifest-whose-capability-set-mutates-after-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-signed-mcp-manifest-whose-capability-set-mutates-after-attestation.warrant.json
# Markdown SHA-256:   cc369e36daf730f42a0024b59c2f3713a611425311f2c6567e58c8581dbe2ef0
# Code AST SHA-256:   930dcbafd65a264ac8a49d37e14ec4a2eb1bb070401aa49e8e237a972f701a9c
# Verified Classes:   AttestationDivergenceError, AttestedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttestationDivergenceError(RuntimeError):
    """Raised when a served MCP tool surface diverges from the attested, signed manifest."""


@dataclass(frozen=True)
class AttestedManifest:
    publisher_key_id: str
    tools: dict          # name -> schema dict
    content_hash: str    # sha256 over canonical (name, schema) pairs


def _canonical_hash(tools: dict) -> str:
    blob = json.dumps(
        sorted((name, schema) for name, schema in tools.items()),
        sort_keys=True,
        separators=(",", ":"),
    ).encode()
    return hashlib.sha256(blob).hexdigest()


def verify_manifest(raw: bytes, signature_valid: bool, pinned_key_id: str,
                    expected_key_id: str) -> AttestedManifest:
    if not signature_valid:
        raise AttestationDivergenceError("manifest signature did not verify")
    if pinned_key_id != expected_key_id:
        raise AttestationDivergenceError(
            f"manifest signed by unpinned key {pinned_key_id!r}, expected {expected_key_id!r}"
        )
    doc = json.loads(raw)
    tools = {t["name"]: t.get("inputSchema", {}) for t in doc["tools"]}
    return AttestedManifest(
        publisher_key_id=pinned_key_id,
        tools=tools,
        content_hash=_canonical_hash(tools),
    )


def gate_tool_call(attested: AttestedManifest, served_listing: dict,
                   tool_name: str, arguments: dict) -> None:
    """Enforce served-surface == attested-surface before every call."""
    served_hash = _canonical_hash(served_listing)
    if served_hash != attested.content_hash:
        raise AttestationDivergenceError(
            f"served tool surface hash {served_hash[:12]} != attested "
            f"{attested.content_hash[:12]}; server mutated capabilities post-attestation"
        )
    if tool_name not in attested.tools:
        raise AttestationDivergenceError(
            f"tool {tool_name!r} not present in attested capability set"
        )
    schema = attested.tools[tool_name]
    required = schema.get("required", [])
    for field in required:
        if field not in arguments:
            raise AttestationDivergenceError(
                f"call to {tool_name!r} missing attested-required field {field!r}"
            )
    # Schema is an upper bound; semantic confinement (path resolution, host
    # allowlisting) must still be enforced client-side, never delegated here.
