# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-mcp-tool-surface-mid-session-the-stale-schema-dispatch-hazard.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mutates-its-mcp-tool-surface-mid-session-the-stale-schema-dispatch-hazard.warrant.json
# Markdown SHA-256:   7ce223b46e3f6fda77cf90edc86d87900a814aef7f7aa304c9c4c645b1fdf0d7
# Code AST SHA-256:   b076a2b1267ebb0ebf3e318928e47cec5d50e64aa322ab47bc7b1751b8e49318
# Verified Classes:   SurfaceDriftError, ToolSchema, SurfaceCache, PlannedCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SurfaceDriftError(RuntimeError):
    """Raised when a tool call is planned against a stale MCP tool surface."""


@dataclass(frozen=True)
class ToolSchema:
    name: str
    schema: dict

    @property
    def schema_hash(self) -> str:
        canonical = repr(sorted(self.schema.items()))
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class SurfaceCache:
    version: int = 0
    dirty: bool = False
    tools: dict[str, ToolSchema] = field(default_factory=dict)

    def apply_list(self, tools: list[ToolSchema]) -> None:
        self.tools = {t.name: t for t in tools}
        self.version += 1
        self.dirty = False

    def on_list_changed(self) -> None:
        self.dirty = True


@dataclass(frozen=True)
class PlannedCall:
    name: str
    planned_version: int
    planned_schema_hash: str


def dispatch(cache: SurfaceCache, call: PlannedCall, args: dict) -> dict:
    if cache.dirty:
        raise SurfaceDriftError(
            f"surface dirty at dispatch for {call.name!r}; re-pull tools/list first"
        )
    if call.planned_version != cache.version:
        raise SurfaceDriftError(
            f"{call.name!r} planned at v{call.planned_version}, "
            f"surface now v{cache.version}; re-plan required"
        )
    live = cache.tools.get(call.name)
    if live is None:
        raise SurfaceDriftError(
            f"{call.name!r} removed from surface; not retryable"
        )
    if live.schema_hash != call.planned_schema_hash:
        raise SurfaceDriftError(
            f"{call.name!r} re-registered with divergent schema "
            f"({call.planned_schema_hash[:8]} -> {live.schema_hash[:8]}); "
            "treat as a different tool"
        )
    return {"tool": call.name, "args": args, "status": "dispatched"}
