# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-tools-list-snapshot-as-a-versioned-contract-rather-than-a-live-view-during-a-long-running-tool-call-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-mcp-tools-list-snapshot-as-a-versioned-contract-rather-than-a-live-view-during-a-long-running-tool-call-loop.warrant.json
# Markdown SHA-256:   3c32d622b032b90e58af4ddc8c57bcb30f3e86d9b271bf49e28d14803542bff4
# Code AST SHA-256:   1a171c8a595238c3d31b5bc25ada4c927fb3f30eb64ce791968e8b8e69b28a57
# Verified Classes:   SchemaEpochMismatch, SchemaPin
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SchemaEpochMismatch(RuntimeError):
    """Raised when the live MCP tools/list diverges from the pinned session schema.

    This is the guardrail against silent semantic drift: a server that adds an
    enum member, flips an optional field to required, or edits a description
    without a wire-visible breaking change. The client cannot catch these via
    validation errors, so it must catch them via epoch hash comparison.
    """


def canonical_tool_hash(tools: list[dict[str, Any]]) -> str:
    """Hash the FULL tool surface, including descriptions and inputSchema.

    Parameter names alone are insufficient: default-value changes and
    description edits are the drift class that validation cannot catch.
    """
    normalized = sorted(
        (
            {
                "name": t.get("name"),
                "description": t.get("description", ""),
                "inputSchema": t.get("inputSchema", {}),
            }
            for t in tools
        ),
        key=lambda t: t["name"] or "",
    )
    blob = json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class SchemaPin:
    epoch: str
    tools: dict[str, dict[str, Any]] = field(default_factory=dict)

    @classmethod
    def from_listing(cls, tools: list[dict[str, Any]]) -> "SchemaPin":
        return cls(
            epoch=canonical_tool_hash(tools),
            tools={t["name"]: t for t in tools},
        )


def assert_schema_epoch(pin: SchemaPin, live_tools: list[dict[str, Any]]) -> None:
    """Verify the live tool surface still matches the pinned epoch.

    Call this before any state-mutating tools/call. On mismatch, the caller
    MUST halt and re-plan from the fresh schema; it MUST NOT proceed with the
    cached plan, because the drift may be semantically silent.
    """
    live_epoch = canonical_tool_hash(live_tools)
    if live_epoch != pin.epoch:
        changed = _diff_names(pin.tools, {t["name"]: t for t in live_tools})
        raise SchemaEpochMismatch(
            f"tools/list epoch drifted: pinned={pin.epoch[:12]} "
            f"live={live_epoch[:12]} changed_tools={changed}. "
            "Halt tool-call loop and re-derive plan from live schema."
        )


def _diff_names(
    pinned: dict[str, dict[str, Any]], live: dict[str, dict[str, Any]]
) -> list[str]:
    names = set(pinned) | set(live)
    return sorted(n for n in names if pinned.get(n) != live.get(n))


def dispatch_tool_call(
    pin: SchemaPin,
    live_tools: list[dict[str, Any]],
    tool_name: str,
    arguments: dict[str, Any],
) -> dict[str, Any]:
    """Guarded dispatch: refuse to execute against a stale schema epoch."""
    assert_schema_epoch(pin, live_tools)
    tool = pin.tools.get(tool_name)
    if tool is None:
        raise SchemaEpochMismatch(f"tool {tool_name!r} not present in pinned schema")
    # In a real runtime this is where the MCP tools/call HTTP request is sent.
    return {"tool": tool_name, "arguments": arguments, "epoch": pin.epoch}
