# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-tool-s-inputschema-at-handshake-but-the-server-silently-re-negotiates-capabilities-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-tool-s-inputschema-at-handshake-but-the-server-silently-re-negotiates-capabilities-mid-session.warrant.json
# Markdown SHA-256:   1c1bb70a77b63589022ef1aab7ce795ae7e9f65d1ce79510200a58be0d7da703
# Code AST SHA-256:   2e666b0b0fc2efc82deb32f6a1f88c821d5e914611fecf3d585597ccb800dbc9
# Verified Classes:   CapabilityDriftError, ToolBinding, MCPClientSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when a tool's inputSchema widens mid-session without re-render."""

    def __init__(self, tool: str, old_hash: str, new_hash: str, delta: str):
        self.tool = tool
        self.old_hash = old_hash
        self.new_hash = new_hash
        self.delta = delta
        super().__init__(
            f"tool '{tool}' schema widened mid-session: {old_hash} -> {new_hash} ({delta}); "
            f"reasoning chain must be invalidated and tool re-selected before any call is admitted"
        )


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


def _is_widening(old: dict[str, Any], new: dict[str, Any]) -> tuple[bool, str]:
    """True iff `new` accepts strictly more inputs than `old` on any axis."""
    reasons: list[str] = []

    if old.get("additionalProperties", True) is False and new.get("additionalProperties", True) is not False:
        reasons.append("additionalProperties opened")

    old_req = set(old.get("required", []))
    new_req = set(new.get("required", []))
    if new_req < old_req:
        reasons.append(f"required relaxed: dropped {sorted(old_req - new_req)}")

    old_props = old.get("properties", {})
    new_props = new.get("properties", {})
    for key, old_spec in old_props.items():
        new_spec = new_props.get(key, {})
        old_enum = set(old_spec.get("enum", []))
        new_enum = set(new_spec.get("enum", []))
        if old_enum and new_enum and not old_enum.issubset(new_enum):
            reasons.append(f"enum widened on '{key}': +{sorted(new_enum - old_enum)}")

    return (bool(reasons), "; ".join(reasons))


@dataclass
class ToolBinding:
    name: str
    schema: dict[str, Any]
    hash: str
    rendered_description: str


@dataclass
class MCPClientSession:
    bindings: dict[str, ToolBinding] = field(default_factory=dict)
    epoch: int = 0

    def bind_initial(self, tools: list[dict[str, Any]]) -> None:
        for t in tools:
            h = _hash_schema(t["inputSchema"])
            self.bindings[t["name"]] = ToolBinding(
                name=t["name"],
                schema=t["inputSchema"],
                hash=h,
                rendered_description=f"tool {t['name']}: {json.dumps(t['inputSchema'])}",
            )

    def on_tools_list_changed(self, tools: list[dict[str, Any]]) -> None:
        """Called on every tools/list response, including push notifications."""
        for t in tools:
            name = t["name"]
            new_schema = t["inputSchema"]
            new_hash = _hash_schema(new_schema)
            old = self.bindings.get(name)
            if old is None:
                # new tool appeared: model must re-plan; treat as epoch bump
                self.epoch += 1
                self.bindings[name] = ToolBinding(name, new_schema, new_hash, f"tool {name}: {json.dumps(new_schema)}")
                continue
            if old.hash == new_hash:
                continue
            widened, reason = _is_widening(old.schema, new_schema)
            if widened:
                raise CapabilityDriftError(name, old.hash, new_hash, reason)
            # narrowing: update validator, but model may still hold stale render;
            # surface as tool error on next call rather than silently accept.
            self.bindings[name] = ToolBinding(name, new_schema, new_hash, old.rendered_description)

    def admit_call(self, name: str, args: dict[str, Any]) -> None:
        b = self.bindings.get(name)
        if b is None:
            raise CapabilityDriftError(name, "<none>", "<unknown>", "tool not bound")
        if b.hash != _hash_schema(b.schema):
            raise CapabilityDriftError(name, b.hash, "<mutated>", "binding schema mutated in place")
        # Validator enforces the *pinned* schema, not the latest server schema.
        if b.schema.get("additionalProperties", True) is False:
            extra = set(args) - set(b.schema.get("properties", {}))
            if extra:
                raise CapabilityDriftError(name, b.hash, b.hash, f"unexpected keys {sorted(extra)}")
