Why does an instance lose tool-call continuity when an MCP Streamable-HTTP SSE channel reconnects between `Last-Event-ID` delivery and the in-flight request being replayed?

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers using the Streamable HTTP transport where a single session multiplexes client→server JSON-RPC requests against a server→client SSE stream carrying responses and notifications, and where the client resumes via `Last-Event-ID` after transport drop. Does not apply to stateless stdio transports, nor to pure request/response HTTP without an SSE channel.

Core Distinction

The failure is not "the connection dropped." It is that **resumption and replay are two different clocks that the transport spec lets drift apart**. `Last-Event-ID` resumption replays the *notification/response event log* from a cursor, but it does not replay the *inbound request* that was in flight when the stream broke. The server, on reconnect, considers the session alive (it has the session ID) but has no obligation to re-execute the request whose response event was never emitted before the cursor. The client, meanwhile, treats "stream resumed from cursor N" as "no work was lost," because the SSE contract's implicit invariant is *event log is the source of truth for everything the server wanted to tell me*. That invariant is false the moment a request's side effect is committed but its response event is not.

The precise boundary: **a tool call whose execution is non-idempotent and whose completion event lands after the disconnect cursor but whose side effect landed before it.** The event log and the effect log diverge by exactly one request, and neither the client nor the server can tell which one without an external witness.

What Was Observed

A single-session agent loop issuing `tools/call` over Streamable HTTP. The sequence under load:

  1. Client sends `POST /mcp` with JSON-RPC `tools/call` (id `c-4417`), carrying `Mcp-Session-Id`. Server accepts, begins executing a tool with an external side effect (an append to a remote ledger), and streams a `202 Accepted` with an SSE channel.
  2. Server commits the side effect at T+0. Server writes the JSON-RPC response event to the session's event buffer with `event: message`, `id: 118`. The write to the socket fails (NAT rebind, LB idle timeout at 60s, or a proxy half-close). The event sits in the buffer, unacknowledged.
  3. Client's SSE reader raises `RemoteProtocolError`. The agent runtime, following the transport spec, reconnects with `GET /mcp` + `Last-Event-ID: 117` (last *successfully parsed* event, not 118, because 118 never arrived).
  4. Server resumes the stream from 117 and **replays event 118**, which is the response to `c-4417`. Good — this is the happy path, and it works.
  5. The failure case: the disconnect happens *before* the server writes event 118, at T+0 but between the side-effect commit and the buffer append. Server reconnects at `Last-Event-ID: 117`, replays nothing new (118 not yet written), and the client's pending-request table still holds `c-4417` with no response. The agent's per-request timeout fires at T+30s. The runtime — reasonably, given no response — **retries `c-4417` with the same JSON-RPC id**.
  6. Server sees `c-4417` again. Its session state has no dedup entry (the response was never emitted, so nothing recorded the id as answered). It executes the tool again. The ledger gets two appends.

The non-obvious part: in step 5 the server *did* keep the session alive and *did* honor resumption semantics correctly. The spec is satisfied on both sides. The duplicate side effect is a consequence of the spec leaving request-level idempotency to the application while the transport's resumption machinery creates the exact window where a client is *forced* to retry an unacknowledged request.

A second observed variant: the server writes event 118 *and* the client parses it, but the client crashes between parse and dispatch to the pending-request table (process restart, OOM kill of the worker). On cold start the agent has the session ID from its checkpoint but not the in-memory pending table, so it reconnects, gets no replay (cursor is past 118), and either hangs the tool call forever or re-issues it. Here the event was delivered but the *dispatch* was lost — a checkpoint/resume gap that the SSE cursor cannot see.

Condition of Validity

The invariant "SSE resumption preserves tool-call continuity" holds only when **all three** of the following are true:

When any one is false, the client is in a state where it *must* either hang (no response, no replay) or duplicate (retry into a server that re-executes). There is no third option available at the transport layer.

Decision Boundary

The agent runtime must decide, on stream drop with pending requests, between **replay-wait** and **retry**, and the correct choice depends on a fact the runtime does not have: whether the side effect committed. The boundary is:

Concretely, the runtime should refuse to retry any `tools/call` whose tool is declared non-idempotent unless it carries an idempotency key the server has acknowledged. The declaration must live in the tool's schema, not in the agent's prompt — a probabilistic reasoner will not reliably remember which tools are safe to retry under context pressure.

Operational Effect

The downstream consequences compound in ways that look like reasoning failures but are transport artifacts:

The guardrail that bounds this is the three-condition invariant above, enforced at the transport integration layer, not at the agent layer. The agent cannot be trusted to enforce it because the agent is the component whose finite context and probabilistic retry policy create the window.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ResumptionContinuityError(RuntimeError):
    """Raised when SSE resumption cannot prove tool-call continuity."""
    pass


@dataclass
class PendingCall:
    jsonrpc_id: str
    idempotency_key: str
    tool_name: str
    non_idempotent: bool
    cursor_at_send: int
    dispatched: bool = False


@dataclass
class SessionState:
    session_id: str
    last_event_id: int = 0
    pending: dict = field(default_factory=dict)
    # server-advertised: ids the server has committed effects for but not yet
    # emitted response events for. Empty set + no endpoint => unknown.
    server_unanswered: Optional[set] = None
    server_dedup_supported: bool = False


def make_idempotency_key(session_id: str, jsonrpc_id: str, tool_name: str) -> str:
    return hashlib.sha256(
        f"{session_id}:{jsonrpc_id}:{tool_name}".encode()
    ).hexdigest()[:32]


def on_stream_drop(state: SessionState) -> None:
    """Called when the SSE reader raises. Decide replay-wait vs retry."""
    if not state.pending:
        return
    for call in state.pending.values():
        if call.non_idempotent:
            if state.server_unanswered is None:
                raise ResumptionContinuityError(
                    f"non-idempotent call {call.jsonrpc_id} ({call.tool_name}) "
                    f"in flight; server exposes no pending-set endpoint, so "
                    f"outcome is unknown. Refusing to retry — would duplicate "
                    f"a committed side effect. Requires server-side dedup or "
                    f"pending-set advertisement to proceed."
                )
            if call.jsonrpc_id in state.server_unanswered:
                # server proves the request is alive; wait for replay, do not retry
                continue
            # server proves the request is answered but event was lost;
            # only safe to retry if the server dedups on idempotency key
            if not state.server_dedup_supported:
                raise ResumptionContinuityError(
                    f"call {call.jsonrpc_id} answered server-side but response "
                    f"event lost past cursor {state.last_event_id}; server does "
                    f"not honor idempotency keys, retry would re-execute."
                )


def advance_cursor(state: SessionState, event_id: int, routed: bool) -> None:
    """Cursor must advance only after dispatch, not on parse."""
    if not routed:
        raise ResumptionContinuityError(
            f"refusing to advance Last-Event-ID to {event_id}: event parsed "
            f"but not dispatched to pending table; crash here loses the "
            f"response with no replay path (cursor would be past it)."
        )
    state.last_event_id = max(state.last_event_id, event_id)


def resume(state: SessionState, advertised_cursor: int) -> None:
    if advertised_cursor > state.last_event_id:
        raise ResumptionContinuityError(
            f"server cursor {advertised_cursor} ahead of persisted cursor "
            f"{state.last_event_id}; events in between were never dispatched. "
            f"Cold-start gap — reconcile pending table before resuming."
        )