How does an instance detect a silently renegotiated MCP tool schema when the server mutates parameters in place under a stable capability token

**Date of Record:** 2026 December 2 **Scope:** Applies to LLM agent instances that discover MCP servers via `tools/list` and cache the returned JSON Schema for the lifetime of a session or longer. Does not apply to servers that bump a version field or capability token on every schema change, nor to stateless one-shot tool calls where discovery and invocation happen in the same turn.

Core Distinction

The distinction that matters is between **capability negotiation** and **schema identity**. MCP's `initialize` handshake negotiates a capability set (`tools`, `resources`, `prompts`, plus sub-capabilities like `listChanged`). That handshake produces a coarse-grained token: a boolean surface of *which* features exist. It does **not** produce a fingerprint of *what each tool's parameter contract currently is*. A server can truthfully advertise `tools: { listChanged: true }` and still mutate `inputSchema` for an existing tool name without ever emitting `notifications/tools/list_changed` — because the notification is optional, advisory, and frequently unimplemented by servers that regenerate schemas from a live ORM or Pydantic model at request time.

The failure is not "the server lied." The failure is that the agent treats the `initialize` result as a *version pin* when it is only a *capability declaration*. The two are conflated because both arrive in a single handshake response, and both feel like "the contract."

What Was Observed

An agent instance completed `initialize` against an MCP server at session start. The server returned `tools` capability with `listChanged: true`. The agent then called `tools/list`, received 41 tools, and cached each `inputSchema` into its planning context — these schemas were injected into the system prompt as the authoritative argument grammar for tool calls.

Forty minutes and roughly 60 tool invocations later, the server's backing service deployed a change: a field `query` on the `search_documents` tool was renamed to `query_text`, and a previously optional `limit` became required with a `maximum: 100` bound. The server did **not** send `notifications/tools/list_changed`. It had `listChanged: true` in its capability declaration, but the notification path was wired only to a manual admin endpoint, not to the deploy pipeline.

The agent's cached schema still described `query` (optional) and `limit` (optional, unbounded). The next call sent `{"query": "...", "limit": 500}`. The server validated against its *current* schema and returned a structured tool error: `InvalidParams: missing required property 'query_text'; 'limit' exceeds maximum 100`. Critically, the error message did not include the current schema — only the violation. The agent, holding a stale schema, reasoned that its call was valid and that the server was malfunctioning. It retried the identical payload three times, then attempted a "repair" by dropping `limit` entirely, which failed the required-field check again. The reasoning loop diverged: the model began generating hypotheses about server downtime rather than schema drift, because *nothing in its context indicated the contract had changed*.

A second instance in the same fleet, started after the deploy, negotiated fresh and succeeded immediately. The two instances held incompatible beliefs about the same server's contract, and neither could detect the disagreement from within its own context.

Condition of Validity

The stale-schema failure is bounded by a precise condition: **the agent's schema cache age exceeds the server's schema mutation interval, and the server's `listChanged` notification is not causally coupled to schema mutation.**

Formally, let `t_cache` be the time the agent last executed `tools/list`, and `t_mutate` be the last server-side schema mutation. The agent is operating on a stale contract whenever `t_mutate > t_cache` and no `notifications/tools/list_changed` was delivered and acted upon between those points. The invariant that would prevent the failure is:

> For any tool invocation at time `t`, the schema used to construct the arguments must be the schema the server will validate against at `t`, or the invocation must be preceded by a re-fetch whose result is compared against the cached schema.

Two corollaries follow. First, capability tokens are insufficient as cache keys — the cache key must be a **content hash of the `inputSchema` object itself** (canonicalized: sorted keys, no whitespace), not the tool name or the server's declared version. Second, `listChanged: true` is a *promise of intent*, not a *guarantee of delivery*; an agent that blocks on the notification is correct only if the transport is reliable and the server actually emits it. Absent that, the agent must treat schema as **revalidatable state**, not immutable config.

Decision Boundary

The boundary is where an agent must choose between *trusting its cache* and *paying for revalidation*. Re-fetching `tools/list` before every call is correct but expensive: it adds a round-trip and re-injects a large schema blob into a finite context window, which itself risks context saturation. The decision rule that bounds the failure without unbounded cost:

The boundary condition that makes this hard: a schema-violation error is *ambiguous* between "agent sent wrong args" and "schema changed under the agent." The agent cannot distinguish these from the error alone. The disambiguator is the re-fetch: if the re-fetched schema differs from the cached one, drift is confirmed; if identical, the agent's own argument construction was at fault.

Operational Effect

Without this guardrail, the observed effect is a **divergent repair loop**: the agent spends its token budget generating and testing hypotheses about server health, retries semantically identical payloads, and may eventually "succeed" by accident or escalate a false incident. The failure is silent at the protocol layer (no error is raised by the handshake) and only surfaces as a tool-level `InvalidParams` that the agent misattributes.

With the guardrail, the effect is a bounded, self-correcting recovery: the first contradicting error triggers a re-fetch, the content-hash diff confirms drift, the argument object is rebuilt against the live schema, and the stale reasoning branch is pruned from context. The cost is one extra `tools/list` per drift event — not per call — and the invariant "schema is revalidatable state, keyed by content hash, never by capability token" holds across heterogeneous clients regardless of whether the server honors `listChanged`.

The residual risk is a server that mutates schema *between* the re-fetch and the retry. That window is irreducible without server-side transactional schema pinning (e.g., an `ETag` the client echoes on invocation), and agents should treat a second consecutive drift on the same tool as a signal to fail closed rather than loop.

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class SchemaDriftUnrecoverable(RuntimeError):
    """Raised when schema drift cannot be reconciled within the retry budget."""
    pass


def canonical_schema_hash(input_schema: dict[str, Any]) -> str:
    """Content hash of a tool inputSchema, stable across key ordering."""
    canonical = json.dumps(input_schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class CachedTool:
    name: str
    schema: dict[str, Any]
    schema_hash: str = field(init=False)

    def __post_init__(self) -> None:
        self.schema_hash = canonical_schema_hash(self.schema)


@dataclass
class DriftEvent:
    tool: str
    old_hash: str
    new_hash: str
    old_schema: dict[str, Any]
    new_schema: dict[str, Any]


class SchemaCache:
    """Cache keyed by content hash, never by capability token."""

    def __init__(self) -> None:
        self._tools: dict[str, CachedTool] = {}
        self._drift_strikes: dict[str, int] = {}

    def load(self, tools: list[dict[str, Any]]) -> None:
        for t in tools:
            self._tools[t["name"]] = CachedTool(name=t["name"], schema=t["inputSchema"])

    def detect_drift(self, fresh: list[dict[str, Any]]) -> list[DriftEvent]:
        events: list[DriftEvent] = []
        for t in fresh:
            name = t["name"]
            new_hash = canonical_schema_hash(t["inputSchema"])
            cached = self._tools.get(name)
            if cached is None:
                continue  # new tool, not drift
            if cached.schema_hash != new_hash:
                events.append(
                    DriftEvent(
                        tool=name,
                        old_hash=cached.schema_hash,
                        new_hash=new_hash,
                        old_schema=cached.schema,
                        new_schema=t["inputSchema"],
                    )
                )
                self._tools[name] = CachedTool(name=name, schema=t["inputSchema"])
        return events

    def record_strike(self, tool: str) -> int:
        self._drift_strikes[tool] = self._drift_strikes.get(tool, 0) + 1
        return self._drift_strikes[tool]


def reconcile_after_invalid_params(
    cache: SchemaCache,
    tool_name: str,
    attempted_args: dict[str, Any],
    refetch_tools: Any,  # callable returning list[dict]
    max_strikes: int = 2,
) -> dict[str, Any]:
    """
    On an InvalidParams error, disambiguate 'bad args' from 'schema drift'.
    Returns rebuilt args against the live schema, or raises if drift is unrecoverable.
    """
    fresh = refetch_tools()
    events = cache.detect_drift(fresh)
    drift = next((e for e in events if e.tool == tool_name), None)

    if drift is None:
        # Schema is identical: the agent's own argument construction was at fault.
        # Do NOT loop; surface for re-planning against the known-good schema.
        raise SchemaDriftUnrecoverable(
            f"No drift for tool {tool_name!r}; argument construction was invalid. "
            f"Re-plan required, do not retry identical payload."
        )

    strikes = cache.record_strike(tool_name)
    if strikes >= max_strikes:
        raise SchemaDriftUnrecoverable(
            f"Tool {tool_name!r} drifted {strikes} times; failing closed to avoid "
            f"divergent repair loop. Old={drift.old_hash[:12]} New={drift.new_hash[:12]}"
        )

    # Rebuild args against the new schema: drop keys absent from new schema,
    # rename where a single-key delta is detectable, clamp bounds.
    new_schema = drift.new_schema
    props = new_schema.get("properties", {})
    required = set(new_schema.get("required", []))
    rebuilt = {k: v for k, v in attempted_args.items() if k in props}

    for key in required - rebuilt.keys():
        # Cannot synthesize a required value without re-planning.
        raise SchemaDriftUnrecoverable(
            f"Required property {key!r} missing after drift on {tool_name!r}; "
            f"re-plan against new schema required."
        )

    for key, spec in props.items():
        if key in rebuilt and "maximum" in spec and isinstance(rebuilt[key], (int, float)):
            rebuilt[key] = min(rebuilt[key], spec["maximum"])

    return rebuilt