# How should an instance reconcile a half-consumed SSE event stream when an MCP streamable-session resumes over a fresh HTTP POST **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers/clients using the streamable HTTP transport with optional SSE streaming, where a session is resumed via `Last-Event-ID` after a mid-stream disconnect. Does not cover stdio transport, WebSocket transports, or full-duplex bidirectional streaming implementations. ## Core Distinction The failure is not "the connection dropped." It is that **the resumption protocol and the message-delivery protocol disagree about what a `Last-Event-ID` acknowledges.** In a streamable-session MCP transport, an SSE event carries a *frame* (a JSON-RPC message or partial batch), but a single logical response from a tool call may be split across multiple SSE events, and a single event may carry a JSON-RPC batch containing several method calls whose *results* are produced asynchronously. When the client reconnects with `Last-Event-ID: N`, the server's replay-from-N semantics correctly re-emit event N+1 onward — but the client has usually already *partially applied* event N at the application layer (e.g., it parsed the first half of a streamed tool result, dispatched a dependent tool call, and mutated its local task state) before the socket died. The server's replay is frame-accurate; the client's state is not transaction-accurate. The boundary is that **SSE event IDs are a transport-level cursor, not an application-level checkpoint**, and MCP streamable-session resumption conflates the two. The non-obvious part: this only manifests when the disconnect lands *inside* an event that the client had begun processing, i.e. after `Read()` returned a partial buffer but before the `\n\n` frame terminator arrived — or, more insidiously, after the full frame arrived but before the client's `await` on the async handler completed. Most implementations handle the "clean" case (disconnect between events) correctly and therefore pass integration tests. The half-consumed case is the boundary. ## What Was Observed Trace from a reproduction with an MCP server exposing a `run_query` tool whose result is streamed as a sequence of SSE events (`event: message`, `id: 41`, `id: 42`, ...), each carrying a JSON-RPC result chunk with a `partial: true` flag except the last. 1. Client POSTs `initialize`, receives `Mcp-Session-Id`. Negotiates `Accept: text/event-stream`. 2. Client POSTs `tools/call` for `run_query`. Server responds `200`, opens SSE stream. 3. Server emits `id: 41` (chunk 1/3, `partial: true`). Client parses, appends to an in-memory accumulator, **and immediately dispatches a follow-up `tools/call` (`transform_chunk`) using the partial data** — a legal, common optimization. 4. Server emits `id: 42` (chunk 2/3). The TCP connection is severed by an intermediate proxy (idle timeout on the *upstream* leg, unrelated to SSE keepalive). The client's read loop throws. 5. Client reconnects: POSTs `tools/call` again with header `Last-Event-ID: 42`. 6. Server, honoring replay semantics, re-emits **`id: 43`** (chunk 3/3) — it considers 41 and 42 *delivered* because it wrote them to the socket successfully. 7. Client receives `id: 43` only. Its accumulator now holds chunk 1 + chunk 3. **Chunk 2 is permanently lost.** The client's `transform_chunk` was already dispatched on chunk 1 alone and produced a divergent result. 8. Worse: the client's second `tools/call` (step 3) was issued on the *same* session. On session resume, the server may treat the in-flight `transform_chunk` from the pre-disconnect connection as still pending and re-deliver its result on the new stream, or may have GC'd it — behavior is unspecified because the spec does not define request-level idempotency across a stream resumption. The observed outcome: a tool result that is silently missing one-third of its data, a downstream agent that reasons confidently over the corrupted accumulator, and **no error raised anywhere** — because every individual frame was well-formed and every HTTP status was 200. ## Condition of Validity This boundary is only reachable when all of the following hold simultaneously: - The transport is streamable HTTP with SSE enabled and the server implements `Last-Event-ID` replay (a server that ignores the header and restarts the stream avoids the *lost-chunk* variant but introduces a *duplicate-chunk* variant, which is a different failure). - At least one logical response is chunked across ≥2 SSE events (streamed tool output, progress notifications, or batched JSON-RPC). - The client applies side effects (state mutation, dependent tool dispatch, partial commit) *before* the terminal `partial: false` frame is received. - The disconnect occurs after a non-terminal event was written to the socket but before the terminal event. If the client buffers the entire logical response before applying any side effect, the boundary collapses into the benign "clean disconnect" case. If the server keyed replay on *application-level* sequence numbers rather than SSE frame IDs, the client could detect that chunk 2 was missing. Neither is guaranteed by the spec. ## Decision Boundary The architectural invariant required is: **a resumable stream must be resumable at the granularity at which the consumer commits state, not at the granularity at which the producer emits frames.** Operationally this forces one of two decisions, and the choice must be explicit per tool: 1. **Atomic-response tools** (`run_query`, anything whose partial output is not independently meaningful): the client MUST NOT apply side effects until the terminal frame. The accumulator is a staging buffer; `Last-Event-ID` replay is safe because re-delivery of a partial buffer is idempotent (overwrite, not append). Guardrail: the client tracks the highest *contiguous* applied offset per logical response, not the highest *received* event ID. 2. **Streaming tools** (progressive tokens, incremental progress): the client MUST treat each chunk as independently meaningful and MUST NOT dispatch dependent calls on partial state. If it does, it must record the dispatch against the chunk's `id` and, on resume, either replay the dispatch or abort it — never leave it orphaned. The decision boundary is: *does the consumer of this stream ever act on a non-terminal frame?* If yes, frame-level `Last-Event-ID` semantics are insufficient and the client must implement application-level checkpointing (e.g., a monotonic `applied_seq` carried in the JSON-RPC payload, verified on resume). If no, the transport-level cursor is adequate. Additionally: on resume the client MUST reconcile against the *server's* view of pending requests, not its own. If the pre-disconnect connection had an in-flight `tools/call`, the client must re-issue it with a client-generated idempotency key or query session state, because the server may have completed, dropped, or is still running it — and the spec permits all three. ## Operational Effect Without the invariant, the failure is silent and *correlated*: the same proxy timeout that severs one stream severs many, so a fleet of agents resuming simultaneously all lose the same chunk index and all reason over identically corrupted state — producing a consensus of wrong answers that looks like a legitimate result. Verification replay (a peer agent re-running the same tool) will *also* resume at the same boundary if it shares the transport, so cross-checking fails to catch it. The only reliable detection is a client-side contiguous-offset assertion that raises before the partial result is consumed. With the invariant, the resume either replays the missing chunk (atomic mode) or explicitly aborts the dependent dispatch (streaming mode), converting a silent data-loss event into a bounded, observable retry. ```python from dataclasses import dataclass, field class StreamResumptionGap(RuntimeError): """Raised when an SSE stream resumed via Last-Event-ID would omit a chunk the consumer already acted on, or when the contiguous applied offset does not match the server's replay cursor.""" @dataclass class ChunkAccumulator: # Highest contiguous chunk offset the consumer has COMMITTED to state. applied_seq: int = -1 # Frames received but not yet committed (staging buffer). staged: dict = field(default_factory=dict) terminal_seen: bool = False def receive(self, seq: int, payload: str, partial: bool) -> None: if seq <= self.applied_seq: # Idempotent re-delivery of an already-committed chunk: overwrite. return self.staged[seq] = (payload, partial) def commit_contiguous(self) -> str: """Commit only up to the first gap. Never skip a missing seq.""" out = [] next_seq = self.applied_seq + 1 while next_seq in self.staged: payload, partial = self.staged.pop(next_seq) out.append(payload) self.applied_seq = next_seq if not partial: self.terminal_seen = True next_seq += 1 return "".join(out) def resume_stream(acc: ChunkAccumulator, last_event_id: int, server_cursor: int) -> None: """Called after reconnect. server_cursor is the highest event the server believes it delivered (its replay baseline).""" if acc.terminal_seen: return # The server will replay from last_event_id+1, but it considers everything # <= server_cursor as delivered. If our contiguous applied offset is below # the server's cursor, the frames in between are gone forever. if acc.applied_seq < server_cursor and server_cursor > last_event_id: raise StreamResumptionGap( f"resume would lose chunks {acc.applied_seq + 1}..{server_cursor}: " f"applied_seq={acc.applied_seq}, last_event_id={last_event_id}, " f"server_cursor={server_cursor}; abort dependent dispatch and retry " f"the logical request with an idempotency key" ) # Safe to continue: server cursor is not ahead of our committed state. if acc.applied_seq != last_event_id and acc.applied_seq < last_event_id: raise StreamResumptionGap( f"client committed {acc.applied_seq} but claimed Last-Event-ID " f"{last_event_id}; frames between were received but never applied" ) ```