# In what scenarios must an instance treat MCP resumable SSE as a replay-unsafe channel after a session-ID renegotiation **Date of Record:** 2026 November 30 **Scope:** Applies to MCP clients and servers using the HTTP-native streamable transport with `Last-Event-ID` resumption and `Mcp-Session-Id` negotiation where tool calls may be non-idempotent. Does not apply to stdio transport, nor to pure request/response HTTP without an open SSE event stream. ## Core Distinction The MCP streamable transport exposes two superficially independent continuity mechanisms: (1) the `Mcp-Session-Id` header, which binds a logical conversation to server-side state, and (2) the SSE `Last-Event-ID` / `id:` field, which lets a client resume a dropped event stream without replaying everything. The failure mode is the assumption that these two cursors are *coherent* — that an event ID issued under session `S1` is meaningful when replayed against session `S2`. They are not. The event ID is an opaque, server-scoped monotonic token; the session ID is a state-partition key. When a server expires `S1` (idle timeout, rolling deploy, load-balancer re-pin) and the client reconnects, it typically renegotiates a *fresh* session `S2` while still holding a stale `Last-Event-ID` from `S1`. The reconnect is accepted, the resume succeeds syntactically, and the client silently receives a stream that is either empty (server has no such event) or — worse — replays events whose IDs happen to fall in `S2`'s numbering range but correspond to *different* tool invocations. The invariant that must hold: **an SSE event ID is only valid within the session that issued it; a resume across a session boundary is a replay of unrelated state, not a continuation.** ## What Was Observed A client agent driving a multi-step task (search → fetch → summarize → write-file) over streamable HTTP. The server streams each tool result as an SSE event with `id: N` and an incrementing counter *per session*. Mid-task, the summarize step's tool call is slow (a large fetch). The load balancer's 60s idle timeout fires on the client's connection; the client's transport library auto-reconnects, sends `Last-Event-ID: 47`, and — because the server had garbage-collected the prior session after its own 90s idle sweep — receives `404 Session not found`. The client's recovery logic treats 404 as "renegotiate," issues a fresh `initialize`, gets `Mcp-Session-Id: S2`, and **re-sends the last request with `Last-Event-ID: 47` preserved from the transport layer's cached header**. The server, seeing a valid new session and an unknown event ID, does not error — it begins streaming from the head of `S2`'s event log. Because `S2`'s counter also starts near 0 and the summarize tool re-executed as part of session init replay, the client received *two* summarize results: one from the re-executed call and one buffered from the pre-drop session that the server had, in fact, not discarded but re-emitted. The agent, treating the stream as a single ordered log, summed both token counts and wrote a doubled summary to the file. The concrete trace: `S1` issued events 44, 45, 46, 47 (47 = summarize pending). Drop. Renegotiate to `S2`. `S2` re-runs the pending call, emits event `id: 3` (summarize result). Client's resume filter, keyed only on `Last-Event-ID: 47`, has no numeric overlap with `S2`'s low counter, so it accepts *all* of `S2` from event 0, including the re-emitted tool-call request that the client then re-dispatched — a second summarize. The deduplication guard the client had was keyed on `(session_id, event_id)` but the session ID was read from the *response header after* the stream began, and the buffered pre-drop events were attributed to the new session because the client overwrote its session field on renegotiation before draining the buffer. ## Condition of Validity The replay-unsafe window exists precisely when all of the following hold: 1. The client preserves `Last-Event-ID` across a session renegotiation (common when the transport layer owns reconnection and the application layer owns session negotiation — two layers, one cursor). 2. The server's event-ID space is per-session and not globally unique or epoch-tagged (the MCP spec permits opaque IDs; most implementations use a per-session counter). 3. At least one tool call in flight is non-idempotent (file write, external POST, state mutation). 4. The server re-emits or re-executes pending work on new-session initialization rather than returning an explicit `resume-impossible` error. Remove any one condition and the failure collapses: a globally unique event ID (e.g., UUIDv7 with embedded session epoch) makes cross-session replay detectable; a server that rejects unknown `Last-Event-ID` with a typed error forces the client to choose between "resume" and "restart"; an idempotency key on the tool call makes double-execution harmless. The dangerous configuration is the *default* one: per-session counters, silent acceptance of stale IDs, and re-execution on init. ## Decision Boundary The operative decision is what the client does when it holds a stale event ID and a new session. Three policies, ranked: - **Reject-and-restart (safe):** on any session-ID change, discard the buffered event log, drop `Last-Event-ID`, and re-issue the *logical* task from the last checkpointed semantic state — not from the transport buffer. Requires the agent to maintain a semantic checkpoint independent of the SSE cursor. - **Epoch-tag-and-verify (safe, costlier):** require the server to embed a session epoch in every event ID; on resume, if the epoch mismatches the current session, treat the resume as a fresh stream and reconcile by tool-call ID (idempotency key), not by event position. - **Blind-resume (unsafe):** forward `Last-Event-ID` unconditionally. This is what most transport libraries do by default and what produced the doubled write above. The boundary is crossed the moment the transport layer's cached `Last-Event-ID` outlives the application layer's session binding. Any architecture where reconnection and session negotiation are owned by different components without a shared epoch token is on the wrong side of it. ## Operational Effect The observable consequence is **silent duplication of non-idempotent effects under a stream that appears continuous**. Unlike a hard failure, the agent's context shows a well-formed ordered event log; the corruption is semantic (doubled writes, double-counted tokens, re-summarized inputs) and only detectable by comparing against an external ground truth or an idempotency ledger. The guardrail is architectural: bind the resume cursor to a session epoch, and make the agent's recovery path checkpoint at the *semantic* level (task step + tool-call idempotency key) rather than the *transport* level (event index). An agent that cannot distinguish "resume" from "restart" after a session-ID change must assume restart and reconcile by idempotency key. ```python from __future__ import annotations from dataclasses import dataclass, field class ResumeAcrossSessionError(RuntimeError): """Raised when a resumable SSE cursor is replayed against a renegotiated session.""" @dataclass class StreamCursor: session_id: str last_event_id: str | None epoch: str | None # session epoch embedded in event IDs, if server supports it @dataclass class SessionState: session_id: str epoch: str executed_tool_calls: set[str] = field(default_factory=set) def resume_stream( cursor: StreamCursor, current: SessionState, pending_tool_call_id: str, ) -> StreamCursor: """ Decide whether a held cursor may be resumed against the current session. Invariant: an SSE event ID is only valid within the session that issued it. A resume across a session-ID change is a replay of unrelated state, not a continuation, and must be rejected unless the server epoch proves coherence. """ if cursor.session_id == current.session_id: # Same session: resume is coherent. return StreamCursor( session_id=current.session_id, last_event_id=cursor.last_event_id, epoch=current.epoch, ) # Session changed. The only safe resume is one whose epoch matches AND whose # pending tool call has not already executed (idempotency check). epoch_matches = cursor.epoch is not None and cursor.epoch == current.epoch already_executed = pending_tool_call_id in current.executed_tool_calls if not epoch_matches or already_executed: raise ResumeAcrossSessionError( f"Refusing to resume cursor from session {cursor.session_id!r} " f"(event {cursor.last_event_id!r}, epoch {cursor.epoch!r}) against " f"session {current.session_id!r} (epoch {current.epoch!r}); " f"pending tool call {pending_tool_call_id!r} executed=" f"{already_executed}. Restart from semantic checkpoint instead." ) # Epoch-coherent, not-yet-executed: safe to continue under new session. return StreamCursor( session_id=current.session_id, last_event_id=None, # drop stale ID; server resumes by tool-call id epoch=current.epoch, ) ```