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/fix-onerror-nested-catch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/server': patch
---

Fix nested try-catch in StreamableHTTP transport onerror handler to prevent unhandled exceptions from bubbling up.
6 changes: 4 additions & 2 deletions packages/server/src/server/streamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,8 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
if (options?.parsedBody === undefined) {
try {
rawMessage = await req.json();
} catch {
} catch (error) {
this.onerror?.(error as Error);
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON');
}
} else {
Expand All @@ -649,7 +650,8 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
messages = Array.isArray(rawMessage)
? rawMessage.map(msg => JSONRPCMessageSchema.parse(msg))
: [JSONRPCMessageSchema.parse(rawMessage)];
} catch {
} catch (error) {
this.onerror?.(error as Error);
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON-RPC message');
}

Expand Down
32 changes: 32 additions & 0 deletions packages/server/test/server/streamableHttp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,38 @@ describe('Zod v4', () => {
expectErrorResponse(errorData, -32_700, /Parse error.*Invalid JSON/);
});

it('should call onerror when receiving invalid JSON', async () => {
const errors: Error[] = [];
transport.onerror = error => errors.push(error);

const request = new Request('http://localhost/mcp', {
method: 'POST',
headers: {
Accept: 'application/json, text/event-stream',
'Content-Type': 'application/json'
},
body: 'not valid json'
});
const response = await transport.handleRequest(request);

expect(response.status).toBe(400);
expect(errors.length).toBe(1);
});

it('should call onerror when receiving invalid JSON-RPC message', async () => {
sessionId = await initializeServer();
const errors: Error[] = [];
transport.onerror = error => errors.push(error);

const request = createRequest('POST', { invalid: 'not a jsonrpc message' } as unknown as JSONRPCMessage, { sessionId });
const response = await transport.handleRequest(request);

expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32_700, /Parse error.*Invalid JSON-RPC/);
expect(errors.length).toBe(1);
});

it('should accept notifications without session and return 202', async () => {
sessionId = await initializeServer();

Expand Down
Loading