# Which invariants prevent silent loss of server-initiated requests across MCP streamable-session resumption **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using the HTTP-native "streamable" transport with `Last-Event-ID`-based session resumption, where the server issues JSON-RPC requests to the client (sampling, elicitation, roots refresh) over a server→client SSE stream that may be reconnected mid-flight. Does not apply to stdio transport, nor to purely client-initiated request/response flows with no server-originated requests. ## Core Distinction There are two distinct notions of "resumed" that are routinely conflated in streamable-session resumption: 1. **Stream resumption** — the client reconnects to the SSE stream and supplies `Last-Event-ID`, and the server replays events with sequence numbers strictly greater than that ID. 2. **Request resumption** — an in-flight *server-initiated* request (e.g., `sampling/createMessage`, `elicitation/create`) that was emitted before the disconnect, whose response the client will still send after reconnecting, is correctly correlated by the server to the original request. The failure mode lives precisely in the gap between these two: stream resumption can succeed *perfectly* — every event replayed, no gaps in the event ID sequence — while request resumption silently fails because the server has already abandoned or re-keyed the pending request. The event stream is continuous; the request correlation is not. A client that trusts "no missing event IDs" as evidence of continuity will block forever on a request the server no longer remembers, or the server will receive a response for a request ID it has since garbage-collected and drop it as unknown. The invariant that must hold is not "the stream is gap-free" but **"the set of live server-initiated request IDs is a monotone function of the session, and every request ID that the client may still respond to remains resolvable at the server across reconnects."** ## What Was Observed A representative trace. Server S issues a sampling request to client C over the SSE stream: ``` event: message id: 41 data: {"jsonrpc":"2.0","id":"srv-7a3","method":"sampling/createMessage","params":{...}} ``` Client C begins inference to answer. The TCP connection drops (mobile handoff, proxy idle-timeout, load-balancer drain). The server's per-connection request registry — keyed by connection or by a connection-scoped ID map — is torn down. S marks `srv-7a3` as orphaned and either (a) deletes it, or (b) times it out on a short timer. C reconnects with `Last-Event-ID: 41`. S replays nothing (no events > 41 yet) and accepts the resumed session. The stream is healthy. C finishes sampling and posts the response: ``` POST /mcp {"jsonrpc":"2.0","id":"srv-7a3","result":{"role":"assistant","content":...}} ``` S has no pending entry for `srv-7a3`. Depending on implementation it responds `-32602 Invalid params` (unknown id), silently 204s, or — worst case — treats it as a fresh client request with an unrecognized shape. C's tool-call loop now waits on a server response that will never come, or the user-visible turn ends with a dangling promise. The agent's reasoning loop has lost a branch with no error surfaced on the stream. A second observed variant: S *does* keep the pending request but re-keys it under a new connection-scoped ID (`srv-7a3` → `srv-9c1`) and re-emits the request as a new event with a higher sequence number on resume. C, having already begun work on `srv-7a3`, now sees a *duplicate* request under `srv-9c1`, answers both, and the server executes the sampling result twice — double-counting a side effect (e.g., two tool invocations embedded in the sampled content, or two elicitation prompts to the user). In both variants the stream-level resumption is clean. The defect is entirely in request identity and lifetime management. ## Condition of Validity The guardrail only holds under the following conditions, and each is independently necessary: - **Stable request identity across connections.** Server-initiated request IDs must be scoped to the *session*, not to the connection. The ID `srv-7a3` must mean the same pending request before and after a reconnect. Re-keying on resume is a violation. - **Response acceptance window ⊇ client's in-flight window.** The server must retain every outstanding server-initiated request until either its response arrives or the *client* has acknowledged (via a subsequent event or explicit cancel) that it will not respond. A server-side timeout shorter than the client's maximum inference latency is a silent-loss generator. - **Replay is idempotent at the request layer, not just the event layer.** If the server re-emits a server-initiated request on resume (because it cannot prove the client saw it), the client must deduplicate by request ID before acting, and the server must accept at most one response per ID. - **`Last-Event-ID` monotonicity is enforced by the server.** Event IDs must be strictly increasing per session and never reused across a resume; otherwise a client's `Last-Event-ID` can point into a re-used range and the server replays the wrong window. - **Explicit cancellation, not timeout, for abandonment.** If the server decides to abandon a pending request, it must emit a cancellation event (or a JSON-RPC error response to the request) *on the stream* so the client can stop work, rather than letting the pending entry silently expire. If any of these is absent, the "resumed" session is a session that has lost request continuity while appearing healthy at the transport layer. ## Decision Boundary The operational decision is: **on reconnect, does the server treat the pending-request set as part of session state (preserved) or as part of connection state (discarded)?** - If pending requests are **connection state**, then any transport drop is a request-loss event, and the client must be prepared to see its in-flight server-initiated requests vanish. In that model the correct client behavior is to treat a reconnect as invalidating all in-flight server-initiated work and to surface an error to the reasoning loop — never to keep waiting. This is safe but wastes inference already spent. - If pending requests are **session state**, then the server must implement the full set of invariants above: stable IDs, response window ≥ client latency, idempotent replay, monotone event IDs, explicit cancellation. This is the model that preserves continuity but is where every observed defect lives, because implementations adopt session-scoped *streams* without session-scoped *request registries*. The boundary is crossed the moment an implementation keeps the SSE stream resumable (session-scoped event log) but keeps the request registry connection-scoped. That mismatch — resumable stream, non-resumable requests — is the precise defect. It is invisible in testing because stream resumption tests pass: events replay, no gaps, connection healthy. Only a test that drops the connection *between* a server-initiated request and its response, then asserts the response is accepted, exercises the boundary. ## Operational Effect Downstream of this boundary, the agent exhibits a characteristic pathology: **a reasoning loop that stalls on a server-initiated sub-call whose result was already computed but whose response was rejected.** The LLM has done the sampling work; the transport has discarded the correlation. From the orchestrator's view the turn hangs until an outer timeout fires, at which point the whole turn is retried — re-running the sampling, re-invoking any tools embedded in it, and re-issuing the user-facing elicitation. The observable symptom is duplicated side effects and inflated latency, attributed (incorrectly) to model slowness rather than to a request-correlation gap. The defense is to make request correlation a first-class, session-scoped, explicitly-lifetimed object with a cancellation path, and to instrument the reconnect handler to assert that the pending-request set is non-empty-preserved across the reconnect. The check below encodes the invariant as an executable guard: it fails loudly when a resumed session cannot resolve a request the client is still entitled to answer, and when a replayed request would be double-executed. ```python from dataclasses import dataclass, field from typing import Dict, Optional class RequestCorrelationError(RuntimeError): """Raised when session resumption breaks server-initiated request continuity.""" @dataclass class PendingRequest: request_id: str session_id: str emitted_event_id: int responded: bool = False cancelled: bool = False @dataclass class StreamableSession: session_id: str # Session-scoped request registry: survives connection churn. pending: Dict[str, PendingRequest] = field(default_factory=dict) last_event_id: int = 0 def emit_server_request(self, request_id: str) -> int: if request_id in self.pending: raise RequestCorrelationError( f"duplicate server request id {request_id!r} in session {self.session_id!r}" ) self.last_event_id += 1 self.pending[request_id] = PendingRequest( request_id=request_id, session_id=self.session_id, emitted_event_id=self.last_event_id, ) return self.last_event_id def resume(self, client_last_event_id: int) -> None: # Invariant: event IDs are monotone and the client's cursor is not ahead. if client_last_event_id > self.last_event_id: raise RequestCorrelationError( f"client Last-Event-ID {client_last_event_id} exceeds server " f"high-water mark {self.last_event_id} for session {self.session_id!r}" ) # Invariant: resumption must NOT clear the pending-request registry. # Pending requests are session state, not connection state. # (This method intentionally performs no clearing; the guard is the test below.) def accept_response(self, request_id: str) -> None: req: Optional[PendingRequest] = self.pending.get(request_id) if req is None: raise RequestCorrelationError( f"response for unknown/expired server request {request_id!r} " f"in session {self.session_id!r}; correlation lost across resume" ) if req.cancelled: raise RequestCorrelationError( f"response for cancelled server request {request_id!r}" ) if req.responded: raise RequestCorrelationError( f"duplicate response for server request {request_id!r}; " f"replay was not idempotent" ) req.responded = True def cancel(self, request_id: str) -> None: req = self.pending.get(request_id) if req is None: raise RequestCorrelationError( f"cannot cancel unknown server request {request_id!r}" ) req.cancelled = True def assert_resumption_preserves_pending(session: StreamableSession, client_last_event_id: int, in_flight_request_ids: list[str]) -> None: """Guard to run in the reconnect handler. Fails if resume drops live requests.""" before = set(session.pending) session.resume(client_last_event_id) after = set(session.pending) lost = before - after if lost: raise RequestCorrelationError( f"resume dropped live server requests {sorted(lost)}; " f"stream resumed but request correlation did not" ) unresolved = [rid for rid in in_flight_request_ids if rid not in session.pending] if unresolved: raise RequestCorrelationError( f"client holds in-flight requests {unresolved} the server can no longer " f"resolve after resume; responses would be rejected as unknown" ) ```