Skip to content

Commit 68401d6

Browse files
committed
fix: call onerror for silently swallowed transport errors
Fixes modelcontextprotocol#1395 - Several handleRequest error paths in WebStandardStreamableHTTPServerTransport were returning error responses via createJsonErrorResponse() without calling the onerror callback, making transport errors invisible to consumers. Added this.onerror?.() calls at 16 locations: - handleGetRequest: Missing Accept header (406), concurrent SSE stream (409) - replayEvents: Event store not configured (400), invalid event ID (400), stream conflict (409) - handlePostRequest: Invalid Accept header (406), unsupported Content-Type (415), JSON parse error (400), invalid JSON-RPC (400), re-initialization (400), multiple init requests (400) - validateSession: Server not initialized (400), missing session ID (400), session ID mismatch (404) - validateProtocolVersion: Unsupported protocol version (400) - handleUnsupportedRequest: Method not allowed (405) - writeSSEEvent: SSE write failure Added 11 test cases verifying onerror is called for each error condition.
1 parent c4ee360 commit 68401d6

2 files changed

Lines changed: 199 additions & 1 deletion

File tree

‎packages/server/src/server/streamableHttp.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
404404
// The client MUST include an Accept header, listing text/event-stream as a supported content type.
405405
const acceptHeader = req.headers.get('accept');
406406
if (!acceptHeader?.includes('text/event-stream')) {
407+
this.onerror?.(new Error('Not Acceptable: Client must accept text/event-stream'));
407408
return this.createJsonErrorResponse(406, -32_000, 'Not Acceptable: Client must accept text/event-stream');
408409
}
409410

@@ -430,6 +431,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
430431
// Check if there's already an active standalone SSE stream for this session
431432
if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {
432433
// Only one GET SSE stream is allowed per session
434+
this.onerror?.(new Error('Conflict: Only one SSE stream is allowed per session'));
433435
return this.createJsonErrorResponse(409, -32_000, 'Conflict: Only one SSE stream is allowed per session');
434436
}
435437

@@ -481,6 +483,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
481483
*/
482484
private async replayEvents(lastEventId: string): Promise<Response> {
483485
if (!this._eventStore) {
486+
this.onerror?.(new Error('Event store not configured'));
484487
return this.createJsonErrorResponse(400, -32_000, 'Event store not configured');
485488
}
486489

@@ -491,11 +494,13 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
491494
streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
492495

493496
if (!streamId) {
497+
this.onerror?.(new Error('Invalid event ID format'));
494498
return this.createJsonErrorResponse(400, -32_000, 'Invalid event ID format');
495499
}
496500

497501
// Check conflict with the SAME streamId we'll use for mapping
498502
if (this._streamMapping.get(streamId) !== undefined) {
503+
this.onerror?.(new Error('Conflict: Stream already has an active connection'));
499504
return this.createJsonErrorResponse(409, -32_000, 'Conflict: Stream already has an active connection');
500505
}
501506
}
@@ -577,7 +582,8 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
577582
eventData += `data: ${JSON.stringify(message)}\n\n`;
578583
controller.enqueue(encoder.encode(eventData));
579584
return true;
580-
} catch {
585+
} catch (error) {
586+
this.onerror?.(error as Error);
581587
return false;
582588
}
583589
}
@@ -586,6 +592,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
586592
* Handles unsupported requests (`PUT`, `PATCH`, etc.)
587593
*/
588594
private handleUnsupportedRequest(): Response {
595+
this.onerror?.(new Error('Method not allowed.'));
589596
return Response.json(
590597
{
591598
jsonrpc: '2.0',
@@ -614,6 +621,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
614621
const acceptHeader = req.headers.get('accept');
615622
// The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.
616623
if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {
624+
this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));
617625
return this.createJsonErrorResponse(
618626
406,
619627
-32_000,
@@ -623,6 +631,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
623631

624632
const ct = req.headers.get('content-type');
625633
if (!ct || !ct.includes('application/json')) {
634+
this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));
626635
return this.createJsonErrorResponse(415, -32_000, 'Unsupported Media Type: Content-Type must be application/json');
627636
}
628637

@@ -636,6 +645,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
636645
try {
637646
rawMessage = await req.json();
638647
} catch {
648+
this.onerror?.(new Error('Parse error: Invalid JSON'));
639649
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON');
640650
}
641651
} else {
@@ -650,6 +660,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
650660
? rawMessage.map(msg => JSONRPCMessageSchema.parse(msg))
651661
: [JSONRPCMessageSchema.parse(rawMessage)];
652662
} catch {
663+
this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));
653664
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON-RPC message');
654665
}
655666

@@ -660,9 +671,11 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
660671
// If it's a server with session management and the session ID is already set we should reject the request
661672
// to avoid re-initialization.
662673
if (this._initialized && this.sessionId !== undefined) {
674+
this.onerror?.(new Error('Invalid Request: Server already initialized'));
663675
return this.createJsonErrorResponse(400, -32_600, 'Invalid Request: Server already initialized');
664676
}
665677
if (messages.length > 1) {
678+
this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));
666679
return this.createJsonErrorResponse(400, -32_600, 'Invalid Request: Only one initialization request is allowed');
667680
}
668681
this.sessionId = this.sessionIdGenerator?.();
@@ -842,18 +855,21 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
842855
}
843856
if (!this._initialized) {
844857
// If the server has not been initialized yet, reject all requests
858+
this.onerror?.(new Error('Bad Request: Server not initialized'));
845859
return this.createJsonErrorResponse(400, -32_000, 'Bad Request: Server not initialized');
846860
}
847861

848862
const sessionId = req.headers.get('mcp-session-id');
849863

850864
if (!sessionId) {
851865
// Non-initialization requests without a session ID should return 400 Bad Request
866+
this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));
852867
return this.createJsonErrorResponse(400, -32_000, 'Bad Request: Mcp-Session-Id header is required');
853868
}
854869

855870
if (sessionId !== this.sessionId) {
856871
// Reject requests with invalid session ID with 404 Not Found
872+
this.onerror?.(new Error('Session not found'));
857873
return this.createJsonErrorResponse(404, -32_001, 'Session not found');
858874
}
859875

@@ -877,6 +893,12 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
877893
const protocolVersion = req.headers.get('mcp-protocol-version');
878894

879895
if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) {
896+
this.onerror?.(
897+
new Error(
898+
`Bad Request: Unsupported protocol version: ${protocolVersion}` +
899+
` (supported versions: ${this._supportedProtocolVersions.join(', ')})`
900+
)
901+
);
880902
return this.createJsonErrorResponse(
881903
400,
882904
-32_000,

‎packages/server/test/server/streamableHttp.test.ts‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,182 @@ describe('Zod v4', () => {
754754
});
755755
});
756756

757+
describe('HTTPServerTransport - onerror callback', () => {
758+
let transport: WebStandardStreamableHTTPServerTransport;
759+
let mcpServer: McpServer;
760+
let onerrorSpy: ReturnType<typeof vi.fn<(error: Error) => void>>;
761+
762+
beforeEach(async () => {
763+
onerrorSpy = vi.fn<(error: Error) => void>();
764+
mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } });
765+
766+
mcpServer.registerTool(
767+
'greet',
768+
{
769+
description: 'A simple greeting tool',
770+
inputSchema: z.object({ name: z.string().describe('Name to greet') })
771+
},
772+
async ({ name }): Promise<CallToolResult> => {
773+
return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
774+
}
775+
);
776+
777+
transport = new WebStandardStreamableHTTPServerTransport({
778+
sessionIdGenerator: () => randomUUID()
779+
});
780+
transport.onerror = onerrorSpy;
781+
782+
await mcpServer.connect(transport);
783+
});
784+
785+
afterEach(async () => {
786+
await transport.close();
787+
});
788+
789+
async function initializeServer(): Promise<string> {
790+
onerrorSpy.mockClear();
791+
const request = createRequest('POST', TEST_MESSAGES.initialize);
792+
const response = await transport.handleRequest(request);
793+
expect(response.status).toBe(200);
794+
return response.headers.get('mcp-session-id') as string;
795+
}
796+
797+
it('should call onerror for invalid JSON in POST', async () => {
798+
await initializeServer();
799+
const request = new Request('http://localhost/mcp', {
800+
method: 'POST',
801+
headers: {
802+
Accept: 'application/json, text/event-stream',
803+
'Content-Type': 'application/json'
804+
},
805+
body: 'not valid json'
806+
});
807+
await transport.handleRequest(request);
808+
809+
expect(onerrorSpy).toHaveBeenCalled();
810+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Invalid JSON/);
811+
});
812+
813+
it('should call onerror for invalid JSON-RPC message', async () => {
814+
const sessionId = await initializeServer();
815+
const request = new Request('http://localhost/mcp', {
816+
method: 'POST',
817+
headers: {
818+
Accept: 'application/json, text/event-stream',
819+
'Content-Type': 'application/json',
820+
'mcp-session-id': sessionId,
821+
'mcp-protocol-version': '2025-11-25'
822+
},
823+
body: JSON.stringify({ not: 'a valid jsonrpc message' })
824+
});
825+
await transport.handleRequest(request);
826+
827+
expect(onerrorSpy).toHaveBeenCalled();
828+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Invalid JSON-RPC message/);
829+
});
830+
831+
it('should call onerror for missing Accept header on POST', async () => {
832+
const request = createRequest('POST', TEST_MESSAGES.initialize, { accept: 'application/json' });
833+
await transport.handleRequest(request);
834+
835+
expect(onerrorSpy).toHaveBeenCalled();
836+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Not Acceptable/);
837+
});
838+
839+
it('should call onerror for unsupported Content-Type', async () => {
840+
const request = new Request('http://localhost/mcp', {
841+
method: 'POST',
842+
headers: {
843+
Accept: 'application/json, text/event-stream',
844+
'Content-Type': 'text/plain'
845+
},
846+
body: JSON.stringify(TEST_MESSAGES.initialize)
847+
});
848+
await transport.handleRequest(request);
849+
850+
expect(onerrorSpy).toHaveBeenCalled();
851+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Unsupported Media Type/);
852+
});
853+
854+
it('should call onerror when server is not initialized', async () => {
855+
const request = createRequest('POST', TEST_MESSAGES.toolsList);
856+
await transport.handleRequest(request);
857+
858+
expect(onerrorSpy).toHaveBeenCalled();
859+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Server not initialized/);
860+
});
861+
862+
it('should call onerror for invalid session ID', async () => {
863+
await initializeServer();
864+
const request = createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'invalid-session-id' });
865+
await transport.handleRequest(request);
866+
867+
expect(onerrorSpy).toHaveBeenCalled();
868+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Session not found/);
869+
});
870+
871+
it('should call onerror for re-initialization attempt', async () => {
872+
await initializeServer();
873+
const request = createRequest('POST', TEST_MESSAGES.initialize);
874+
await transport.handleRequest(request);
875+
876+
expect(onerrorSpy).toHaveBeenCalled();
877+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Server already initialized/);
878+
});
879+
880+
it('should call onerror for missing Accept header on GET', async () => {
881+
const sessionId = await initializeServer();
882+
const request = createRequest('GET', undefined, { sessionId, accept: 'application/json' });
883+
await transport.handleRequest(request);
884+
885+
expect(onerrorSpy).toHaveBeenCalled();
886+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Not Acceptable/);
887+
});
888+
889+
it('should call onerror for concurrent SSE streams', async () => {
890+
const sessionId = await initializeServer();
891+
892+
// First SSE stream
893+
const request1 = createRequest('GET', undefined, { sessionId });
894+
const response1 = await transport.handleRequest(request1);
895+
expect(response1.status).toBe(200);
896+
897+
// Second SSE stream should trigger onerror
898+
const request2 = createRequest('GET', undefined, { sessionId });
899+
await transport.handleRequest(request2);
900+
901+
expect(onerrorSpy).toHaveBeenCalled();
902+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Only one SSE stream/);
903+
});
904+
905+
it('should call onerror for unsupported protocol version', async () => {
906+
const sessionId = await initializeServer();
907+
908+
const request = new Request('http://localhost/mcp', {
909+
method: 'POST',
910+
headers: {
911+
'Content-Type': 'application/json',
912+
Accept: 'application/json, text/event-stream',
913+
'mcp-session-id': sessionId,
914+
'mcp-protocol-version': 'unsupported-version'
915+
},
916+
body: JSON.stringify(TEST_MESSAGES.toolsList)
917+
});
918+
await transport.handleRequest(request);
919+
920+
expect(onerrorSpy).toHaveBeenCalled();
921+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Unsupported protocol version/);
922+
});
923+
924+
it('should call onerror for unsupported HTTP methods', async () => {
925+
const request = new Request('http://localhost/mcp', { method: 'PUT' });
926+
await transport.handleRequest(request);
927+
928+
expect(onerrorSpy).toHaveBeenCalled();
929+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Method not allowed/);
930+
});
931+
});
932+
757933
describe('HTTPServerTransport - start() method', () => {
758934
it('should throw error when started twice', async () => {
759935
const transport = new WebStandardStreamableHTTPServerTransport({

0 commit comments

Comments
 (0)