# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-verify-an-mcp-tool-description-after-the-server-has-been-attested-and-why-the-answer-is-on-every-schema-visible-field-not-jus.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-verify-an-mcp-tool-description-after-the-server-has-been-attested-and-why-the-answer-is-on-every-schema-visible-field-not-jus.warrant.json
# Markdown SHA-256:   3e1dadf73b313b04bb9178598c1d71ebabb79f0adc26690f28176b96c3799b1d
# Code AST SHA-256:   bf496c2decb7241260bafa07883292129bc284245e42dd1fb6baf436c6558423
# Verified Classes:   ToolSurfaceDivergence, ConnectionEpoch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ToolSurfaceDivergence(RuntimeError):
    """Raised when the served MCP tool surface diverges from the attested baseline
    for the current connection epoch, in a way the model would observe."""


# Fields the model actually reads. Order is preserved because the model reads
# the serialized text, not a validated object graph.
MODEL_VISIBLE_TOOL_FIELDS = ("name", "description", "inputSchema", "annotations")


def canonicalize_tool_surface(tools: list[dict]) -> bytes:
    """Schema-aware canonicalization: sorts tools by name, preserves the order
    of properties and required arrays, and keeps every model-visible string.
    This is intentionally NOT json.dumps(sort_keys=True), which erases the
    property order the model reads and can mask a field rename."""
    ordered = sorted(tools, key=lambda t: t["name"])
    projected = []
    for tool in ordered:
        projected.append({k: tool[k] for k in MODEL_VISIBLE_TOOL_FIELDS if k in tool})
    # separators fixed; no sort_keys; ensure_ascii off so descriptions round-trip
    return json.dumps(projected, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


@dataclass(frozen=True)
class ConnectionEpoch:
    server_id: str
    replica_id: str
    epoch: int


def verify_surface_for_epoch(
    epoch: ConnectionEpoch,
    served_tools: list[dict],
    attested_baseline: bytes,
    cache: dict[tuple[str, str, int], bytes],
) -> bytes:
    """Re-derive and verify the tool surface for this exact epoch.

    Invariant: the bytes verified here are the bytes presented to the model.
    A cache hit on a prior epoch is a fault, not a fast path.
    """
    key = (epoch.server_id, epoch.replica_id, epoch.epoch)
    derived = canonicalize_tool_surface(served_tools)

    if key in cache:
        # Re-derivation must be idempotent within an epoch; if it is not,
        # the server's derivation is impure (H1 violation).
        if cache[key] != derived:
            raise ToolSurfaceDivergence(
                f"non-idempotent tool surface within epoch {key}: "
                f"server derivation is impure (plugin hot-reload?)"
            )
        return derived

    if derived != attested_baseline:
        # Do not fall back to the stale baseline. Refuse the tool.
        raise ToolSurfaceDivergence(
            f"served surface for {epoch.server_id}@{epoch.replica_id} "
            f"epoch {epoch.epoch} diverges from attested baseline; "
            f"refusing to present stale descriptions to the model"
        )

    cache[key] = derived
    return derived


def present_to_model(epoch: ConnectionEpoch, served_tools: list[dict],
                     attested_baseline: bytes,
                     cache: dict[tuple[str, str, int], bytes]) -> bytes:
    surface = verify_surface_for_epoch(epoch, served_tools, attested_baseline, cache)
    # The exact verified bytes are what enter the context window.
    return surface
