# Which invariants prevent MCP Streamable-HTTP resumption from replaying a server-initiated push into a post-resume sampling turn **Date of Record:** 2026 November 19 **Scope:** Applies to MCP servers exposing the Streamable HTTP transport (single `/mcp` endpoint, `GET` SSE channel for server→client messages, `Last-Event-ID` resumption, and server-initiated `sampling/createMessage` / `elicitation/create` requests). Does not apply to stdio transports, nor to pure tool-call request/response flows that never cross a disconnect. ## Core Distinction The failure is not "the SSE stream dropped." Disconnects are routine and resumption is designed for them. The failure is that **resumption replays a server-initiated request whose *correlation* is still valid but whose *causal context* is not.** A `Last-Event-ID` cursor guarantees at-least-once delivery of every event after the cursor. It says nothing about whether a replayed *request* (a `sampling/createMessage` the server pushed to the client) still has a live expectation of a response, whether the client already answered it before the socket died, or whether the answer was consumed by a server-side handler that no longer exists after a server restart. The cursor is a transport artifact; the request is a protocol-level obligation. Resuming the stream silently conflates the two. The specific non-obvious boundary: an event ID is monotonic and durable, but the *server-side pending-request table* keyed by `id` is neither. On a server process restart (common in serverless/autoscaled MCP deployments), the stream resumes from the client's `Last-Event-ID`, the server re-emits the buffered `sampling/createMessage` because it is in the replay window, and the client — seeing a request `id` it has never seen *in this session's memory* — issues a fresh LLM sampling turn. The original turn already produced an answer that was lost. The result is a **duplicate sampling turn**: two independent, non-deterministic LLM completions for one logical request, one of which the server will discard, and an unbounded token cost with a divergent side effect if the sampling prompt carried tool calls. ## What Was Observed A client agent (Claude-class, context window ~200k) connected to a Streamable-HTTP MCP server backed by an autoscaling pool. The server pushed a `sampling/createMessage` request (event id `evt-4471`) asking the client to summarize a 40k-token artifact so the server could continue a multi-step workflow. Mid-generation, the client's SSE connection was severed by an idle-timeout at the load balancer (60s, no keepalive configured on the `GET` stream). Trace: 1. Server emits `event: message, id: evt-4471, data: {jsonrpc:"2.0", id:"req-88", method:"sampling/createMessage", ...}` on the SSE channel. Server records `req-88 → pending` in its in-memory table. 2. Client begins the sampling turn. LLM call takes 71s (long artifact, verbose model). 3. At t=60s the LB drops the `GET` stream. Client's SSE reader raises; the client library schedules a resume with `Last-Event-ID: evt-4471`. 4. The autoscaler had already recycled the server instance. The new instance has an empty `pending` table but a **durable replay buffer** (Redis-backed) retaining the last 1000 events including `evt-4471`. 5. Client reconnects with `Last-Event-ID: evt-4471`. Server replays `evt-4471` verbatim — same `id: req-88`. 6. Client's in-memory dedup map was scoped to the *connection*, not the *session*. It has no record of `req-88`. It treats the replayed event as a fresh server request and launches a **second** sampling turn. 7. The first turn's completion (from step 2) is delivered when the original client coroutine finishes — but the server-side handler for `req-88` is gone (instance recycled). The response is a JSON-RPC reply to `req-88` that the new instance rejects as `unknown request id`. 8. The second turn completes, is accepted, and the workflow proceeds — but with a *different* summary than the one the (now-dead) workflow step intended, and at 2× the token cost. Observed symptom in logs: `sampling/createMessage req-88` appears twice in the client's audit trail with distinct completion hashes; the server logs one `unknown request id req-88` rejection and one success. ## Condition of Validity The replay-causes-duplicate-turn failure is *bounded* (does not occur) only when all three of the following hold simultaneously: - **Dedup is session-scoped, not connection-scoped.** The client must persist a set of seen request `id`s keyed to the *MCP session* (the `Mcp-Session-Id` header value), surviving reconnects, and must treat a replayed `sampling/createMessage` with a seen `id` as a *no-op replay* — either re-sending the cached response or dropping it — never as a new turn. - **The server's replay buffer is bounded by a request-expiry horizon, not just a count.** A durable buffer that retains `evt-4471` past the point where `req-88`'s pending entry was GC'd is the exact hazard. The replay window must be the intersection of (event count) and (pending-request TTL), and the server must emit a `resumption-lost` sentinel when the client's `Last-Event-ID` predates the oldest live pending request. - **The client's sampling turn is cancellable / idempotent.** Because the LLM completion is non-deterministic, the only safe recovery is to *not re-run* it. The client must key its in-flight sampling futures by request `id` and, on resume, attach the replayed event to the existing future rather than spawning a new one. Outside these conditions — i.e., the common case of a naive client library that treats every SSE event as fresh, plus a server with a durable-but-unbounded replay buffer — the failure is not just possible but *likely* under autoscaling, because instance recycling is the norm and pending tables are process-local. ## Decision Boundary The architectural invariant that must be enforced: **transport-level at-least-once delivery of events is not protocol-level at-most-once execution of requests.** The two guarantees live at different layers and must be reconciled explicitly. Concretely, the boundary decision is: *on resume, does the client re-execute a replayed server-initiated request?* - If the request `id` is in the session-scoped seen-set **and** a response was already sent → drop the replay, optionally re-send the cached response (idempotent). - If the request `id` is in the seen-set **and** no response was sent (turn still in flight) → re-attach to the existing future; do not spawn. - If the request `id` is **not** in the seen-set **and** the server's replay buffer is within the pending-TTL horizon → it is a genuinely new request; execute. - If the request `id` is **not** in the seen-set **but** the `Last-Event-ID` predates the server's oldest live pending entry → the server must have emitted a `resumption-lost` sentinel; the client must fail the session closed rather than execute a request whose causal predecessor is unknown. The last branch is the one most implementations omit. Without it, a client that lost its seen-set (e.g., client process restart) will happily re-execute every replayed request, and there is no signal that it is doing so. ## Operational Effect When the invariant is violated, the observable effects are: duplicate non-deterministic LLM completions (token cost, and divergent outputs if the sampling prompt is stateful or carries tool calls with side effects); server-side `unknown request id` rejections that mask the real problem; and — worst — a workflow that *completes* with a semantically wrong artifact because the second turn's output was substituted for the first's. The failure is silent: no error surfaces to the user, only a cost anomaly and a hash mismatch in audit logs. When the invariant holds, resumption is safe: the client re-attaches or drops, the server's `resumption-lost` sentinel bounds the unknown-predecessor case, and the pending-request TTL and replay-buffer horizon are kept in lockstep so the buffer never outlives the pending table. The operational rule for agent operators: **treat `Mcp-Session-Id` as the dedup key, `Last-Event-ID` as a cursor only, and require the server to advertise its replay horizon so the client can detect the unknown-predecessor branch.** A client that cannot detect that branch must fail closed on any resume that crosses a server restart. ```python class ResumptionCausalityError(RuntimeError): """Raised when a replayed server-initiated request cannot be safely re-attached or dropped because its causal predecessor is unknown.""" def resume_stream( last_event_id: str, seen_request_ids: set[str], server_oldest_live_pending_id: str | None, replay_buffer: list[dict], ) -> list[dict]: """Filter a replayed event buffer down to events safe to execute. Invariant: a replayed sampling/elicitation request is executed only if its id is unseen AND the cursor is within the server's live pending horizon. Otherwise it is dropped (seen) or the session fails closed (unknown predecessor). """ if server_oldest_live_pending_id is None: # Server has no live pending requests: any replay is stale. return [e for e in replay_buffer if e.get("method") not in ("sampling/createMessage", "elicitation/create")] if last_event_id < server_oldest_live_pending_id: raise ResumptionCausalityError( f"Last-Event-ID {last_event_id!r} predates oldest live pending " f"request {server_oldest_live_pending_id!r}; replay would " f"re-execute requests with unknown causal predecessors. " f"Fail session closed." ) safe: list[dict] = [] for evt in replay_buffer: method = evt.get("method") if method in ("sampling/createMessage", "elicitation/create"): req_id = evt.get("id") if req_id in seen_request_ids: continue # drop: already answered or in flight safe.append(evt) return safe ```