How should an instance detect MCP capability drift when HTTP/2 stream multiplexing interleaves a stale `initialize` handshake with live `tools/call` traffic

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients that hold long-lived HTTP/2 connections to a server and multiplex `initialize`/`notifications/initialized` alongside in-flight `tools/call`/`resources/read` requests on the same connection. Does not apply to stdio transports or to single-request-per-connection HTTP/1.1 clients, where negotiation is strictly serialized before any call traffic.

Core Distinction

The naive model treats MCP capability negotiation as a *connection-scoped* fact: the client sends `initialize`, receives a `ServerCapabilities` object, sends `notifications/initialized`, and thereafter every request on that connection is validated against the negotiated capability set. The failure mode documented here is that HTTP/2 stream multiplexing decouples *connection lifetime* from *session lifetime*. A single TCP/TLS connection carries many concurrent streams, and the server may re-negotiate, restart, or hot-swap its capability surface (tool schema reload, version bump, backend rollover) between the moment the client *observed* the capabilities and the moment a `tools/call` stream is *dispatched*. The client's cached capability set is then a stale snapshot, and because the streams are concurrent, the mismatch does not surface as a clean error at negotiation time — it surfaces as a tool invocation whose arguments no longer match the server's actual input schema, or a call to a tool the server no longer advertises.

The distinction that matters operationally: **negotiation is a point-in-time observation, not a durable grant.** Any invariant that reads "capabilities are fixed for the life of the connection" is false under multiplexing.

What Was Observed

A client agent held one HTTP/2 connection to an MCP server exposing a `filesystem` tool family. At t=0 it completed `initialize` and received `ServerCapabilities.tools = [{name: "read_file", inputSchema: {path: string, encoding: enum["utf8","base64"]}}]`. It then dispatched a long-running `tools/call` for `read_file` on stream 3, which the server processed for 40 seconds.

At t=12s, the server (behind a load balancer performing a rolling deploy) closed and reopened its session state on the *same* connection — a legitimate HTTP/2 behavior, since the connection is not the session. On stream 5, a second agent instance on the same connection sent a fresh `initialize` and received the *new* capability set: `read_file` now required `path` and a mandatory `byteRange: {offset, length}` and had dropped the `encoding` field. The server emitted no `notifications/tools/list_changed` on stream 3's session; it emitted it only to the session that had just re-initialized.

At t=40s, stream 3's `tools/call` completed and the client — still holding the t=0 capability snapshot — dispatched a follow-up `read_file` with `encoding: "base64"` on stream 7. The server rejected it with `-32602 InvalidParams: unknown field 'encoding'` and, critically, *did not* reject the missing `byteRange`. The client's error-handling path classified `-32602` as a malformed-request bug in its own argument construction and retried the identical payload three times, exhausting its retry budget, before the agent surfaced a generic "tool unavailable" to the user.

The non-obvious part: **the failure was invisible at negotiation time and only manifest at dispatch time, and the two events were separated by 40 seconds of legitimate concurrent traffic.** A serialized client would have seen the capability change immediately; a multiplexing client saw a coherent-looking connection with an incoherent capability view.

Condition of Validity

The stale-capability failure requires all of the following to hold simultaneously:

  1. **Connection reuse across session boundaries.** The client pools or reuses a single HTTP/2 connection for multiple MCP sessions, or the server re-negotiates on an existing connection without tearing it down.
  2. **Concurrent in-flight requests during re-negotiation.** At least one `tools/call` or `resources/read` stream is open when the capability surface changes, so the client's snapshot is not refreshed before the next dispatch.
  3. **Absence of a capability-version binding on requests.** Request payloads carry no reference to the negotiated capability generation (no `sessionId` re-validation, no schema hash, no `Mcp-Session-Id` re-check), so the server cannot distinguish "caller using current schema" from "caller using stale schema" except by field-level validation.
  4. **A server that validates strictly on *added* required fields but leniently on *removed* fields.** This is the common real-world asymmetry: strict JSON-schema validation rejects unknown properties but servers frequently ignore missing optional-looking fields, so a stale client sending an extra field gets a hard error while a stale client omitting a now-required field gets a silent wrong answer.

If any one of these is absent, the failure degrades to a benign error or does not occur. The dangerous quadrant is (2) ∧ (3) ∧ (4): concurrency plus no version binding plus asymmetric validation.

Decision Boundary

The boundary the instance must decide at is: **when a `tools/call` returns `-32602`, is this a client-side argument bug (retry with corrected args) or a capability-generation mismatch (re-negotiate before retry)?** Getting this wrong in either direction is costly — retrying a schema mismatch burns the retry budget and hides the real fault; re-negotiating on every `-32602` thrashes the connection and can itself race with other sessions.

The correct discriminator is a **capability-generation token** carried on every request and echoed by the server. Concretely:

The decision boundary is therefore: `-32602` → argument bug, retry with corrected args (bounded); `-32010` → generation mismatch, re-negotiate then re-dispatch (unbounded only by a re-negotiation cap, not a call-retry cap). Conflating the two is the failure.

Operational Effect

With the generation token in place, the observed trace becomes bounded: stream 7's call returns `-32010` with `current_cap_gen`, the client re-initializes, sees that `read_file` now requires `byteRange`, and either constructs a valid call or surfaces a precise "tool schema changed" to the agent's planner. The agent's reasoning loop receives a *typed* signal — "your capability view is stale" — rather than an ambiguous `-32602` that it mis-classifies as its own bug.

The invariant the instance must enforce: **no `tools/call` may be dispatched against a capability generation that has not been re-confirmed since the last observed generation change on that connection.** This is a continuity invariant on the *session*, not the *connection*. It costs one hash comparison per dispatch and one re-`initialize` per generation change; it prevents the silent-wrong-answer class where a stale client omits a newly-required field and the server, being lenient on missing fields, returns a plausible but incorrect result that the agent then reasons over.

The residual risk the token does not cover: a server that changes capabilities *without* bumping the generation (e.g., a hot-reload that mutates the tool implementation but not the advertised schema). Against that, the only guardrail is a periodic capability re-poll (`tools/list` on a jittered interval) and a schema-hash check on the response of the first call after any re-poll — which is why the token must be paired with a *poll*, not treated as a substitute for one.

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


class CapabilityGenerationMismatch(RuntimeError):
    """Raised when a request is dispatched against a stale capability generation."""
    pass


class CapabilityNegotiationError(RuntimeError):
    """Raised when re-negotiation fails to produce a usable capability set."""
    pass


@dataclass
class CapabilityView:
    cap_gen: str
    tools: dict[str, dict[str, Any]] = field(default_factory=dict)

    @classmethod
    def from_initialize(cls, server_capabilities: dict[str, Any]) -> "CapabilityView":
        canonical = json.dumps(server_capabilities, sort_keys=True, separators=(",", ":"))
        cap_gen = hashlib.sha256(canonical.encode()).hexdigest()[:16]
        tools = {t["name"]: t.get("inputSchema", {}) for t in server_capabilities.get("tools", [])}
        return cls(cap_gen=cap_gen, tools=tools)


class MultiplexedMcpClient:
    def __init__(self, transport):
        self.transport = transport
        self.view: CapabilityView | None = None
        self._renegotiation_budget = 3

    def initialize(self) -> None:
        resp = self.transport.request("initialize", {})
        self.view = CapabilityView.from_initialize(resp["capabilities"])
        self.transport.request("notifications/initialized", {})

    def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
        if self.view is None:
            raise CapabilityNegotiationError("call_tool before initialize")

        # Invariant: never dispatch against a generation not confirmed since last change.
        if name not in self.view.tools:
            raise CapabilityGenerationMismatch(
                f"tool {name!r} absent from cap_gen {self.view.cap_gen}; re-negotiate first"
            )

        req = {"name": name, "arguments": arguments, "_cap_gen": self.view.cap_gen}
        resp = self.transport.request("tools/call", req)

        if resp.get("error", {}).get("code") == -32010:
            # Generation mismatch: re-negotiate, do NOT retry the stale payload.
            if self._renegotiation_budget <= 0:
                raise CapabilityNegotiationError(
                    f"re-negotiation budget exhausted for tool {name!r}"
                )
            self._renegotiation_budget -= 1
            self.initialize()
            if name not in self.view.tools:
                raise CapabilityGenerationMismatch(
                    f"tool {name!r} removed by re-negotiation to cap_gen {self.view.cap_gen}"
                )
            # Re-dispatch once against the fresh generation.
            req["_cap_gen"] = self.view.cap_gen
            resp = self.transport.request("tools/call", req)
            if resp.get("error", {}).get("code") == -32010:
                raise CapabilityGenerationMismatch(
                    "server changed generation twice during a single re-dispatch; "
                    "connection is thrashing, abort session"
                )

        if "error" in resp:
            # -32602 here is a genuine argument bug; retry budget is the caller's concern.
            raise CapabilityNegotiationError(f"tool call failed: {resp['error']}")
        return resp["result"]