Skip to content

[v2] Standalone GET stream is never primed, so notifications sent across closeStandaloneSSEStream() are lost #3211

Open

Description

@kai0310

What happened?

POST SSE streams open with a priming event (id, plus retry when retryInterval is set). The standalone GET stream doesn't, so until the server sends something on it the client has no event id to resume from. If closeStandaloneSSEStream() is called in that window, StreamableHTTPClientTransport reconnects on schedule but without Last-Event-ID, and anything sent while it was disconnected sits in the event store and is never delivered.

SDK client against an in-process server (retryInterval: 300), one notification sent right after the close and one after the reconnect:

[19ms]  client GET, Last-Event-ID=(none)
[221ms] server closeStandaloneSSEStream()
[528ms] client GET, Last-Event-ID=(none)
received: [ 'after-reconnect' ]     <- 'during-gap' was stored as e2, never replayed

writePrimingEvent() is only called from the POST path; handleGetRequest() and replayEvents() never prime. v1.x (1.32.2) has the same code in webStandardStreamableHttp.ts.

What did you expect?

The GET stream primed on open and on resume, same as POST, so the client reconnects with Last-Event-ID and gets what it missed.

The 2025-11-25 transports spec, for GET streams: "If the server closes the connection without terminating the stream, it SHOULD follow the same polling behavior as described for POST requests: sending a retry field and allowing the client to reconnect." The POST rules it points to only allow closing after an event ID has been sent.

Two things a fix has to handle: the priming event has to be stored before the stream is registered, otherwise a concurrent send() can land ahead of it, and replay should skip stored priming events because _GET_stream is reused across connections. The Python SDK primes resumed GETs but not fresh ones, so it has the same gap on first connect. I have this on a branch with tests and can open a PR if the approach works for you.

Related: #2499

Code to reproduce

// Shows the missing priming event. Output:
// POST: "id: 30847839-..._0\nretry: 1000\ndata: \n\n"
// GET:  ""
import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import type { EventStore } from '@modelcontextprotocol/server';

const events = new Map<string, unknown>();
const eventStore: EventStore = {
    async storeEvent(streamId, message) {
        const id = `${streamId}_${events.size}`;
        events.set(id, message);
        return id;
    },
    async replayEventsAfter() {
        return '';
    }
};

const transport = new WebStandardStreamableHTTPServerTransport({
    sessionIdGenerator: () => crypto.randomUUID(),
    eventStore,
    retryInterval: 1000
});
await new McpServer({ name: 'repro', version: '0' }).connect(transport);

const init = await transport.handleRequest(
    new Request('http://localhost/mcp', {
        method: 'POST',
        headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
        body: JSON.stringify({
            jsonrpc: '2.0',
            id: 1,
            method: 'initialize',
            params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'c', version: '0' } }
        })
    })
);
const sessionId = init.headers.get('mcp-session-id')!;
const initReader = init.body!.getReader();
console.log('POST:', JSON.stringify(new TextDecoder().decode((await initReader.read()).value)));
await initReader.cancel();

const get = await transport.handleRequest(
    new Request('http://localhost/mcp', {
        headers: { accept: 'text/event-stream', 'mcp-session-id': sessionId, 'mcp-protocol-version': '2025-11-25' }
    })
);
setTimeout(() => transport.closeStandaloneSSEStream(), 100);
console.log('GET: ', JSON.stringify(await get.text()));
await transport.close();

SDK version

@modelcontextprotocol/server 2.4.0 (main @ 5ee54ee)

Area

Transports

Activity

  1. added
    v1Issues / PRs related to v1.x
    v2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes
    on Nov 20, 2026
  2. A7mdMe commented on Nov 21, 2026

    @A7mdMe

    Standalone GET Priming, Reconnection Semantics & Gapless Replay Considerations

    This is an acute issue in production MCP deployments—especially where gateways, load balancers, or Cloudflare enforce connection rotation (e.g. 60–100s idle limits) and the server relies on closeStandaloneSSEStream() to gracefully cycle long-lived connections.

    Root Cause & Protocol Mechanics

    Under the MCP 2025-11-25 / 2024-11-05 transport specification, clients rely on SSE id: frames to track the stream cursor. When opening a standalone GET stream, if the server emits nothing until an application event occurs, the client's Last-Event-ID remains null. When closeStandaloneSSEStream() terminates the connection:

    1. The client reconnects on schedule via retry: <interval>, but sends no Last-Event-ID.
    2. The server treats the reconnection as a brand new stream cursor.
    3. Any notifications (progress events, logs, asynchronous completions) buffered in the EventStore during the disconnect-to-reconnect gap are permanently bypassed and never replayed.

    Two Critical Implementation Details for the Fix

    When implementing stream priming on the GET path, two concurrency and replay details are essential:

    1. Atomic Store-Before-Register Ordering:
      The priming event (id: ${streamId}_1\nretry: ${retryInterval}\ndata: \n\n) must be persisted in the EventStore before the active stream listener is registered. If registered prior to priming, a concurrent transport.send() can acquire sequence 1 while the priming frame arrives with sequence 2 out-of-order.
    2. Replay Filtering for Priming Frames:
      Because EventStore retains the initial priming record, any subsequent resumption using Last-Event-ID from an earlier point (or across stream resets) must filter out empty priming frames (isPriming: true or empty payload) so clients are not spammed with empty heartbeats.
    3. Buffering Prevention Headers:
      Ensuring headers include X-Accel-Buffering: no and Cache-Control: no-cache, no-transform prevents intermediate proxies (Nginx, reverse proxies) from holding the priming event in transit.

    Disclosure: I maintain MCP Production Kit, an open-source hardening suite for MCP servers. We implemented and verified this standalone SSE stream priming, monotonic sequence tracking, and gapless replay pattern in our test suite (Module 30).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    v1Issues / PRs related to v1.xv2Ideas, requests and plans for v2 of the SDK which will incorporate major changes and fixes

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions