# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-validly-signed-mcp-manifest-whose-tool-surface-has-silently-drifted-from-the-attested-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-validly-signed-mcp-manifest-whose-tool-surface-has-silently-drifted-from-the-attested-hash.warrant.json
# Markdown SHA-256:   6462009abeec1a9b80775271c13d64f687fded755aec35df838aa54d568b814b
# Code AST SHA-256:   23ae37c1f88c01746eeeb227dbed10cef81b099aa1eaba9d7de8601a8eddd5d9
# Verified Classes:   ManifestDriftError, SchemaClosureError, AttestedSurface
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any, Callable


class ManifestDriftError(RuntimeError):
    """Raised when the live MCP tool surface diverges from the attested, signed manifest."""


class SchemaClosureError(RuntimeError):
    """Raised when a server accepts an argument key outside the attested schema."""


def _canonical(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _hash_tool(descriptor: dict) -> str:
    return hashlib.sha256(_canonical(descriptor)).hexdigest()


@dataclass
class AttestedSurface:
    manifest_hash: str            # hash of signed manifest body
    tool_hashes: dict[str, str]   # tool name -> attested descriptor hash
    signer_key_id: str


def admit_server(
    attested: AttestedSurface,
    verify_signature: Callable[[bytes, str], bool],
    manifest_body: bytes,
    list_tools: Callable[[], list[dict]],
    call_tool: Callable[[str, dict], Any],
) -> dict[str, dict]:
    # 1. Signature must verify over the exact manifest bytes we hash.
    if hashlib.sha256(manifest_body).hexdigest() != attested.manifest_hash:
        raise ManifestDriftError("manifest body does not match attested hash")
    if not verify_signature(manifest_body, attested.signer_key_id):
        raise ManifestDriftError(f"signature invalid for key {attested.signer_key_id}")

    # 2. Reconcile the LIVE surface against the attested per-tool hashes.
    live = {t["name"]: t for t in list_tools()}
    if set(live) != set(attested.tool_hashes):
        raise ManifestDriftError(
            f"tool set drift: attested={sorted(attested.tool_hashes)} live={sorted(live)}"
        )
    for name, desc in live.items():
        if _hash_tool(desc) != attested.tool_hashes[name]:
            raise ManifestDriftError(
                f"schema drift on tool '{name}': served hash {_hash_tool(desc)} "
                f"!= attested {attested.tool_hashes[name]}"
            )

    # 3. Probe handler closure: server must reject out-of-schema args.
    for name, desc in live.items():
        declared = set(desc.get("inputSchema", {}).get("properties", {}))
        probe = {k: None for k in ("__attest_probe__",)}
        try:
            call_tool(name, probe)
        except Exception:
            continue  # rejection is the expected, healthy outcome
        # Accepted an undeclared key -> handler surface is wider than attested.
        raise SchemaClosureError(
            f"tool '{name}' accepted undeclared arg {list(probe)}; "
            f"declared={sorted(declared)}"
        )

    return live
