# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-mcp-capability-downgrade-but-retains-stale-tool-schemas-from-a-prior-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-mcp-capability-downgrade-but-retains-stale-tool-schemas-from-a-prior-session.warrant.json
# Markdown SHA-256:   92167dd5f85975f27392d03475a67bce41e081bc4cdfd22860633ef42c0ea550
# Code AST SHA-256:   6c49c9ecd5be24bbd07b2a2949aa72db89db85a63f2e34ed4649222dba08d0f3
# Verified Classes:   StaleSchemaError, ServerInstanceKey, SchemaRecord, MCPClientSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleSchemaError(RuntimeError):
    """Raised when a tool call would be constructed from a schema that does not
    match the currently negotiated server instance."""


@dataclass
class ServerInstanceKey:
    name: str
    version: str
    protocol_version: str

    def digest(self) -> str:
        raw = json.dumps(
            [self.name, self.version, self.protocol_version], sort_keys=True
        ).encode()
        return hashlib.sha256(raw).hexdigest()


@dataclass
class SchemaRecord:
    instance_digest: str
    tool_schemas: dict[str, Any] = field(default_factory=dict)

    def schema_digest(self) -> str:
        raw = json.dumps(self.tool_schemas, sort_keys=True).encode()
        return hashlib.sha256(raw).hexdigest()


class MCPClientSession:
    def __init__(self) -> None:
        self._record: SchemaRecord | None = None

    def on_initialize(self, server_info: dict, protocol_version: str) -> ServerInstanceKey:
        key = ServerInstanceKey(
            name=server_info["name"],
            version=server_info["version"],
            protocol_version=protocol_version,
        )
        # Capability equality is NOT sufficient; instance key drives refresh.
        if self._record is None or self._record.instance_digest != key.digest():
            self._record = SchemaRecord(instance_digest=key.digest())
        return key

    def install_tools_list(self, tools: list[dict]) -> None:
        if self._record is None:
            raise StaleSchemaError("tools/list received before initialize")
        self._record.tool_schemas = {t["name"]: t["inputSchema"] for t in tools}

    def build_call(self, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
        if self._record is None:
            raise StaleSchemaError("no negotiated session; refusing to build call")
        schema = self._record.tool_schemas.get(tool_name)
        if schema is None:
            raise StaleSchemaError(
                f"tool {tool_name!r} not present in schema for instance "
                f"{self._record.instance_digest[:12]}; refresh tools/list"
            )
        allowed = set(schema.get("properties", {}).keys())
        extra = set(arguments) - allowed
        if extra:
            raise StaleSchemaError(
                f"arguments {sorted(extra)} not in schema for {tool_name!r}; "
                f"schema may be stale relative to negotiated server instance"
            )
        return {"name": tool_name, "arguments": arguments}

    def classify_error(self, code: int, message: str) -> str:
        # -32602 with unknown-field diagnostics => staleness, not model error.
        if code == -32602 and ("additional propert" in message or "unknown" in message):
            self._record = None  # force renegotiation + re-list
            return "SCHEMA_STALE_REFRESH"
        if code == -32601:
            self._record = None
            return "CAPABILITY_STALE_RENEGOTIATE"
        return "OTHER"
