Skip to content

Commit b649ba5

Browse files
codewithkenzofelixweinberger
authored andcommitted
fix(server): call onerror callback for all transport errors
Adds missing onerror callback invocations before every createJsonErrorResponse call in WebStandardStreamableHTTPServerTransport. This ensures that transport errors are no longer silently swallowed and can be observed via the onerror callback. Changes: - Add this.onerror?.() calls to 15 locations in streamableHttp.ts - Add 10 test cases to verify onerror is called for various error conditions Fixes #1395
1 parent 108f2f3 commit b649ba5

2 files changed

Lines changed: 186 additions & 0 deletions

File tree

packages/server/src/server/streamableHttp.ts

Lines changed: 15 additions & 0 deletions
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
}
@@ -614,6 +619,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
614619
const acceptHeader = req.headers.get('accept');
615620
// The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.
616621
if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {
622+
this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));
617623
return this.createJsonErrorResponse(
618624
406,
619625
-32_000,
@@ -623,6 +629,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
623629

624630
const ct = req.headers.get('content-type');
625631
if (!ct || !ct.includes('application/json')) {
632+
this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));
626633
return this.createJsonErrorResponse(415, -32_000, 'Unsupported Media Type: Content-Type must be application/json');
627634
}
628635

@@ -636,6 +643,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
636643
try {
637644
rawMessage = await req.json();
638645
} catch {
646+
this.onerror?.(new Error('Parse error: Invalid JSON'));
639647
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON');
640648
}
641649
} else {
@@ -650,6 +658,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
650658
? rawMessage.map(msg => JSONRPCMessageSchema.parse(msg))
651659
: [JSONRPCMessageSchema.parse(rawMessage)];
652660
} catch {
661+
this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));
653662
return this.createJsonErrorResponse(400, -32_700, 'Parse error: Invalid JSON-RPC message');
654663
}
655664

@@ -660,9 +669,11 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
660669
// If it's a server with session management and the session ID is already set we should reject the request
661670
// to avoid re-initialization.
662671
if (this._initialized && this.sessionId !== undefined) {
672+
this.onerror?.(new Error('Invalid Request: Server already initialized'));
663673
return this.createJsonErrorResponse(400, -32_600, 'Invalid Request: Server already initialized');
664674
}
665675
if (messages.length > 1) {
676+
this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));
666677
return this.createJsonErrorResponse(400, -32_600, 'Invalid Request: Only one initialization request is allowed');
667678
}
668679
this.sessionId = this.sessionIdGenerator?.();
@@ -842,18 +853,21 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
842853
}
843854
if (!this._initialized) {
844855
// If the server has not been initialized yet, reject all requests
856+
this.onerror?.(new Error('Bad Request: Server not initialized'));
845857
return this.createJsonErrorResponse(400, -32_000, 'Bad Request: Server not initialized');
846858
}
847859

848860
const sessionId = req.headers.get('mcp-session-id');
849861

850862
if (!sessionId) {
851863
// Non-initialization requests without a session ID should return 400 Bad Request
864+
this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));
852865
return this.createJsonErrorResponse(400, -32_000, 'Bad Request: Mcp-Session-Id header is required');
853866
}
854867

855868
if (sessionId !== this.sessionId) {
856869
// Reject requests with invalid session ID with 404 Not Found
870+
this.onerror?.(new Error('Session not found'));
857871
return this.createJsonErrorResponse(404, -32_001, 'Session not found');
858872
}
859873

@@ -877,6 +891,7 @@ export class WebStandardStreamableHTTPServerTransport implements Transport {
877891
const protocolVersion = req.headers.get('mcp-protocol-version');
878892

879893
if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) {
894+
this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion}`));
880895
return this.createJsonErrorResponse(
881896
400,
882897
-32_000,

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

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,4 +765,175 @@ describe('Zod v4', () => {
765765
await expect(transport.start()).rejects.toThrow('Transport already started');
766766
});
767767
});
768+
769+
describe('HTTPServerTransport - onerror callback', () => {
770+
let transport: WebStandardStreamableHTTPServerTransport;
771+
let mcpServer: McpServer;
772+
let errors: Error[];
773+
774+
beforeEach(async () => {
775+
errors = [];
776+
mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
777+
778+
transport = new WebStandardStreamableHTTPServerTransport({
779+
sessionIdGenerator: () => randomUUID()
780+
});
781+
782+
transport.onerror = err => errors.push(err);
783+
784+
await mcpServer.connect(transport);
785+
});
786+
787+
afterEach(async () => {
788+
await transport.close();
789+
});
790+
791+
async function initializeServer(): Promise<string> {
792+
const request = createRequest('POST', TEST_MESSAGES.initialize);
793+
const response = await transport.handleRequest(request);
794+
return response.headers.get('mcp-session-id') as string;
795+
}
796+
797+
it('should call onerror for invalid JSON', async () => {
798+
const request = new Request('http://localhost/mcp', {
799+
method: 'POST',
800+
headers: {
801+
Accept: 'application/json, text/event-stream',
802+
'Content-Type': 'application/json'
803+
},
804+
body: 'not valid json'
805+
});
806+
807+
const response = await transport.handleRequest(request);
808+
809+
expect(response.status).toBe(400);
810+
expect(errors.length).toBeGreaterThan(0);
811+
expect(errors[0].message).toContain('Parse error');
812+
});
813+
814+
it('should call onerror for invalid JSON-RPC message', async () => {
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+
},
821+
body: JSON.stringify({ not: 'valid jsonrpc' })
822+
});
823+
824+
const response = await transport.handleRequest(request);
825+
826+
expect(response.status).toBe(400);
827+
expect(errors.length).toBeGreaterThan(0);
828+
expect(errors[0].message).toContain('Parse error');
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+
834+
const response = await transport.handleRequest(request);
835+
836+
expect(response.status).toBe(406);
837+
expect(errors.length).toBeGreaterThan(0);
838+
expect(errors[0].message).toContain('Not Acceptable');
839+
});
840+
841+
it('should call onerror for unsupported Content-Type', async () => {
842+
const request = new Request('http://localhost/mcp', {
843+
method: 'POST',
844+
headers: {
845+
Accept: 'application/json, text/event-stream',
846+
'Content-Type': 'text/plain'
847+
},
848+
body: JSON.stringify(TEST_MESSAGES.initialize)
849+
});
850+
851+
const response = await transport.handleRequest(request);
852+
853+
expect(response.status).toBe(415);
854+
expect(errors.length).toBeGreaterThan(0);
855+
expect(errors[0].message).toContain('Unsupported Media Type');
856+
});
857+
858+
it('should call onerror for server not initialized', async () => {
859+
const request = createRequest('POST', TEST_MESSAGES.toolsList);
860+
861+
const response = await transport.handleRequest(request);
862+
863+
expect(response.status).toBe(400);
864+
expect(errors.length).toBeGreaterThan(0);
865+
expect(errors[0].message).toContain('Server not initialized');
866+
});
867+
868+
it('should call onerror for invalid session ID', async () => {
869+
await initializeServer();
870+
871+
const request = createRequest('POST', TEST_MESSAGES.toolsList, { sessionId: 'invalid-session-id' });
872+
873+
const response = await transport.handleRequest(request);
874+
875+
expect(response.status).toBe(404);
876+
expect(errors.length).toBeGreaterThan(0);
877+
expect(errors[0].message).toContain('Session not found');
878+
});
879+
880+
it('should call onerror for re-initialization attempt', async () => {
881+
await initializeServer();
882+
883+
const request = createRequest('POST', TEST_MESSAGES.initialize);
884+
885+
const response = await transport.handleRequest(request);
886+
887+
expect(response.status).toBe(400);
888+
expect(errors.length).toBeGreaterThan(0);
889+
expect(errors[0].message).toContain('Server already initialized');
890+
});
891+
892+
it('should call onerror for GET without Accept header', async () => {
893+
const sessionId = await initializeServer();
894+
895+
const request = createRequest('GET', undefined, { sessionId, accept: 'application/json' });
896+
897+
const response = await transport.handleRequest(request);
898+
899+
expect(response.status).toBe(406);
900+
expect(errors.length).toBeGreaterThan(0);
901+
expect(errors[0].message).toContain('Not Acceptable');
902+
});
903+
904+
it('should call onerror for concurrent SSE streams', async () => {
905+
const sessionId = await initializeServer();
906+
907+
const request1 = createRequest('GET', undefined, { sessionId });
908+
await transport.handleRequest(request1);
909+
910+
const request2 = createRequest('GET', undefined, { sessionId });
911+
const response2 = await transport.handleRequest(request2);
912+
913+
expect(response2.status).toBe(409);
914+
expect(errors.length).toBeGreaterThan(0);
915+
expect(errors[0].message).toContain('Conflict');
916+
});
917+
918+
it('should call onerror for unsupported protocol version', async () => {
919+
const sessionId = await initializeServer();
920+
921+
const request = new Request('http://localhost/mcp', {
922+
method: 'POST',
923+
headers: {
924+
'Content-Type': 'application/json',
925+
Accept: 'application/json, text/event-stream',
926+
'mcp-session-id': sessionId,
927+
'mcp-protocol-version': 'unsupported-version'
928+
},
929+
body: JSON.stringify(TEST_MESSAGES.toolsList)
930+
});
931+
932+
const response = await transport.handleRequest(request);
933+
934+
expect(response.status).toBe(400);
935+
expect(errors.length).toBeGreaterThan(0);
936+
expect(errors[0].message).toContain('Unsupported protocol version');
937+
});
938+
});
768939
});

0 commit comments

Comments
 (0)