# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-after-a-clean-manifest-re-verification-the-toctou-gap-between-manifest-signature-validation-and-tool-c.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-mcp-tool-after-a-clean-manifest-re-verification-the-toctou-gap-between-manifest-signature-validation-and-tool-c.warrant.json
# Markdown SHA-256:   9ce20621ed60988b83daa76aaaca946a83ad103e66ca9e2eb4e3bb8ad493fc65
# Code AST SHA-256:   686dabccad8f3d3a13d09a12f6cf7512b5ea918643bfa8857a38343eafbc0103
# Verified Classes:   SurfaceDivergenceError, SignedTool, PinnedManifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SurfaceDivergenceError(RuntimeError):
    """Raised when the live MCP tool surface is not byte-identical to the pinned signed manifest."""


@dataclass(frozen=True)
class SignedTool:
    name: str
    description_hash: str
    input_schema_hash: str


@dataclass(frozen=True)
class PinnedManifest:
    server_id: str
    tools: tuple[SignedTool, ...]


def _sha256(obj) -> str:
    payload = json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(payload).hexdigest()


def reconcile_surface(pinned: PinnedManifest, served_tools: list[dict]) -> None:
    """
    Reconcile the live tools/list response against the pinned signed manifest.
    Must be called at hydration, on reconnect, on compaction-resume, and on
    every notifications/tools/list_changed. Raises on any divergence.
    """
    signed = {t.name: t for t in pinned.tools}
    served = {t["name"]: t for t in served_tools}

    extra = set(served) - set(signed)
    if extra:
        # An unsigned tool is never admissible. This is the poisoned-tool vector.
        raise SurfaceDivergenceError(
            f"server {pinned.server_id} advertised unsigned tools: {sorted(extra)}"
        )

    missing = set(signed) - set(served)
    if missing:
        # Safe-degrade: the model simply cannot call what is absent. Log, do not admit.
        raise SurfaceDivergenceError(
            f"server {pinned.server_id} dropped signed tools: {sorted(missing)}"
        )

    for name, tool in served.items():
        expected = signed[name]
        served_desc_hash = _sha256(tool.get("description", ""))
        served_schema_hash = _sha256(tool.get("inputSchema", {}))
        if served_desc_hash != expected.description_hash:
            # Description poisoning: signed hash never recomputed against served bytes.
            raise SurfaceDivergenceError(
                f"tool {name} description diverged from signed manifest"
            )
        if served_schema_hash != expected.input_schema_hash:
            raise SurfaceDivergenceError(
                f"tool {name} inputSchema diverged from signed manifest"
            )


def hydrate_session(pinned: PinnedManifest, transport) -> list[dict]:
    """
    Establish the callable surface ONLY after reconciling the live tools/list
    against the pinned manifest. The transport is untrusted until this returns.
    """
    served = transport.tools_list()
    reconcile_surface(pinned, served)
    # Pin the reconciled surface hash into the session checkpoint so that
    # resume after compaction cannot silently reopen the TOCTOU window.
    transport.pin_surface_hash(_sha256(served))
    return served


def on_tools_list_changed(pinned: PinnedManifest, transport) -> None:
    """
    MCP servers may emit notifications/tools/list_changed. This is a
    re-validation trigger, not a cache invalidation hint.
    """
    served = transport.tools_list()
    try:
        reconcile_surface(pinned, served)
    except SurfaceDivergenceError:
        # Surface changed outside the signed manifest: drop the session and
        # require a fresh signed manifest from the registry before reconnecting.
        transport.close()
        raise


def resume_from_checkpoint(pinned: PinnedManifest, transport, checkpoint: dict) -> None:
    """
    On resume, the pinned manifest and surface hash must both match. A server
    whose surface changed during the gap is a reopened TOCTOU window.
    """
    served = transport.tools_list()
    reconcile_surface(pinned, served)
    live_hash = _sha256(served)
    if checkpoint.get("surface_hash") != live_hash:
        transport.close()
        raise SurfaceDivergenceError(
            f"server {pinned.server_id} surface changed across checkpoint gap; "
            "refusing resume without fresh signed manifest"
        )
