# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tools-list-schema-as-version-pinned-across-a-single-task-and-what-breaks-when-the-server-silently.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tools-list-schema-as-version-pinned-across-a-single-task-and-what-breaks-when-the-server-silently.warrant.json
# Markdown SHA-256:   41bfecca172738d2ddc28b84cf9c81b9021a3d702fe6a5ca5a484677683e3a18
# Code AST SHA-256:   e410954086437768ec8cca0f51b142ccbe8af69b1ea2a68c16f4dfd46f2e9bef
# Verified Classes:   SchemaRenegotiationRequired, ArgumentRepairForbidden, ToolContract, TaskState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SchemaRenegotiationRequired(RuntimeError):
    """Raised when a tool's inputSchema fingerprint diverges from the
    fingerprint recorded at plan time. Signals task-level renegotiation,
    NOT a call-level argument repair."""
    pass


class ArgumentRepairForbidden(SchemaRenegotiationRequired):
    """Raised when the model attempts to repair arguments after a -32602
    while the schema fingerprint has moved. Repair would fit arguments to
    a contract the model cannot see; abort instead."""
    pass


def fingerprint(schema: dict[str, Any]) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]


@dataclass
class ToolContract:
    name: str
    input_schema: dict[str, Any]
    fp: str = field(init=False)

    def __post_init__(self) -> None:
        self.fp = fingerprint(self.input_schema)


@dataclass
class TaskState:
    planned_fps: dict[str, str]          # tool name -> fingerprint at plan time
    cached_schemas: dict[str, dict]      # tool name -> schema the model holds in context
    renegotiated: bool = False


def guarded_call(
    state: TaskState,
    tool: str,
    args: dict[str, Any],
    live_contract: ToolContract,
    server_error: str | None = None,
) -> dict[str, Any]:
    planned_fp = state.planned_fps.get(tool)
    if planned_fp is None:
        raise SchemaRenegotiationRequired(
            f"tool {tool!r} was never fingerprinted at plan time; "
            f"cannot verify contract stability"
        )

    if live_contract.fp != planned_fp:
        # Contract moved mid-task. Do not dispatch, do not repair.
        state.renegotiated = True
        raise SchemaRenegotiationRequired(
            f"schema for {tool!r} moved: planned fp={planned_fp} "
            f"live fp={live_contract.fp}; abort task segment and re-fetch tools/list"
        )

    if server_error is not None and "-32602" in server_error:
        # Fingerprint matches, so the arguments are genuinely wrong.
        # Repair is permitted, but only because we just proved the contract
        # did not move.
        return {"action": "repair_arguments", "tool": tool, "args": args}

    return {"action": "dispatch", "tool": tool, "args": args}


def on_invalid_params(
    state: TaskState,
    tool: str,
    live_contract: ToolContract,
) -> None:
    """Called when the model wants to repair arguments after a -32602.
    Forbidden if the schema moved; the model would be fitting to an
    invisible contract."""
    planned_fp = state.planned_fps.get(tool)
    if planned_fp is not None and live_contract.fp != planned_fp:
        raise ArgumentRepairForbidden(
            f"refusing argument repair for {tool!r}: schema moved "
            f"({planned_fp} -> {live_contract.fp}). The -32602 was a contract "
            f"change, not an argument error. Renegotiate, do not retry."
        )
