# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-mcp-server-is-re-fingerprinted-across-a-transport-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-drift-when-an-mcp-server-is-re-fingerprinted-across-a-transport-upgrade.warrant.json
# Markdown SHA-256:   fbe27c6034f2f766efeaa8c8c8a2a0f05a1f3643651afe51afe06c180d3ff215
# Code AST SHA-256:   5d10dffcd154461e8a308a623c167b9f3b5d4f3c3c325d4a686ba0438d41243a
# Verified Classes:   CapabilityDriftError, CapabilityFingerprint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when a post-transport-upgrade capability surface narrows the cached contract."""


@dataclass(frozen=True)
class CapabilityFingerprint:
    name: str
    input_schema_hash: str
    output_schema_hash: str
    annotations_hash: str


def _canonical_hash(obj: Any) -> str:
    # Sort keys, drop transport envelope fields, normalize before hashing so the
    # hash reflects semantics, not the transport that carried it.
    if obj is None:
        obj = {}
    stripped = {k: v for k, v in obj.items() if k not in {"$schema", "x-transport"}}
    blob = json.dumps(stripped, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode()).hexdigest()


def fingerprint_tool(tool: dict) -> CapabilityFingerprint:
    return CapabilityFingerprint(
        name=tool["name"],
        input_schema_hash=_canonical_hash(tool.get("inputSchema")),
        output_schema_hash=_canonical_hash(tool.get("outputSchema")),
        annotations_hash=_canonical_hash(tool.get("annotations")),
    )


def _narrows(old: dict, new: dict) -> bool:
    """True if new schema is a strict narrowing of old (new required field,
    removed enum member, tightened pattern). Conservative: any doubt -> narrow."""
    old_req = set(old.get("required", []))
    new_req = set(new.get("required", []))
    if new_req - old_req:
        return True
    for key, old_prop in old.get("properties", {}).items():
        new_prop = new.get("properties", {}).get(key, {})
        old_enum = set(old_prop.get("enum", []))
        new_enum = set(new_prop.get("enum", []))
        if old_enum and new_enum and (old_enum - new_enum):
            return True
        if "pattern" in new_prop and new_prop.get("pattern") != old_prop.get("pattern"):
            return True
    return False


def reconcile_after_upgrade(
    cached: dict[str, dict],
    live: list[dict],
    server_capabilities: dict,
) -> dict[str, CapabilityFingerprint]:
    """Gate placed between initialize() and the first post-upgrade tool call."""
    live_by_name = {t["name"]: t for t in live}
    accepted: dict[str, CapabilityFingerprint] = {}

    for name, old_tool in cached.items():
        if name not in live_by_name:
            continue  # removal handled by caller's plan invalidation
        new_tool = live_by_name[name]
        old_fp = fingerprint_tool(old_tool)
        new_fp = fingerprint_tool(new_tool)

        if old_fp == new_fp:
            accepted[name] = new_fp
            continue

        if _narrows(old_tool.get("inputSchema", {}), new_tool.get("inputSchema", {})):
            raise CapabilityDriftError(
                f"capability '{name}' narrowed across transport upgrade: "
                f"cached input schema {old_fp.input_schema_hash[:12]} -> "
                f"live {new_fp.input_schema_hash[:12]}; cached plan step must be re-derived"
            )

        # Widening-only mutation: accept but mark for re-plan.
        accepted[name] = new_fp

    if server_capabilities.get("resources", {}).get("subscribe") is False:
        # A flipped capability flag is a drift event, not a tool-list afterthought.
        raise CapabilityDriftError(
            "server dropped resources.subscribe across upgrade; "
            "live subscription handles must be torn down before next await"
        )

    return accepted
