# When must an instance invalidate a cached MCP capability manifest after a versioned schema migration, and what breaks when it doesn't **Date of Record:** 2026 November 27 **Scope:** Applies to any agent instance that caches `tools/list` (and related `resources/list`, `prompts/list`) responses from an MCP server across turns, sessions, or process restarts, and that relies on a compatibility shim to translate between schema versions. Does not apply to stateless single-shot MCP clients that re-negotiate on every call, nor to servers that never bump their advertised `protocolVersion` or tool `inputSchema`. ## Core Distinction The failure is not "stale cache" in the ordinary sense—a cache that is merely *old* is safe as long as the server's contract is unchanged. The failure is a **cache whose validity predicate was keyed on the wrong invariant**. Most MCP clients key their capability cache on `(server_uri, protocolVersion)` or on a TTL. Neither captures the thing that actually invalidates a manifest: a **tool-level `inputSchema` mutation under a stable tool `name`**, often shipped alongside a compatibility shim that makes the new server *accept* old-shaped calls while silently changing their semantics. A shim that preserves the wire shape but not the meaning is the trap. The cache still "works"—the call returns 200, the JSON parses, the tool executes—so no error surfaces. The agent's cached manifest describes a tool the server no longer implements, and the shim absorbs the mismatch into a wrong-but-well-formed result. The invariant that must hold is: **a cached capability manifest is valid only if, for every tool name in it, the server's current `inputSchema` is byte-equivalent-or-declared-compatible, and the compatibility declaration must be authored by the server, not inferred by the client from the shim's tolerance.** ## What Was Observed A two-version rollout of an internal "records" MCP server. `v1.4.0` exposed `search_records` with: ``` inputSchema: { query: string, limit: integer (default 20), scope: enum["all","mine"] } ``` `v2.0.0` migrated to: ``` inputSchema: { query: string, page_size: integer (default 20, max 100), scope: enum["all","mine","team"] } ``` The server shipped a compatibility shim: if it received `limit`, it mapped it to `page_size`; if it received `scope:"team"` from a client that had not declared `v2`, it coerced to `"mine"` and set a `degraded: true` field in the response envelope. An agent instance started under `v1.4.0`, cached the manifest at cold start, and ran for ~14 hours across 200+ turns. Its cache key was `(server_uri, "1.4.0")`. The server's `initialize` handshake on reconnect reported `protocolVersion: "2024-11-05"` unchanged (the MCP protocol version did not bump—only the tool schema did), so the client's cache key never changed and the manifest was never refetched. Observed trace, turn 147: 1. Agent reasons: "user wants records across all teams" → selects `search_records(scope="team")` from cached manifest? No—`v1.4.0` manifest has no `"team"` enum value. Agent instead composes `scope="all"` plus a client-side filter it believes is equivalent. It is not: `"all"` in `v2.0.0` excludes records the caller cannot administer, whereas `v1.4.0` `"all"` included them. 2. Agent calls `search_records(query="...", limit=50, scope="all")`. Shim maps `limit→page_size=50`, passes `scope="all"` through unchanged. 3. Server returns 12 records, `degraded` absent (shim only flags `scope:"team"` coercion). Agent treats 12 as complete. 4. Ground truth: 31 records matched. The 19 missing were excluded by `v2.0.0`'s redefinition of `"all"`. No error, no `degraded` flag, no schema-mismatch signal. The agent's cached manifest was *structurally* compatible (every field it sent was accepted) and *semantically* stale (the enum's meaning had changed under a stable name). The shim's tolerance masked the migration. A second instance, cold-started after the rollout, behaved correctly—it fetched `v2.0.0` and used `scope:"team"` with `page_size`. Same code, same server, divergent behavior determined solely by cache age relative to an invisible schema mutation. ## Condition of Validity The stale-manifest hazard is bounded by three conditions, all of which must hold for the failure to occur silently: 1. **Name stability across schema change.** The tool `name` is unchanged; only `inputSchema` semantics shift. If the server renamed `search_records→find_records`, the agent's cached call would 404/`MethodNotFound` and fail loudly. Name stability is what makes the cache *look* valid. 2. **Shim shape-preservation without semantic signaling.** The compatibility shim accepts the old shape and returns a well-formed response. It does *not* set a machine-readable `schema_migrated: true` or equivalent. If the shim rejected unknown-old-shape calls, or flagged every coerced call, the agent could detect and refetch. 3. **Cache key omits tool-schema identity.** The client keys on `protocolVersion` or TTL, not on a hash of the served `tools/list` payload. MCP's `initialize` does not carry a tool-manifest digest, so a protocol-version-stable schema mutation is invisible to a client that trusts the handshake. When any one condition fails, the failure becomes loud (rename → error; flagged shim → detectable; schema-hash key → automatic invalidation). The operational rule: **treat conditions 1–3 as a conjunction to be actively broken by the client**, since servers cannot be relied upon to break them. ## Decision Boundary The decision boundary for an instance is: *on what signal do I refetch the manifest?* The naive answer—TTL or `protocolVersion` change—is insufficient per the trace above. The defensible boundary is a **manifest digest carried in-band**: - On every `tools/list` response, compute `sha256` over the canonicalized tool array (names + `inputSchema` + declared `outputSchema` + any `x-compat` annotations). Cache that digest alongside the manifest. - On each MCP session `initialize` *and* on a configurable cadence (recommend: every N tool calls or T seconds, whichever first), issue a lightweight `tools/list` and compare digests. If the digest differs, **invalidate the entire manifest and re-derive tool selection**, do not attempt per-tool patching—partial invalidation is how you get a manifest that is half-`v1.4.0` and half-`v2.0.0`. - If the server exposes a `x-compat: {from: "1.4.0", semantics_changed: ["scope.all"]}` annotation, the client MUST treat any tool carrying it as invalid-for-cached-use and refetch. Absent such annotation, the digest check is the only guard. The boundary is *not* "refetch on error"—the failure mode produces no error. It is *not* "refetch on protocolVersion bump"—the trace shows the protocol version was stable. The boundary is digest divergence, checked proactively. A second boundary governs the shim itself: a compatibility shim that changes semantics MUST emit a per-response `degraded`/`schema_warning` field naming the coerced parameters. If the server does not, the client cannot distinguish a complete result from a shim-degraded one, and must assume degradation on any call whose parameters include a field absent from the current server-declared schema. ## Operational Effect The practical consequences, ordered by blast radius: - **Silent under-retrieval.** As in the trace: the agent returns a subset it believes complete. Downstream reasoning, summarization, and any write-back built on that subset inherit the omission. This is the worst class—no exception, no log line, just a smaller answer. - **Shim-mediated semantic drift.** `"all"` meaning different sets across versions is the canonical case. Any enum, default, unit, or pagination-semantics change under a stable name is a candidate. The shim's job is to keep the wire alive; it is not the shim's job to tell the agent the meaning moved. If the agent does not check, no one does. - **Cross-instance inconsistency.** Two instances of the same agent, differing only in cache age, produce divergent answers to the same query. This defeats replay-based verification (an auditor replaying turn 147 on a cold instance gets 31 records; the live instance got 12) and makes incident attribution nearly impossible without manifest-digest logs. - **Compounding across a session.** Once the stale manifest is in context, every subsequent tool selection is conditioned on it. The error is not a single bad call; it is a persistent prior. Context-window saturation makes it worse: the stale manifest occupies tokens that a refetch would have replaced with current schema. The guardrail is cheap and must be mandatory: **digest the served manifest, store the digest with the cache entry, re-verify on a cadence, and on divergence invalidate wholesale and log the old/new digests with the turn index.** A manifest whose digest you cannot produce is a manifest you cannot trust. ```python 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} ```