# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-tool-schema-that-mutates-mid-session-the-silent-capability-drift-boundary-in-mcp.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-tool-schema-that-mutates-mid-session-the-silent-capability-drift-boundary-in-mcp.warrant.json
# Markdown SHA-256:   7fcd12a16283b507ea31e0e42ae51f27a0c23e0d68a5b90b88ebc5acf8c8b2b2
# Code AST SHA-256:   4558c3035b47c62da3c20547bc025595f755effa5da37e0117c4c81f98aedba3
# Verified Classes:   StaleSchemaError, SchemaDriftUnrecoverable, NegotiatedSchema, VersionedMCPClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class StaleSchemaError(RuntimeError):
    """Raised when a tool call is validated against a schema version the
    server no longer serves. Must be handled as control flow (re-negotiate),
    never surfaced to the model as a tool failure."""
    pass


class SchemaDriftUnrecoverable(RuntimeError):
    """Raised when re-negotiation cannot produce a schema compatible with the
    in-flight plan, forcing a hard stop instead of model improvisation."""
    pass


@dataclass
class NegotiatedSchema:
    version: str
    tools: dict = field(default_factory=dict)

    @classmethod
    def from_listing(cls, listing: dict) -> "NegotiatedSchema":
        blob = json.dumps(listing, sort_keys=True).encode()
        version = hashlib.sha256(blob).hexdigest()[:16]
        return cls(version=version, tools={t["name"]: t for t in listing["tools"]})


class VersionedMCPClient:
    def __init__(self, transport):
        self.transport = transport
        self.schema = NegotiatedSchema.from_listing(transport.list_tools())

    def _relist(self) -> NegotiatedSchema:
        return NegotiatedSchema.from_listing(self.transport.list_tools())

    def call_tool(self, name: str, args: dict, task_plan_tools: set[str]):
        # Invariant: every dispatch names the schema version it validated against.
        if name not in self.schema.tools:
            raise SchemaDriftUnrecoverable(
                f"tool {name!r} absent from negotiated schema {self.schema.version}"
            )
        try:
            return self.transport.call(
                name, args, schema_version=self.schema.version
            )
        except StaleSchemaError:
            # Control-flow recovery: re-list, diff, then decide.
            fresh = self._relist()
            dropped = task_plan_tools - set(fresh.tools)
            if dropped:
                # Plan depends on tools the new schema removed: hard stop.
                raise SchemaDriftUnrecoverable(
                    f"re-negotiation removed tools required by plan: {dropped}"
                )
            self.schema = fresh
            # Re-issue the ORIGINAL call against the verified-live schema.
            return self.transport.call(
                name, args, schema_version=self.schema.version
            )
