# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-invalidate-a-cached-mcp-capability-manifest-after-a-versioned-schema-migration-and-what-breaks-when-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-invalidate-a-cached-mcp-capability-manifest-after-a-versioned-schema-migration-and-what-breaks-when-it-doesn-t.warrant.json
# Markdown SHA-256:   8ab6e44d2be05dc70e4a3bbf7a357c0dfcf6dcaf08c668316470cdb73af1b03a
# Code AST SHA-256:   1f6c61acd310fe1339fa36786cb644837e6419624c127b7d0714884da7eaf3be
# Verified Classes:   StaleManifestError, ManifestCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleManifestError(RuntimeError):
    """Raised when a cached MCP capability manifest's digest no longer
    matches the server's currently served tools/list payload, or when a
    compatibility shim has coerced call semantics without signaling it."""


@dataclass
class ManifestCache:
    server_uri: str
    digest: str
    tools: list[dict[str, Any]]
    fetched_at_turn: int
    calls_since_verify: int = 0

    @staticmethod
    def canonical_digest(tools: list[dict[str, Any]]) -> str:
        # Canonicalize: sort by name, strip volatile fields, stable key order.
        canon = sorted(
            (
                {
                    "name": t["name"],
                    "inputSchema": t.get("inputSchema", {}),
                    "outputSchema": t.get("outputSchema", {}),
                    "x-compat": t.get("x-compat", {}),
                }
                for t in tools
            ),
            key=lambda t: t["name"],
        )
        blob = json.dumps(canon, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(blob).hexdigest()


def verify_manifest(
    cache: ManifestCache,
    freshly_served: list[dict[str, Any]],
    current_turn: int,
    max_calls_between_verify: int = 25,
) -> ManifestCache:
    """Re-verify a cached manifest against a fresh tools/list.

    Called on session initialize and on cadence. On digest divergence the
    entire manifest is invalidated and replaced; partial patching is
    forbidden because a half-migrated manifest yields mixed-version tool
    selection.
    """
    fresh_digest = ManifestCache.canonical_digest(freshly_served)

    if fresh_digest != cache.digest:
        # Detect whether the divergence is a silent semantic migration:
        # same tool names, changed inputSchema, no x-compat declaration.
        old_by_name = {t["name"]: t for t in cache.tools}
        new_by_name = {t["name"]: t for t in freshly_served}
        silent_migrations = []
        for name in set(old_by_name) & set(new_by_name):
            old, new = old_by_name[name], new_by_name[name]
            if old.get("inputSchema") != new.get("inputSchema"):
                compat = new.get("x-compat", {})
                if not compat.get("semantics_changed"):
                    silent_migrations.append(name)

        if silent_migrations:
            raise StaleManifestError(
                f"Manifest digest changed for {cache.server_uri} "
                f"(cached_turn={cache.fetched_at_turn}, now_turn={current_turn}); "
                f"tools with silent schema mutation and no x-compat declaration: "
                f"{silent_migrations}. Refusing to serve cached manifest; "
                f"re-derive tool selection from freshly served schema."
            )

        # Migration was declared via x-compat; wholesale replacement is safe.
        return ManifestCache(
            server_uri=cache.server_uri,
            digest=fresh_digest,
            tools=freshly_served,
            fetched_at_turn=current_turn,
            calls_since_verify=0,
        )

    cache.calls_since_verify = 0
    return cache


def guarded_tool_call(
    cache: ManifestCache,
    tool_name: str,
    args: dict[str, Any],
    freshly_served: list[dict[str, Any]],
    current_turn: int,
) -> dict[str, Any]:
    """Wrapper that enforces manifest freshness before dispatch and rejects
    calls whose parameters rely on fields absent from the current schema
    (i.e., shim-mediated degradation that the server did not flag)."""
    cache = verify_manifest(cache, freshly_served, current_turn)

    schema = next(
        (t.get("inputSchema", {}) for t in cache.tools if t["name"] == tool_name),
        None,
    )
    if schema is None:
        raise StaleManifestError(
            f"Tool {tool_name!r} not present in verified manifest for "
            f"{cache.server_uri}; cached selection is invalid."
        )

    allowed = set(schema.get("properties", {}).keys())
    unknown = set(args) - allowed
    if unknown:
        # The shim may accept these, but the current schema does not declare
        # them—semantics are unverified. Fail closed.
        raise StaleManifestError(
            f"Call to {tool_name!r} passes undeclared parameters {sorted(unknown)}; "
            f"current inputSchema declares {sorted(allowed)}. "
            f"Refusing shim-mediated call whose semantics cannot be verified."
        )

    # ... dispatch to transport, attach cache.digest to the request trace ...
    return {"_manifest_digest": cache.digest, "_dispatched": True}
