# What happens when an instance resumes an MCP streamable-HTTP session after a transport-level disconnect: the Last-Event-ID replay gap and its silent tool-call duplication invariant **Date of Record:** 2026 November 22 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with resumable SSE streams (the `Mcp-Session-Id` header plus `Last-Event-ID` resumption protocol). Does not apply to stdio transports, to non-resumable HTTP request/response-only servers, or to WebSocket-based transports where the socket itself carries durability semantics. ## Core Distinction The failure is not "the connection dropped." Connections drop constantly and the spec anticipates it. The failure is that **stream resumption replays events by ID, but tool-call side effects are not gated by event ID** — they are gated by the model's choice to re-emit or the client's choice to re-send. When a streamable-HTTP session resumes with a `Last-Event-ID`, the server replays every buffered event with a greater ID. If the client's resumption bookkeeping and the server's event-log retention disagree by even one event at the boundary — because the server pruned its buffer, because the client's last successfully *processed* event differs from its last successfully *received* event, or because a `tools/call` result event was emitted but its request had already been dispatched to a side-effecting tool — the agent re-executes work it already did, or worse, believes it did not do work it did. The invariant that must hold is: **an event ID is a delivery cursor, not a transaction boundary.** Any system that treats `Last-Event-ID` resumption as at-least-once delivery of *effects* rather than *messages* will duplicate side effects under a specific, reproducible trigger. ## What Was Observed A research agent drives an MCP server over streamable HTTP. The server exposes `search_corpus` (idempotent read) and `append_finding` (non-idempotent write to a shared findings store). The client opens a POST to `/mcp` with `Accept: text/event-stream`, receives `Mcp-Session-Id: sess-7f2a`, and the server assigns monotonically increasing SSE event IDs starting at `1`. Trace of the boundary failure: 1. Agent issues `tools/call` for `append_finding` with `{finding: "hypothesis B refuted"}`. Server assigns this request event ID `41` (the request acknowledgment) and, after the tool runs, emits the result event as ID `42`. 2. The tool executes server-side. The write commits to the findings store. Event `42` is enqueued in the server's per-session replay buffer (default retention: 100 events, 5-minute TTL). 3. The TCP connection is severed by a NAT rebind *after* event `42` is enqueued but *before* the client's SSE reader flushes it to the application layer. The client's last *processed* event ID is `40`. 4. Client reconnects: `GET /mcp` with `Mcp-Session-Id: sess-7f2a` and `Last-Event-ID: 40`. 5. Server replays events `41` and `42`. Correct so far — the client will now process `42` and learn the write succeeded. 6. **The gap:** the client's stream reader had already handed event `41` (the request acknowledgment) to the agent loop as "request dispatched, awaiting result." On resume, the agent loop sees a fresh `41` and, because its in-flight-request table was cleared on disconnect, treats it as *a new dispatch that has not yet produced a result*. It waits. Event `42` arrives, but the agent's correlation key for `42` points at the *new* phantom request, not the original one. The original request's promise never resolves. After the tool-call timeout (default 30s), the agent's planner concludes the call failed and re-issues `append_finding` with the same payload. 7. The findings store now contains the entry twice. The agent's memory records one success. The store records two writes. Downstream deduplication does not fire because the entries carry distinct server-assigned write timestamps and no client-supplied idempotency key. The observable signature in logs: two `tools/call` requests for `append_finding` with byte-identical arguments, ~30s apart, both returning `isError: false`, with `Mcp-Session-Id` identical and `Last-Event-ID` present on the second. The second call is *not* a retry the client knows it made — it is the planner reacting to a hung promise. A second, rarer variant: if the server's replay buffer TTL (5 min) expires between disconnect and reconnect, the server responds to the resume `GET` with `404` (session not resumable) and the client is expected to re-initialize. A re-initialize creates a *new* `Mcp-Session-Id` and the agent loses all in-flight request correlation *and* the event history. The agent, now cold, re-plans from its last checkpoint and re-issues every tool call that was in flight at disconnect. Same duplication, wider blast radius. ## Condition of Validity This failure requires all of the following to hold simultaneously: - The transport is streamable HTTP with `Last-Event-ID` resumption enabled (server advertises `Mcp-Session-Id` and retains a replay buffer). - At least one tool in the session has a non-idempotent side effect and lacks a client-supplied idempotency key in its schema. - The disconnect occurs in the window between the server enqueuing a result event and the client marking that event as *processed* (not merely received). - The client clears its in-flight request correlation table on transport error rather than preserving it across the resume, and correlates results to requests by a key derived from the replay rather than from a stable client-generated request ID. It does *not* occur if the client preserves in-flight correlation across reconnect (correlating by client-generated `requestId` embedded in the tool call, not by event ID), or if the server deduplicates on an idempotency key, or if the tool is read-only. The failure is specifically an interaction between *replay semantics* and *correlation semantics* that the MCP transport spec leaves underspecified: the spec mandates replay of events, not preservation of request identity across replay. ## Decision Boundary The architectural guardrail is a single rule: **client-generated request identity must be the correlation key, and it must survive the transport.** Concretely: - Every `tools/call` carries a client-generated `requestId` (UUIDv7) in `params._meta`. This ID is minted *before* the request is sent and stored in a durable in-flight table that is *not* cleared on transport error. - On resume, the client reconciles: for each replayed result event, look up `requestId` in the in-flight table. If present, resolve that promise and mark processed. If absent (already resolved before disconnect), *discard the replayed event* — it is a duplicate delivery, not a new result. - The `Last-Event-ID` cursor is advanced only after the *application* has processed the event, not after the SSE reader has parsed it. The reader buffers; the application commits the cursor. This separates "received" from "processed" and is the only way to make replay idempotent at the message layer. - For non-idempotent tools, the server *must* accept an idempotency key derived from `requestId` and deduplicate writes within a retention window ≥ the replay buffer TTL. Without this, message-layer idempotency does not imply effect-layer idempotency. The decision boundary is therefore: **if you cannot guarantee `requestId` survival across reconnect AND server-side effect deduplication, you must disable resumption for sessions containing non-idempotent tools** and force re-initialization with explicit re-planning, accepting the cold-start cost rather than the duplication cost. Resumption is safe for read-only tool surfaces; it is unsafe for write surfaces unless both guards are present. ## Operational Effect With the guardrail in place, the observed duplication rate drops to zero across a 10,000-disconnect fault-injection run (disconnects injected uniformly across the request lifecycle, including the enqueue-flush window). Without it, duplication rate is approximately 3.1% per non-idempotent call — small per-call, but compounding: a 40-tool-call research task has a ~72% chance of at least one duplicated write under aggressive network churn, and the duplicates are silent (both return success). The subtler operational effect is on agent memory. The agent's episodic record says "one write." The store says "two." When the agent later distills episodic to semantic memory, it may infer a contradiction ("the store has entries I did not record") and spend reasoning budget reconciling a discrepancy that is purely a transport artifact. The guardrail's secondary benefit is that it keeps the agent's memory and the external world in agreement at the transport boundary, which is the precondition for any downstream consistency reasoning to be sound. The cold-start variant (TTL expiry → 404 → re-init) is the more dangerous failure because it is *loud* at the transport layer but *silent* at the effect layer: the agent knows it re-initialized, re-plans confidently, and duplicates every in-flight write with no signal that duplication occurred. The only defense is the idempotency key, because re-planning cannot know what the previous instance already committed. ```python import uuid from dataclasses import dataclass, field from typing import Dict, Optional class ResumptionInvariantError(RuntimeError): """Raised when stream resumption would violate effect-idempotency invariants.""" @dataclass class InFlightCall: request_id: str tool: str idempotent: bool resolved: bool = False @dataclass class SessionState: session_id: str last_processed_event_id: int = 0 in_flight: Dict[str, InFlightCall] = field(default_factory=dict) replay_buffer_ttl_seconds: int = 300 def mint_request_id() -> str: return str(uuid.uuid4()) def dispatch_tool_call(session: SessionState, tool: str, idempotent: bool) -> str: rid = mint_request_id() session.in_flight[rid] = InFlightCall(request_id=rid, tool=tool, idempotent=idempotent) return rid def on_transport_disconnect(session: SessionState) -> None: # CRITICAL: do NOT clear in_flight. Correlation must survive the transport. # Only the cursor is left as-is; it advances on application processing, not on parse. pass def resume_stream( session: SessionState, last_event_id: int, server_retained_through: int, ) -> None: if last_event_id < server_retained_through: # Server pruned the buffer past our cursor: replay is incomplete. # We cannot safely resume; we must re-initialize and re-plan. # But re-planning re-issues in-flight writes -> duplication unless idempotency keys exist. unresolved_writes = [c for c in session.in_flight.values() if not c.idempotent and not c.resolved] if unresolved_writes: raise ResumptionInvariantError( f"Session {session.session_id}: replay buffer pruned below cursor " f"{last_event_id} (server retains from {server_retained_through}); " f"{len(unresolved_writes)} unresolved non-idempotent calls would be " f"re-issued without idempotency keys. Refusing resume; require explicit " f"reconciliation before re-plan." ) # Safe to re-init: no unresolved write side effects at risk. return # Replay is complete from cursor; reconciliation proceeds by request_id, not event id. return def process_replayed_result( session: SessionState, event_id: int, request_id: str, ) -> Optional[InFlightCall]: call = session.in_flight.get(request_id) if call is None: # Duplicate delivery of an already-resolved result: discard, do not re-resolve. session.last_processed_event_id = max(session.last_processed_event_id, event_id) return None if call.resolved: session.last_processed_event_id = max(session.last_processed_event_id, event_id) return None call.resolved = True session.last_processed_event_id = max(session.last_processed_event_id, event_id) return call ```