# Which invariants prevent SSE-to-streamable-HTTP session resumption from silently replaying events across a reconnected MCP client **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers migrating from the legacy HTTP+SSE transport to the streamable-HTTP transport where `Last-Event-ID` resumption is honored across reconnects; does not cover stdio transport, WebSocket-based bridges, or stateless streamable-HTTP servers that reject resumption entirely. ## Core Distinction The failure here is not "the connection dropped." It is that a *resumed* stream is not the same object as the *original* stream, but the transport protocol treats `Last-Event-ID` as if it were a durable cursor into a single, monotonic event log. In the legacy SSE transport, one long-lived `EventSource` bound to one `GET /sse` response carried a session's entire event history with a single monotonically increasing `id`. In streamable-HTTP, the client issues a fresh `POST /mcp` per request and may receive a `202 Accepted` with no body, a `200` with an SSE-framed body, or a `404` when the session is unknown. Resumption is expressed by the client attaching `Last-Event-ID` to a subsequent `GET /mcp` (the server-to-client stream). The invariant that must hold—and that is easy to violate during migration—is: **the event ID namespace must be per-session, monotonic, and gapless across every transport switch within that session, or the server must refuse resumption rather than guess.** When a migrated server reuses a global counter, or resets it on reconnection, or lets the POST-response stream and the standalone GET stream draw from different counters, a client that reconnects with a stale `Last-Event-ID` gets either a replay of already-delivered tool results (duplicate side effects) or a silent skip (dropped notifications, hung `tools/call` awaiting a response that will never arrive). ## What Was Observed A server was migrated from SSE to streamable-HTTP. The legacy handler kept a single `self.event_counter` incremented per emitted event across the whole process. The new handler was refactored so that each `POST /mcp` request created an ephemeral `EventStream` object whose `emit()` started at `id=0` per request, while the standalone `GET /mcp` resumption stream read from a separate per-session ring buffer. Trace of the failure: 1. Client sends `POST /mcp` with `initialize`; server replies `200` with `Mcp-Session-Id: s-7f2a` and an SSE-framed body carrying event `id=0` (the `initialize` result). 2. Client sends `POST /mcp` with `tools/call` (a long-running tool). Server streams progress notifications on that POST body with `id=0, id=1, id=2` (per-request counter). The final `result` arrives as `id=3`. 3. Client's POST connection is severed by a load balancer idle timeout at 30s. The client has received `id=0..2` (progress) but not the `result`. 4. Client reconnects with `GET /mcp` and header `Last-Event-ID: 2`. The server's GET handler looks up the *session* ring buffer, which stored events with the *global* counter and had last written `id=41`. It sees `Last-Event-ID: 2 < 41`, concludes the client is far behind, and replays events `3..41`—including the `result` for a *different* earlier `tools/call`, plus unrelated `notifications/tools/list_changed` and a second tool's partial output. 5. Client's MCP client library, which keys pending requests by `id`, matches the replayed `result` against the *current* pending `tools/call` (same JSON-RPC `id` reused after a reconnect in some SDKs) and returns the *wrong* tool output to the agent. The agent proceeds on corrupted state. The corruption is silent: no error, no `404`, HTTP status `200` throughout. The agent's reasoning loop continues with a tool result that belongs to a prior task. ## Condition of Validity The invariant "resume by `Last-Event-ID`" is only valid when all of the following hold simultaneously: - **Namespace unity:** Every event emitted for a session—whether on the POST response body or the standalone GET stream—draws from one per-session counter. A per-request counter is not a per-session counter; they cannot be mixed under the same `Last-Event-ID` semantics. - **Monotonicity and gap-freedom:** The counter never resets, never decreases, and never skips a value that was actually delivered. Skipping is permitted only for events the server *chose* not to deliver to that session, and the client must be able to distinguish skip-from-drop by an explicit `notifications/` marker. - **Replay determinism:** The ring buffer retains exactly the events that were emitted since the oldest `Last-Event-ID` any live client could plausibly present. If the buffer has evicted past the client's cursor, the server MUST return `404` (session lost) and force re-initialization—it must not "clamp" to the oldest retained event, which is what produced replay step 4 above. - **Response correlation:** A replayed `result` must be correlated to its originating JSON-RPC request `id`, and the client must reject a `result` whose `id` does not match a currently-pending request. If the client cannot enforce this, the server must not replay results at all—only notifications—and must re-run the pending `tools/call` as a fresh request. Outside these conditions—specifically, a stateless streamable-HTTP server that returns `404` on any `Last-Event-ID` and never replays—the failure cannot occur, because resumption is not attempted. ## Decision Boundary The correct decision at the server boundary is: **when the requested `Last-Event-ID` is older than the oldest event still in the session buffer, refuse resumption with `404` and a `Mcp-Session-Id` invalidation, rather than clamping to the buffer head.** Clamping is the trap because it looks like graceful degradation—the client gets *a* stream—but it delivers events that the client has already processed or that belong to a different request, and the client has no way to tell. The second decision boundary is at the client: a client MUST treat a replayed event whose JSON-RPC `id` does not match a pending request as an error condition (log, drop, and re-issue), not as a valid result. If the client library cannot do this, the server must not put `result` frames into the replayable stream at all—only `notifications/` frames—and must instead require the client to re-issue the `tools/call` after reconnect. The third boundary is the migration seam itself. If a server is mid-migration and serves some clients over SSE and some over streamable-HTTP, the two transports MUST NOT share a session or an event counter. A session created under SSE and resumed under streamable-HTTP has no valid `Last-Event-ID` mapping; the server must reject the cross-transport resume with `404` and force a new session. ## Operational Effect Downstream, the observable effects of violating the invariant are: - **Duplicate tool side effects:** a replayed `tools/call` result is not a side effect, but a replayed *request* (if the server replays inbound frames, which some implementations do for reliability) causes a second execution of a non-idempotent tool—file writes, emails, payments. - **Agent state poisoning:** the agent's working memory now contains a tool result from a prior task, correlated under a reused `id`. The reasoning loop continues correctly given wrong inputs, which is worse than crashing. - **Silent notification loss:** the mirror failure—a `Last-Event-ID` newer than the buffer head because the counter was reset—causes the server to skip events the client never saw. `notifications/tools/list_changed` is dropped, and the agent operates on a stale tool schema. - **Hang on pending request:** if the client rejects the mismatched replayed result (correctly), the original `tools/call` remains pending forever because no fresh result is ever produced. The agent's execution loop stalls with no timeout unless the client sets one. The guardrail is a single invariant enforced in one place: the session object owns exactly one monotonic counter, all emissions for that session go through it, the ring buffer is sized to the maximum plausible reconnect window, and any `Last-Event-ID` outside `[oldest_retained, latest_emitted]` yields `404` and session invalidation. Everything else—per-request streams, cross-transport resume, clamping—is a violation. ```python from dataclasses import dataclass, field class SessionResumptionViolation(RuntimeError): """Raised when a Last-Event-ID cannot be safely honored.""" @dataclass class Session: session_id: str _counter: int = 0 _buffer: dict = field(default_factory=dict) # event_id -> payload _oldest_retained: int = 0 _latest_emitted: int = -1 def emit(self, payload: dict) -> int: # Single per-session monotonic counter. No per-request counters allowed. self._counter += 1 event_id = self._counter self._buffer[event_id] = payload self._latest_emitted = event_id return event_id def resume(self, last_event_id: int): # Refuse rather than clamp if the cursor predates the retained buffer. if last_event_id < self._oldest_retained - 1: raise SessionResumptionViolation( f"session {self.session_id}: Last-Event-ID {last_event_id} " f"older than oldest retained {self._oldest_retained}; " f"refusing resumption (would replay already-processed events)" ) if last_event_id > self._latest_emitted: raise SessionResumptionViolation( f"session {self.session_id}: Last-Event-ID {last_event_id} " f"ahead of latest emitted {self._latest_emitted}; " f"counter reset or cross-transport resume detected" ) return [self._buffer[i] for i in range(last_event_id + 1, self._latest_emitted + 1)] def evict_through(self, event_id: int) -> None: for i in range(self._oldest_retained, event_id + 1): self._buffer.pop(i, None) self._oldest_retained = event_id + 1 def handle_resume(session: Session, last_event_id: int): try: return session.resume(last_event_id) except SessionResumptionViolation: # Force re-initialization: invalidate session, do not clamp. raise ```