# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-mcp-tool-schema-against-a-stale-capability-manifest-and-the-server-evolves-its-schema-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-mcp-tool-schema-against-a-stale-capability-manifest-and-the-server-evolves-its-schema-mid-session.warrant.json
# Markdown SHA-256:   897318d1504243d07a477ed492e1cb1c95431872d1deb71b5d9b8c39e9a06fe9
# Code AST SHA-256:   649e42959fa5f353ead8d5080a8a862d8207b65193d43c65488ff6dfbd12bab6
# Verified Classes:   SchemaSkewError, NegotiatedTool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SchemaSkewError(RuntimeError):
    """Raised when a tool's live inputSchema diverges from the session-negotiated snapshot."""


@dataclass(frozen=True)
class NegotiatedTool:
    name: str
    schema_hash: str
    input_schema: dict[str, Any]


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


def negotiate(tool_name: str, live_schema: dict[str, Any]) -> NegotiatedTool:
    return NegotiatedTool(
        name=tool_name,
        schema_hash=_hash_schema(live_schema),
        input_schema=live_schema,
    )


def dispatch(
    negotiated: NegotiatedTool,
    args: dict[str, Any],
    fetch_live_schema,
) -> dict[str, Any]:
    """
    Verify schema identity before sending arguments built from a cached contract.
    fetch_live_schema(name) -> current inputSchema from the server manifest.
    """
    live = fetch_live_schema(negotiated.name)
    live_hash = _hash_schema(live)

    if live_hash != negotiated.schema_hash:
        # The server evolved the schema under a live session. Do NOT retry with
        # guessed values; escalate to re-negotiation.
        raise SchemaSkewError(
            f"tool {negotiated.name!r} schema skew: "
            f"negotiated={negotiated.schema_hash[:12]} live={live_hash[:12]}; "
            f"session must re-negotiate before dispatch"
        )

    # Only reached when the cached contract matches the live one.
    return {"tool": negotiated.name, "arguments": args, "schema_hash": live_hash}
