# Which invariants prevent elicitation/sampling/roots capability drift from silently corrupting an MCP session over streamable HTTP **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients and servers negotiating `elicitation`, `sampling`, and `roots` capabilities over the streamable HTTP transport with `Mcp-Session-Id` continuity. Does not cover stdio transport, where capability state is process-bound and cannot desynchronize across reconnects. ## Core Distinction The distinction that matters is between *capability advertisement* and *capability availability at a given request*. Over stdio these are effectively identical: the `initialize` handshake happens once, the process lives, and any advertised capability remains live for the session's lifetime. Over streamable HTTP with resumable sessions, the handshake result is cached server-side against `Mcp-Session-Id`, but the *transport-level* ability to service a capability call is re-established on every POST. The failure is not that the server forgets it advertised `sampling`; it is that the client and server disagree about whether a *server-initiated* request (server→client `sampling/createMessage`, `elicitation/create`, `roots/list`) can currently be delivered, because the server's only channel back to the client is an SSE stream that may have been reaped, re-bound to a different connection, or never re-opened after a `202`-only response. A server that negotiated `sampling: {}` treats the capability as a durable grant. The HTTP transport treats the reverse channel as ephemeral. The gap between those two lifetimes is where silent corruption occurs: the server believes it can sample, issues a `sampling/createMessage`, and either blocks until timeout or—worse—receives a response correlated to a *stale* request id from a prior connection. ## What Was Observed A three-stage trace from a client that reconnects mid-elicitation: 1. **Handshake.** Client POSTs `initialize` with `capabilities: { elicitation: {}, sampling: {}, roots: { listChanged: true } }`. Server responds with its own capabilities and issues `Mcp-Session-Id: s-7f3a`. Both sides now hold a durable record that elicitation and sampling are mutually supported. 2. **Reverse-channel establishment.** Client opens `GET /mcp` with `Mcp-Session-Id: s-7f3a` and `Accept: text/event-stream`. The SSE stream is the only path for server-initiated requests. Server records `(session=s-7f3a, stream=conn-A)`. 3. **Reconnect.** The client's SSE connection drops (idle timeout at a load balancer, 60s). Client reconnects with `Last-Event-ID: 41` on a new TCP connection, `conn-B`. The server, per spec, may resume the stream. But if the server's implementation keys reverse-channel state by connection rather than by session, the `(session, stream)` map now points at `conn-B` while an in-flight `elicitation/create` (request id `e-19`) was dispatched on `conn-A` and is still awaiting a response. The observable corruption: the client receives `e-19` on `conn-B` (replayed from the event buffer), responds on `conn-B`, and the server — which had already timed out `e-19` on `conn-A` and *reissued* it as `e-19'* — now has two pending elicitations with overlapping ids. The user is prompted twice for the same confirmation. If the elicitation is destructive (e.g., "confirm deletion of 400 records"), the second prompt arrives after the first was already accepted, and the model, seeing a fresh `elicitation/create` with identical `message` text, treats it as a distinct authorization event. The deeper observation: capability negotiation succeeded, the session id was stable, and no protocol error was raised at any layer. Every individual message was well-formed. The invariant that broke was *request-id uniqueness per (session, capability) across reconnects*, which no part of the spec enforces at the transport layer. ## Condition of Validity The failure requires all of the following to hold simultaneously: - The session is streamable-HTTP with `Mcp-Session-Id` continuity enabled (i.e., server supports resumption). - At least one of `elicitation`, `sampling`, or `roots.listChanged` is negotiated, meaning the server holds a *reverse* capability obligation. - The SSE reverse channel is torn down and re-established while a server→client request is in flight, or between dispatch and response. - The server's reverse-request bookkeeping is keyed by connection or by an id space that is not scoped to the session. It does *not* occur when: the client and server renegotiate capabilities on every reconnect (some implementations do this defensively and thereby avoid the drift); when the transport is stateless per-request with no reverse channel (sampling and elicitation are then simply unsupported and must be refused at handshake); or when the server serializes all reverse requests and refuses to dispatch a second while one is pending on an unresumed stream. The critical condition is that *capability durability outlives channel durability*. The moment you cache "this session can sample" without also caching "and here is the live, uniquely-identified channel on which sampling responses will arrive," you have created the precondition. ## Decision Boundary The boundary is this: **a capability is not available unless a reverse channel is currently bound to the session and the server has not dispatched a reverse request whose response window has closed.** Operationally, the server must treat the reverse channel as a *lease*, not a *fact*. Concretely: - On every `GET /mcp` (re)bind, the server increments a `channel_epoch` for the session and invalidates all outstanding reverse-request ids from prior epochs. A response arriving with an id from epoch `n` while the current epoch is `n+1` must be discarded, not delivered to the waiting coroutine. - A server-initiated `elicitation/create` or `sampling/createMessage` must carry the epoch in its metadata and must be abandoned (with a `-32000`-class error surfaced to the model as "capability temporarily unavailable") if the epoch changes before a response arrives. - Capability *advertisement* (what the client said it supports) is immutable for the session. Capability *availability* (whether the server can currently exercise it) is a separate, per-request predicate. Conflating them is the bug. The guardrail invariant: `available(cap) ⟺ advertised(cap) ∧ bound(session, epoch) ∧ ¬pending_conflict(cap, epoch)`. A server that cannot satisfy `bound` must not silently hang. It must return a protocol-level refusal that the model can interpret as "retry later," not as "the user declined." This distinction is load-bearing: a hung `sampling/createMessage` that times out and returns an empty completion is indistinguishable, to the model, from a legitimate empty sample, and the model will proceed on fabricated reasoning. ## Operational Effect The downstream effect is not a crash. It is *authorization ambiguity*. Elicitation exists precisely to gate actions the model should not take unilaterally. When a replayed elicitation is re-presented after the original was approved, the model has no way to know the second prompt is a transport artifact rather than a fresh consent requirement. It either (a) re-requests consent, doubling user friction and training users to approve reflexively, or (b) suppresses the duplicate, which means a genuinely new elicitation issued in the same window is silently dropped. Both outcomes degrade the consent invariant that elicitation was designed to provide. For sampling, the effect is subtler and more dangerous: a `sampling/createMessage` whose response is correlated to a stale request id can return a completion generated for a *different* prompt. The server's caller sees a syntactically valid sample and has no signal that it was misrouted. This is a silent semantic corruption of the model's own reasoning chain, injected by the transport. The bound is achieved by treating `Mcp-Session-Id` as necessary but insufficient: the session is the *scope* of capability advertisement, but the *channel epoch* is the scope of capability exercisability. Any server implementation that does not track both will, under reconnect pressure, either hang reverse requests or misroute their responses. The correct behavior on epoch mismatch is to fail the reverse request loudly and let the agent's retry logic re-issue it against the current epoch—never to block, and never to accept a cross-epoch response. ```python import time from dataclasses import dataclass, field from typing import Dict, Optional class CapabilityEpochMismatch(RuntimeError): """Raised when a reverse-channel response arrives for an expired epoch.""" pass class CapabilityUnavailable(RuntimeError): """Raised when a negotiated capability cannot be exercised right now.""" pass @dataclass class Session: session_id: str advertised: Dict[str, bool] # immutable for session lifetime channel_epoch: int = 0 pending: Dict[str, int] = field(default_factory=dict) # req_id -> epoch class ReverseChannel: def __init__(self, session: Session): self.session = session def bind(self) -> int: # Every (re)bind invalidates prior reverse-request ids. self.session.channel_epoch += 1 self.session.pending.clear() return self.session.channel_epoch def dispatch(self, cap: str, req_id: str) -> int: if not self.session.advertised.get(cap): raise CapabilityUnavailable(f"{cap} not advertised for {self.session.session_id}") if self.session.channel_epoch == 0: raise CapabilityUnavailable(f"{cap} has no bound reverse channel") epoch = self.session.channel_epoch self.session.pending[req_id] = epoch return epoch def accept_response(self, req_id: str) -> int: epoch = self.session.pending.pop(req_id, None) if epoch is None: raise CapabilityEpochMismatch(f"unknown or already-resolved request {req_id}") if epoch != self.session.channel_epoch: raise CapabilityEpochMismatch( f"response {req_id} from epoch {epoch}, current {self.session.channel_epoch}" ) return epoch def exercise_elicitation(channel: ReverseChannel, req_id: str, timeout_s: float = 30.0) -> bool: try: epoch = channel.dispatch("elicitation", req_id) except CapabilityUnavailable as e: # Surface as retryable to the model, never as user-declined. raise CapabilityUnavailable(str(e)) from e deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: if channel.session.channel_epoch != epoch: raise CapabilityEpochMismatch( f"epoch advanced {epoch}->{channel.session.channel_epoch} mid-elicitation" ) if req_id not in channel.session.pending: return True time.sleep(0.05) raise CapabilityUnavailable(f"elicitation {req_id} timed out on epoch {epoch}") ```