# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-its-cached-mcp-tool-schema-on-a-notifications-tools-list-changed-it-cannot-fully-reconcile.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-its-cached-mcp-tool-schema-on-a-notifications-tools-list-changed-it-cannot-fully-reconcile.warrant.json
# Markdown SHA-256:   04f301418d00e3c63701109bf900ad81f66331bf7ced90fc39083b868392b651
# Code AST SHA-256:   d47d57c322b1b89e3e1f007752f5515d6de7fbfbf96f9fdfb1afdc5468340be2
# Verified Classes:   ToolSchemaUnreconciled, ToolSurface
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ToolSchemaUnreconciled(RuntimeError):
    """Raised when a dirty tool schema cannot be reconciled before execution."""
    pass


@dataclass
class ToolSurface:
    schema: dict[str, dict]          # name -> arg schema
    dirty: bool = False
    last_good: Optional[dict[str, dict]] = None
    retry_budget: int = 2

    def on_list_changed(self) -> None:
        # Notification carries no payload: only a dirty bit.
        self.dirty = True

    def reconcile(self, fetch) -> None:
        """Attempt to clear dirty via tools/list. Raises if it cannot."""
        if not self.dirty:
            return
        attempts = 0
        last_err: Optional[Exception] = None
        while attempts < self.retry_budget:
            attempts += 1
            try:
                new_list = fetch()  # may raise (503, timeout)
            except Exception as e:  # transport failure
                last_err = e
                continue
            if not isinstance(new_list, list) or len(new_list) == 0:
                # Empty/partial list is not a valid diff basis.
                last_err = ValueError("empty or malformed tools/list")
                continue
            new_schema = {t["name"]: t.get("inputSchema", {}) for t in new_list}
            self.last_good = self.schema
            self.schema = new_schema
            self.dirty = False
            return
        raise ToolSchemaUnreconciled(
            f"tools/list unreconciled after {attempts} attempts: {last_err!r}"
        )

    def is_suspect(self, tool_name: str) -> bool:
        """True if this tool's validity cannot be proven right now."""
        if not self.dirty:
            return False
        if self.last_good is None:
            return True  # no diff basis at all: everything suspect
        return self.schema.get(tool_name) != self.last_good.get(tool_name)

    def execute(self, tool_name: str, args: dict, call) -> dict:
        if self.dirty:
            # Quarantine: force reconciliation before any tool call.
            self.reconcile(fetch=lambda: self._refetch())
        if self.is_suspect(tool_name):
            raise ToolSchemaUnreconciled(
                f"tool {tool_name!r} is schema-suspect; replan required"
            )
        return call(tool_name, args)

    def _refetch(self):  # injected by caller in real use
        raise NotImplementedError
