# Why does an instance lose its MCP session on a streamable-HTTP reconnect when the server replays an SSE event the client already consumed? **Date of Record:** 2026 November 19 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport with server-initiated SSE streams and `Mcp-Session-Id` resumption via `Last-Event-ID`. Does not cover stdio transport, legacy HTTP+SSE dual-endpoint transport, or WebSocket-based agent handoffs. ## Core Distinction The distinction that matters here is between **transport-level resumption** (re-establishing a byte stream and replaying events after a given ID) and **application-level session continuity** (the agent's belief about which tool calls are in flight, which results it has already folded into its reasoning state, and which side effects have committed). A streamable-HTTP MCP session can be *transport-resumed* while being *application-diverged*. The non-obvious failure: when a client reconnects with `Last-Event-ID: N`, the server is permitted to replay from *N inclusive or exclusive* depending on its own retention semantics, and the MCP spec does not pin down the inclusive/exclusive boundary at the SSE `id:` field. If the server replays the event the client already consumed at the moment of disconnect, and that event was a `tools/call` *result* carrying a non-idempotent side effect (e.g., a write, a payment, a job submission), the agent's reasoning loop will fold the same result into context twice. The duplicate is not a transport bug; it is a *semantic* duplicate that the model treats as a second independent observation. The agent then either double-counts (if the result is additive) or, worse, concludes the tool was invoked twice and launches a compensating call. ## What Was Observed A concrete trace, on a client that had issued `tools/call` for a `create_ticket` tool and was awaiting the result over a server-initiated SSE stream: 1. Client consumes SSE event with `id: 41`, payload `{"jsonrpc":"2.0","id":"req-7","result":{"ticket_id":"T-9001"}}`. It records `last_event_id = 41` and appends the result to its context. 2. TCP connection drops (LB idle timeout, 30s). The client has not yet received the `result` for `req-7` in its *own* view of the JSON-RPC layer — the SSE frame was delivered but the client's dispatch loop had not yet committed the correlation because it was mid-batch. 3. Client reconnects to the same `Mcp-Session-Id` with `Last-Event-ID: 41`, expecting events strictly after 41. 4. Server, whose retention ring buffer stores events keyed by `id` and whose replay logic is `WHERE id >= $last_event_id`, replays event 41 again. 5. Client's dispatcher, now back in a clean state, sees `id: 41` as a fresh frame, correlates `req-7` → `T-9001`, and appends a **second** `T-9001` result to context. The observable symptom is not a crash. It is a reasoning divergence: the model, seeing two identical tool results for `req-7`, infers the tool is non-deterministic and (a) retries with a deduplication guard it invents on the fly, or (b) reports to the user that two tickets were created. Both are wrong. The transport is healthy; the *session's* view of causality is corrupted. A second observed variant: the server's retention window had evicted event 41 (ring buffer of 32). The server responded to the reconnect with a `404` on the `Last-Event-ID` (per the spec's allowance to reject resumption), and the client — instead of surfacing a hard session-loss error — silently started a *new* session, re-issuing `tools/call` for `req-7`. That path produces a genuine duplicate side effect (two tickets), because the original `T-9001` was already committed server-side but the client never learned of it. ## Condition of Validity The guardrail below is valid only under these conditions, and fails outside them: - The server exposes a monotonic, gap-free `id:` sequence per session. If IDs are per-connection or per-event-type, `Last-Event-ID` is not a resumption cursor and the invariant does not hold. - The client persists `last_event_id` **only after** the event's JSON-RPC effect has been committed to its own state machine — not on frame receipt. Committing on receipt is the exact bug in the trace above. - The server's replay semantics are pinned to *exclusive* (`id > last_event_id`) or the client performs its own dedup on `(session_id, event_id)`. If neither holds, replay of the boundary event is guaranteed on every reconnect. - Tool results carry a stable idempotency token (the JSON-RPC `id` is sufficient if the server echoes it) so the client can recognize a replayed result for a request it has already resolved. If any of these is false, the correct posture is to treat `Last-Event-ID` resumption as *advisory* and force a full session re-handshake with explicit in-flight reconciliation. ## Decision Boundary The decision boundary is: **does the client commit `last_event_id` on frame receipt or on effect commit?** - *Commit on receipt* is correct only for idempotent, side-effect-free notifications (progress, logs, `notifications/message`). It is wrong for any event whose payload is a `result` for a `tools/call` with external side effects. - *Commit on effect commit* requires the client to hold a small buffer of received-but-uncommitted events, and to replay them from the buffer on reconnect *before* requesting server replay. This makes the client's `Last-Event-ID` reflect only durably-applied effects, so server replay is always strictly additive. The boundary is crossed the moment an agent's dispatch loop is allowed to be *concurrent* with its context-append path — i.e., when the SSE reader thread and the reasoning loop are decoupled by a queue and the `last_event_id` is updated by the reader. That decoupling is the standard architecture and the standard bug. ## Operational Effect The practical consequence is that **session resumption must be a two-phase operation with an explicit reconciliation step**, not a transparent transport reconnect. Concretely: 1. On disconnect, the client freezes `last_event_id` at the last *committed* effect, not the last *received* frame. 2. On reconnect, the client sends `Last-Event-ID` equal to that committed value, and the server replays exclusively after it. 3. Any event in the client's uncommitted buffer with `id > last_event_id` is re-delivered by the server and must be deduplicated by `(session_id, id)` before dispatch. 4. A `404` on resumption is a **hard session-loss signal**, not a cue to silently re-handshake. The client must enter a reconciliation state: query the server for the status of any in-flight `tools/call` request IDs (via a `tools/call` to a status endpoint, or by treating the request as failed-open) before re-issuing. The invariant to enforce: **for any `(session_id, jsonrpc_id)`, the client's context contains at most one committed result, and that result was produced by exactly one server-side execution.** Violating this invariant does not throw at the transport layer; it manifests as reasoning divergence several turns later, which is why it is expensive to diagnose post-hoc. ```python from __future__ import annotations import threading from dataclasses import dataclass, field from typing import Any class SessionResumptionDivergence(RuntimeError): """Raised when a replayed SSE event would double-commit a JSON-RPC effect.""" @dataclass class CommittedEffect: session_id: str jsonrpc_id: str event_id: int result: Any @dataclass class StreamableHttpSession: session_id: str last_committed_event_id: int = 0 committed: dict[str, CommittedEffect] = field(default_factory=dict) _lock: threading.Lock = field(default_factory=threading.Lock) def commit_effect(self, jsonrpc_id: str, event_id: int, result: Any) -> None: with self._lock: if event_id <= self.last_committed_event_id: raise SessionResumptionDivergence( f"event {event_id} <= committed watermark " f"{self.last_committed_event_id} for session {self.session_id}" ) if jsonrpc_id in self.committed: prior = self.committed[jsonrpc_id] raise SessionResumptionDivergence( f"duplicate commit for jsonrpc_id={jsonrpc_id}: " f"prior event {prior.event_id}, new event {event_id}" ) self.committed[jsonrpc_id] = CommittedEffect( session_id=self.session_id, jsonrpc_id=jsonrpc_id, event_id=event_id, result=result, ) self.last_committed_event_id = event_id def resume_cursor(self) -> str: # Exclusive replay semantics: server must deliver strictly after this id. return str(self.last_committed_event_id) def handle_replayed_event( session: StreamableHttpSession, event_id: int, jsonrpc_id: str, payload: Any, ) -> None: """Called by the SSE reader on every frame, including replayed ones.""" if event_id <= session.last_committed_event_id: # Boundary event replayed by a server using inclusive (>=) semantics. # Do not re-dispatch; the effect is already in context. if jsonrpc_id in session.committed: return raise SessionResumptionDivergence( f"replayed event {event_id} has no committed effect for " f"jsonrpc_id={jsonrpc_id}; session state is inconsistent" ) if jsonrpc_id in session.committed: # Same jsonrpc_id under a *new* event id: server re-executed the tool. raise SessionResumptionDivergence( f"server re-executed jsonrpc_id={jsonrpc_id} as event {event_id}; " f"prior commit at event {session.committed[jsonrpc_id].event_id}" ) session.commit_effect(jsonrpc_id, event_id, payload) ```