Skip to content

Commit 7c943bd

Browse files
committed
fix: prevent unhandled rejections on close and detect stdin EOF
Two fixes for the "Connection closed" crash (MCP error -32000): 1. Protocol._onclose() now defers pending response handler rejections to the next microtask via Promise.resolve().then(), giving callers time to attach .catch() handlers. This prevents Node.js from triggering unhandled promise rejections when the transport closes unexpectedly while requests are in-flight. 2. StdioServerTransport now listens for the stdin 'end' event (EOF) and triggers a clean close(). Previously, when the client process exited, the server had no way to detect the disconnection, leaving it running indefinitely with pending requests that would never resolve. Together these fixes address the crash reported in modelcontextprotocol#1049 where stdio-based MCP servers would die with "MCP error -32000: Connection closed" unhandled rejections when the client process exits. Also addresses the root cause described in modelcontextprotocol#392 (promise/async handling causes unhandled rejections). Fixes modelcontextprotocol#1049 Refs modelcontextprotocol#392
1 parent 7ba58da commit 7c943bd

4 files changed

Lines changed: 148 additions & 1 deletion

File tree

‎packages/core/src/shared/protocol.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,8 +511,17 @@ export abstract class Protocol<ContextT extends BaseContext> {
511511
try {
512512
this.onclose?.();
513513
} finally {
514+
// Reject pending response handlers on the next microtask to allow
515+
// callers time to attach .catch() handlers and prevent unhandled
516+
// promise rejections (see #1049, #392).
514517
for (const handler of responseHandlers.values()) {
515-
handler(error);
518+
void Promise.resolve().then(() => {
519+
try {
520+
handler(error);
521+
} catch (handlerError) {
522+
this._onerror(handlerError instanceof Error ? handlerError : new Error(String(handlerError)));
523+
}
524+
});
516525
}
517526

518527
for (const controller of requestHandlerAbortControllers.values()) {

‎packages/core/test/shared/protocol.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,59 @@ describe('protocol tests', () => {
217217
expect(oncloseMock).toHaveBeenCalled();
218218
});
219219

220+
test('should reject pending requests with ConnectionClosed when transport closes', async () => {
221+
await protocol.connect(transport);
222+
const mockSchema = z.object({ result: z.string() });
223+
const requestPromise = testRequest(protocol, { method: 'example', params: {} }, mockSchema);
224+
225+
// Close transport while request is pending
226+
await transport.close();
227+
228+
// The pending request should reject with ConnectionClosed
229+
await expect(requestPromise).rejects.toThrow('Connection closed');
230+
await expect(requestPromise).rejects.toMatchObject({
231+
code: SdkErrorCode.ConnectionClosed
232+
});
233+
});
234+
235+
test('should not cause unhandled promise rejections when transport closes with pending requests', async () => {
236+
await protocol.connect(transport);
237+
const mockSchema = z.object({ result: z.string() });
238+
239+
// Track unhandled rejections
240+
const unhandledRejections: unknown[] = [];
241+
const handler = (event: PromiseRejectionEvent) => {
242+
unhandledRejections.push(event.reason);
243+
event.preventDefault();
244+
};
245+
246+
// In Node.js, listen on process instead of globalThis
247+
const processHandler = (reason: unknown) => {
248+
unhandledRejections.push(reason);
249+
};
250+
process.on('unhandledRejection', processHandler);
251+
252+
try {
253+
// Create a pending request and attach .catch() to prevent the expected rejection
254+
// from triggering the handler
255+
const requestPromise = testRequest(protocol, { method: 'example', params: {} }, mockSchema);
256+
requestPromise.catch(() => {
257+
// Expected — the request was rejected due to connection close
258+
});
259+
260+
// Close transport
261+
await transport.close();
262+
263+
// Wait for microtasks to flush
264+
await new Promise(resolve => setTimeout(resolve, 50));
265+
266+
// No unhandled rejections should have occurred
267+
expect(unhandledRejections).toHaveLength(0);
268+
} finally {
269+
process.off('unhandledRejection', processHandler);
270+
}
271+
});
272+
220273
test('should abort in-flight request handlers when the connection is closed', async () => {
221274
await protocol.connect(transport);
222275

‎packages/server/src/server/stdio.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ export class StdioServerTransport implements Transport {
4444
// Ignore errors during close — we're already in an error path
4545
});
4646
};
47+
_onend = () => {
48+
// stdin EOF means the client process has disconnected.
49+
// Trigger a clean close so pending requests are properly rejected
50+
// and the server can shut down gracefully (see #1049).
51+
this.close().catch(() => {
52+
// Ignore errors during close — we're already in a shutdown path
53+
});
54+
};
4755

4856
/**
4957
* Starts listening for messages on `stdin`.
@@ -57,6 +65,7 @@ export class StdioServerTransport implements Transport {
5765

5866
this._started = true;
5967
this._stdin.on('data', this._ondata);
68+
this._stdin.on('end', this._onend);
6069
this._stdin.on('error', this._onerror);
6170
this._stdout.on('error', this._onstdouterror);
6271
}
@@ -84,6 +93,7 @@ export class StdioServerTransport implements Transport {
8493

8594
// Remove our event listeners first
8695
this._stdin.off('data', this._ondata);
96+
this._stdin.off('end', this._onend);
8797
this._stdin.off('error', this._onerror);
8898
this._stdout.off('error', this._onstdouterror);
8999

‎packages/server/test/server/stdio.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,78 @@ test('should fire onerror before onclose on stdout error', async () => {
179179

180180
expect(events).toEqual(['error', 'close']);
181181
});
182+
183+
test('should close transport when stdin emits end (EOF)', async () => {
184+
const server = new StdioServerTransport(input, output);
185+
server.onerror = error => {
186+
throw error;
187+
};
188+
189+
let didClose = false;
190+
server.onclose = () => {
191+
didClose = true;
192+
};
193+
194+
await server.start();
195+
expect(didClose).toBeFalsy();
196+
197+
// Simulate client disconnecting (stdin EOF)
198+
input.push(null);
199+
200+
// Wait for the async close() to complete
201+
await new Promise(resolve => setTimeout(resolve, 50));
202+
expect(didClose).toBeTruthy();
203+
});
204+
205+
test('should not fire onclose twice when stdin EOF followed by explicit close()', async () => {
206+
const server = new StdioServerTransport(input, output);
207+
server.onerror = error => {
208+
throw error;
209+
};
210+
211+
let closeCount = 0;
212+
server.onclose = () => {
213+
closeCount++;
214+
};
215+
216+
await server.start();
217+
218+
// stdin EOF triggers close
219+
input.push(null);
220+
await new Promise(resolve => setTimeout(resolve, 50));
221+
222+
// Explicit close should be idempotent
223+
await server.close();
224+
225+
expect(closeCount).toBe(1);
226+
});
227+
228+
test('should process remaining messages before closing on stdin EOF', async () => {
229+
const server = new StdioServerTransport(input, output);
230+
server.onerror = error => {
231+
throw error;
232+
};
233+
234+
const messages: JSONRPCMessage[] = [];
235+
server.onmessage = message => {
236+
messages.push(message);
237+
};
238+
239+
await server.start();
240+
241+
const message: JSONRPCMessage = {
242+
jsonrpc: '2.0',
243+
id: 1,
244+
method: 'ping'
245+
};
246+
247+
// Push a message followed by EOF
248+
input.push(serializeMessage(message));
249+
input.push(null);
250+
251+
// Wait for processing
252+
await new Promise(resolve => setTimeout(resolve, 50));
253+
254+
// The message should have been processed before close
255+
expect(messages).toEqual([message]);
256+
});

0 commit comments

Comments
 (0)