# Which invariants prevent MCP tool-schema drift from silently corrupting a long-lived agent's tool-call contract **Date of Record:** 2026 November 28 **Scope:** Applies to MCP hosts that maintain a persistent tool registry across multiple `tools/list` refreshes while one or more connected servers mutate their input schemas (added required fields, widened enums, changed `$ref` targets, or reordered `oneOf` branches) between negotiations. Does not apply to stateless single-shot sessions where the registry is rebuilt from scratch per request, nor to servers that version-lock their entire tool surface per connection. ## Core Distinction The failure is not "the tool changed." That is expected and legal under MCP. The failure is that the *host's cached capability manifest* and the *server's live schema* diverge in a way that is **structurally valid on both sides but semantically incompatible at call time** — and the agent's plan, constructed against the cached schema, is executed against the live one. A schema mismatch that produces a validation error is benign (it fails loudly, the agent retries). The dangerous class is a mismatch that produces a *valid-looking but wrong* call: a new field with a default, a widened enum whose new member happens to be the string the model already emitted, or a `oneOf` reorder that changes which branch an ambiguous payload binds to. The invariant at stake is: **every tool call the host emits must be validated against the schema version the model actually reasoned over, not the schema version currently advertised by the server.** ## What Was Observed A host agent runs a 40-minute incident-triage task against three MCP servers. Mid-task, server `metrics` ships a rolling deploy that changes `query_range`'s `step` parameter from optional to required, and simultaneously widens `aggregation` from `["avg","max"]` to `["avg","max","p99"]`. The host's registry still holds the pre-deploy manifest. The model, reasoning against the cached schema, emits: ``` {"query": "http_errors{svc=api}", "aggregation": "p99"} ``` `p99` is *not in the cached enum*, so under the cached schema this is an invalid call — but the model never sees the cached schema as authoritative at validation time because the host validates against the **live** server schema fetched lazily on first call. The live schema accepts `p99` (valid) and silently applies a server-side default for the now-required `step` (valid). The call succeeds. The result is a 300-point p99 series that the agent interprets as a mean-latency series, because the cached manifest's description string said "aggregation defaults to mean semantics for the returned series." The agent's downstream reasoning is now poisoned by a semantically wrong but schema-valid response, and it takes eleven more tool calls before the numeric implausibility trips a sanity check. The trace shows the exact seam: `tools/list` was called once at session start (t=0), the deploy landed at t=14:22, the first post-deploy call was at t=14:31, and the host's validation path used `server.get_schema(tool)` (live) while the model's context window still held the t=0 manifest serialized into the system prompt. Two sources of truth, one call. ## Condition of Validity The invariant holds — and the failure is bounded — only when all three of the following are enforced: 1. **Schema-hash pinning per reasoning turn.** Each tool call carries the manifest hash the model reasoned over; the host refuses to dispatch if the live server hash differs, forcing a re-negotiation and a context refresh before execution. Without this, "valid at call time" and "valid at reasoning time" are independent predicates. 2. **Monotonic capability versioning with explicit deprecation.** A server may not mutate a tool's schema in place; it must publish `v1`→`v2` with both listed, and the host must treat the old version as callable-but-deprecated until the agent explicitly migrates. In-place mutation is the trigger condition; the invariant is that a schema identifier, once observed by a client, never resolves to different bytes. 3. **Closed-world enum semantics.** Widening an enum is a *breaking* change for any client holding a cached manifest, because the client cannot distinguish "server now accepts p99" from "server always accepted p99 and my cache was stale." The invariant: enum membership is part of the contract identity, and any change to it bumps the contract identity. When any of these is absent, the system is in the failure regime, and the failure is *silent* precisely because both sides validate successfully against their own view. ## Decision Boundary The host must choose between two dispatch policies at the moment of a detected hash mismatch: - **Fail-closed (re-negotiate):** Abort the call, re-fetch `tools/list`, re-serialize the manifest into context, and require the model to re-plan the affected step. Correct but expensive: it burns a context refresh and may invalidate a partially-constructed multi-step plan. Choose this when the tool's output feeds a downstream irreversible action (a write, a paging alert, a remediation command). - **Fail-open-with-quarantine (dispatch against pinned schema, tag result):** Dispatch against the *pinned* schema the model reasoned over, and if the server rejects, surface a structured `schema_drift` error to the model rather than a generic validation failure. Choose this for read-only observational tools where a wrong-but-valid result is recoverable by a follow-up call. The boundary is not "is the tool dangerous" in the abstract — it is **whether the agent can detect a semantically wrong result from the tool's own output.** For `query_range`, it could not (a p99 series and a mean series are indistinguishable without the description string). For a tool returning a typed record with a `units` field, it could. The decision must be made per-tool at negotiation time and recorded in the manifest, not improvised at call time. ## Operational Effect With hash-pinning and closed-world enums enforced, the observed incident class disappears: the t=14:31 call fails the hash check, the host re-negotiates, the refreshed manifest marks `step` required and `p99` as a new enum member with an explicit `semantics: "percentile"` annotation, and the model re-plans with correct semantics. The cost is one extra round-trip and a context refresh per drift event — measurable but bounded. Without them, the effect is *reasoning contamination that survives the tool call*: the wrong series enters the agent's episodic memory as a fact ("mean latency was 300ms"), is distilled into a semantic belief, and persists across later turns and even across checkpoint/resume, because nothing in the memory layer records *which schema version* produced the observation. The failure is not the bad call; it is the un-versioned memory entry that outlives the schema that caused it. The guardrail must therefore extend past dispatch into the memory write path: every observation stored by an agent must carry the `(tool, schema_hash)` provenance tuple, and a later distillation pass must be able to invalidate beliefs whose provenance hash is deprecated. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class SchemaDriftError(RuntimeError): """Raised when the live server schema diverges from the manifest the model reasoned over.""" pass class UnversionedObservationError(RuntimeError): """Raised when an observation is written to memory without schema provenance.""" pass @dataclass(frozen=True) class ToolManifest: server: str tool: str version: str schema: dict[str, Any] semantics_notes: str @property def hash(self) -> str: blob = json.dumps( {"v": self.version, "s": self.schema, "n": self.semantics_notes}, sort_keys=True, ).encode() return hashlib.sha256(blob).hexdigest()[:16] @dataclass class PinnedRegistry: """Host-side registry that pins the manifest hash the model reasoned over.""" pinned: dict[tuple[str, str], ToolManifest] = field(default_factory=dict) def pin(self, m: ToolManifest) -> None: self.pinned[(m.server, m.tool)] = m def dispatch( self, server: str, tool: str, args: dict[str, Any], live_manifest: ToolManifest, ) -> dict[str, Any]: key = (server, tool) if key not in self.pinned: raise SchemaDriftError( f"no pinned manifest for {server}.{tool}; refusing to dispatch blind" ) pinned = self.pinned[key] if pinned.hash != live_manifest.hash: # The model reasoned over `pinned`; the server will validate against `live`. # Dispatch would be schema-valid on both sides but semantically divergent. raise SchemaDriftError( f"schema drift on {server}.{tool}: model reasoned over {pinned.hash} " f"(v{pinned.version}), server now advertises {live_manifest.hash} " f"(v{live_manifest.version}). Re-negotiate before dispatch." ) return {"dispatched_against": pinned.hash, "args": args} @dataclass class ProvenancedMemory: """Episodic store that refuses observations lacking (tool, schema_hash) provenance.""" entries: list[dict[str, Any]] = field(default_factory=list) def record(self, observation: dict[str, Any], tool: str, schema_hash: str) -> None: if not tool or not schema_hash: raise UnversionedObservationError( "observation written without (tool, schema_hash) provenance; " "cannot be invalidated on future schema deprecation" ) self.entries.append( {"obs": observation, "tool": tool, "schema_hash": schema_hash} ) def invalidate_deprecated(self, deprecated_hashes: set[str]) -> int: before = len(self.entries) self.entries = [e for e in self.entries if e["schema_hash"] not in deprecated_hashes] return before - len(self.entries) ```