Skip to content

Commit 7e10f2c

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 12 test cases verifying onerror is called for each error condition. All tests verified to fail without the fix and pass with it.
1 parent c4ee360 commit 7e10f2c

2 files changed

Lines changed: 253 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: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,236 @@ 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+
// Verify spy starts clean (no calls from beforeEach setup)
856+
expect(onerrorSpy).not.toHaveBeenCalled();
857+
858+
const request = createRequest('POST', TEST_MESSAGES.toolsList);
859+
await transport.handleRequest(request);
860+
861+
expect(onerrorSpy).toHaveBeenCalledTimes(1);
862+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Server not initialized/);
863+
});
864+
865+
it('should call onerror for invalid session ID', async () => {
866+
await initializeServer();
867+
const request = createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'invalid-session-id' });
868+
await transport.handleRequest(request);
869+
870+
expect(onerrorSpy).toHaveBeenCalled();
871+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Session not found/);
872+
});
873+
874+
it('should call onerror for re-initialization attempt', async () => {
875+
await initializeServer();
876+
const request = createRequest('POST', TEST_MESSAGES.initialize);
877+
await transport.handleRequest(request);
878+
879+
expect(onerrorSpy).toHaveBeenCalled();
880+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Server already initialized/);
881+
});
882+
883+
it('should call onerror for missing Accept header on GET', async () => {
884+
const sessionId = await initializeServer();
885+
const request = createRequest('GET', undefined, { sessionId, accept: 'application/json' });
886+
await transport.handleRequest(request);
887+
888+
expect(onerrorSpy).toHaveBeenCalled();
889+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Not Acceptable/);
890+
});
891+
892+
it('should call onerror for concurrent SSE streams', async () => {
893+
const sessionId = await initializeServer();
894+
895+
// First SSE stream
896+
const request1 = createRequest('GET', undefined, { sessionId });
897+
const response1 = await transport.handleRequest(request1);
898+
expect(response1.status).toBe(200);
899+
900+
// Second SSE stream should trigger onerror
901+
const request2 = createRequest('GET', undefined, { sessionId });
902+
await transport.handleRequest(request2);
903+
904+
expect(onerrorSpy).toHaveBeenCalled();
905+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Only one SSE stream/);
906+
});
907+
908+
it('should call onerror for unsupported protocol version', async () => {
909+
const sessionId = await initializeServer();
910+
911+
const request = new Request('http://localhost/mcp', {
912+
method: 'POST',
913+
headers: {
914+
'Content-Type': 'application/json',
915+
Accept: 'application/json, text/event-stream',
916+
'mcp-session-id': sessionId,
917+
'mcp-protocol-version': 'unsupported-version'
918+
},
919+
body: JSON.stringify(TEST_MESSAGES.toolsList)
920+
});
921+
await transport.handleRequest(request);
922+
923+
expect(onerrorSpy).toHaveBeenCalled();
924+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Unsupported protocol version/);
925+
});
926+
927+
it('should call onerror for unsupported HTTP methods', async () => {
928+
// Verify spy starts clean (no calls from beforeEach setup)
929+
expect(onerrorSpy).not.toHaveBeenCalled();
930+
931+
const request = new Request('http://localhost/mcp', { method: 'PUT' });
932+
await transport.handleRequest(request);
933+
934+
expect(onerrorSpy).toHaveBeenCalledTimes(1);
935+
expect(onerrorSpy.mock.calls[0]![0]!.message).toMatch(/Method not allowed/);
936+
});
937+
938+
it('should call onerror for invalid event ID in replay', async () => {
939+
// Transport with event store that returns undefined for unknown IDs
940+
const eventStore: EventStore = {
941+
async storeEvent(): Promise<EventId> {
942+
return 'evt-1';
943+
},
944+
async getStreamIdForEventId(): Promise<StreamId | undefined> {
945+
return undefined; // Unknown event ID
946+
},
947+
async replayEventsAfter(): Promise<StreamId> {
948+
return 'stream-1';
949+
}
950+
};
951+
const storeTransport = new WebStandardStreamableHTTPServerTransport({
952+
sessionIdGenerator: () => randomUUID(),
953+
eventStore
954+
});
955+
const storeSpy = vi.fn<(error: Error) => void>();
956+
storeTransport.onerror = storeSpy;
957+
958+
const storeMcpServer = new McpServer({ name: 'test', version: '1.0.0' });
959+
await storeMcpServer.connect(storeTransport);
960+
961+
// Initialize first
962+
const initReq = createRequest('POST', TEST_MESSAGES.initialize);
963+
const initResp = await storeTransport.handleRequest(initReq);
964+
const sid = initResp.headers.get('mcp-session-id') as string;
965+
storeSpy.mockClear();
966+
967+
// GET with unknown Last-Event-ID
968+
const request = new Request('http://localhost/mcp', {
969+
method: 'GET',
970+
headers: {
971+
Accept: 'text/event-stream',
972+
'mcp-session-id': sid,
973+
'mcp-protocol-version': '2025-11-25',
974+
'Last-Event-ID': 'unknown-event-id'
975+
}
976+
});
977+
const response = await storeTransport.handleRequest(request);
978+
979+
expect(response.status).toBe(400);
980+
expect(storeSpy).toHaveBeenCalledTimes(1);
981+
expect(storeSpy.mock.calls[0]![0]!.message).toMatch(/Invalid event ID format/);
982+
983+
await storeTransport.close();
984+
});
985+
});
986+
757987
describe('HTTPServerTransport - start() method', () => {
758988
it('should throw error when started twice', async () => {
759989
const transport = new WebStandardStreamableHTTPServerTransport({

0 commit comments

Comments
 (0)