# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-mcp-client-and-server-negotiate-tools-across-a-versioned-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-mcp-client-and-server-negotiate-tools-across-a-versioned-handshake.warrant.json
# Markdown SHA-256:   1668927473b69763a608462b15b275473351899c0ac2aef73f5e89859a322b6d
# Code AST SHA-256:   87754bf236e01d8395ff1dd53b3e744e1d8f502cb1462323018f604eab3d9580
# Verified Classes:   CapabilityDriftError, ToolSchema, NegotiatedSurface
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class CapabilityDriftError(RuntimeError):
    """Raised when a tool call is shaped against a schema the server no longer enforces."""
    pass


@dataclass
class ToolSchema:
    name: str
    params: dict

    def content_hash(self) -> str:
        # Content-addressed: identity is the full definition, not a version string.
        canonical = json.dumps(
            {"name": self.name, "params": self.params},
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(canonical.encode()).hexdigest()


@dataclass
class NegotiatedSurface:
    server_id: str
    protocol_version: str
    tools: dict = field(default_factory=dict)  # name -> ToolSchema
    dirty: bool = False

    def hash_for(self, tool_name: str) -> str:
        if tool_name not in self.tools:
            raise CapabilityDriftError(
                f"tool {tool_name!r} not in negotiated surface for {self.server_id}"
            )
        return self.tools[tool_name].content_hash()


def on_list_changed(surface: NegotiatedSurface) -> None:
    # Invariant 2: list_changed is a hard invalidation, never a hint.
    surface.dirty = True


def invoke_tool(
    surface: NegotiatedSurface,
    fresh_tools: dict,
    tool_name: str,
    args: dict,
    plan_depends_on: set,
) -> dict:
    if surface.dirty:
        raise CapabilityDriftError(
            f"surface for {surface.server_id} is dirty; re-fetch tools/list before invoking"
        )

    if tool_name not in fresh_tools:
        # Narrowing: tool removed. If the plan depends on it, abort.
        if tool_name in plan_depends_on:
            raise CapabilityDriftError(
                f"tool {tool_name!r} removed from server; in-flight plan depends on it"
            )
        raise CapabilityDriftError(f"tool {tool_name!r} no longer advertised")

    fresh = fresh_tools[tool_name]
    cached_hash = surface.hash_for(tool_name)
    fresh_hash = fresh.content_hash()

    if cached_hash != fresh_hash:
        # Invariant 1: hash mismatch means the snapshot is stale.
        # Determine narrowing vs widening by comparing param sets.
        old_params = surface.tools[tool_name].params
        new_params = fresh.params
        narrowed = _is_narrowing(old_params, new_params)
        if narrowed and tool_name in plan_depends_on:
            raise CapabilityDriftError(
                f"schema for {tool_name!r} narrowed mid-plan "
                f"(cached={cached_hash[:8]} fresh={fresh_hash[:8]}); re-plan required"
            )
        surface.tools[tool_name] = fresh  # absorb widening change

    # Invariant 3: strict validation at the boundary. Reject, do not coerce.
    return _strict_validate_and_call(fresh, args)


def _is_narrowing(old_params: dict, new_params: dict) -> bool:
    for key, new_spec in new_params.items():
        old_spec = old_params.get(key)
        if old_spec is None:
            return True  # added a required param
        if "enum" in new_spec and "enum" not in old_spec:
            return True  # free-form -> enum
        if "enum" in new_spec and "enum" in old_spec:
            if not set(new_spec["enum"]).issuperset(old_spec["enum"]):
                return True  # enum tightened
    return False


def _strict_validate_and_call(schema: ToolSchema, args: dict) -> dict:
    for key, spec in schema.params.items():
        if "enum" in spec and key in args and args[key] not in spec["enum"]:
            # Do NOT coerce "7d" -> "24h". Reject loudly.
            raise CapabilityDriftError(
                f"arg {key}={args[key]!r} not in accepted enum {spec['enum']}"
            )
    return {"status": "invoked", "tool": schema.name, "args": args}
