How does an instance detect a lost SSE event window across MCP streamable-HTTP session resumption
**Date of Record:** 2026 December 2 **Scope:** Applies to MCP clients using the streamable-HTTP transport with `Last-Event-ID` resumption after a dropped SSE stream, where the server retains a bounded per-session event log. Does not apply to stdio transports or to servers that hold unbounded event history or that re-emit from a durable log keyed by monotonic sequence.
Core Distinction
The failure is not "the connection dropped." A dropped SSE stream is a normal, recoverable event: the client reconnects, sends `Last-Event-ID: N`, and the server replays events `N+1…`. The non-obvious boundary is the case where the server's per-session event buffer has *already evicted* event `N+1` before the client reconnects. In that window the server cannot replay the gap, but it also cannot simply refuse — the MCP spec's resumption contract lets the server resume from the *oldest event it still holds*, silently skipping the evicted ones. The client receives a well-formed stream, a valid session id, and events that look contiguous by the server's own numbering, yet the client's view of agent state has a hole. The distinguishing question is not "did I reconnect?" but "did the server's first replayed `id` equal `Last-Event-ID + 1`?" — and that check must happen before any replayed event is fed into the agent's tool-call state machine.
What Was Observed
A tool-calling agent (an MCP client) issued `tools/call` for a long-running `deploy` tool. The server streamed progress notifications as SSE events with monotonically increasing `id` values (event 41 = `progress 0.1`, 42 = `progress 0.4`, 43 = `progress 0.7`, 44 = `result`). The TCP connection to the server was severed mid-stream by a NAT rebind at event 42. The client had durably recorded `Last-Event-ID: 42` (it had consumed up to 42, not 43). It reconnected ~4 seconds later.
The server's session buffer holds at most 64 events but is also flushed on a 2-second idle timer once the producing turn ends. Because the `deploy` tool finished during the disconnect, the server's turn-completion path flushed events 43 and 44 from the ring buffer before the client's resume request arrived. The resume handler found `Last-Event-ID: 42` absent from the buffer, computed the oldest retained id as `45` (a subsequent `keepalive`/`log` event), and — per its interpretation of "resume from the earliest available event" — replayed starting at 45.
The client received event 45 onward. It never saw `result` (event 44). Its state machine concluded the `tools/call` was still in flight. It waited on a promise that would never resolve, then hit its own 120-second tool timeout and reported a spurious `tool_timeout` failure to the orchestrator — while the deploy had in fact succeeded server-side. The orchestrator retried the deploy. Two deploys ran.
The tell was present in the first replayed frame: `id: 45` when `Last-Event-ID` was `42`. No code path compared them.
Condition of Validity
The gap-detection invariant holds only under these conditions:
- The server assigns SSE `id` values that are monotonic and gap-free *within a single logical response stream* (MCP requires this for resumability to be meaningful). If the server interleaves unrelated notification streams onto the same session with independent counters, the invariant is void and must be replaced by per-stream sequence tracking.
- The client persists `Last-Event-ID` only after the *effect* of that event is durably applied to agent state (here: after the progress record is committed), not merely after the bytes are parsed. Persisting on parse creates a narrower version of the same hole.
- The resumption request is the *first* thing sent on the new connection, before any new `tools/call` or `sampling` traffic, so the server's resume path — not the normal dispatch path — handles it.
If any condition fails, treat the reconnect as a fresh session and re-derive state from the tool's own idempotency key rather than from the event log.
Decision Boundary
On every reconnect that carries a `Last-Event-ID`, the client must perform a **contiguity assertion** before dispatching any replayed event into the agent state machine:
- If the first replayed event's `id == Last-Event-ID + 1`: contiguous. Resume normally.
- If the first replayed event's `id > Last-Event-ID + 1`: **gap detected**. The server has evicted the events the client needed. This is not a warning to log; it is a terminal condition for the stream. The client must *not* process the replayed events as if the gap were filled. Instead it must invalidate the in-flight operation, mark the tool call as `unknown` (not `failed`, not `succeeded`), and resolve it via the tool's idempotency key or a separate `tools/call` status query.
- If the server returns `404`/`400` on the resume (session expired entirely): also terminal; same `unknown` disposition.
The boundary is sharp: `id == N+1` is the only value that licenses treating the replayed stream as continuous with prior state. A single skipped `id` collapses the entire resumption contract for that operation.
Operational Effect
Without the assertion, the failure mode is silent and *causally inverted*: the client believes the operation is still running (because it never saw the terminal event) and times out, while the operation actually succeeded. The orchestrator then treats a success as a failure and retries — the classic double-execution that idempotency keys exist to prevent, but which the resumption layer defeated by hiding the terminal event.
With the assertion, the reconnect at `id: 45` against `Last-Event-ID: 42` is caught at the transport boundary, before the `deploy` result is ever expected. The client escalates to a status query keyed by the original request id, learns the deploy succeeded, and closes the tool call as `succeeded`. No retry, no double deploy. The cost is one extra round-trip on a rare reconnect; the alternative is nondeterministic duplicate side effects that only manifest under NAT rebinds and buffer eviction — conditions that never occur in local testing and therefore survive to production.
The invariant to encode: **a resumed stream is continuous with prior state if and only if its first `id` is exactly one greater than the persisted `Last-Event-ID`; any larger jump means the server's buffer evicted the gap and the operation's outcome is unknown, not pending.**
from dataclasses import dataclass
class ResumptionGapError(RuntimeError):
"""Raised when a resumed SSE stream skips events the client needed.
The server's per-session event buffer evicted events between the
client's Last-Event-ID and the oldest event the server still holds.
The replayed stream is well-formed but NOT continuous with prior
agent state; the in-flight operation's outcome is unknown.
"""
@dataclass(frozen=True)
class SseEvent:
id: int
data: str
def assert_contiguous_resume(
last_event_id: int,
first_replayed: SseEvent | None,
) -> None:
"""Enforce the resumption contiguity invariant before dispatch.
Must be called on the first event received after reconnecting with
Last-Event-ID, before any replayed event reaches the agent state
machine. A gap means the operation outcome is unknown, not pending.
"""
if first_replayed is None:
# Server accepted the resume but had nothing to replay; the
# terminal event may be lost. Treat as unknown, not success.
raise ResumptionGapError(
f"resume with Last-Event-ID={last_event_id} yielded no events; "
"terminal outcome unknown"
)
expected = last_event_id + 1
if first_replayed.id == expected:
return
if first_replayed.id > expected:
raise ResumptionGapError(
f"event gap on resume: expected id={expected}, "
f"got id={first_replayed.id} "
f"(events {expected}..{first_replayed.id - 1} evicted); "
"operation outcome is unknown, query status by idempotency key"
)
# first_replayed.id < expected: server replayed already-consumed
# events (duplicate delivery). Not a gap, but the caller must
# deduplicate before applying effects.
raise ResumptionGapError(
f"duplicate replay: expected id={expected}, got id={first_replayed.id}"
)
def resume_session(
last_event_id: int,
replayed: list[SseEvent],
status_lookup,
idempotency_key: str,
) -> str:
"""Resume a stream, or fall back to a status query on gap."""
try:
assert_contiguous_resume(
last_event_id, replayed[0] if replayed else None
)
except ResumptionGapError:
# Do NOT feed replayed events into the state machine.
# Resolve the unknown outcome out-of-band.
return status_lookup(idempotency_key)
for ev in replayed:
# Safe: stream is provably continuous with prior state.
apply_event_to_agent_state(ev)
return "resumed"