Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sse-connection-header.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/server': patch
---

SSE responses no longer set `Connection: keep-alive`, so the HTTP server decides whether the connection stays open. Before, a request sent with `Connection: close` that got an SSE response left the socket open, and the client's next request on it got a bare `400 Bad Request` from Node's HTTP parser.
150 changes: 150 additions & 0 deletions packages/middleware/node/test/connectionClose.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { randomUUID } from 'node:crypto';
import type { Server } from 'node:http';
import { createServer } from 'node:http';
import type { Socket } from 'node:net';
import { connect } from 'node:net';

import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, PROTOCOL_VERSION_META_KEY } from '@modelcontextprotocol/core-internal';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { listenOnRandomPort } from '@modelcontextprotocol/test-helpers';
import { afterEach, describe, expect, it } from 'vitest';
import * as z from 'zod/v4';

import { NodeStreamableHTTPServerTransport } from '../src/streamableHttp';
import { toNodeHandler } from '../src/toNodeHandler';

const MODERN_REVISION = '2026-07-28';
const ENVELOPE = {
[PROTOCOL_VERSION_META_KEY]: MODERN_REVISION,
[CLIENT_INFO_META_KEY]: { name: 'connection-close-client', version: '1.0.0' },
[CLIENT_CAPABILITIES_META_KEY]: {}
};

function post(body: unknown, headers: Record<string, string> = {}): string {
const payload = JSON.stringify(body);
const lines = Object.entries({
Host: 'localhost',
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
Connection: 'close',
...headers,
'Content-Length': String(Buffer.byteLength(payload))
}).map(([name, value]) => `${name}: ${value}\r\n`);
return `POST /mcp HTTP/1.1\r\n${lines.join('')}\r\n${payload}`;
}

/** Resolves with the raw response once its body is complete (Content-Length, chunked, or none). */
function readResponse(socket: Socket): Promise<string> {
return new Promise((resolve, reject) => {
let text = '';
const onData = (chunk: Buffer) => {
text += chunk.toString();
const headEnd = text.indexOf('\r\n\r\n');
if (headEnd === -1) return;
const head = text.slice(0, headEnd);
const body = text.slice(headEnd + 4);
const length = /^content-length: (\d+)/im.exec(head);
const complete = length
? Buffer.byteLength(body) >= Number(length[1])
: !/^transfer-encoding: chunked/im.test(head) || body.endsWith('0\r\n\r\n');
if (complete) {
socket.off('data', onData);
resolve(text);
}
};
socket.on('data', onData);
socket.once('error', reject);
});
}

/** Sends two requests as an HTTP/1.1 client does: the second reuses the socket unless the first response said `Connection: close`. */
async function sendTwo(url: URL, first: string, second: (firstResponse: string) => string): Promise<[string, string]> {
const open = () => connect(Number(url.port), url.hostname);
const socket = open();
socket.write(first);
const firstResponse = await readResponse(socket);
const next = /^connection: close\r?$/im.test(firstResponse.split('\r\n\r\n')[0]!) ? open() : socket;
next.write(second(firstResponse));
const secondResponse = await readResponse(next);
socket.destroy();
next.destroy();
return [firstResponse, secondResponse];
}

describe('a request sent with Connection: close', () => {
let server: Server | undefined;

afterEach(() => {
server?.close();
server = undefined;
});

it('closes the connection after an SSE response, so the next request is not rejected (NodeStreamableHTTPServerTransport)', async () => {
const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
await new McpServer({ name: 'test-server', version: '1.0.0' }).connect(transport);
server = createServer((req, res) => void transport.handleRequest(req, res));
const url = await listenOnRandomPort(server);

const initialize = {
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test-client', version: '1.0' } }
};
const [initResponse, notificationResponse] = await sendTwo(url, post(initialize), initResponse =>
post(
{ jsonrpc: '2.0', method: 'notifications/initialized' },
{
'Mcp-Session-Id': /^mcp-session-id: (\S+)/im.exec(initResponse)![1]!,
'Mcp-Protocol-Version': '2025-11-25'
}
)
);

expect(initResponse).toMatch(/^HTTP\/1\.1 200/);
expect(notificationResponse).toMatch(/^HTTP\/1\.1 202/);
await transport.close();
});

it('closes the connection after an SSE response, so the next request is not rejected (createMcpHandler)', async () => {
const handler = createMcpHandler(() => {
const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' });
mcpServer.registerTool('progress-then-echo', { inputSchema: z.object({}) }, async (_args, ctx) => {
await ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: 'tok', progress: 1 } });
return { content: [{ type: 'text', text: 'done' }] };
});
return mcpServer;
});
const node = toNodeHandler(handler);
server = createServer((req, res) => void node(req, res));
const url = await listenOnRandomPort(server);

const call = post(
{ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'progress-then-echo', arguments: {}, _meta: ENVELOPE } },
{ 'Mcp-Protocol-Version': MODERN_REVISION, 'Mcp-Method': 'tools/call', 'Mcp-Name': 'progress-then-echo' }
);
const [firstResponse, secondResponse] = await sendTwo(url, call, () => call);

expect(firstResponse).toMatch(/^content-type: text\/event-stream/im);
expect(secondResponse).toMatch(/^HTTP\/1\.1 200/);
await handler.close();
});

it('closes the connection after a subscriptions/listen stream ends, so the next request is not rejected', async () => {
const handler = createMcpHandler(() => new McpServer({ name: 'test-server', version: '1.0.0' }));
const node = toNodeHandler(handler);
server = createServer((req, res) => void node(req, res));
const url = await listenOnRandomPort(server);

// Nothing in the filter is honored, so the server completes the listen stream right after the ack.
const listen = post(
{ jsonrpc: '2.0', id: 1, method: 'subscriptions/listen', params: { _meta: ENVELOPE, notifications: {} } },
{ 'Mcp-Protocol-Version': MODERN_REVISION, 'Mcp-Method': 'subscriptions/listen' }
);
const [firstResponse, secondResponse] = await sendTwo(url, listen, () => listen);

expect(firstResponse).toMatch(/^content-type: text\/event-stream/im);
expect(secondResponse).toMatch(/^HTTP\/1\.1 200/);
await handler.close();
});
});
1 change: 0 additions & 1 deletion packages/server/src/server/listenRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@ export function createListenRouter(options: ListenRouterOptions): ListenRouter {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no'
}
});
Expand Down
1 change: 0 additions & 1 deletion packages/server/src/server/perRequestTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,6 @@ export class PerRequestHTTPServerTransport implements Transport {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
// Disable proxy buffering so streamed messages are
// delivered as they are written.
'X-Accel-Buffering': 'no'
Expand Down
3 changes: 0 additions & 3 deletions packages/server/src/server/streamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,6 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
const headers: Record<string, string> = {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no'
};

Expand Down Expand Up @@ -622,7 +621,6 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
const headers: Record<string, string> = {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no'
};

Expand Down Expand Up @@ -974,7 +972,6 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
const headers: Record<string, string> = {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no'
};

Expand Down
Loading