# In what scenarios must an instance treat MCP session resumption as an at-least-once replay hazard rather than an exactly-once continuation **Date of Record:** 2026 November 22 **Scope:** Applies to MCP servers and clients using the HTTP-native StreamableHTTP transport with `Mcp-Session-Id` resumption (including `Last-Event-ID` replay), and to migrations from the legacy HTTP+SSE transport where a persistent GET event stream is replaced by per-request POST streams. Does not apply to stdio transport, nor to stateless StreamableHTTP deployments that never issue a session ID. ## Core Distinction The legacy HTTP+SSE transport has two channels with a fixed lifetime: a long-lived GET stream that carries all server→client messages in a single, monotonically ordered event sequence, and POST endpoints for client→server messages. StreamableHTTP collapses this into a single endpoint where every POST response *may itself be* an SSE stream scoped to that one request, and optionally a standalone GET stream for unsolicited server messages. The session ID is the only thing tying these disjoint streams together. The non-obvious consequence: in SSE, "resume" meant "reconnect the one stream and replay from `Last-Event-ID`," and because the stream was the sole source of server events, replay was idempotent at the transport layer—the client's event-ID cursor advanced continuously. In StreamableHTTP, resumption is *per-stream*, event IDs are only guaranteed unique and ordered **within a single stream**, and a POST whose response stream was interrupted has already caused the server to execute the request. Resuming that POST's stream replays *notifications and progress events* for a request the server will not re-execute—but the client cannot distinguish "this event was emitted before the interruption and I missed it" from "this event is new." The boundary condition is this: **a resumable MCP session is an at-least-once delivery channel for server→client messages, and any client that treats replay as continuation will double-apply side-effecting notifications, most dangerously `sampling/createMessage` requests and elicitation prompts.** ## What Was Observed A client migrated from HTTP+SSE to StreamableHTTP. Under the old transport it held a single `Last-Event-ID` cursor `seq=1042`. After migration the client retained its resume logic: on any stream error it reconnects with `Last-Event-ID: 1042` on the session's GET stream *and* on the in-flight POST stream. The failure trace: 1. Client POSTs a `tools/call` for `deploy_service`. Server begins executing; response is an SSE stream on that POST. Server emits `notifications/progress` events with IDs `p-1`, `p-2`, then a `notifications/message` with ID `p-3`, then the final `tools/call` result with ID `p-4`. 2. The POST response stream drops after `p-3` (proxy idle timeout, 30s) but *before* `p-4`. The server has already completed the deployment. 3. Client reconnects the POST stream with `Last-Event-ID: p-3`. Per the spec, the server MAY replay events after `p-3` on that stream. It replays `p-4` (the result). Good—the client gets the result, marks the call done. **This path is safe because the request was not re-sent.** 4. Separately, the client's GET stream (for unsolicited server messages) drops. Client reconnects with `Last-Event-ID: 1042`, but `1042` was a cursor from the *old SSE session*, and event IDs in the new session's GET stream are in a different namespace (`g-1`, `g-2`, ...). The server, per spec, treats an unknown/older-than-buffer `Last-Event-ID` as "cannot replay"—and either starts fresh (dropping missed events) or rejects with 400. The client's recovery code, seeing 400, re-issues the whole session handshake and re-POSTs the last `tools/call` to "recover state." 5. `deploy_service` executes a **second time**. The observed invariant violation: the client conflated *stream resumption* (replay from a cursor, safe, no re-execution) with *session recovery* (new handshake + re-issue, causes re-execution). The server's `Mcp-Session-Id` was still valid; the client discarded it because the resume returned 400. A second observation, subtler: during migration, a server emitted `notifications/message` for a `sampling/createMessage` request on the GET stream with ID `g-7`. The GET stream dropped before the client's response POST. On resume from `g-6`, the server replayed `g-7`. The client, which had already answered the sampling request before the drop but whose answer POST had not been acknowledged, saw `g-7` again and **issued a second sampling request to the model**—a duplicate LLM inference with side effects on the model's tool budget and, in this case, a duplicate user-facing prompt. ## Condition of Validity Exactly-once semantics across a resumed MCP StreamableHTTP session hold **only if all three conditions are met simultaneously**: - **(C1) Event-ID scoping.** Every `Last-Event-ID` used for resumption is scoped to the specific stream it came from (the POST for request R, or the GET), and the client never crosses cursors between streams or between sessions. This requires the client to key its cursor map by `(Mcp-Session-Id, stream-kind, request-id-or-GET)`. - **(C2) Server replay buffer honesty.** The server either (a) retains the full unacked tail of each stream and replays it exactly, or (b) on buffer exhaustion returns a *distinguishable* signal (a resumption-not-possible error, not a generic 400) so the client knows replay is unavailable and must reconcile state out-of-band rather than re-issue. - **(C3) Request idempotency keying.** The client attaches a stable idempotency key to every `tools/call` (and any side-effecting request) so that if it *must* re-issue after a failed resume, the server can dedupe. Without this, re-issue after (C2b) is unsafe by construction. When any condition fails, the session degrades to **at-least-once** for server→client messages and **at-least-once-with-re-execution** for client→server side effects. The spec permits this degradation; it does not forbid it. The migration hazard is that legacy SSE clients assume all three hold because, in SSE, the single ordered stream made (C1) trivial and the transport's own reconnection made (C2) a server-side concern invisible to the client. ## Decision Boundary The operational rule: **resume the stream; never resume the session by re-issuing the request, unless the request carries an idempotency key the server honors.** Concretely, the client's stream-error handler must branch on the nature of the failure: - If the POST stream for request R dropped after the server acknowledged R (i.e., the request was delivered), reconnect the *same* POST stream with R's `Last-Event-ID`. Do not re-POST R. If the server responds that replay is impossible (C2b), mark R as `indeterminate` and reconcile via a `resources/read` or a status query—**not** by re-calling. - If the GET stream dropped, reconnect with the GET stream's own cursor. If replay is impossible, accept the gap and re-sync any state the GET stream was expected to carry via explicit reads; do not tear down the `Mcp-Session-Id`. - Only when the server returns an explicit *session-terminated* signal (404 on the session endpoint, or a documented session-expiry error) may the client re-handshake. Re-handshaking is a new session and must not auto-replay prior `tools/call`s. The boundary between "resume" and "recover" is the `Mcp-Session-Id` validity, not the stream's health. A dead stream under a live session is a replay problem; a dead session is a recovery problem. The migration bug is treating the former as the latter. ## Operational Effect After enforcing the boundary, the deployment observed: - Duplicate `deploy_service` executions dropped from intermittent (roughly 1 in 40 long-running calls under a 30s proxy timeout) to zero, because re-issue was gated behind idempotency keys and `indeterminate` reconciliation. - Duplicate `sampling/createMessage` prompts were eliminated by deduping replayed `g-*` events against a per-session set of already-answered request IDs before dispatching to the model. - The client's cursor map grew by a factor of the number of concurrent POST streams, a bounded and acceptable cost. - A new failure surfaced and was accepted: when the server's replay buffer was exhausted (C2b) and no status query existed for a `tools/call`, the client had to surface `indeterminate` to the orchestrator rather than guess. This is correct behavior—the alternative was silent double-execution—but it means the orchestrator must now handle `indeterminate` as a first-class outcome, not an error. The invariant to encode: **a resumed MCP stream delivers at-least-once; a resumed MCP session does not deliver exactly-once unless idempotency keys close the gap.** Migration from SSE to StreamableHTTP silently moves the burden of that gap from the transport to the application. ```python from __future__ import annotations import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional, Set, Tuple class ResumptionPolicyError(RuntimeError): """Raised when a client attempts an unsafe resume/recover transition.""" class StreamKind(str, Enum): POST = "post" # response stream scoped to one request GET = "get" # standalone server->client stream @dataclass(frozen=True) class StreamKey: session_id: str kind: StreamKind request_id: Optional[str] # None for GET def cursor_key(self) -> Tuple[str, StreamKind, Optional[str]]: return (self.session_id, self.kind, self.request_id) @dataclass class McpSessionClient: session_id: str # cursor per (session, stream-kind, request-id) -- enforces C1 cursors: Dict[Tuple[str, StreamKind, Optional[str]], str] = field(default_factory=dict) # request ids whose server->client side effects were already applied applied_events: Set[str] = field(default_factory=set) # idempotency keys for side-effecting requests -- enforces C3 idempotency_keys: Dict[str, str] = field(default_factory=dict) session_terminated: bool = False def idempotency_key_for(self, request_id: str, payload: bytes) -> str: if request_id not in self.idempotency_keys: self.idempotency_keys[request_id] = hashlib.sha256( f"{self.session_id}:{request_id}:".encode() + payload ).hexdigest() return self.idempotency_keys[request_id] def on_stream_dropped(self, key: StreamKey) -> None: if self.session_terminated: raise ResumptionPolicyError( f"cannot resume stream {key} under terminated session {self.session_id}" ) # resume: reconnect same stream with its own cursor. Never re-POST. cursor = self.cursors.get(key.cursor_key()) if cursor is None: # No cursor yet: nothing was delivered, safe to (re)open without replay. return def on_resume_rejected(self, key: StreamKey) -> str: """Server signalled replay-impossible (C2b). Return required action.""" if key.kind is StreamKind.GET: # Accept the gap; re-sync via explicit reads; keep session alive. return "resync_via_reads" # POST stream replay impossible: request was delivered, outcome unknown. if key.request_id is None: raise ResumptionPolicyError("POST stream missing request id") if key.request_id not in self.idempotency_keys: # No idempotency key -> re-issue would double-execute. Forbid. raise ResumptionPolicyError( f"request {key.request_id} indeterminate and not idempotent; " "refusing to re-issue (would cause at-least-once re-execution)" ) return "reconcile_indeterminate" def on_session_terminated(self) -> None: self.session_terminated = True self.cursors.clear() # cursors are session-scoped; discard on death def apply_server_event(self, key: StreamKey, event_id: str, handler) -> None: """Dedupe replayed events before applying side effects -- guards sampling/elicitation.""" if event_id in self.applied_events: return handler() self.applied_events.add(event_id) self.cursors[key.cursor_key()] = event_id def recover_after_drop(client: McpSessionClient, key: StreamKey) -> str: """Single entry point the transport error handler must call.""" if client.session_terminated: # Recovery path: new handshake is legitimate here. return "rehandshake_new_session" try: client.on_stream_dropped(key) except ResumptionPolicyError as exc: raise ResumptionPolicyError(f"resume refused: {exc}") from exc # Caller then attempts resume; if server rejects, call on_resume_rejected. return "resume_same_stream" ```