Why does an instance lose JSON-RPC batch atomicity when an MCP SSE stream resumes mid-batch

**Date of Record:** 2026 December 2

**Scope:** Applies to MCP servers exposing the HTTP-native streaming transport (Streamable HTTP) with `Last-Event-ID` resumable SSE and JSON-RPC 2.0 batch requests, where a single SSE event payload may carry a batch array. Does not apply to stdio transports, single-message-per-event streams, or servers that reject batches outright.

Core Distinction

The distinction that matters is between **event-level resumability** and **batch-level atomicity**. The MCP Streamable HTTP transport defines resumption in terms of SSE event IDs: a client reconnects with `Last-Event-ID: N` and the server replays events after `N`. This is a *stream cursor* contract. JSON-RPC 2.0 batching, separately, defines that a batch is a single logical request whose responses may be returned in any order but must be *complete* — every request in the batch gets exactly one response (or error), and the batch's responses are correlated by `id`, not by position.

These two contracts are orthogonal, and the transport spec does not compose them. When a batch is serialized as the payload of one SSE event, resumption resumes *between events*, not *within* a batch. But when a server fragments a batch's responses across multiple events to keep each event under a size or flush interval, the `Last-Event-ID` cursor can land in the middle of a batch. The client resumes, receives the tail of the batch, and has no way to know the head was already delivered — or was never delivered because the connection died mid-flush. The batch is now a partial set of responses with no marker that it is partial. This is not a dropped-message problem (SSE resumption handles that); it is a *batch-identity* problem: the resumed stream has no batch boundary to anchor to.

What Was Observed

A tool-call batch of 40 `tools/call` requests was issued to an MCP server over Streamable HTTP. The server emitted responses in 6 SSE events, each carrying a sub-array of the batch (7, 7, 7, 7, 7, 5 entries), with event IDs 101–106. The client connection dropped after event 104 was received (TCP reset during a long-running `tools/call` on the 29th request). The client reconnected with `Last-Event-ID: 104`.

The server, treating the resume as a fresh stream continuation, replayed events 105 and 106. The client's JSON-RPC layer, which had been accumulating responses keyed by `id`, received 12 responses for the 40-request batch and — because no `id` collided — concluded the batch was complete for the 12 it saw. The remaining 28 requests were silently abandoned: no error, no timeout, no `-32603`. The agent's planner, which awaited the batch as a unit, proceeded with a partial result set and made a downstream decision (a file write) based on 12 of 40 tool outcomes.

A second observation, from a different server implementation, was the inverse: the server *replayed* event 104 on resume (because it interpreted `Last-Event-ID` inclusively), the client deduplicated by event ID but not by JSON-RPC `id`, and the same 7 responses were appended twice. The dedup layer keyed on SSE event ID, so the duplicated batch fragment passed through and the client saw 47 responses for 40 requests, with 7 `id`s appearing twice. The JSON-RPC layer's "last write wins" merge masked the duplication for idempotent reads but corrupted a `tools/call` that appended to a log.

Both failures share a root: **the batch has no identity in the transport layer**. The SSE event ID identifies a *chunk of a stream*, not a *member of a batch*. The JSON-RPC `id` identifies a *request*, not a *batch*. Nothing in either protocol names the batch as a unit, so resumption cannot be made batch-aware.

Condition of Validity

The invariant that must hold for resumable SSE + batching to be safe is:

> For any batch B delivered across events E₁…Eₙ, the client must be able to determine, after any resume at `Last-Event-ID: k`, either (a) the exact set of B's responses already delivered, or (b) that B is incomplete and must be re-requested in full.

This holds only when one of the following is true:

  1. **Batch-per-event**: every batch is fully contained in a single SSE event, and the server never fragments a batch across events. Then `Last-Event-ID` resumption is batch-atomic by construction. This is the only configuration the current spec text actually guarantees, and it is the one most servers violate under load because a 40-response batch can exceed the per-event flush buffer.
  1. **Batch-tagged fragments**: each event payload carries an explicit batch identifier and a sequence number (e.g., `X-MCP-Batch: <uuid>`, `X-MCP-Batch-Seq: 3/6`), so the client can detect gaps and duplicates on resume. This is not in the spec; it is a server-side extension that must be negotiated via `initialize` capabilities.
  1. **No resumption across batch boundaries**: the server refuses `Last-Event-ID` values that fall inside a batch (returns `409` and a fresh `Mcp-Session-Id`), forcing the client to re-issue the batch. This trades liveness for atomicity and is correct but wasteful.

The failure occurs precisely when none of these hold — which is the default for any server that (a) supports batching, (b) fragments large batches to bound event size, and (c) implements `Last-Event-ID` replay as a raw event-log cursor.

Decision Boundary

The boundary is not "does the server support resumption" but **"does the resumption cursor carry batch semantics."** A server that logs events and replays by ID is correct for unbatched streams and incorrect for fragmented batched streams. The decision an agent runtime must make on `initialize` is:

The subtle boundary: a server can be *individually* correct on batching and on resumption and still be *composed* incorrect. Capability negotiation must therefore test the *conjunction*, not the parts. An agent that checks `supports_batching && supports_resume` and concludes "safe to batch and resume" has made the exact error this record documents.

Operational Effect

The downstream effect is **silent partial-batch acceptance**, which is worse than a hard failure because it does not trip any error path. The agent's tool-call loop sees a set of responses, all with valid `id`s and valid JSON-RPC envelopes, and has no signal that the set is incomplete. The planner's join over the batch resolves early (all awaited `id`s that arrived are satisfied; the missing ones were never registered because the client never learned they existed — the batch manifest was in the request, which the client *sent*, but the client's response accumulator keyed only on received `id`s, not on the requested `id` set).

The guardrail is to make the batch manifest a first-class client-side object: on send, record the full set of request `id`s; on resume, diff received against requested and treat any missing `id` as a batch failure requiring full re-issue. This is a client-side invariant that does not depend on server cooperation, and it is the only defense that holds against servers that are individually spec-compliant.

A secondary effect: duplicate delivery on inclusive `Last-Event-ID` replay corrupts non-idempotent `tools/call` side effects. The client-side fix is to make the response accumulator idempotent by `(batch_id, jsonrpc_id)` and to reject — not merge — a second response for the same `id` within a batch, escalating to the planner as a transport integrity violation.

import uuid
from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class BatchIntegrityError(RuntimeError):
    """Raised when a resumed SSE stream yields a batch that violates atomicity."""
    pass


@dataclass
class BatchManifest:
    batch_id: str
    requested_ids: Set[str]
    received_ids: Set[str] = field(default_factory=set)
    delivered_events: Set[int] = field(default_factory=set)
    last_event_id: Optional[int] = None
    fragments_expected: Optional[int] = None
    fragments_seen: int = 0

    @classmethod
    def new(cls, requested_ids):
        return cls(batch_id=str(uuid.uuid4()), requested_ids=set(requested_ids))


class ResumableBatchClient:
    def __init__(self, server_advertises_batch_fragments: bool):
        self.batch_fragments = server_advertises_batch_fragments
        self.active: Dict[str, BatchManifest] = {}

    def on_send(self, requested_ids) -> BatchManifest:
        m = BatchManifest.new(requested_ids)
        self.active[m.batch_id] = m
        return m

    def on_event(self, manifest: BatchManifest, event_id: int,
                 batch_id: Optional[str], seq: Optional[int],
                 responses: list) -> None:
        # Duplicate event replay (inclusive Last-Event-ID) must be rejected.
        if event_id in manifest.delivered_events:
            raise BatchIntegrityError(
                f"event {event_id} replayed for batch {manifest.batch_id}; "
                f"server used inclusive Last-Event-ID cursor"
            )
        manifest.delivered_events.add(event_id)
        manifest.last_event_id = event_id

        if not self.batch_fragments:
            # No fragment metadata: any multi-event batch is non-resumable.
            # We accept fragments only if the batch completes in one event.
            if len(manifest.delivered_events) > 1:
                raise BatchIntegrityError(
                    f"batch {manifest.batch_id} fragmented across events without "
                    f"batch-fragment capability; atomicity cannot be guaranteed"
                )

        for r in responses:
            rid = str(r["id"])
            if rid in manifest.received_ids:
                raise BatchIntegrityError(
                    f"duplicate JSON-RPC id {rid} in batch {manifest.batch_id}; "
                    f"non-idempotent tool side effect at risk"
                )
            manifest.received_ids.add(rid)

    def on_resume(self, manifest: BatchManifest, last_event_id: int,
                  first_replayed_event_id: int) -> None:
        # The cursor landed inside the batch: the head may already be delivered
        # and the tail may be missing. Without fragment metadata we cannot
        # reconstruct the boundary, so we must fail closed.
        if not self.batch_fragments and manifest.delivered_events:
            raise BatchIntegrityError(
                f"resume at Last-Event-ID {last_event_id} lands inside batch "
                f"{manifest.batch_id}; partial responses already delivered, "
                f"full batch re-issue required"
            )
        if first_replayed_event_id != last_event_id + 1 and self.batch_fragments:
            raise BatchIntegrityError(
                f"resume gap: expected event {last_event_id + 1}, "
                f"got {first_replayed_event_id} for batch {manifest.batch_id}"
            )

    def on_complete(self, manifest: BatchManifest) -> None:
        missing = manifest.requested_ids - manifest.received_ids
        if missing:
            raise BatchIntegrityError(
                f"batch {manifest.batch_id} completed with {len(missing)} "
                f"missing responses: {sorted(missing)[:5]}..."
            )