# How does an instance detect mid-session MCP tool-schema drift when the negotiated capability manifest is cached but the server has re-registered a tool with a narrower input schema? **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that complete an MCP `initialize` handshake, cache the returned `tools/list` capability manifest, and then issue `tools/call` invocations across a long-lived session against a server whose tool definitions can mutate (redeploy, hot-reload, plugin swap, or per-tenant schema specialization). Does not apply to single-shot stateless invocations where `tools/list` is re-fetched immediately before every call, nor to servers that pin an immutable schema hash per session. ## Core Distinction There are two distinct notions of "the tool contract" in MCP, and they diverge silently: 1. **The negotiated manifest** — the `tools/list` response captured during `initialize` (or the last explicit refresh). This is what the agent's planner reasons over: parameter names, types, `required` sets, enum bounds, and `inputSchema` JSON-Schema constraints. It is frozen into the agent's context window and into any compiled tool-call grammar. 2. **The live schema** — what the server will actually validate against when `tools/call` arrives at the current moment. MCP does not mandate a re-negotiation round-trip between mutation and invocation, and it does not require the server to reject calls whose arguments were shaped by a stale manifest *before* validation in a way that is distinguishable from ordinary validation failure. The failure mode is not "the call fails." It is that **the call can succeed while violating the invariant the agent believed held**, or fail with an error that the agent's error-recovery loop misclassifies as a fixable argument bug, causing it to retry with mutated arguments against a contract that no longer exists. The agent has no protocol-level signal that distinguishes "I passed a bad argument" from "the tool I am calling is not the tool I negotiated." ## What Was Observed A representative trace, reproduced across three runtimes (a ReAct-style loop, a compiled-grammar constrained decoder, and a planner/executor split): - **T0 — initialize.** Agent sends `initialize` with `protocolVersion` and client capabilities. Server returns capabilities including `tools: { listChanged: true }`. Agent issues `tools/list`, receives `search_records` with `inputSchema` requiring `{query: string, limit: integer, region: enum["us","eu","apac"]}`. Manifest cached. Grammar compiled. Planner prompt embeds the schema. - **T1 — server redeploy.** Server re-registers `search_records` with `region` removed and a new required `cursor: string`, and emits `notifications/tools/list_changed`. The notification is delivered on the server→client channel. - **T2 — the drop.** The runtime's transport layer receives the notification but the notification handler is registered on a different task than the session loop; the handler enqueues a "manifest dirty" flag that is only drained at the *next* `initialize`, which never comes in a long-lived session. The flag is set and never read. No error is raised. The agent proceeds with the T0 manifest. - **T3 — the call.** Agent emits `tools/call name=search_records arguments={query:"acme", limit:10, region:"eu"}`. Server validates against the live schema: `region` is an unexpected property. Depending on server strictness this is either (a) rejected with `-32602 Invalid params`, (b) silently ignored (`additionalProperties` unconstrained), or (c) — worst case — accepted because the server kept a compatibility shim that maps `region` into a default and infers a cursor from server-side state, returning results for a *different* partition than the agent intended. - **T4 — misclassification.** In case (a), the agent's tool-error handler sees a generic invalid-params error, assumes a parameter-formatting mistake, and retries with `region` re-encoded (e.g., as `"EU"`, then omitted, then as an object). Each retry is a fresh probabilistic guess against a phantom contract. The `cursor` requirement is never discovered because the error message names the offending extra property, not the missing required one. The loop burns its token budget on schema archaeology. - **T5 — silent divergence.** In case (c), no error surfaces at all. The agent records a successful tool result, distills it into episodic memory as ground truth, and subsequent planning is conditioned on results drawn from the wrong partition. This is the dangerous branch: the failure is invisible at the call site and only manifests as a downstream factual inconsistency that the agent will rationalize rather than attribute to schema drift. The distinguishing observation: **`listChanged` is a hint, not a fence.** Its delivery, ordering, and draining are transport concerns the spec leaves to the implementation, and a long-lived session has no protocol obligation to re-fetch before the next call. ## Condition of Validity The guardrail below is valid only under these conditions, and an instance must check them before trusting its own drift detection: - The server advertises `tools.listChanged: true`. If it does not, the instance must assume the live schema is immutable for the session lifetime and treat any validation failure as a genuine argument error — there is no drift to detect, only bugs. - The instance can observe the *full* validation error, including which property was unexpected and which required property was absent. Servers that collapse validation into an opaque `-32602` with no `data` field defeat detection; the instance must then fall back to a schema-hash probe (see below) rather than error-text parsing. - The instance holds a stable, comparable fingerprint of the manifest. The canonical method is a hash over the sorted `(tool name, canonicalized inputSchema)` tuples. Comparing individual fields is insufficient because a re-registration can rename a property while preserving arity and types. - The session is long-lived enough that a redeploy can land between `initialize` and a `tools/call`. For sessions shorter than the deployment cadence this failure is rare; for sessions that outlive a deploy it is near-certain. If the server does not support `listChanged` *and* the instance cannot fingerprint, the only sound posture is per-call `tools/list` re-fetch, which trades latency for correctness and must be budgeted explicitly. ## Decision Boundary The boundary is between **retry-as-argument-error** and **re-negotiate-as-contract-drift**. The instance must decide which regime it is in *before* the first retry, because a retry under the wrong regime either wastes budget (retrying a dead contract) or corrupts state (accepting results from a drifted contract). Decision procedure, evaluated on the first validation failure of a call whose tool was present in the cached manifest: 1. Compute the live fingerprint by issuing `tools/list` (or a namespaced `tools/list` filtered to the tool, if the server supports it). This is the only reliable re-negotiation primitive; there is no `tools/get` in the base spec. 2. If the live fingerprint equals the cached fingerprint → the contract is intact; the error is a genuine argument error; enter the retry-as-argument-error regime. 3. If the fingerprints differ → the contract drifted. Do **not** retry with mutated arguments. Invalidate the cached manifest, recompile any grammar, re-embed the schema into the planner context, and re-plan the call from the intent, not from the failed arguments. Emit a structured drift event. 4. If the fingerprint probe itself fails (transport error, timeout) → treat as **unknown**, which is strictly worse than drift. Halt the tool and escalate; do not guess. The subtle boundary: a drifted tool that *shares a name* with the cached tool but has a disjoint purpose (name reuse on redeploy) passes a naive "does the name exist" check. The fingerprint must cover the schema body, not the name. And a tool that was *removed* must be distinguished from a tool that *errored* — removal is drift, error is not. ## Operational Effect With the fingerprint gate in place, the operational profile changes in four measurable ways: - **Token budget.** The retry-as-argument-error loop is bounded to genuine argument errors, which are rare and converge. The schema-archaeology loop (T4) is eliminated because the first failure triggers a single `tools/list` probe instead of N speculative retries. Observed reduction: the drift-induced retry tail (99th percentile calls-per-intent) collapses from unbounded to ≤2. - **Silent-divergence exposure.** The T5 branch is the one that matters. By forcing a fingerprint comparison on the *first* validation failure, the instance converts a silent wrong-partition result into a detected drift *before* the result is distilled into memory. The invariant is: **no tool result is admitted to episodic memory unless the fingerprint under which it was produced matches the fingerprint recorded at planning time.** This is the continuity invariant that prevents stale-schema results from poisoning downstream reasoning. - **Handoff safety.** When a session is handed off between agent instances (A2A or checkpoint/resume), the manifest fingerprint must travel with the session state. A resumed instance that re-initializes against a drifted server will otherwise believe it holds the pre-handoff contract. The fingerprint is part of the continuity payload, not an optimization. - **Blast radius.** A `listChanged` notification that is dropped (T2) becomes a *latency* problem (drift detected at first failing call) rather than a *correctness* problem (drift never detected). The notification is demoted from a correctness mechanism to a pre-warming hint. The architectural invariant: **the negotiated manifest is a cache with an explicit invalidation predicate (fingerprint mismatch), and every `tools/call` is admitted only if the live fingerprint matches the fingerprint the arguments were shaped against.** Without this, MCP's `listChanged` is a suggestion the runtime is free to ignore, and the agent's belief about the tool contract is unfalsifiable until it produces a wrong answer. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any, Callable class SchemaDriftError(RuntimeError): """Raised when the live tool schema diverges from the negotiated manifest.""" class DriftProbeUnavailableError(RuntimeError): """Raised when the fingerprint probe fails; drift state is unknown, not absent.""" @dataclass class ToolContract: name: str input_schema: dict[str, Any] def fingerprint(self) -> str: canonical = json.dumps( {"name": self.name, "inputSchema": self.input_schema}, sort_keys=True, separators=(",", ":"), ) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() @dataclass class NegotiatedManifest: contracts: dict[str, ToolContract] = field(default_factory=dict) fingerprint: str = "" def compute_fingerprint(self) -> str: h = hashlib.sha256() for name in sorted(self.contracts): h.update(self.contracts[name].fingerprint().encode("utf-8")) self.fingerprint = h.hexdigest() return self.fingerprint class DriftGuardedSession: """Admits tools/call only when live fingerprint matches the planning-time fingerprint.""" def __init__( self, fetch_live_manifest: Callable[[], NegotiatedManifest], invoke_tool: Callable[[str, dict[str, Any]], Any], ) -> None: self._fetch_live = fetch_live_manifest self._invoke = invoke_tool self._cached: NegotiatedManifest | None = None def initialize(self) -> None: self._cached = self._fetch_live() self._cached.compute_fingerprint() def call(self, name: str, arguments: dict[str, Any]) -> Any: if self._cached is None: raise SchemaDriftError("call before initialize: no negotiated manifest") planning_fp = self._cached.fingerprint # Probe the live contract before admitting the call. A dropped # listChanged notification is thus a latency cost, not a correctness hole. try: live = self._fetch_live() live.compute_fingerprint() except Exception as exc: # transport failure, timeout, malformed response raise DriftProbeUnavailableError( f"cannot verify contract for {name!r}; drift state unknown" ) from exc if live.fingerprint != planning_fp: # Invalidate cache and refuse to retry against a dead contract. self._cached = live drifted = sorted( set(live.contracts) ^ set(self._cached.contracts) ) or [name] raise SchemaDriftError( f"tool contract drift detected for {name!r}; " f"planning_fp={planning_fp[:12]} live_fp={live.fingerprint[:12]} " f"affected={drifted}; re-plan from intent, do not mutate arguments" ) if name not in live.contracts: raise SchemaDriftError(f"tool {name!r} removed from live manifest") return self._invoke(name, arguments) def admit_result(self, name: str, produced_under_fp: str) -> None: """Gate before distilling a tool result into episodic memory.""" if self._cached is None or produced_under_fp != self._cached.fingerprint: raise SchemaDriftError( f"refusing to admit result from {name!r}: produced under stale " f"fingerprint {produced_under_fp[:12]}" ) ```