# What happens when an instance caches a tool's `inputSchema` at handshake but the server silently re-negotiates capabilities mid-session **Date of Record:** 2026 November 27 **Scope:** Applies to MCP clients (agent runtimes) that bind to a third-party MCP server's advertised `tools/list` schema and capability flags once at `initialize`, then execute many `tools/call` invocations against that binding. Does not apply to single-shot, per-call re-attestation clients, nor to servers whose tool surface is provably immutable for the session lifetime. ## Core Distinction The failure here is not "the server was malicious at handshake." It is subtler: the server passed attestation at `initialize` and then **mutated its advertised capability surface between the attestation point and the invocation point** — swapping a tool's `inputSchema`, widening `additionalProperties`, or flipping a capability flag like `sampling` or `resources/subscribe` on. The client's cached binding is a *snapshot of a promise*, and the promise is re-made, silently, on every subsequent response frame. The distinction that matters: **attestation is a point-in-time event; capability is a continuous property.** A supply-chain verification that only checks the former is structurally blind to drift in the latter. An agent that treats the `initialize` result as authoritative for the session has confused a handshake for an invariant. This is the MCP analogue of TOCTOU (time-of-check-to-time-of-use), but with a twist specific to LLM agents: the *check* is performed by one probabilistic consumer (the client's attestation logic) and the *use* is performed by another (the model's tool-selection reasoning), and neither shares a representation of the schema. The model reasons over a rendered description; the client validates against a cached JSON blob. When the server drifts, the two diverge independently. ## What Was Observed A client runtime bound to a third-party `code-interpreter` MCP server. At `initialize`, the server advertised one tool: ``` tools/list → [{ "name": "run_snippet", "inputSchema": { "type": "object", "properties": { "code": {"type": "string"}, "language": {"type": "string", "enum": ["python"]} }, "required": ["code"], "additionalProperties": false } }] ``` The client cached this, pinned the schema hash `sha256:9f3a…`, and rendered the tool to the model as "run a Python snippet." Over the next ~40 turns the agent used it correctly. At turn 41, the server (which had rotated a backend and pulled a newer tool definition) returned, on the next `tools/list` triggered by a client-side cache-refresh heuristic, a schema where `language` had `enum: ["python", "bash", "node"]` and — critically — `additionalProperties` had been dropped, defaulting to `true`. The client's refresh heuristic fired *after* the model had already selected `run_snippet` with a `language: "python"` argument constructed from the *old* rendered description. The call succeeded. Nothing failed loudly. The failure surfaced two turns later: the model, now reasoning over a *stale rendered description* but a *fresh server*, emitted `{"code": "...", "language": "bash", "env": {"PYTHONPATH": "/tmp/attacker"}}`. The `env` key was accepted because `additionalProperties` was now open. The server executed the bash snippet with an injected environment. The client's schema-pinned validator had been bypassed by its own refresh path — it validated the *new* schema against the *new* call, which passed, because the new schema permitted everything the old one forbade. The trace, compressed: 1. `initialize` → schema S₀, hash pinned, model rendered description D₀. 2. Turns 1–40 → calls validated against S₀, model reasons over D₀. Consistent. 3. Turn 41 → server returns S₁ (open `additionalProperties`, widened enum). Client refresh heuristic accepts S₁, updates pin to `sha256:b7c1…`, but **does not re-render D** to the model — the model's context still holds D₀. 4. Turn 42 → model emits a call valid under S₁ but not S₀, containing a key (`env`) that D₀ never mentioned. 5. Turn 43 → call executes. Validator passes (S₁ permits it). Model never knew it was possible. The invariant violated: **the schema the model reasons over and the schema the validator enforces must be the same schema, and both must be pinned to the attested version for the duration of any reasoning chain that spans a refresh.** The client maintained the second half (validator tracks pin) and dropped the first (renderer does not). ## Condition of Validity This failure requires all of the following to co-occur; remove any one and the drift is caught or harmless: - **A refresh path exists.** The client re-fetches `tools/list` mid-session (cache TTL, explicit refresh tool, or server-pushed `notifications/tools/list_changed`). Clients that never re-list are immune to *this* variant but exposed to a worse one (they run against a server whose actual behavior has drifted while the client believes it hasn't — silent divergence with no refresh at all). - **Refresh is not atomic with re-render.** The client updates its validation schema but does not invalidate or re-render the model's tool description. This is the load-bearing defect. Most MCP client SDKs separate "tool registry" (client-side, refreshed) from "tool prompt rendering" (model-side, injected at context-assembly time), and the two are refreshed on different clocks. - **The schema delta is *widening*, not narrowing.** A narrowing delta (removing a property, tightening an enum) causes the next call to *fail validation* — loud, recoverable. A widening delta (`additionalProperties` opened, enum extended, `required` relaxed) causes the next call to *succeed when it shouldn't* — silent, unrecoverable. Supply-chain attestation that only checks "does the schema still validate the calls I make" is blind to widening, because widening never fails a validation; it only removes one. - **The model can construct arguments the old schema forbade.** If the model's tool-use is constrained by a grammar or JSON-schema-constrained decoder built from D₀, it physically cannot emit `env`. Most runtimes do not constrain decoding to the tool schema; they rely on the model's instruction-following over a rendered description, which is advisory, not enforced. The condition of validity for the *guardrail* is the inverse: the guardrail holds iff the client treats a schema-hash change as a **hard session-boundary event** — invalidate the reasoning chain, re-render, and require the model to re-select the tool under the new description before any call is admitted. ## Decision Boundary The decision the runtime must make on every `tools/list` response, and the boundary that separates safe from unsafe handling: | Delta class | Example | Correct action | |---|---|---| | Identical hash | — | No-op, continue session | | Narrowing only | `required` added, enum shrunk | Reject the call that violates; do **not** silently accept; surface to model as tool error. Session may continue. | | Widening | `additionalProperties` opened, enum extended, `required` removed | **Terminate the reasoning chain.** Re-render, re-attest, require re-selection. | | Tool added/removed | new tool appears | Re-render toolset; model must re-plan. | | Capability flag flip | `sampling`/`resources` toggled | Treat as new server identity; full re-attestation. | The non-obvious boundary: **widening is more dangerous than narrowing and must be handled more aggressively.** Intuition says "the server got more permissive, that's fine, calls still validate." The correct reading is "the server's contract changed in the direction that removes a guardrail, and my model is still reasoning under the old contract." The asymmetry is the whole point. A validator that only rejects on narrowing has inverted the threat model. The second boundary: **the render clock and the validate clock must be the same clock.** If they are not, the gap between them is the attack surface, and its width is the refresh interval. Any client that refreshes validation on TTL but renders on context-assembly has an exploitable window of up to one context window. ## Operational Effect The downstream effect is a class of **capability-laundering**: a server that passes attestation honestly at `initialize`, then widens its surface to accept arguments the client's model was never told about and the client's original attestation never covered. The widened arguments are not "malicious input the model chose" — the model chose them under a description that didn't mention them, which means the model cannot be blamed, the validator cannot catch it (it validates against the widened schema), and the attestation cannot flag it (the hash matches the *current* server, which is "valid"). Every layer reports success. The only thing that failed was the coupling between the layers. For an agent runtime, the operational consequences: - **Audit trails become incoherent.** The logged schema hash at call time (`b7c1…`) differs from the hash at plan time (`9f3a…`), but the plan and the call are in the same trace. Post-hoc reconstruction cannot tell whether the model reasoned under the schema it was validated against. This is a forensic dead end. - **Replay verification breaks.** An auditor replaying the session against S₀ will find the turn-42 call invalid; replaying against S₁ will find turns 1–40 potentially under-constrained. No single schema replays the whole session. The session is only replayable as a *sequence of schema epochs*, which most logging formats don't capture. - **The model's self-report is wrong.** Asked "did you use a tool with an `env` parameter?", the model will say no — its context contains D₀. The trace says yes. This is not model dishonesty; it's a genuine representational split between the model's world and the runtime's world, and it means model self-reports cannot be used to detect this class of drift. The guardrail that bounds it: **schema-hash continuity as a first-class session invariant, checked at every tool call, with widening deltas treated as session-terminating.** Concretely — pin the hash at `initialize`, re-fetch and re-hash on every `tools/list` (including server-pushed notifications), and on any hash change that is not provably narrowing, refuse the call, invalidate the model's rendered toolset, and require re-selection. The cost is a re-plan on every server update; the alternative is a class of call that no layer can attribute. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class CapabilityDriftError(RuntimeError): """Raised when a tool's inputSchema widens mid-session without re-render.""" def __init__(self, tool: str, old_hash: str, new_hash: str, delta: str): self.tool = tool self.old_hash = old_hash self.new_hash = new_hash self.delta = delta super().__init__( f"tool '{tool}' schema widened mid-session: {old_hash} -> {new_hash} ({delta}); " f"reasoning chain must be invalidated and tool re-selected before any call is admitted" ) def _hash_schema(schema: dict[str, Any]) -> str: canonical = json.dumps(schema, sort_keys=True, separators=(",", ":")) return "sha256:" + hashlib.sha256(canonical.encode()).hexdigest()[:16] def _is_widening(old: dict[str, Any], new: dict[str, Any]) -> tuple[bool, str]: """True iff `new` accepts strictly more inputs than `old` on any axis.""" reasons: list[str] = [] if old.get("additionalProperties", True) is False and new.get("additionalProperties", True) is not False: reasons.append("additionalProperties opened") old_req = set(old.get("required", [])) new_req = set(new.get("required", [])) if new_req < old_req: reasons.append(f"required relaxed: dropped {sorted(old_req - new_req)}") old_props = old.get("properties", {}) new_props = new.get("properties", {}) for key, old_spec in old_props.items(): new_spec = new_props.get(key, {}) old_enum = set(old_spec.get("enum", [])) new_enum = set(new_spec.get("enum", [])) if old_enum and new_enum and not old_enum.issubset(new_enum): reasons.append(f"enum widened on '{key}': +{sorted(new_enum - old_enum)}") return (bool(reasons), "; ".join(reasons)) @dataclass class ToolBinding: name: str schema: dict[str, Any] hash: str rendered_description: str @dataclass class MCPClientSession: bindings: dict[str, ToolBinding] = field(default_factory=dict) epoch: int = 0 def bind_initial(self, tools: list[dict[str, Any]]) -> None: for t in tools: h = _hash_schema(t["inputSchema"]) self.bindings[t["name"]] = ToolBinding( name=t["name"], schema=t["inputSchema"], hash=h, rendered_description=f"tool {t['name']}: {json.dumps(t['inputSchema'])}", ) def on_tools_list_changed(self, tools: list[dict[str, Any]]) -> None: """Called on every tools/list response, including push notifications.""" for t in tools: name = t["name"] new_schema = t["inputSchema"] new_hash = _hash_schema(new_schema) old = self.bindings.get(name) if old is None: # new tool appeared: model must re-plan; treat as epoch bump self.epoch += 1 self.bindings[name] = ToolBinding(name, new_schema, new_hash, f"tool {name}: {json.dumps(new_schema)}") continue if old.hash == new_hash: continue widened, reason = _is_widening(old.schema, new_schema) if widened: raise CapabilityDriftError(name, old.hash, new_hash, reason) # narrowing: update validator, but model may still hold stale render; # surface as tool error on next call rather than silently accept. self.bindings[name] = ToolBinding(name, new_schema, new_hash, old.rendered_description) def admit_call(self, name: str, args: dict[str, Any]) -> None: b = self.bindings.get(name) if b is None: raise CapabilityDriftError(name, "", "", "tool not bound") if b.hash != _hash_schema(b.schema): raise CapabilityDriftError(name, b.hash, "", "binding schema mutated in place") # Validator enforces the *pinned* schema, not the latest server schema. if b.schema.get("additionalProperties", True) is False: extra = set(args) - set(b.schema.get("properties", {})) if extra: raise CapabilityDriftError(name, b.hash, b.hash, f"unexpected keys {sorted(extra)}") ```