# How should an instance treat MCP Streamable-HTTP `Last-Event-ID` resumption when a stateless tool call was already committed server-side but its SSE event was lost to backpressure **Date of Record:** 2026 November 22 **Scope:** Applies to MCP clients using the Streamable HTTP transport (SSE-over-POST with `Mcp-Session-Id` and `Last-Event-ID` resumption) where the agent treats tool invocation as stateless and idempotent. Does not apply to stdio transport, to stateful long-lived WebSocket sessions, or to tools explicitly declared non-idempotent by their server manifest. ## Core Distinction The failure is not "the connection dropped." It is that **resumption semantics and backpressure semantics disagree about what a lost event means.** MCP Streamable HTTP lets a client resume an SSE stream by replaying from `Last-Event-ID`. The server is expected to retain a bounded replay buffer keyed by event ID. When a client is slow to drain (context window is full, the agent is mid-reasoning, the reader goroutine is blocked), the server's per-session buffer overflows and the oldest un-acked events are evicted. On resume, the client asks for `Last-Event-ID: N`, and the server — having evicted `N+1..N+k` — either (a) silently continues from the oldest retained event `N+k+1`, or (b) returns a fresh stream with no replay at all and no explicit gap signal. The critical, non-obvious point: **the tool call itself was already executed and committed server-side before its result event was written to the SSE buffer.** Tool execution and event emission are not atomic with respect to the replay buffer. So a client that resumes and sees no event for tool call `T` cannot distinguish "T was never dispatched" from "T was dispatched, committed, and its result event was evicted." Statelessness at the *agent* layer does not imply statelessness at the *transport* layer, and the two are conflated by the naive resume loop. ## What Was Observed A research agent invoked a `git_commit` tool through an MCP server over Streamable HTTP. The sequence: 1. Client POSTs `tools/call` with `Mcp-Session-Id: s1`, request id `r7`, tool `git_commit`, args `{repo, message, files}`. 2. Server accepts, begins SSE stream, assigns event IDs `e100` (progress), `e101` (progress), `e102` (result: commit SHA `abc123`). 3. The agent's SSE reader is blocked: the orchestrator is waiting on a parallel sub-agent, and the reader goroutine's channel has a bounded buffer of 1 that is full with `e100`. `e101` and `e102` are written by the server into the session replay buffer. 4. The HTTP connection times out at the client's 30s idle threshold. Client reconnects with `Last-Event-ID: e100`. 5. Meanwhile the server's replay buffer is capped at 2 events; a subsequent heartbeat/keepalive pushes `e101` out. On resume the server replays from `e102`… but the client's resume handler had already re-issued the `tools/call` because its local state machine marked `r7` as "no result received, transport error." Result: **two commits.** The second `tools/call` for `git_commit` executed against the same repo and produced SHA `def456`. The agent's final transcript recorded `def456` as the result of `r7` and never saw `abc123`. The replay buffer's eviction of `e101` was the observable symptom; the actual fault was the client re-dispatching a request whose result event it had not yet consumed, without any mechanism to ask "did `r7` already commit?" A second, quieter variant: with a different server that *did* replay from `e102` correctly, the client received the result event but had no matching pending-request entry (it had already moved on to a retry attempt `r7'`), so it dropped the event as "unknown request id." The commit existed; the agent believed the tool failed. ## Condition of Validity The invariant that must hold for safe resumption is: > For every `tools/call` request id `r`, the client MUST be able to determine, after any transport interruption, whether `r` was executed, without re-executing it, and MUST NOT re-dispatch `r` until that determination is made. This is valid only when at least one of the following is true: - The server exposes an idempotency key / request-id dedup window and returns the original result for a duplicate `r` (MCP does not standardize this; it is a server extension). - The client persists `r`'s dispatch state *before* sending, and on resume treats "no result event" as `UNKNOWN`, not `FAILED`, and queries the tool's side-effect state (e.g., `git log`) rather than retrying. - The server's replay buffer is unbounded for the session lifetime, or the server emits an explicit `gap` event when eviction occurs (not part of the base spec; must be negotiated). It does **not** hold when the client uses `Last-Event-ID` resumption as if it were a reliable ordered log, and treats a resumed stream's first event as "the next thing after what I last saw." That assumption is false the moment the server evicts under backpressure, and eviction is exactly what backpressure causes. ## Decision Boundary The boundary is between **transport-level resumption** (replay from an event ID) and **application-level exactly-once intent** (did my side effect happen). The two must be separated by an explicit state, not collapsed. Concretely, the client's per-request state machine must have four states, not three: - `PENDING` — sent, no event yet. - `RESULT_RECEIVED` — result event consumed. - `FAILED` — server returned a JSON-RPC error, or the request was rejected before execution. - `UNKNOWN` — transport interrupted after send, before result event. **This is the missing state.** `UNKNOWN` is not `FAILED`. Re-dispatching from `UNKNOWN` is only safe if the tool is provably idempotent *and* the server dedups by request id. For `git_commit`, `send_email`, `create_ticket`, `transfer_funds`, it is not safe. The boundary decision is: on `UNKNOWN`, the agent must either (a) reconcile against external state, or (b) escalate to a human/auditor, never blind-retry. The backpressure side of the boundary: a bounded replay buffer is a *correct* design choice for memory safety, but it converts a slow consumer into a data-loss event. The client must therefore bound its own read latency or explicitly ack events so the server can apply flow control (SSE `retry` + application-level ack), rather than assuming the server will buffer forever. If the client cannot guarantee it drains within the server's buffer window, it must not use resumption as its reliability mechanism. ## Operational Effect The practical consequences observed across runs: 1. **Duplicate side effects on non-idempotent tools** — the dominant failure. Silent, because the second result overwrites the first in the transcript. 2. **Phantom failures** — the tool succeeded, the event was evicted or orphaned, the agent retries, and the retry fails (e.g., "nothing to commit"), so the agent records failure for a successful operation. 3. **Replay-order corruption** — resuming from an evicted ID yields a stream starting mid-sequence; clients that assume contiguity mis-attribute progress events to the wrong request when multiple requests share a session. 4. **Backpressure amplification** — a slow reader (full context, blocked reasoning) triggers eviction, which triggers resume, which re-dispatches, which adds more in-flight work, which slows the reader further. The failure is self-reinforcing under load. The guardrail that bounds it: persist `r` with state `PENDING` to durable client state *before* the POST, transition to `UNKNOWN` on any transport error, and gate all retries on either a server-side idempotency extension or an external reconciliation probe. Treat the replay buffer as an optimization, never as the source of truth for "did it happen." The agent's memory of a tool call must survive the transport's memory of it. ```python import hashlib import time from dataclasses import dataclass, field from enum import Enum from typing import Optional class ResumptionIntegrityError(RuntimeError): """Raised when a resumed MCP stream cannot prove the fate of an in-flight request.""" class RequestState(Enum): PENDING = "pending" RESULT_RECEIVED = "result_received" FAILED = "failed" UNKNOWN = "unknown" # transport interrupted after send, before result event @dataclass class InFlightRequest: request_id: str tool: str args_digest: str state: RequestState = RequestState.PENDING dispatched_at: float = field(default_factory=time.time) result_event_id: Optional[str] = None class StatelessToolSession: """Client-side session that refuses to conflate transport resumption with exactly-once intent.""" NON_IDEMPOTENT_TOOLS = frozenset({"git_commit", "send_email", "create_ticket", "transfer_funds"}) def __init__(self, session_id: str, server_dedups_by_request_id: bool, replay_buffer_bound: int): self.session_id = session_id self.server_dedups = server_dedups_by_request_id self.replay_buffer_bound = replay_buffer_bound self.inflight: dict[str, InFlightRequest] = {} self.last_seen_event_id: Optional[str] = None def dispatch(self, request_id: str, tool: str, args: dict) -> InFlightRequest: digest = hashlib.sha256(repr(sorted(args.items())).encode()).hexdigest()[:16] req = InFlightRequest(request_id=request_id, tool=tool, args_digest=digest) # Persist PENDING *before* the network send. If this raises, we never sent. self.inflight[request_id] = req return req def on_transport_error(self, request_id: str) -> None: req = self.inflight.get(request_id) if req is None: return if req.state is RequestState.PENDING: # We sent it, we never saw the result event. This is UNKNOWN, not FAILED. req.state = RequestState.UNKNOWN def on_resume(self, requested_last_event_id: str, first_replayed_event_id: Optional[str], replayed_request_ids: set[str]) -> None: # Detect eviction: server cannot honor our resume point. if first_replayed_event_id is not None and first_replayed_event_id != requested_last_event_id: # Gap in the replay log. Any UNKNOWN request not covered by replay is unreconcilable here. for rid, req in self.inflight.items(): if req.state is RequestState.UNKNOWN and rid not in replayed_request_ids: raise ResumptionIntegrityError( f"Replay gap: requested Last-Event-ID={requested_last_event_id} " f"but server resumed at {first_replayed_event_id}; " f"request {rid} ({req.tool}) is UNKNOWN with no replay coverage " f"(buffer bound={self.replay_buffer_bound}). Refusing to re-dispatch." ) def retry(self, request_id: str) -> InFlightRequest: req = self.inflight[request_id] if req.state is RequestState.UNKNOWN: if req.tool in self.NON_IDEMPOTENT_TOOLS and not self.server_dedups: raise ResumptionIntegrityError( f"Cannot safely retry non-idempotent tool {req.tool} for request {request_id}: " f"state is UNKNOWN, server does not dedup by request id, and blind re-dispatch " f"risks duplicate side effects. Reconcile externally or escalate." ) # Safe path: either idempotent or server dedups; re-dispatch same request id. req.state = RequestState.PENDING req.dispatched_at = time.time() return req ```