# When must an instance refuse a Streamable-HTTP `Last-Event-ID` resume because the SSE stream it is resuming was already reaped by the server's session TTL, and how does the client distinguish that from a legitimate event-id gap? **Date of Record:** 2026 December 2 **Scope:** Applies to MCP Streamable HTTP transport (2025-03-26 spec and later) where a client holds an SSE stream open against a session-scoped endpoint and attempts resumption via `Last-Event-ID` after a mid-stream disconnect. Does not apply to stdio transport, nor to stateless MCP servers that emit no event IDs. ## Core Distinction There are two structurally different reasons a `Last-Event-ID` resume can return "no matching event": 1. **A genuine gap** — the server's event log for this session is intact, but the specific ID the client presents was never emitted, or was pruned by an in-session ring buffer while the session itself is still alive. The correct client response is to treat the stream as unrecoverable *for that event* but the *session* as still valid: re-issue the originating JSON-RPC request with a fresh `id`, do not tear down the session. 2. **A reaped stream** — the server's session TTL (or per-stream idle reaper) has already closed and garbage-collected the SSE stream and its event buffer, but the *session ID* remains valid because the session outlives individual streams. The server cannot distinguish "this event ID is unknown" from "this stream no longer exists" using `Last-Event-ID` alone. The correct client response is to abandon the stream and, critically, to *not* replay the request — because replaying against a live session with a still-open-or-queued server-side handler causes duplicate tool execution. The boundary is non-obvious because the wire signal is identical: in both cases the server returns HTTP 200 with a fresh SSE stream and no `id:` line matching the requested `Last-Event-ID`, or it returns a 404/400 with an opaque body. The client must disambiguate using out-of-band session state, not the resume response. ## What Was Observed A client agent issued `tools/call` for a long-running tool (a 90-second web crawl) over Streamable HTTP. The server emitted events `e1`…`e47` on the SSE stream, then the TCP connection dropped at event `e31` due to a load-balancer idle timeout (65s, shorter than the tool's runtime). The client reconnected with `Last-Event-ID: e31`. The server's behavior in the two traces: **Trace A (gap):** Session `sess-9f2` was still live; its per-stream event ring buffer (capacity 256, keyed by stream, not session) still held `e32`…`e47`. The server replayed `e32` onward. Client resumed cleanly. No duplicate execution. **Trace B (reaped):** Session `sess-9f2` was live, but the specific stream `strm-a` had been idle-reaped 40s into the tool run because the reaper's idle timer measured *bytes written to the socket*, not *tool liveness*. The reaper closed the stream and dropped its event buffer, but the tool handler kept running and its eventual result was written to a *new* stream slot. The client reconnected with `Last-Event-ID: e31`. The server, finding no buffer for `strm-a`, opened a *fresh* stream and — because the MCP handler still had the in-flight request registered — re-executed nothing but also replayed nothing. The client saw an empty stream, timed out at 30s, and re-issued `tools/call` with a new JSON-RPC `id`. The server executed the 90-second crawl *a second time*. Two crawl jobs, one billed twice, one result silently discarded. The failure was not the reaper. The failure was that the client could not tell Trace A from Trace B, because both presented as "resume succeeded, stream is empty." ## Condition of Validity The invariant that makes resume safe is: > A `Last-Event-ID` resume is only semantically valid if the server can prove, at resume time, that the stream identified by the presented ID (a) still exists, and (b) has no events after the presented ID that the client has not seen. The MCP spec does not require the server to expose stream identity in the resume response. Therefore the client-side invariant must be: > The client may only treat a resume as *gap* (safe to continue) if it receives at least one event with an `id:` greater than the presented `Last-Event-ID` within a bounded grace window. An empty resume — a 200 with no matching `id:` — MUST be treated as *reaped*, not as *gap*. This inverts the naive reading. The absence of a matching event is not evidence the log is intact; it is evidence the log is gone. A genuine gap (event pruned from a live ring buffer) still yields *later* events, because the buffer holds newer events. A reaped stream yields *nothing*, because the buffer is gone. The validity condition therefore requires the server to either (i) always replay at least the next surviving event after `Last-Event-ID`, or (ii) return a distinct status (e.g., `409 Conflict` with a `stream-reaped` reason token) so the client can disambiguate without a grace-window heuristic. Servers that return 200-with-empty-body on reaped streams violate the invariant and force the client into an unsafe heuristic. ## Decision Boundary The client's decision procedure at reconnect: ``` on_reconnect(last_event_id): resp = POST /mcp { Last-Event-ID: last_event_id } if resp.status == 409 and reason == "stream-reaped": -> ABANDON stream, DO NOT replay request, query session for tool status if resp.status == 200: first_event = read_with_timeout(resp.stream, grace=5s) if first_event is None or first_event.id <= last_event_id: -> AMBIGUOUS: treat as reaped (safe default) -> ABANDON stream, DO NOT replay request else: -> GAP: resume from first_event.id ``` The critical asymmetry: **when ambiguous, assume reaped.** Assuming gap on an ambiguous resume causes duplicate tool execution (the Trace B failure). Assuming reaped on an ambiguous resume causes a spurious tool-status query and, at worst, a client-side retry of a read-only operation. The cost function is not symmetric, so the decision boundary must bias toward reaped. The server-side obligation that removes the ambiguity entirely: a session-scoped event log keyed by session, not by stream, with a monotonic event ID namespace. Then a resume with `Last-Event-ID: e31` on a live session always finds `e32` if it exists, regardless of which stream slot the reaper touched. The stream becomes a *view* over the session log, and stream reaping no longer destroys resumability. This is the architectural guardrail: **event identity must be session-scoped, not stream-scoped**, or resume cannot be made safe. ## Operational Effect Agents that treat empty-resume as gap will, under load-balancer idle timeouts shorter than tool runtimes, systematically duplicate side-effecting tool calls. The duplication is silent: the second call succeeds, the first result is orphaned, and the agent's state reflects only the second. For read-only tools this is wasted tokens; for write tools (file mutations, message sends, payment APIs) it is a correctness violation. The mitigation that survives without server changes is a **client-side request-id ledger**: before issuing `tools/call`, the agent records `(jsonrpc_id, tool, args_hash)` in durable state; on reconnect it queries `tools/status` (or an equivalent) for that `jsonrpc_id` before replaying. This converts the ambiguous resume into a *reconciliation* step rather than a *replay* step. The ledger must be written *before* the call is sent, not after, or a crash between send and record reintroduces the duplicate. Agents that cannot query tool status (servers without a status endpoint) must set the LB idle timeout above the maximum tool runtime, or use per-request SSE streams that the server keeps alive with periodic `: keepalive` comments. The keepalive is not cosmetic; it is the only signal that keeps the reaper from treating a live-but-silent tool as dead. ```python import hashlib import time from dataclasses import dataclass from typing import Optional class AmbiguousResumeError(RuntimeError): """Raised when a Last-Event-ID resume returns no event past the presented ID. This is the Trace B condition: the stream may have been reaped, and a naive replay would duplicate a side-effecting tool call. The caller must reconcile via the request ledger, not replay. """ class DuplicateExecutionGuard(RuntimeError): """Raised when the ledger shows the jsonrpc_id was already dispatched.""" @dataclass class LedgerEntry: jsonrpc_id: str tool: str args_hash: str dispatched_at: float resolved: bool = False class StreamResumeClient: def __init__(self, transport, ledger): self.transport = transport self.ledger = ledger def call_tool(self, jsonrpc_id: str, tool: str, args: dict) -> dict: args_hash = hashlib.sha256(repr(sorted(args.items())).encode()).hexdigest() # Invariant: ledger write MUST precede dispatch. prior = self.ledger.get(jsonrpc_id) if prior is not None and not prior.resolved: raise DuplicateExecutionGuard( f"jsonrpc_id {jsonrpc_id} already dispatched at {prior.dispatched_at}; " f"reconcile via tools/status before retry" ) self.ledger.put(LedgerEntry(jsonrpc_id, tool, args_hash, time.time())) resp = self.transport.post_tool_call(jsonrpc_id, tool, args) last_event_id = resp.last_event_id # Mid-stream disconnect simulated by transport returning a resume token. while resp.needs_resume: resume = self.transport.resume(last_event_id) if resume.status == 409 and resume.reason == "stream-reaped": # Server told us explicitly: stream is gone. Do not replay. raise AmbiguousResumeError( f"stream reaped for {jsonrpc_id}; tool may still be running server-side" ) if resume.status == 200: first = resume.read_first_event(timeout=5.0) if first is None or first.event_id <= last_event_id: # Empty or non-advancing resume: assume reaped. Safe default. raise AmbiguousResumeError( f"ambiguous resume for {jsonrpc_id}: no event past {last_event_id}; " f"treating as reaped to avoid duplicate execution" ) last_event_id = first.event_id resp = resume else: raise AmbiguousResumeError(f"unexpected resume status {resume.status}") self.ledger.mark_resolved(jsonrpc_id) return resp.body ```