# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-mcp-capability-revocation-during-a-live-tool-call-the-schema-drift-window-between-discovery-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-mcp-capability-revocation-during-a-live-tool-call-the-schema-drift-window-between-discovery-and-invocation.warrant.json
# Markdown SHA-256:   6c23351b68e8f82db1336646539e8721f2c6f54f2de7924ad70aa2103c20f3ec
# Code AST SHA-256:   bc2e47b5907f2e1efeb5aa5076b5a46176abea6520e245be973ad730baac504e
# Verified Classes:   SchemaDriftError, UnverifiedSideEffectError, CachedTool, FencedToolClient
# Defensive Guards:   3 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 a cached tool schema no longer matches the live server catalog."""
    pass


class UnverifiedSideEffectError(RuntimeError):
    """Raised when a mutating call's commit state cannot be confirmed via read-back."""
    pass


@dataclass
class CachedTool:
    name: str
    schema: dict
    generation: str          # fingerprint of the discovery payload that produced this schema
    mutating: bool


def _fingerprint(tools_list_payload: dict) -> str:
    canonical = json.dumps(tools_list_payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


class FencedToolClient:
    def __init__(self, discover: Callable[[], dict], invoke: Callable[..., Any],
                 read_back: Callable[[str], Any]):
        self._discover = discover
        self._invoke = invoke
        self._read_back = read_back
        self._cache: dict[str, CachedTool] = {}

    def refresh(self) -> None:
        payload = self._discover()
        gen = _fingerprint(payload)
        self._cache = {}
        for t in payload.get("tools", []):
            self._cache[t["name"]] = CachedTool(
                name=t["name"],
                schema=t.get("inputSchema", {}),
                generation=gen,
                mutating=bool(t.get("annotations", {}).get("mutating", False)),
            )

    def _assert_fence(self, tool_name: str) -> CachedTool:
        cached = self._cache.get(tool_name)
        if cached is None:
            raise SchemaDriftError(f"tool '{tool_name}' not in cached catalog")
        live = self._discover()
        live_gen = _fingerprint(live)
        if live_gen != cached.generation:
            # Drift detected. Invalidate and force re-negotiation.
            self.refresh()
            raise SchemaDriftError(
                f"schema drift for '{tool_name}': cached gen {cached.generation[:12]} "
                f"!= live gen {live_gen[:12]}; cache invalidated, re-discover required"
            )
        return cached

    def call(self, tool_name: str, args: dict) -> Any:
        cached = self._assert_fence(tool_name)
        if cached.mutating:
            # Pre-commit fence passed; invoke, then verify by read-back,
            # never by trusting the response body shape.
            result = self._invoke(tool_name, args)
            observed = self._read_back(tool_name)
            if observed is None:
                raise UnverifiedSideEffectError(
                    f"mutating call '{tool_name}' returned but read-back shows no commit; "
                    f"do NOT retry blindly — side effect may have partially applied"
                )
            return observed
        return self._invoke(tool_name, args)
