# Which invariants prevent resumable MCP HTTP streams from replaying a tool call whose side effect already committed **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers exposing HTTP-native transports (SSE-framed JSON-RPC over `POST`/`GET` with `Last-Event-ID` resumption) where a client may reconnect mid-`tools/call` and re-issue the request. Does not apply to stdio transports, nor to stateless request/response MCP endpoints with no event log. ## Core Distinction The resumption contract of an HTTP-native MCP stream is *transport-level*: `Last-Event-ID` tells the server "resume the byte stream after event N." It says nothing about *effect-level* idempotency. The dangerous conflation is treating a transport replay as a semantic replay — assuming that because the server can re-send events from the log, the client can safely re-send the originating `tools/call` request and expect the tool to run exactly once. These are two different invariants: - **Stream continuity invariant:** every event with `id > Last-Event-ID` is delivered at least once, in order, to the reconnected client. - **Effect-once invariant:** a `tools/call` with a given JSON-RPC `id` executes its side effect at most once, regardless of how many times the request is delivered. A conforming SSE resumption implementation satisfies the first trivially and the second *not at all*. The gap between them is where duplicate side effects live. ## What Was Observed An agent issued `tools/call` for `transfer_funds` (a mutating tool) with JSON-RPC `id: 4471`. The server executed the tool, committed the transfer, and began streaming progress events (`notifications/progress`) followed by the final `result`. The connection dropped after the progress notification (`id: 12`) but before the `result` event (`id: 13`) was flushed to the client. The client's SSE reader saw the socket close, and its retry logic did two things in the wrong order: 1. It reconnected with `Last-Event-ID: 12` — correct, transport-wise. 2. Its request layer, seeing no `result` for `id: 4471`, *also* re-issued the original `tools/call` POST — because the agent's planner had no record that the call had been dispatched. The server, which keyed its event log by stream and not by request `id`, had no dedup table. It ran `transfer_funds` a second time. Both transfers committed. The client eventually received `result` for `4471` from the *second* execution (event `id: 13` of a fresh stream) and reconciled its state to a single success — while the ledger held two debits. The failure is silent: no error, no duplicate `id` rejection, no protocol violation. The stream resumed correctly. The effect doubled. ## Condition of Validity The effect-once invariant holds **only if** the server maintains a durable, request-`id`-keyed record of committed executions, and the record is consulted *before* the tool body runs, and the record is written *atomically with* the side effect (or the side effect is itself idempotent under a client-supplied idempotency key). Absent any one of these, the following is true: **a resumable MCP stream provides at-least-once delivery of events and at-least-once execution of tools.** It does not provide exactly-once anything. The `Last-Event-ID` mechanism bounds *event* duplication; it does not bound *effect* duplication. The subtlety: the client cannot distinguish "my request was never received" from "my request was received, executed, and the result event was lost in the gap." Both look identical to a client that saw a socket close with no `result`. This is the classic two-generals ambiguity, and MCP's resumption layer does not resolve it — it only lets you re-read the *tail* of a stream you already partially consumed. ## Decision Boundary The correct decision, on reconnect, is **not** "re-issue the call." It is: - If the client has a `Last-Event-ID` for the stream, reconnect and drain the stream to its terminal event for `id: 4471`. If the terminal `result` (or an `error`) arrives, the call is resolved — do not re-issue. - If the stream log has been truncated (server-side TTL expired, `Last-Event-ID` older than the retention window), the server MUST respond with a distinguishable signal — an explicit `resumption-failed` error, not a silent fresh stream from `id: 0`. A fresh stream from zero is indistinguishable from a new call and invites the double-execution. - If the client genuinely cannot recover the terminal event, it must query a **separate, idempotent status endpoint** keyed by request `id` — never re-POST the mutating call. The invariant to enforce server-side: **the request `id` is the idempotency key.** A second `tools/call` with an already-committed `id` must return the *recorded* result (or a `duplicate-request` error), never re-execute. This must be checked under the same lock/transaction that guards the side effect, or the check races the commit. ## Operational Effect Without the idempotency key on the request `id`, every mutating tool is a duplicate-effect hazard under any network flap, any client restart mid-call, any load-balancer timeout that severs the SSE stream after the tool committed. The probability is not small: it is the probability that a stream drops in the window between effect-commit and result-flush — which is exactly the window that long-running tools occupy, and exactly why they stream progress events in the first place. The guardrail is a single rule, enforced at the server's tool-dispatch boundary: *look up the request `id` in the committed-effects table before dispatch; on hit, replay the stored result; on miss, execute and record atomically.* The `Last-Event-ID` resume path and the `tools/call` dispatch path must share that table, or the two invariants (stream continuity, effect-once) will drift apart and the drift will be silent. ```python import hashlib import threading from dataclasses import dataclass, field from typing import Any, Optional class DuplicateEffectError(RuntimeError): """Raised when a tool dispatch would re-execute an already-committed request id.""" class ResumptionGapError(RuntimeError): """Raised when Last-Event-ID predates the retained stream log; tail is unrecoverable.""" @dataclass class CommittedEffect: request_id: str result: Any effect_digest: str class EffectOnceDispatcher: """ Enforces: a tools/call with a given JSON-RPC id executes its side effect at most once. Stream resumption (Last-Event-ID) is a separate concern and MUST NOT be used as a proxy for effect dedup. """ def __init__(self, stream_retention_floor: int = 0): self._lock = threading.Lock() self._committed: dict[str, CommittedEffect] = {} self._retention_floor = stream_retention_floor def dispatch(self, request_id: str, tool_body, args: dict) -> Any: with self._lock: prior = self._committed.get(request_id) if prior is not None: # Idempotent replay: return recorded result, do NOT re-execute. return prior.result # Execute under the same lock that guards the commit, so the # check-then-act race cannot double-fire. result = tool_body(**args) digest = hashlib.sha256( f"{request_id}:{result!r}".encode() ).hexdigest() self._committed[request_id] = CommittedEffect( request_id=request_id, result=result, effect_digest=digest ) return result def resume_stream(self, last_event_id: int) -> str: if last_event_id < self._retention_floor: # Silent fresh-stream-from-zero is the bug; make it loud. raise ResumptionGapError( f"Last-Event-ID {last_event_id} predates retention floor " f"{self._retention_floor}; terminal event for in-flight " f"tools/call is unrecoverable — query status by request id, " f"do not re-POST." ) return f"resuming-from:{last_event_id}" def handle_reconnect(dispatcher: EffectOnceDispatcher, request_id: str, last_event_id: int, tool_body, args: dict) -> Any: try: dispatcher.resume_stream(last_event_id) except ResumptionGapError: # Gap: we cannot know whether the effect committed. Refuse to guess. raise # Only dispatch after confirming resume is possible; dispatch is # idempotent on request_id regardless. return dispatcher.dispatch(request_id, tool_body, args) def handle_duplicate_without_record(dispatcher: EffectOnceDispatcher, request_id: str, tool_body, args: dict) -> Any: # Demonstrates the failure the guardrail prevents: if a caller bypasses # the committed-effects table and re-POSTs, we must refuse. with dispatcher._lock: if request_id in dispatcher._committed: raise DuplicateEffectError( f"request id {request_id} already committed; " f"re-POST would double the side effect" ) return dispatcher.dispatch(request_id, tool_body, args) ```