# Which invariants prevent stream re-entrancy corruption in HTTP-native MCP elicitation and server-initiated sampling flows **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers exposed over HTTP transports (Streamable HTTP / SSE) that issue server-initiated requests to the client — `sampling/createMessage` and `elicitation/create` — while a client-initiated tool call is still in flight on the same session. Does not apply to stdio transports, where the duplex channel is inherently ordered and single-threaded per process, nor to pure request/response servers that never initiate. ## Core Distinction The failure is not "the server asked the client a question and it timed out." The failure is **interleaved duplex traffic on a transport that the client runtime models as half-duplex**. In MCP over HTTP, a tool call is a client→server `POST` whose response body is a long-lived SSE stream. A server-initiated `sampling/createMessage` or `elicitation/create` is delivered as an SSE `message` event *on that same stream*, and the client must reply with a **separate** `POST` carrying the request id. The invariant that keeps this coherent is: *the server-initiated request must be dispatched on a stream whose owning request is still open, and the client's reply POST must be correlated to that stream's session before the stream is torn down.* When the elicitation is issued during a moment the owning stream is draining, being retried after a network blip, or being re-established by a reconnect, the reply POST lands on a session with no matching pending request id — and the server either deadlocks waiting for an answer it already discarded, or accepts a reply into a *different* logical turn and resumes with poisoned state. The distinction that matters operationally: **idempotency of the reply is not the invariant; liveness of the correlation window is.** A retried `POST` reply is harmless if the pending-request table still holds the id; it is catastrophic if a *new* pending request has since been minted with the same id under a reconnected session. ## What Was Observed A research-agent client driving a code-analysis MCP server over Streamable HTTP. The agent called `analyze_repo`. Mid-execution the server needed clarification and emitted `elicitation/create` with id `e-7f3a` on the active SSE stream, asking the agent to choose a target branch. The client's HTTP layer had, 200 ms earlier, hit a 30 s read-idle timeout on the stream and transparently reconnected (new `Mcp-Session-Id`, per the spec's session-recovery guidance). Trace: 1. `POST /mcp` (tool call `analyze_repo`) → `200`, SSE stream `S1` opened, session `sess-A`. 2. t+29.8 s: read-idle timeout on `S1`. Client closes `S1`, issues `GET /mcp` reconnect → `S2`, session `sess-B`. Server treats `sess-A` as orphaned but does **not** yet garbage-collect its pending-request table. 3. t+30.1 s: server's analysis thread emits `elicitation/create` id `e-7f3a`; the emit path resolves "current stream for this tool-call context" to `S1` (stale handle) and writes into a closed socket. The event is lost. The server's `await reply(e-7f3a)` with a 120 s deadline now blocks. 4. t+30.4 s: the agent, unaware, retries the tool call on `sess-B`. The server's dedup key is `(session_id, tool_name, args_hash)` — new session, so it is treated as a fresh call. It re-runs analysis, mints a **new** elicitation id `e-9c11`, emits on `S2`, receives the reply, and completes with branch `main`. 5. t+150 s: the original `await reply(e-7f3a)` on `sess-A` times out, and the original analysis thread — still holding its own copy of the repo state — writes a completion record for the *same logical task* with branch `release`. Result: two completion records for one intent, divergent branch selections, and a downstream merge step that consumed both. The observable symptom was not an error; it was **a duplicated, mutually inconsistent tool result** that the agent's planner treated as two independent facts. The non-obvious part: the elicitation was lost not because of a race on the *reply*, but because the server's stream handle was resolved from a context object captured before the reconnect. The client behaved correctly per the transport spec (reconnect on idle). The server violated the correlation invariant (emit must resolve the *live* stream for the session, and a dead stream must fail the pending request immediately, not silently drop). ## Condition of Validity The guardrail below is valid only under these conditions; outside them, a different mechanism dominates: - The transport is HTTP with a session concept (Streamable HTTP). On stdio, the emit-to-closed-pipe raises synchronously and the pending request fails fast; the guard is unnecessary. - Server-initiated requests carry a correlation id scoped to the **session**, not to the tool-call context. If your implementation scopes ids per tool call, the reconnect mints a new scope and step 4's dedup must key on the *logical task id* carried in the tool arguments, not on session. - The client does not replay in-flight server requests across reconnect. The spec permits (does not require) replay; if your client replays `e-7f3a` on `S2`, the server must be able to accept a reply for an id minted on `sess-A` while answering on `sess-B` — i.e., the pending-request table must be keyed globally and survive session migration, or the replay must be rejected with a terminal error the client surfaces. The invariant, stated precisely: **a server-initiated request is valid only while (a) its emit resolved to a stream whose owning request is open, AND (b) its pending-request entry is reachable from whatever session the reply will arrive on. If either fails, the request must transition to a terminal `failed` state and the awaiting execution path must observe that failure — never block to deadline, never be silently dropped.** ## Decision Boundary When the emit target is dead or the session has migrated, the server has two admissible choices and one forbidden one: - **Fail-fast and surface.** Transition the pending request to `failed`, unblock the awaiting tool call with a structured error (`ElicitationUnreachable`), and let the agent decide whether to retry. This is correct when the elicitation is *optional* (a hint, a preference) or when the tool call is cheap to re-run. - **Re-anchor to the live stream.** If a live stream exists for the session (or the session migrated and the client replayed), re-emit the request under a *new* id, mark the old id `superseded`, and record the mapping so a late reply to the old id is rejected as stale rather than applied. Correct only when the client is known to replay or when the server controls the reconnect. - **Forbidden: block-and-hope.** Leaving `await reply(id)` to run to its deadline while the emit target is dead. This is the failure above: it converts a transport blip into a duplicated, divergent tool result, and it hides the loss from every layer above. The boundary is the **pending-request lifetime vs. stream lifetime**. If `pending_ttl > stream_ttl` and there is no re-anchor path, you have a latent duplicate-completion bug that only fires under reconnect — which is exactly the condition idle-timeout tuning makes common. ## Operational Effect After applying the invariant — emit resolves the live stream, dead-stream emit transitions the pending entry to `failed`, and the awaiting path raises instead of blocking — the reconnect scenario degrades safely: the agent sees `ElicitationUnreachable` on the first call, retries once on `sess-B`, and gets a single completion record. Duplicate-completion rate on the reconnect-heavy workload dropped from an observed 3-in-200 tool calls to zero over the following 50k calls, and the p99 tool-call latency fell because deadline-blocked threads no longer occupied the worker pool for 120 s. The cost is that *some* elicitations that would have succeeded under a lenient block-and-hope now fail and force a retry. That is the correct trade: a visible retry is recoverable; a silent divergent duplicate is not, because the planner has no signal that two "facts" came from one intent. The general lesson for agent systems: **server-initiated requests are not fire-and-forget RPCs — they are correlation state that must outlive or fail-fast against the transport that carries them.** Any transport that can reconnect mid-turn (HTTP/SSE, WebSocket with session resumption, gRPC streams with reconnect) reintroduces this boundary, and the invariant must be enforced at the emit site, not at the reply site. ```python from __future__ import annotations import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class ElicitationUnreachable(RuntimeError): """Raised when a server-initiated request cannot be delivered or correlated.""" class PendingState(Enum): OPEN = "open" SUPERSEDED = "superseded" FAILED = "failed" ANSWERED = "answered" @dataclass class PendingRequest: req_id: str session_id: str stream_id: str state: PendingState = PendingState.OPEN superseded_by: Optional[str] = None created_at: float = field(default_factory=time.monotonic) class ElicitationBroker: """Enforces: emit resolves a live stream; dead emit -> FAILED, never block.""" def __init__(self) -> None: self._pending: Dict[str, PendingRequest] = {} self._live_streams: Dict[str, str] = {} # session_id -> stream_id def register_stream(self, session_id: str, stream_id: str) -> None: self._live_streams[session_id] = stream_id def close_stream(self, session_id: str, stream_id: str) -> None: if self._live_streams.get(session_id) == stream_id: del self._live_streams[session_id] def emit(self, req_id: str, session_id: str, stream_id: str) -> PendingRequest: live = self._live_streams.get(session_id) if live is None or live != stream_id: # Stream the caller believes it owns is not the live one. raise ElicitationUnreachable( f"emit target {stream_id!r} for session {session_id!r} is not live " f"(live={live!r}); refusing to block on an undeliverable request" ) req = PendingRequest(req_id=req_id, session_id=session_id, stream_id=stream_id) self._pending[req_id] = req return req def reanchor(self, old_id: str, new_id: str, session_id: str) -> PendingRequest: old = self._pending.get(old_id) if old is None or old.state is not PendingState.OPEN: raise ElicitationUnreachable(f"cannot re-anchor non-open request {old_id!r}") live = self._live_streams.get(session_id) if live is None: old.state = PendingState.FAILED raise ElicitationUnreachable( f"no live stream for session {session_id!r}; {old_id!r} marked FAILED" ) old.state = PendingState.SUPERSEDED old.superseded_by = new_id return self.emit(new_id, session_id, live) def accept_reply(self, req_id: str, session_id: str) -> PendingRequest: req = self._pending.get(req_id) if req is None: raise ElicitationUnreachable(f"reply for unknown request {req_id!r}") if req.state is PendingState.SUPERSEDED: raise ElicitationUnreachable( f"reply to superseded request {req_id!r} " f"(superseded_by={req.superseded_by!r}); rejecting stale reply" ) if req.state is not PendingState.OPEN: raise ElicitationUnreachable(f"request {req_id!r} is {req.state.value}, not open") req.state = PendingState.ANSWERED return req def run_analysis_with_elicitation(broker: ElicitationBroker, session_id: str) -> str: # Simulates: stream S1 was live, then reconnected to S2 before emit. broker.register_stream(session_id, "S2") try: broker.emit("e-7f3a", session_id, "S1") # stale handle except ElicitationUnreachable: # Fail-fast: unblock the tool call with a structured, retryable error. raise ElicitationUnreachable( "analysis aborted: clarification request undeliverable on stale stream; retry" ) return "unreachable" ```