What happens when an instance negotiates MCP capabilities over a reused HTTP/2 stream and inherits a stale `initialize` result

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP clients and servers that multiplex multiple logical MCP sessions over a pooled HTTP/2 connection (or any transport with connection-level state reuse), where `initialize`/capability negotiation is expected to be per-session. Does not apply to stdio transports with one process per session, nor to HTTP/1.1 with `Connection: close` semantics per session.

Core Distinction

The failure here is not "the server forgot to advertise a capability" or "the client sent a malformed `initialize`." It is that the **capability handshake is a session-scoped, ordered precondition, but HTTP/2 stream multiplexing and connection reuse turn it into a connection-scoped side effect that silently leaks across sessions.** A second MCP session opened on an already-warm HTTP/2 connection can receive a `202`/`200` on its `initialize` request *before the server has actually processed it*, because the server's negotiation state is keyed on connection identity (or worse, on a shared global) rather than on the `Mcp-Session-Id` plus the request's own stream.

The agent-level consequence: the client's local capability ledger says "server supports `tools/list_changed` notifications and `sampling`," when in fact that ledger was populated from a *previous* session's negotiation on the same connection. The client then issues a `sampling/createMessage` or relies on change notifications that this session's server — possibly a different backend instance after a load-balancer rebalance — never agreed to honor. The mismatch surfaces not at handshake time but deep in an execution loop, as a hang, a `MethodNotFound`, or a silently dropped notification.

What Was Observed

A client pool (Go `http2.Transport`, max 8 connections, keep-alive) fronted an MCP gateway that multiplexes to N backend MCP servers. Trace of a reproduction:

  1. Session A opens on HTTP/2 connection `C1`. `initialize` → server returns `result.capabilities = {tools:{listChanged:true}, sampling:{}}`, plus `Mcp-Session-Id: A`. Client records capabilities under session A. Fine.
  2. Session A is closed by the client (`DELETE`), but connection `C1` stays in the pool because other in-flight streams (health checks, a concurrent `resources/read`) keep it alive.
  3. Session B is created by the pool on the *same* connection `C1`. The client sends `initialize` on a new stream `S7`. The gateway's per-connection negotiation cache — keyed on `conn_id`, populated at step 1 — short-circuits and returns the cached `result` **without contacting the backend**, and critically **without a fresh `Mcp-Session-Id`** (or echoing A's). Client now believes session B has `sampling` and `listChanged`.
  4. Backend for session B is a different pod that only implements `tools` (no `sampling`). Client calls `sampling/createMessage`. Gateway forwards. Backend returns `-32601 Method not found`. Client's error-handling path assumes "capability was negotiated, so this is a transient failure" and retries three times before surfacing to the agent loop.

The compounding damage: the retry loop consumed ~4s of the turn's token/tool budget, and the agent's reasoning trace had already committed to a plan that assumed sampling was available. The failure was *not* the `-32601`; it was that the client's capability ledger disagreed with the server's actual surface, so the error was misclassified as retryable.

A second variant: `listChanged` notifications from session A leaked to session B's notification stream because the gateway subscribed the connection, not the session, to backend change events. Session B's tool list silently mutated mid-task from another tenant's tool registration.

Condition of Validity

The invariant that must hold: **capability negotiation result for a session is valid if and only if it was produced by an `initialize` request whose response was received on the same logical session, from the same backend that will serve subsequent requests for that session.** This decomposes into three testable conditions:

The failure mode is *not* in scope when the transport guarantees fresh negotiation per session (stdio, or HTTP/1.1 with connection-per-session). It is also out of scope when the client pool is configured to never reuse a connection across session boundaries — but that defeats the point of HTTP/2 pooling, so in practice the invariant must be enforced at the gateway.

Decision Boundary

The boundary is whether to trust a cached negotiation result on a warm connection. The rule:

The subtle part: a `200 OK` on `initialize` is not proof of negotiation. Over a reused stream, the gateway can return the cached result in the time it takes to write headers. The client must treat the *presence of a fresh `Mcp-Session-Id` in the response* and *the absence of a `X-Mcp-Capabilities-Cached: true` header* (or equivalent) as the signal that negotiation actually occurred. Absent that signal, the client should pessimistically assume capabilities are unknown and probe lazily.

Operational Effect

Downstream, this manifests as three distinct symptoms that are easy to misattribute:

  1. **Mid-loop `-32601` on a "negotiated" method**, misclassified as transient and retried, burning budget. Fix: capability ledger entries carry a `negotiated_at` timestamp and a `backend_pin`; on any `-32601` for a method the ledger claims is supported, invalidate the ledger entry and force re-`initialize` before retrying.
  2. **Cross-session notification bleed** (`listChanged`, `resources/updated`) delivered to the wrong session's stream. Fix: subscribe notifications to `Mcp-Session-Id`, not to the HTTP/2 connection; drop notifications with no matching live session.
  3. **Silent capability downgrade after LB rebalance**: session pinned to pod P1 at init, later requests routed to P2 which lacks a capability. Fix: gateway must detect pin change and return a `409 Conflict` with `Mcp-Session-Id` in the body, forcing the client to re-`initialize`; the client must treat `409` on a non-`initialize` request as a negotiation-invalid signal, not a generic error.

The guardrail that bounds all three: **capability negotiation is a session-scoped transaction, and connection reuse is an optimization that must never be allowed to satisfy a negotiation it did not perform.** Enforce it by making the cache key `(Mcp-Session-Id, backend_pin)` and by making the client's ledger invalidation reactive to `-32601` and `409`.

from dataclasses import dataclass, field
from typing import Optional


class StaleNegotiationError(RuntimeError):
    """Raised when a session's capability ledger disagrees with the backend that will serve it."""


@dataclass
class NegotiationRecord:
    session_id: str
    backend_pin: str
    capabilities: dict
    negotiated_at: float


@dataclass
class CapabilityLedger:
    # Keyed by (session_id, backend_pin) — never by connection id.
    records: dict = field(default_factory=dict)

    def record(self, session_id: str, backend_pin: str, capabilities: dict, ts: float) -> None:
        self.records[(session_id, backend_pin)] = NegotiationRecord(
            session_id=session_id,
            backend_pin=backend_pin,
            capabilities=capabilities,
            negotiated_at=ts,
        )

    def assert_supports(self, session_id: str, backend_pin: str, method: str, now: float) -> None:
        rec: Optional[NegotiationRecord] = self.records.get((session_id, backend_pin))
        if rec is None:
            raise StaleNegotiationError(
                f"no negotiation for session={session_id} pin={backend_pin}; "
                f"connection reuse cannot satisfy this request"
            )
        # Explicit expiry: a negotiation older than the session's own lifetime is suspect.
        if now - rec.negotiated_at > 300.0:
            raise StaleNegotiationError(
                f"negotiation for session={session_id} is {now - rec.negotiated_at:.1f}s old"
            )
        if not rec.capabilities.get(method, False):
            raise StaleNegotiationError(
                f"method {method!r} not negotiated for session={session_id} pin={backend_pin}; "
                f"ledger says {sorted(k for k, v in rec.capabilities.items() if v)}"
            )


def dispatch(
    ledger: CapabilityLedger,
    session_id: str,
    backend_pin: str,
    method: str,
    now: float,
) -> None:
    # Guardrail: never trust a cached initialize result on a warm connection
    # unless it is bound to this exact (session, pin) pair.
    try:
        ledger.assert_supports(session_id, backend_pin, method, now)
    except StaleNegotiationError:
        # Force a fresh initialize round-trip before the caller retries.
        raise StaleNegotiationError(
            f"refusing to dispatch {method!r}: re-initialize required for "
            f"session={session_id} pin={backend_pin}"
        )