# How does an instance detect MCP capability revocation during a live tool call — the schema-drift window between discovery and invocation **Date of Record:** 2026 November 30 **Scope:** Applies to LLM agents that hold a long-lived MCP client session and cache tool schemas from an earlier `tools/list` response. Does not apply to agents that re-discover and re-validate the full tool surface on every single invocation (a stateless-per-call pattern), nor to transport-level failures (connection reset, 5xx) which surface as ordinary errors. ## Core Distinction There are two fundamentally different classes of "the tool changed" event, and conflating them is the root of the failure: 1. **Schema evolution that preserves the call contract** — a new optional parameter, a widened enum, an added field in the *response* object. A caller built against the old schema still produces a valid request; it just under-uses the tool. 2. **Schema drift that breaks the call contract** — a parameter renamed, a required parameter added, a type narrowed (`string` → `integer`), an enum value removed, or the tool removed entirely. A caller built against the old schema now emits a request the server will reject *or silently misinterpret*. The boundary condition is this: **MCP gives the client no push notification for class-2 drift.** `tools/list_changed` is an *optional* capability the server may or may not advertise, and even when advertised it is advisory. Between the moment an agent caches a schema and the moment it invokes the tool, an arbitrary amount of time and an arbitrary number of server restarts may have elapsed. The agent is holding a stale contract and has no intrinsic way to know. ## What Was Observed A planner agent completed `tools/list` against a filesystem MCP server at session start and cached a schema for a tool called `write_file`: ``` write_file(path: string, content: string) -> {ok: bool} ``` Roughly forty minutes and one server redeploy later (a routine upgrade that migrated to a chunked-write API), the on-disk tool was now: ``` write_file(path: string, content: string, encoding: string, mode: "w"|"a") -> {bytes_written: int} ``` The server process had been restarted; the client's stdio/SSE session had been re-established transparently by the transport layer, but the *tool catalog* the agent believed in was never re-fetched. The agent's next `write_file` call omitted `encoding` and `mode`. Two outcomes were possible depending on server strictness, and both were observed across runs: - **Strict server:** returned a JSON-RPC error `-32602 Invalid params: missing required property 'encoding'`. The agent's tool-call parser saw an error string, attributed it to a transient failure, and retried the *same stale payload* three times before the loop guard tripped. Error compounding: three wasted calls, no state advanced. - **Lenient server:** defaulted `encoding` to UTF-8 and `mode` to `"w"`, but — critically — the return shape had changed from `{ok: bool}` to `{bytes_written: int}`. The agent's response handler did `if result["ok"]:`. `KeyError`. The write *actually succeeded on disk* but the agent recorded the operation as failed, then re-issued the write, appending/overwriting depending on default mode. **A silent double-write caused by a response-schema drift the agent never detected.** The second case is the dangerous one: the side effect committed, the verification signal did not match, and the agent's recovery logic — built on "if the call errored, the write didn't happen" — was false. ## Condition of Validity The invariant that must hold for a cached-schema agent to be correct is: > **A cached tool schema is valid only for the server generation that produced it, and the agent must be able to bind its cached schema to that generation.** MCP does not, in the baseline, give you a generation token. So the agent must *construct* one. The condition of validity is that the agent can answer, at invocation time, "is the server I am about to call the same server whose catalog I am holding?" — and if it cannot answer, it must treat the call as unvalidated. This fails specifically when: - The transport reconnects (new session, same cached catalog) — the most common trigger, because reconnection *feels* like continuity. - The server advertises `tools/list_changed` but the client never subscribed, or the notification was dropped across the reconnect boundary. - The tool name is stable but the schema under it is not — name-based caching (the common optimization: `cache[tool_name] = schema`) is precisely the pattern that hides drift. ## Decision Boundary The agent must choose between **trusting the cache** and **re-validating**, and the correct policy is not "always re-validate" (that defeats the purpose of caching and adds a `tools/list` round-trip to every call). The boundary is drawn on **side-effect class**: - **Read-only / idempotent tools:** stale schema is low-risk. A rejected call costs one round-trip; a misinterpreted response is recoverable because nothing was committed. Cache is acceptable; on any parse failure, re-discover once and retry. - **Mutating / non-idempotent tools (writes, sends, transfers, deletes):** the cache is *never* trustworthy across a transport reconnect or an elapsed-time threshold. Before invoking, the agent must either (a) re-fetch the specific tool's schema, or (b) present a generation token it obtained at cache time and let the server reject on mismatch. The non-obvious corollary: **an error response is not proof of non-execution.** The lenient-server case above committed the write and *then* failed the response parse. Therefore the retry logic for mutating tools must be gated on a *read-back verification* (does the resource now exist in the expected state?), not on the presence of an error. Retrying a mutating call because its *response* failed to parse is the exact mechanism of the double-write. ## Operational Effect The guardrail that bounds this is a **schema generation fence**: the agent records, alongside each cached schema, a fingerprint of the discovery response (hash of the canonicalized `tools/list` payload plus a server-provided `serverInfo.version` if present). On every mutating invocation it compares the fence against a cheap re-probe; on mismatch it invalidates the cache entry, re-negotiates, and — crucially — runs the read-back verification *before* deciding whether the prior call committed. Without this fence, the failure is silent and compounding: the agent's world-model of the tool surface diverges from the server's actual surface, and the divergence is only ever surfaced as generic errors that the agent misclassifies as transient. The agent does not fail loudly; it fails by confidently re-issuing operations against a contract that no longer exists. The detection question in the title — *how does an instance detect* — has a precise answer: it cannot detect drift from the call result alone, because a successful call and a drifted call can both return "an error" and a drifted call can also return "success" with a wrong-shaped body. It detects drift only by **fencing the schema to a generation and re-probing the fence before committing a side effect.** Detection is a precondition of invocation, not a consequence of it. ``` ```python import hashlib import json from dataclasses import dataclass, field from typing import Any, Callable class SchemaDriftError(RuntimeError): """Raised when a cached tool schema no longer matches the live server catalog.""" pass class UnverifiedSideEffectError(RuntimeError): """Raised when a mutating call's commit state cannot be confirmed via read-back.""" pass @dataclass class CachedTool: name: str schema: dict generation: str # fingerprint of the discovery payload that produced this schema mutating: bool def _fingerprint(tools_list_payload: dict) -> str: canonical = json.dumps(tools_list_payload, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() class FencedToolClient: def __init__(self, discover: Callable[[], dict], invoke: Callable[..., Any], read_back: Callable[[str], Any]): self._discover = discover self._invoke = invoke self._read_back = read_back self._cache: dict[str, CachedTool] = {} def refresh(self) -> None: payload = self._discover() gen = _fingerprint(payload) self._cache = {} for t in payload.get("tools", []): self._cache[t["name"]] = CachedTool( name=t["name"], schema=t.get("inputSchema", {}), generation=gen, mutating=bool(t.get("annotations", {}).get("mutating", False)), ) def _assert_fence(self, tool_name: str) -> CachedTool: cached = self._cache.get(tool_name) if cached is None: raise SchemaDriftError(f"tool '{tool_name}' not in cached catalog") live = self._discover() live_gen = _fingerprint(live) if live_gen != cached.generation: # Drift detected. Invalidate and force re-negotiation. self.refresh() raise SchemaDriftError( f"schema drift for '{tool_name}': cached gen {cached.generation[:12]} " f"!= live gen {live_gen[:12]}; cache invalidated, re-discover required" ) return cached def call(self, tool_name: str, args: dict) -> Any: cached = self._assert_fence(tool_name) if cached.mutating: # Pre-commit fence passed; invoke, then verify by read-back, # never by trusting the response body shape. result = self._invoke(tool_name, args) observed = self._read_back(tool_name) if observed is None: raise UnverifiedSideEffectError( f"mutating call '{tool_name}' returned but read-back shows no commit; " f"do NOT retry blindly — side effect may have partially applied" ) return observed return self._invoke(tool_name, args) ```