# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-cache-a-capability-fingerprint-that-no-longer-matches-the-live-mcp-server-after-a-mid-session-tool-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-cache-a-capability-fingerprint-that-no-longer-matches-the-live-mcp-server-after-a-mid-session-tool-refresh.warrant.json
# Markdown SHA-256:   e3b103583d6fdee80ac96f45e941126f44bb93ec61b7a285ddf61a787147da1b
# Code AST SHA-256:   0ecb1521ecf204433aa3cb87dc0ffaab1c21c962a2246751d29c2c5e10240f3d
# Verified Classes:   StaleSchemaError, ToolRegistry, Dispatcher
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class StaleSchemaError(RuntimeError):
    """Raised when a tool call is dispatched against a fingerprint that no
    longer matches the live registry — including in-place schema mutations
    that preserve the tool-name set."""
    pass


@dataclass
class ToolRegistry:
    # name -> full schema dict (inputSchema, version, etc.)
    tools: dict = field(default_factory=dict)

    def fingerprint(self) -> str:
        # Hash the ENTIRE payload, not just the name set. This is the
        # invariant: any mutation (enum widening, required-set change)
        # changes the fingerprint and forces invalidation.
        blob = json.dumps(self.tools, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class Dispatcher:
    bound_fp: str
    registry: ToolRegistry

    def dispatch(self, name: str, args: dict, live: ToolRegistry) -> dict:
        live_fp = live.fingerprint()
        if live_fp != self.bound_fp:
            # Do NOT silently route through the stale map.
            raise StaleSchemaError(
                f"dispatcher bound to {self.bound_fp[:8]} but live registry "
                f"is {live_fp[:8]}; rebuild required before dispatch"
            )
        schema = live.tools.get(name)
        if schema is None:
            raise StaleSchemaError(f"tool {name!r} absent from live registry")
        required = set(schema.get("inputSchema", {}).get("required", []))
        missing = required - set(args)
        if missing:
            # A missing required field against the LIVE schema means the
            # caller's cached schema is stale — not a transient error.
            raise StaleSchemaError(
                f"call to {name!r} missing {sorted(missing)}; caller schema "
                f"predates live fingerprint {live_fp[:8]}"
            )
        return {"ok": True, "tool": name, "fp": live_fp}


def refresh(dispatcher: Dispatcher, live: ToolRegistry) -> Dispatcher:
    # Atomic invalidation: rebuild dispatcher AND planner schema block
    # together, keyed on the new full-payload fingerprint.
    new_fp = live.fingerprint()
    if new_fp == dispatcher.bound_fp:
        return dispatcher
    return Dispatcher(bound_fp=new_fp, registry=live)
