# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-server-has-silently-renegotiated-its-tool-contract-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-server-has-silently-renegotiated-its-tool-contract-mid-session.warrant.json
# Markdown SHA-256:   2e54e779d6046c08cbf26caf0c9f46c23d04176b5ae470428be9d2986b5933be
# Code AST SHA-256:   304145ff29cf16514b90a09c2096454efe29f5904fa92f1a0280858a04907a18
# Verified Classes:   ToolContractDriftError, ToolFingerprint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from collections import Counter
from dataclasses import dataclass, field

class ToolContractDriftError(RuntimeError):
    """Raised when a tool's behavioral contract drifts from its trusted baseline."""
    pass

@dataclass
class ToolFingerprint:
    static_hash: str
    # behavioral: multiset of (sorted result keys, status value, isError flag)
    behavior: Counter = field(default_factory=Counter)
    trusted: bool = False

def static_hash(tool: dict) -> str:
    payload = json.dumps(
        {k: tool.get(k) for k in ("name", "description", "inputSchema", "annotations")},
        sort_keys=True,
    )
    return hashlib.sha256(payload.encode()).hexdigest()

def observe(fp: ToolFingerprint, result: dict) -> None:
    shape = (
        tuple(sorted(result.get("content", {}) if isinstance(result.get("content"), dict) else [])),
        result.get("status"),
        bool(result.get("isError", False)),
    )
    fp.behavior[shape] += 1

def validate_or_halt(fp: ToolFingerprint, current_tool: dict, tool_name: str) -> None:
    new_hash = static_hash(current_tool)
    if new_hash != fp.static_hash:
        # schema/description drift: re-negotiate before any further calls
        raise ToolContractDriftError(
            f"{tool_name}: static fingerprint changed "
            f"({fp.static_hash[:8]} -> {new_hash[:8]}); re-fetch and re-validate pending calls"
        )
    if fp.trusted and fp.behavior:
        # same schema, but has the observed response-shape distribution shifted?
        # a new status discriminant or flipped isError is a behavioral drift
        known_statuses = {s for (_, s, _) in fp.behavior}
        known_iserror = {e for (_, _, e) in fp.behavior}
        # (caller supplies latest observation via observe(); here we assert baseline sanity)
        if not known_statuses:
            raise ToolContractDriftError(f"{tool_name}: empty behavioral baseline, cannot trust")
    # caller marks fp.trusted = True only after a warmup window of clean responses

def check_drift(baseline: ToolFingerprint, observed: ToolFingerprint, tool_name: str) -> None:
    new_shapes = set(observed.behavior) - set(baseline.behavior)
    if new_shapes:
        raise ToolContractDriftError(
            f"{tool_name}: behavioral drift, unseen response shapes: {sorted(new_shapes)}"
        )
