# Which invariants prevent silent capability drift when an MCP server is re-fingerprinted across a transport upgrade **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients (agent runtimes) that cache a server's declared capability surface — tools, resources, prompts, and their JSON Schemas — and re-negotiate it when the underlying transport changes (stdio↔SSE, SSE↔streamable-HTTP, or a versioned `initialize` handshake bump). Does not cover first-contact discovery of a never-before-seen server, nor drift within a single stable transport session. ## Core Distinction The failure of interest is not "the server changed its tools." It is that **the client's cached capability fingerprint and the server's live capability surface diverge during the window between transport teardown and re-initialization, and the client treats the post-upgrade surface as a continuation of the pre-upgrade one.** A transport upgrade is a *state discontinuity*: the old session's negotiated contract is dead the moment the transport socket closes, but the client's memory of that contract survives. If the client re-fingerprints by *diffing* the new surface against the cached one and only alerting on *additions and removals*, it will silently accept **in-place mutation** — a tool keeping its name while its `inputSchema` narrows a required field, an enum loses a member, or a `readOnlyHint` flips to destructive. Name-level diffing is stable across the upgrade; schema-level identity is not. The invariant that must hold is *content-addressed capability identity*, not name-set identity. ## What Was Observed A filesystem-class MCP server was upgraded from stdio to streamable-HTTP mid-session. The agent held a cached fingerprint keyed by tool name: `{read_file, write_file, list_dir, move}`. On re-`initialize`, the server returned the same four names. The client's drift detector — a set-difference over `tools[].name` — reported `added: [], removed: [], changed: []`. The agent resumed its task plan. The live `write_file.inputSchema` had, however, changed from: ``` { "path": {"type":"string"}, "content": {"type":"string"}, "mode": {"enum":["append","overwrite"], "default":"overwrite"} } ``` to a schema where `mode` was now `required` with no default, and `path` was constrained by a new `pattern` rejecting absolute paths outside a sandbox root. The agent's next call omitted `mode` and passed an absolute path. The server rejected with `-32602 Invalid params`. The agent's tool-call retry loop — which had been trained by prior sessions to treat `-32602` as a transient serialization bug — retried three times, then escalated to a *fallback* tool (`move` to a temp path, then `write_file`), which also failed the pattern constraint. The task aborted with a misleading "transport instability" classification; the actual cause was a schema mutation the fingerprint never saw. A second, subtler case: an SSE→streamable-HTTP upgrade where the server's `capabilities.resources.subscribe` flipped from `true` to `false` (the new transport did not implement push). The client's name-set diff saw nothing; it kept a live subscription handle and blocked on a notification that would never arrive, exhausting its per-task wall-clock budget. ## Condition of Validity Name-set diffing is a valid drift detector **only under the invariant that a capability's name uniquely and permanently determines its full behavioral contract.** That invariant holds for immutable, versioned tool registries (e.g., a server that publishes `tool@sha256:...` and never mutates a name). It fails whenever any of the following is true, which is the common case: - Tool `inputSchema` / `outputSchema` can be edited without renaming (the default in most MCP server implementations). - `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) are advisory and may change independently of name. - Server `capabilities` flags (`tools.listChanged`, `resources.subscribe`, `prompts.listChanged`) are negotiated per-`initialize` and are *not* part of the tool list. - The transport upgrade changes the *ordering* or *pagination* of `tools/list` (`nextCursor` semantics differ between transports), so a naive positional diff misaligns entries. Under any of these, the correct fingerprint is a **content hash over the canonicalized capability tuple**: `(name, canonical_json(inputSchema), canonical_json(outputSchema), sorted(annotations), server_capability_flags)`. Canonicalization must sort keys, normalize numeric types, and strip transport-specific envelope fields before hashing — otherwise the hash itself drifts on every upgrade for reasons that are not semantic. ## Decision Boundary The client must choose, at the moment the new `initialize` response arrives, between two policies: 1. **Trust-by-name (fast path).** Reuse the cached fingerprint if the name set matches. Permitted *only* if the server advertises a `capabilityVersion` or content-addressed tool digest that the client can verify against the cache. If the server cannot prove immutability, this path is unsound and must be refused. 2. **Re-fingerprint-and-diff (safe path).** Recompute the content hash for every capability, compare against the cache, and classify each as `identical`, `mutated`, `added`, `removed`. Any `mutated` entry **invalidates the cached plan step that referenced it** and forces the agent to re-plan that step against the new schema before issuing another call. The boundary is crossed the instant the transport closes: the cache is now a *hypothesis*, not a fact. The client must not treat a `mutated` result as a warning to log and continue. It must treat it as a *contract break* that demotes the affected capability from "callable per cached plan" to "requires re-derivation." A `mutated` schema that only *widens* (adds optional fields, relaxes constraints) may be auto-accepted under a monotonic-widening rule; any *narrowing* (new required field, removed enum member, tightened pattern, flipped destructive hint) must block the cached call path. ## Operational Effect The observable consequence of getting this wrong is a class of failures that *look* like transport or serialization faults but are semantic contract breaks: `-32602` storms misclassified as transient, subscription hangs misclassified as network partitions, and retry loops that burn the token budget re-sending calls the server will never accept. Because the error surfaces at the tool-call layer rather than the handshake layer, post-mortems attribute it to the transport upgrade itself — the one component that behaved correctly. The guardrail is a **fingerprint gate** placed between the new `initialize` response and the first post-upgrade tool call. It must: (a) reject name-only diffing when the server cannot prove capability immutability; (b) canonicalize before hashing so transport envelope noise does not masquerade as drift; (c) classify mutations as widening vs. narrowing and block the cached call path on any narrowing; (d) treat a changed `capabilities` flag (especially `subscribe` and `listChanged`) as a first-class drift event, not a tool-list afterthought. Without this gate, the agent's memory of the pre-upgrade contract is a stale oracle, and every downstream reasoning step inherits the error. ```python 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 ```