# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-mid-session-mcp-tool-schema-renegotiation-when-a-streamable-http-server-silently-swaps-capability-manifests-between-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-mid-session-mcp-tool-schema-renegotiation-when-a-streamable-http-server-silently-swaps-capability-manifests-between-tools.warrant.json
# Markdown SHA-256:   59811a7edd1368acf43fc944b285535af18816d6fcbf38244e878281891df0bb
# Code AST SHA-256:   409a60ab61b4c5d901e2289ff804e315ee2beb32bde8995bfee0fe8757eeca1d
# Verified Classes:   SchemaDriftError, ManifestCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SchemaDriftError(RuntimeError):
    """Raised when a tool-call failure is attributable to a stale cached manifest,
    not to malformed arguments. The caller MUST re-fetch tools/list and re-plan;
    retrying the same call is a protocol violation."""
    pass


@dataclass
class ManifestCache:
    session_id: str
    tool_schemas: dict[str, str] = field(default_factory=dict)  # tool -> schema hash

    def load(self, tools: list[dict]) -> None:
        self.tool_schemas = {
            t["name"]: hashlib.sha256(
                json.dumps(t.get("inputSchema", {}), sort_keys=True).encode()
            ).hexdigest()
            for t in tools
        }


def handle_tool_error(
    cache: ManifestCache,
    tool_name: str,
    error_code: int,
    live_tools: list[dict],
) -> None:
    """Called on any tool-call failure. Enforces the schema-epoch invariant:
    a schema-validation error (JSON-RPC -32602 class) on a cached tool requires
    a manifest diff before any retry is permitted."""
    if error_code != -32602:
        return  # application error: normal retry-with-correction is safe

    live = {
        t["name"]: hashlib.sha256(
            json.dumps(t.get("inputSchema", {}), sort_keys=True).encode()
        ).hexdigest()
        for t in live_tools
    }

    cached = cache.tool_schemas.get(tool_name)
    current = live.get(tool_name)

    if cached is None:
        raise SchemaDriftError(
            f"tool {tool_name!r} was cached but is absent from live manifest; "
            "tool removed mid-session — discard plan."
        )
    if current is None:
        raise SchemaDriftError(
            f"tool {tool_name!r} present in cache but missing from server's live "
            "tools/list; server dropped capability silently."
        )
    if cached != current:
        raise SchemaDriftError(
            f"schema drift on {tool_name!r}: cached={cached[:12]} live={current[:12]}. "
            "Model reasoned against stale schema; retry is divergent. "
            "Refresh manifest and re-prompt."
        )
    # hashes equal: error is genuinely argument-level; retry-with-correction is bounded.
    return
