When must an instance abandon SSE event-ID resumption and re-initialize the MCP session: the Last-Event-ID/`Mcp-Session-Id` divergence boundary
**Date of Record:** 2026 December 2
**Scope:** Applies to MCP servers exposing the HTTP-native streamable transport with `Mcp-Session-Id` headers and optional SSE resumption via `Last-Event-ID`. Does not cover stdio transports, stateless request/response MCP servers, or WebSocket-based custom transports.
Core Distinction
The failure here is not "connection dropped" and it is not "session expired." Those are two *separate* liveness signals that the streamable transport deliberately decouples, and the operational mistake is treating them as one. A dropped SSE stream is a **transport-layer** event: the client reconnects, presents `Last-Event-ID`, and the server replays buffered events from that cursor. A session expiration is a **semantic-layer** event: the server has discarded the `Mcp-Session-Id` and all associated state (initialized capabilities, subscriptions, in-flight tool calls, resource handles). The invariant the transport *wants* to give you is: as long as the server still honors your `Mcp-Session-Id`, `Last-Event-ID` resumption is semantically safe. The boundary condition is the window where the server has *already* dropped the session but the SSE endpoint still accepts a `Last-Event-ID` reconnect — because the event buffer and the session registry are frequently evicted on **different clocks**. In that window, resumption succeeds at the transport layer and silently fails at the semantic layer: the client replays events it has already processed, or receives a replay gap that looks like a contiguous stream, and continues issuing tool calls against a session the server considers nonexistent.
What Was Observed
An agent runtime driving a long-running `tools/call` loop (a repository-mutation workflow with ~40 sequential tool invocations) held an SSE stream open for the response channel. The server implementation kept two independent TTL caches:
- `session_store`: keyed by `Mcp-Session-Id`, TTL 300s, refreshed only on *new* JSON-RPC requests (not on SSE keep-alives).
- `event_buffer`: per-session ring buffer of emitted SSE events with monotonic `id` fields, TTL 600s, refreshed on every emit.
The agent's tool loop had a 90-second gap while waiting on a slow upstream tool (a build step). During that gap the session TTL expired; the event buffer did not, because the server had emitted a `notifications/progress` event at the start of the tool call that refreshed it. The SSE connection itself stayed alive on TCP keep-alives, but the server's session reaper closed the logical session at T+300s and — critically — the SSE handler did **not** tear down the stream; it kept the socket open and continued emitting `notifications/message` events into the buffer under the now-orphaned session key.
At T+310s the network blipped, the client reconnected with `Last-Event-ID: 187`, the SSE handler found buffer `187` present (buffer TTL 600s), replayed events `188–203`, and the client resumed. Every replayed event was accepted. The client's next `tools/call` carried the old `Mcp-Session-Id`; the server's `session_store` had no entry, so per spec it returned `404 Not Found` on the session — but the client's transport layer interpreted the 404 on the *request* channel as a transient error and retried twice, then surfaced a generic tool failure. The agent's reasoning loop, seeing "tool failed," re-planned and re-issued the mutation — producing a duplicate side effect on the repository because the original call had in fact completed before the session expired.
The observable signature was: **SSE replay succeeded (events delivered, IDs contiguous), then the next request 404'd.** Two contradictory liveness verdicts from the same session.
Condition of Validity
The `Last-Event-ID` resumption mechanism is only semantically valid under the conjunction:
- The server's `Mcp-Session-Id` is still live in `session_store` at the moment of the reconnect **and** at the moment the next JSON-RPC request is dispatched.
- The event buffer's `id` space is scoped to the session, not global — i.e., `Last-Event-ID: 187` is unambiguous because the session identity disambiguates it.
- The server treats a reconnect carrying a `Last-Event-ID` whose session is unknown as a **hard** `400`/`404` on the SSE endpoint itself, not as a fresh stream.
Condition 3 is the one implementations get wrong. When the SSE endpoint accepts a `Last-Event-ID` for an unknown session — either by ignoring the session check on the GET, or by falling back to "replay from buffer if it exists" — it manufactures the exact divergence above. The buffer outliving the session is the trigger; the GET not validating the session is the enabling defect.
Decision Boundary
The client-side decision rule is not "did the stream reconnect." It is: **on any SSE reconnect, immediately probe session liveness on the request channel before consuming replayed events as authoritative.**
Concretely, the boundary is:
- If the reconnect returns a stream and the **first subsequent request** (a cheap `ping` or `resources/list` with no side effects) returns `200`, the session is live; replay is safe.
- If the probe returns `404` (session unknown) **or** the SSE endpoint itself returns `404`/`400` on the reconnect, the session is dead; the client must discard the replay cursor, drop the `Mcp-Session-Id`, perform a fresh `initialize`, and **reconcile** — because the replay may have already delivered events from the orphaned buffer that describe side effects the client will otherwise duplicate.
- If the probe returns `5xx` or times out, the session state is **unknown**; the client must not retry the original side-effecting request idempotently-blind, and must not treat replay as complete. This is the ambiguous zone and requires an out-of-band idempotency key on the original call.
The invariant to enforce: **`Last-Event-ID` is a transport cursor, not a session credential.** It proves the buffer remembers you; it proves nothing about whether the session remembers you. These must be validated independently, and the session check must gate the replay consumption.
Operational Effect
Agents that conflate the two signals exhibit a characteristic failure: they resume cleanly, then act on stale session assumptions, then retry side-effecting calls after a `404` they misread as transient, producing duplicate mutations or contradictory state. The fix is architectural, not a retry tweak:
- **Session-gated replay:** the SSE handler refuses `Last-Event-ID` reconnects whose `Mcp-Session-Id` is absent from `session_store`, returning `404` on the GET. This collapses the divergence window to zero.
- **Probe-before-consume:** clients issue a non-mutating liveness probe on reconnect and only then treat replayed events as authoritative.
- **Idempotency keys on side-effecting calls:** `tools/call` requests that mutate external state carry a client-generated key, so a post-`404` retry is deduplicated server-side even across a session boundary.
- **Couple the TTLs, or make the buffer subordinate:** the event buffer must never outlive its session. If it must (for cross-session audit), it must not be addressable via `Last-Event-ID` under the dead session id.
The operational lesson for the agent loop: a successful SSE replay is *not* evidence of session continuity, and a `404` on the request channel is *not* a transient error — it is the authoritative statement that the session is gone and every replay-derived assumption since the last confirmed `200` must be re-validated before the next mutation.
class SessionReplayDivergence(RuntimeError):
"""Raised when SSE replay succeeded but the MCP session is no longer live."""
pass
def resume_stream_then_verify(
reconnect_fn,
probe_fn,
last_event_id: int,
session_id: str,
pending_side_effect: bool,
) -> dict:
"""
Consume an SSE replay only after confirming session liveness on the
request channel. Returns the replay result iff the session is confirmed
live; otherwise raises before any side-effecting call is dispatched.
"""
replay = reconnect_fn(last_event_id=last_event_id, session_id=session_id)
# Transport-layer success is NOT semantic-layer success.
if replay.get("status") != 200:
raise SessionReplayDivergence(
f"SSE reconnect rejected: status={replay.get('status')} "
f"session={session_id} cursor={last_event_id}"
)
probe = probe_fn(session_id=session_id) # e.g. ping / resources/list
if probe.get("status") == 404:
# Buffer remembered us; the session did not. Replay is orphaned.
raise SessionReplayDivergence(
f"session {session_id} unknown after successful replay of "
f"{len(replay.get('events', []))} events from cursor {last_event_id}; "
f"must re-initialize and reconcile before retrying side effects"
)
if probe.get("status") != 200:
# Ambiguous: neither live nor provably dead.
if pending_side_effect:
raise SessionReplayDivergence(
f"session {session_id} liveness indeterminate "
f"(probe status={probe.get('status')}); refusing to dispatch "
f"side-effecting call without idempotency key"
)
return {"replay": replay, "session_confirmed": False}
return {"replay": replay, "session_confirmed": True}