How does an instance detect a split-brain SSE stream when an MCP session resumes on a second HTTP node mid-tool-call

**Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native streamable transport (Streamable HTTP, `text/event-stream` responses with `Mcp-Session-Id` and `Last-Event-ID` resumption) where session state may migrate across load-balanced nodes. Does not apply to stdio transport, nor to single-node deployments where session affinity is guaranteed by the process boundary.

Core Distinction

There are two categorically different meanings of "resume" in MCP Streamable HTTP, and conflating them produces a silent correctness failure:

  1. **Event replay resume** — the client reconnects with `Last-Event-ID: N` and the server replays buffered SSE events from `N+1`. This is a *transport* guarantee about the byte stream.
  2. **Session state resume** — the server rebinds `Mcp-Session-Id` to the same logical agent context (in-flight tool call, pending `sampling/` or `roots/` state, negotiated capabilities). This is a *state* guarantee about the execution.

The MCP spec defines (1) explicitly via `Last-Event-ID` and requires servers to support it *if* they advertise resumability. It does **not** require (2) across nodes. A well-meaning deployment that puts an MCP server behind a round-robin HTTP load balancer with a shared session store often implements (1) on each node independently while failing (2) — the new node replays the event stream from its own (or a shared) buffer, the client believes it is continuing the same logical turn, but the tool invocation that was mid-flight on node A is still running there, unwatched, while node B has no record of it. The client sees a coherent token stream. The system has split-brained.

The non-obvious part: **there is no protocol-level signal that distinguishes "resumed correctly" from "resumed onto a node that has the event buffer but not the execution."** Both cases produce a valid `text/event-stream` with a valid `id:` sequence. The invariant that must be defended is not "did we reconnect" but "is the *executor identity* of the in-flight tool call the same as the *session identity* the client believes it is talking to."

What Was Observed

A multi-step agent invoked a long-running MCP tool (`run_migration_plan`, ~90s of wall time, streaming progress events). The client's HTTP connection to node A dropped at t≈40s (a routine LB idle-timeout reset on a NAT boundary, not a server crash). The client reconnected per spec:

GET /mcp HTTP/1.1
Mcp-Session-Id: 7f3c2a...
Last-Event-ID: 118

The LB routed to node B. Node B's session store held the *event log* for `7f3c2a...` (replicated, cheap) but not the *execution handle* (node-local, a `subprocess` + a `asyncio.Task` running on node A). Node B replayed events 119–131 from the shared buffer — these were the last events flushed to the log before the drop, which happened to include a `progress` notification at 60% and no terminal event. Node B then, per its implementation, treated the absence of a terminal event as "call still in progress" and began emitting *its own* keepalive `progress` events synthesized from the last known progress value, because its `progress` emitter had no backing task and defaulted to holding the last value.

Meanwhile node A's task completed at t≈90s, emitted its terminal `result` event into the shared event log (event 132), and released the execution handle. The client never saw event 132, because node B's SSE stream had already passed `Last-Event-ID` 131 and node B does not re-scan the log for events appended after the reconnect — it only replays up to the current tail *at reconnect time*, then streams live events *for its own session binding*, which is empty. The client sat on a stream emitting frozen 60% progress until its own turn timeout, then issued a *new* `tools/call` — because from its perspective the previous one never returned. The tool executed a second time. The migration plan ran twice.

The failure is not "connection dropped" (expected) and not "event lost" (spec-permitted if resumability is not advertised). The failure is that **resumption produced a session that was transport-consistent and execution-inconsistent, with no error surfaced at any layer.**

Condition of Validity

The split-brain is only possible when all of the following hold simultaneously. Each is a necessary condition; removing any one bounds the failure:

The invariant that fails is: **for a given `Mcp-Session-Id` and `Last-Event-ID`, the node serving the resumed stream must be able to prove it holds (or can reach) the executor that will produce the next event with `id > Last-Event-ID`.** If it cannot, it must not open a live stream; it must either replay-to-terminal-and-close or return an explicit session-migration error.

Decision Boundary

The server, on receiving a resumed `GET /mcp` with `Last-Event-ID: N`, must make a binary decision before writing a single byte to the stream:

The boundary is *not* "did the reconnect succeed" but "can this node produce the next event, or must it defer." The default LB behavior — route anywhere, answer locally — violates this boundary on every reconnect that lands on a non-owner during the execution tail.

Operational Effect

Concretely, the unguarded system exhibits:

The guardrail is a **session-executor lease**: the owning node holds a renewable lease on the `Mcp-Session-Id`; the session store records `{session_id, owner_node, lease_expiry, last_event_id}`; any node serving a resumed stream must verify `owner_node == self` OR `lease_expiry < now` (orphaned) before opening a live stream, and must return `409 session_migration_required` otherwise. This makes the C1 decoupling explicit and forces the non-owner to defer rather than synthesize.

import time
from dataclasses import dataclass
from typing import Optional


class SessionMigrationConflict(RuntimeError):
    """Raised when a resumed SSE stream cannot be served by this node
    because the in-flight execution is owned elsewhere and still live."""


@dataclass
class SessionLease:
    session_id: str
    owner_node: str
    lease_expiry: float          # monotonic seconds
    last_event_id: int
    has_terminal_event: bool


def open_resumed_stream(
    self_node: str,
    session_id: str,
    last_event_id: int,
    lease: Optional[SessionLease],
    replay_tail: int,
    now: Optional[float] = None,
) -> str:
    """Decide whether this node may open a live SSE stream for a resumed
    MCP session, or must defer. Returns a mode string; raises on the
    split-brain boundary rather than synthesizing keepalives.
    """
    now = time.monotonic() if now is None else now

    if lease is None:
        # No lease record at all: session unknown to the store.
        raise SessionMigrationConflict(
            f"no lease for session {session_id}; refusing live stream"
        )

    # Case 1: terminal event already durable past the client's cursor.
    if lease.has_terminal_event and replay_tail > last_event_id:
        return "replay_to_terminal_and_close"

    # Case 2: this node owns the live execution.
    if lease.owner_node == self_node and lease.lease_expiry >= now:
        return "live_stream"

    # Case 3: another node owns a live execution. Do NOT open a stream.
    if lease.owner_node != self_node and lease.lease_expiry >= now:
        raise SessionMigrationConflict(
            f"session {session_id} owned by {lease.owner_node} "
            f"(lease live until {lease.lease_expiry:.3f}); "
            f"client cursor {last_event_id}, replay tail {replay_tail}"
        )

    # Case 4: lease expired -> orphaned execution. Emit a terminal
    # error event so the client's turn resolves deterministically.
    return "emit_orphan_terminal_error"