# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-mcp-capabilities-against-a-server-whose-tool-list-mutates-between-initialize-and-first-tools-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-mcp-capabilities-against-a-server-whose-tool-list-mutates-between-initialize-and-first-tools-call.warrant.json
# Markdown SHA-256:   01c066630ec2291b95ffa408784d4b1a8eb01b000a3ee9277d96b6dd3e2fb7c8
# Code AST SHA-256:   a46533e75193edfe07e5a52aeb9bbf9dfaf22590ab55501494c7a196d13b4f43
# Verified Classes:   StaleCatalogError, CapabilityGapError, CatalogSnapshot, MCPClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable


class StaleCatalogError(RuntimeError):
    """Raised when a tool call is attempted against a catalog snapshot that
    has been invalidated by a list_changed notification, a prior -32601/-32602,
    or TTL expiry. Callers must re-resolve the catalog before retrying."""
    pass


class CapabilityGapError(RuntimeError):
    """Raised when re-resolution succeeds but no tool in the fresh catalog
    matches the original intent. Must surface to the orchestrator; the agent
    must NOT synthesize a substitute tool name."""
    pass


@dataclass
class CatalogSnapshot:
    version: int
    tools: dict[str, dict]          # name -> input schema
    captured_at: float
    ttl_seconds: float
    invalidated: bool = False

    def is_valid(self, now: float | None = None) -> bool:
        now = time.monotonic() if now is None else now
        return (not self.invalidated) and (now - self.captured_at) < self.ttl_seconds


@dataclass
class MCPClient:
    list_tools: Callable[[], dict[str, dict]]
    call_tool: Callable[[str, dict], dict]
    snapshot: CatalogSnapshot | None = None
    _version: int = field(default=0)

    def refresh(self) -> CatalogSnapshot:
        self._version += 1
        self.snapshot = CatalogSnapshot(
            version=self._version,
            tools=self.list_tools(),
            captured_at=time.monotonic(),
            ttl_seconds=60.0,
        )
        return self.snapshot

    def on_list_changed(self) -> None:
        if self.snapshot is not None:
            self.snapshot.invalidated = True

    def invoke(self, tool_name: str, args: dict, intent: str) -> dict:
        if self.snapshot is None or not self.snapshot.is_valid():
            self.refresh()
        assert self.snapshot is not None

        if tool_name not in self.snapshot.tools:
            raise StaleCatalogError(
                f"tool {tool_name!r} absent from snapshot v{self.snapshot.version}; "
                f"re-resolve before call"
            )

        try:
            return self.call_tool(tool_name, args)
        except Exception as exc:
            code = getattr(exc, "code", None)
            if code not in (-32601, -32602):
                raise
            # A -32601/-32602 on a snapshot-drawn tool is a catalog-invalidation
            # trigger, not an argument-repair trigger.
            self.snapshot.invalidated = True
            fresh = self.refresh()

            replacement = self._resolve_by_intent(intent, fresh.tools)
            if replacement is None:
                raise CapabilityGapError(
                    f"intent {intent!r} has no match in catalog v{fresh.version} "
                    f"after {tool_name!r} returned {code}; halting for orchestrator"
                )
            return self.call_tool(replacement, args)

    @staticmethod
    def _resolve_by_intent(intent: str, tools: dict[str, dict]) -> str | None:
        # Semantic resolution against the fresh catalog. In production this is
        # an embedding match or an explicit rename map; the point is that it
        # consults the NEW catalog, never the stale snapshot.
        for name, schema in tools.items():
            if intent in name or intent in schema.get("description", ""):
                return name
        return None
