# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-mid-session-mcp-tool-schema-drift-when-the-negotiated-capability-manifest-is-cached-but-the-server-has-re-registered-a-too.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-mid-session-mcp-tool-schema-drift-when-the-negotiated-capability-manifest-is-cached-but-the-server-has-re-registered-a-too.warrant.json
# Markdown SHA-256:   982c2bd307cc127cb452f72926b2f930ff2eae1fe97b1d15d6da53e180b5ed22
# Code AST SHA-256:   8eadd020bd729a5355541f1d3df9b0fabab1045b56dcdcf7ffd46096c4a106a4
# Verified Classes:   SchemaDriftError, DriftProbeUnavailableError, ToolContract, NegotiatedManifest, DriftGuardedSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SchemaDriftError(RuntimeError):
    """Raised when the live tool schema diverges from the negotiated manifest."""


class DriftProbeUnavailableError(RuntimeError):
    """Raised when the fingerprint probe fails; drift state is unknown, not absent."""


@dataclass
class ToolContract:
    name: str
    input_schema: dict[str, Any]

    def fingerprint(self) -> str:
        canonical = json.dumps(
            {"name": self.name, "inputSchema": self.input_schema},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class NegotiatedManifest:
    contracts: dict[str, ToolContract] = field(default_factory=dict)
    fingerprint: str = ""

    def compute_fingerprint(self) -> str:
        h = hashlib.sha256()
        for name in sorted(self.contracts):
            h.update(self.contracts[name].fingerprint().encode("utf-8"))
        self.fingerprint = h.hexdigest()
        return self.fingerprint


class DriftGuardedSession:
    """Admits tools/call only when live fingerprint matches the planning-time fingerprint."""

    def __init__(
        self,
        fetch_live_manifest: Callable[[], NegotiatedManifest],
        invoke_tool: Callable[[str, dict[str, Any]], Any],
    ) -> None:
        self._fetch_live = fetch_live_manifest
        self._invoke = invoke_tool
        self._cached: NegotiatedManifest | None = None

    def initialize(self) -> None:
        self._cached = self._fetch_live()
        self._cached.compute_fingerprint()

    def call(self, name: str, arguments: dict[str, Any]) -> Any:
        if self._cached is None:
            raise SchemaDriftError("call before initialize: no negotiated manifest")

        planning_fp = self._cached.fingerprint

        # Probe the live contract before admitting the call. A dropped
        # listChanged notification is thus a latency cost, not a correctness hole.
        try:
            live = self._fetch_live()
            live.compute_fingerprint()
        except Exception as exc:  # transport failure, timeout, malformed response
            raise DriftProbeUnavailableError(
                f"cannot verify contract for {name!r}; drift state unknown"
            ) from exc

        if live.fingerprint != planning_fp:
            # Invalidate cache and refuse to retry against a dead contract.
            self._cached = live
            drifted = sorted(
                set(live.contracts) ^ set(self._cached.contracts)
            ) or [name]
            raise SchemaDriftError(
                f"tool contract drift detected for {name!r}; "
                f"planning_fp={planning_fp[:12]} live_fp={live.fingerprint[:12]} "
                f"affected={drifted}; re-plan from intent, do not mutate arguments"
            )

        if name not in live.contracts:
            raise SchemaDriftError(f"tool {name!r} removed from live manifest")

        return self._invoke(name, arguments)

    def admit_result(self, name: str, produced_under_fp: str) -> None:
        """Gate before distilling a tool result into episodic memory."""
        if self._cached is None or produced_under_fp != self._cached.fingerprint:
            raise SchemaDriftError(
                f"refusing to admit result from {name!r}: produced under stale "
                f"fingerprint {produced_under_fp[:12]}"
            )
