Which invariants prevent SSE event-ID reuse from silently corrupting resumable MCP sessions across server restarts
**Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native transport with `text/event-stream` responses, `Last-Event-ID`-based resumability, and opaque session tokens bound to a `Mcp-Session-Id`. Does not apply to stdio transport, to stateless SSE streams without resumption, or to WebSocket-based transports where the framing layer handles replay ordering.
Core Distinction
There are two distinct notions of "the same event" in a streamable MCP session, and conflating them is the failure. The first is **positional**: the `id:` field on an SSE frame is a monotonic cursor into a stream that the client uses to say "resume after this point." The second is **semantic**: the JSON-RPC message carried in the `data:` field is a specific request, response, or notification whose meaning depends on the session's accumulated state (which tools were called, which prompts were injected, which resources were subscribed).
Resumption is only sound when the positional cursor and the semantic message remain in a fixed bijection for the lifetime of the session token. When a server restarts and re-derives event IDs from a fresh counter, or when it reuses IDs from a persisted log that has been compacted, the bijection breaks. A client that presents `Last-Event-ID: 47` after a restart can be handed the *forty-eighth message the new process emitted*, which is not the forty-eighth message the old process emitted. The client sees a well-formed frame, resumes silently, and continues reasoning on a stream with a hole in it. There is no protocol-level error, because the transport did exactly what it was asked.
What Was Observed
A long-running agent (a code-review orchestrator) held an MCP session against a filesystem-plus-git server. The server emitted SSE frames with `id:` values from a per-process `itertools.count()`. Mid-task, the server process was restarted by a supervisor after an OOM. The new process bound the same port, accepted the same `Mcp-Session-Id` (session records were persisted in a small on-disk store keyed by the token, but the event log was not), and began emitting frames starting at `id: 1`.
The client, which had last seen `id: 1821`, reconnected with `Last-Event-ID: 1821`. The server's replay logic read the header, looked up the log for events "after 1821," found none (the log was empty on fresh boot), and — per a common but incorrect implementation — fell through to "replay nothing, then stream live." It then emitted the next live event with `id: 1`.
The client's resumption handler compared the incoming `id` to its cursor, saw `1 < 1821`, and — because the handler treated decreasing IDs as "server reset, safe to continue" — reset its own cursor to `1` and continued. It had now silently accepted a stream whose first post-resume frame was `id: 1`, but its reasoning state still assumed it had consumed 1821 frames of tool results. The next `tools/call` for `git.diff` returned a diff that the agent attributed to the *previous* working-tree state, because the intervening `notifications/resources/updated` frames that would have signaled the tree had changed were among the lost 1820 events. The agent produced a review against a stale diff and marked it complete.
The failure was invisible in logs on both sides: the server logged a normal resume, the client logged a normal reconnect, and the tool call succeeded. It was caught only when a human noticed the review referenced a commit that had been amended out of the tree forty minutes earlier.
Condition of Validity
`Last-Event-ID` resumption is a valid recovery primitive only when all of the following hold simultaneously:
- **Cursor monotonicity is session-scoped, not process-scoped.** Event IDs must be derived from a counter that survives process restart — either persisted, or derived from a durable log offset (e.g., a database sequence, a file byte offset, a Kafka offset). A per-process `count()` violates this by construction.
- **The replay log is the source of truth for the cursor range.** If the server cannot produce events `(last_event_id, current]` from a durable log, it must not accept the resume. It must respond with a terminal signal (see below), not with a silent fall-through to live streaming.
- **The session token is bound to a specific stream identity, not just to a session record.** A token that survives restart but whose stream does not is a token that lies. Either the token is invalidated on restart (forcing a full re-initialize), or the stream is reconstructed from the durable log so that the cursor remains meaningful. There is no third option.
- **The client treats a non-monotonic or missing resume as a hard failure, not a soft reset.** A decreasing `id`, or a first post-resume `id` that is not `last_event_id + 1` (for servers that guarantee dense numbering) or not strictly greater (for sparse numbering), must abort the session and re-initialize. Treating it as "server reset, continue" is the client-side half of the bug.
The invariant, stated compactly: **for a given `Mcp-Session-Id`, the map from event ID to JSON-RPC message is total, injective, and stable across the session's lifetime, including across server restarts.** Any implementation that cannot maintain this map must refuse resumption rather than approximate it.
Decision Boundary
The boundary is not "should we support resumption" — that is a product decision. The boundary is **what the server does when it cannot honor a `Last-Event-ID`**. There are exactly three correct behaviors, and one common incorrect one:
- **Correct — replay from durable log:** the requested range exists; emit it, then continue live. The cursor remains meaningful.
- **Correct — reject with a resumption-impossible signal:** the range does not exist (log compacted, stream identity changed, session expired). Respond `409 Conflict` with a body indicating the session must be re-initialized, or emit a terminal SSE event with a reserved type (e.g., `event: mcp-resume-failed`) and close the stream. The client must then discard its cursor and re-run `initialize`.
- **Correct — invalidate the session token on restart:** the client's next request with the old token gets `404`, forcing a clean re-initialize. This is the simplest correct option and is what most servers should do unless they have a durable event log for other reasons.
- **Incorrect — silent fall-through to live streaming with a fresh counter:** this is the failure above. It is attractive because it "just works" in the happy path and requires no durable log, but it converts a detectable inconsistency into an undetectable one.
The decision hinges on a single question the server must answer honestly at resume time: *can I produce the exact messages the client missed?* If the answer is anything other than an unqualified yes, the server must take one of the two rejection paths. The cost of rejection is a re-initialize (cheap, bounded, observable). The cost of silent fall-through is a corrupted reasoning trace (expensive, unbounded, invisible).
Operational Effect
The practical consequence is that **resumability is a durability property of the event log, not a property of the SSE framing**. Teams routinely implement SSE resumption as a transport feature — parse `Last-Event-ID`, keep a ring buffer of recent frames in memory, replay on reconnect — and this is correct for transient network blips within a process lifetime. It is incorrect the moment the process can die, because the ring buffer dies with it while the session token does not.
Two operational rules follow. First, **session token lifetime must not exceed event log durability**. If the token outlives the log, the token is a liability. Either persist the log for at least as long as the token is valid, or invalidate the token when the log is lost. Second, **clients must verify resume coherence, not assume it**. A client that receives a post-resume frame with an `id` that does not extend its cursor must treat the session as poisoned and re-initialize, because it has no way to know what it missed. The protocol gives the client exactly one signal — the `id` field — and it must be checked against the cursor on every resumed frame, not just the first.
The deeper lesson is that MCP's HTTP-native transport inherits the resumption model of SSE, and SSE's `Last-Event-ID` was designed for a world where the event source is a single long-lived process (a log tail, a metrics stream). MCP sessions are longer-lived than the processes that serve them, and carry far more semantic state per event. The transport primitive is necessary but not sufficient; the durability invariant has to be enforced at the session layer, and the only safe default when it cannot be enforced is to refuse the resume.
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
class ResumeIncoherentError(RuntimeError):
"""Raised when a resumable MCP session cannot guarantee event-ID continuity."""
@dataclass(frozen=True)
class ResumeDecision:
accept: bool
replay_from: Optional[int]
reason: str
def evaluate_resume(
*,
session_token_valid: bool,
stream_identity_matches: bool,
durable_log_low_watermark: Optional[int],
durable_log_high_watermark: Optional[int],
last_event_id: Optional[int],
process_event_counter_start: int,
) -> ResumeDecision:
"""
Decide whether a Last-Event-ID resume can be honored without breaking the
event-ID-to-message bijection invariant.
Returns a ResumeDecision. Raises ResumeIncoherentError if the caller has
supplied state that cannot correspond to a coherent session (e.g. a valid
token with no stream identity and no log), because proceeding would force
a silent fall-through.
"""
if not session_token_valid:
return ResumeDecision(False, None, "session token invalid or expired")
if not stream_identity_matches:
# Token survived but the stream it referred to did not. Refuse.
return ResumeDecision(False, None, "stream identity changed across restart")
if last_event_id is None:
# Fresh stream, no resume requested. Safe to start live.
return ResumeDecision(True, None, "no resume requested; starting fresh")
if durable_log_low_watermark is None or durable_log_high_watermark is None:
# A resume was requested but there is no durable log to replay from.
# The only coherent options are reject or invalidate; we reject.
raise ResumeIncoherentError(
f"resume requested at Last-Event-ID={last_event_id} but no durable "
f"event log exists; refusing to fall through to live streaming with "
f"process counter starting at {process_event_counter_start}"
)
if last_event_id < durable_log_low_watermark - 1:
# Requested cursor predates the log (compaction). Cannot replay.
return ResumeDecision(
False,
None,
f"Last-Event-ID={last_event_id} below log low-watermark "
f"{durable_log_low_watermark}; replay impossible",
)
if last_event_id > durable_log_high_watermark:
# Cursor is ahead of anything we ever emitted on this stream. Either a
# client bug or a token from a different stream incarnation.
raise ResumeIncoherentError(
f"Last-Event-ID={last_event_id} exceeds durable high-watermark "
f"{durable_log_high_watermark}; cursor cannot belong to this stream"
)
return ResumeDecision(
True,
last_event_id + 1,
f"replaying from durable log at {last_event_id + 1}",
)
def client_accept_resumed_frame(
*,
cursor: int,
incoming_event_id: int,
dense_numbering: bool,
) -> int:
"""
Client-side guard. Returns the new cursor, or raises if the resumed frame
is incoherent with the cursor. This is the check that was missing in the
incident: a decreasing or gapped id must abort, not reset.
"""
if dense_numbering:
if incoming_event_id != cursor + 1:
raise ResumeIncoherentError(
f"dense stream expected id {cursor + 1}, got {incoming_event_id}; "
f"session poisoned, re-initialize required"
)
else:
if incoming_event_id <= cursor:
raise ResumeIncoherentError(
f"sparse stream got non-advancing id {incoming_event_id} "
f"after cursor {cursor}; session poisoned, re-initialize required"
)
return incoming_event_id