Skip to content

SSEClientTransport keeps reconnecting after Client.connect() rejects #3193

Open

Description

@campoy

When an SSE connection fails, Client.connect() rejects, but the transport's EventSource stays open and keeps reconnecting. The process never exits.

Here's the smallest repro I found, with @modelcontextprotocol/sdk 1.32.2 on Node 22.23.4:

// Run: node sse-leak.mjs [close]
import net from 'node:net';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';

// Find a port nothing listens on.
const server = net.createServer().listen(0, '127.0.0.1');
await new Promise((resolve) => server.once('listening', resolve));
const { port } = server.address();
await new Promise((resolve) => server.close(resolve));

const transport = new SSEClientTransport(new URL(`http://127.0.0.1:${port}/sse`));
let errors = 0;
transport.onerror = () => errors++;
try {
  await new Client({ name: 'repro', version: '1.0.0' }).connect(transport);
} catch (err) {
  console.log('connect rejected:', err.message);
}
if (process.argv[2] === 'close') await transport.close();

const before = errors;
setTimeout(() => console.log(`errors in the next 10 s: ${errors - before}`), 10_000).unref();
$ timeout 15 node sse-leak.mjs; echo $?
connect rejected: SSE error: TypeError: fetch failed: connect ECONNREFUSED 127.0.0.1:53069
errors in the next 10 s: 3
124
$ timeout 15 node sse-leak.mjs close; echo $?
connect rejected: SSE error: TypeError: fetch failed: connect ECONNREFUSED 127.0.0.1:53087
0

Without close(), it's still reconnecting when timeout kills it. With it, it exits right away.

Why? On v1.x, the onerror handler in _startOrAuth() (src/client/sse.ts) rejects start() but never closes the EventSource, and Client.connect() doesn't close the transport either. I'd expect a failed start() to close it, as the invalid-endpoint path in the same function already does. main has the same handler, though I've only read that code.

This hurts anyone who opens a session per call. Google's ADK for TypeScript (2.3) does, so every failed MCP call leaves one more EventSource behind. DABH found this while reviewing temporalio/ai-integrations#534: four failed calls added up to about 800 transport errors in ten minutes.

Activity

  1. nithishreddy5771 commented on Nov 17, 2026

    @nithishreddy5771

    I'd like to investigate the initial-start failure cleanup on v1.x. I saw #3140 covers terminal stream failures after start; I would keep this scoped to a failed initial start and coordinate any shared onerror changes. Could you assign this issue to me if that scope is welcome?

  2. 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 17, 2026
  3. A7mdMe commented on Nov 17, 2026

    @A7mdMe

    Great catch @campoy. This is an acute issue for production agent runners and orchestrators (like Google ADK, Temporal, and serverless workers) that spin up client sessions per tool call.

    Root Cause Analysis

    In @modelcontextprotocol/sdk/client/sse.js (inside _startOrAuth), the initial connection lifecycle hooks this._eventSource.onerror:

    1. When the handshake fails (e.g. ECONNREFUSED or unreachable port), onerror fires and rejects the start() promise.
    2. However, unlike the endpoint validation branch (which explicitly invokes cleanup), this._eventSource is never closed on handshake rejection.
    3. Because standard EventSource implementations auto-reconnect by design, the underlying background connection timers remain scheduled in the Node.js event loop, preventing clean process exit and generating background error noise indefinitely (explaining the ~800 errors across 4 failed calls observed in Temporal).

    Upstream Fix in src/client/sse.ts

    Within _startOrAuth, the initial onerror handler should close the active EventSource before rejecting:

    this._eventSource.onerror = (event: MessageEvent) => {
      const error = new Error(`SSE error: ${event.message || 'Connection failed'}`);
      // Guarantee teardown of background reconnect timers on handshake rejection
      try {
        this._eventSource?.close();
      } catch {}
      reject(error);
    };

    Drop-in Client Wrapper Workaround (For Consumers Today)

    For anyone running into this in consumer code or agent orchestrators before the upstream patch lands, you can wrap the transport with an automatic teardown guard:

    import { Client } from '@modelcontextprotocol/sdk/client/index.js';
    import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
    
    export function wrapTransportWithTeardownGuard<T extends { start(): Promise<void>; close(): Promise<void> }>(
      transport: T
    ): T {
      const originalStart = transport.start.bind(transport);
      transport.start = async () => {
        try {
          await originalStart();
        } catch (err) {
          // Teardown EventSource immediately so background reconnect loop halts
          try {
            await transport.close();
          } catch {}
          throw err;
        }
      };
      return transport;
    }
    
    // Usage in orchestrators/runners:
    const transport = wrapTransportWithTeardownGuard(
      new SSEClientTransport(new URL('http://127.0.0.1:8000/sse'))
    );
    
    try {
      await client.connect(transport);
    } catch (err) {
      // Guaranteed clean exit; 0 zombie reconnect loops left behind
      console.error('Handshake failed cleanly:', err.message);
    }

    Disclosure: I maintain MCP Production Kit, an open-source kit and commercial suite containing reliability, teardown, and Slowloris lifecycle guards for production MCP servers and clients.

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