# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-mcp-tool-schema-against-a-server-that-re-advertises-the-same-capability-name-with-a-mutated-inputschema-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-mcp-tool-schema-against-a-server-that-re-advertises-the-same-capability-name-with-a-mutated-inputschema-mid.warrant.json
# Markdown SHA-256:   01b0adf16f77e9c448150510f79b77db4a5566c890d2457ae4e449bad0b5adb3
# Code AST SHA-256:   e25247e405df366244f9a84df19e6e1ffd706bafd58a0ec37fe455eba16ad46a
# Verified Classes:   StaleSchemaDispatchError, SchemaEpoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class StaleSchemaDispatchError(RuntimeError):
    """Raised when a tools/call would be issued against an unverifiable schema epoch."""


@dataclass(frozen=True)
class SchemaEpoch:
    server_instance_id: str
    fetched_at: float          # monotonic seconds
    input_schema: dict[str, Any]

    def fingerprint(self) -> str:
        blob = json.dumps(self.input_schema, sort_keys=True).encode()
        return hashlib.sha256(blob).hexdigest()


SUBTRACTIVE_CAPABLE = {"mode", "overwrite", "force", "encoding"}  # properties whose loss changes semantics


def assert_dispatch_safe(
    cached: SchemaEpoch,
    live_instance_id: str,
    now: float,
    deploy_window: float,
    list_changed_since_fetch: bool,
) -> None:
    """Guard invoked immediately before every tools/call dispatch."""
    if cached.server_instance_id != live_instance_id:
        raise StaleSchemaDispatchError(
            f"server instance changed: cached={cached.server_instance_id!r} "
            f"live={live_instance_id!r}; re-fetch tools/list before dispatch"
        )
    if list_changed_since_fetch:
        raise StaleSchemaDispatchError(
            "received tools/list_changed since last fetch; cached schema is unverified"
        )
    age = now - cached.fetched_at
    if age > deploy_window and SUBTRACTIVE_CAPABLE & set(cached.input_schema.get("properties", {})):
        raise StaleSchemaDispatchError(
            f"cache age {age:.1f}s exceeds deploy window {deploy_window:.1f}s and schema "
            f"carries subtractive-capable properties; re-fetch required"
        )


def classify_tool_error(
    is_error: bool,
    error_text: str,
    cached: SchemaEpoch,
    live_schema: dict[str, Any] | None,
) -> str:
    """Map a tool rejection to a retry-vs-replan decision."""
    if not is_error:
        return "success"
    if live_schema is None:
        # cannot disambiguate; strict posture is to re-fetch, never blind-retry
        raise StaleSchemaDispatchError(
            "tool returned isError with no live schema to diff against; "
            "refusing to retry against stale cache"
        )
    live_fp = SchemaEpoch(
        server_instance_id=cached.server_instance_id,
        fetched_at=cached.fetched_at,
        input_schema=live_schema,
    ).fingerprint()
    if live_fp != cached.fingerprint():
        return "schema_drift_replan"
    return "genuine_invalid_input"
