forked from modelcontextprotocol/typescript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamableHttp.test.ts
1163 lines (968 loc) · 36.9 KB
/
streamableHttp.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createServer, type Server, IncomingMessage, ServerResponse } from "node:http";
import { AddressInfo } from "node:net";
import { randomUUID } from "node:crypto";
import { EventStore, StreamableHTTPServerTransport, EventId, StreamId } from "./streamableHttp.js";
import { McpServer } from "./mcp.js";
import { CallToolResult, JSONRPCMessage } from "../types.js";
import { z } from "zod";
/**
* Test server configuration for StreamableHTTPServerTransport tests
*/
interface TestServerConfig {
sessionIdGenerator?: () => string | undefined;
enableJsonResponse?: boolean;
customRequestHandler?: (req: IncomingMessage, res: ServerResponse, parsedBody?: unknown) => Promise<void>;
eventStore?: EventStore;
}
/**
* Helper to create and start test HTTP server with MCP setup
*/
async function createTestServer(config: TestServerConfig = {}): Promise<{
server: Server;
transport: StreamableHTTPServerTransport;
mcpServer: McpServer;
baseUrl: URL;
}> {
const mcpServer = new McpServer(
{ name: "test-server", version: "1.0.0" },
{ capabilities: { logging: {} } }
);
mcpServer.tool(
"greet",
"A simple greeting tool",
{ name: z.string().describe("Name to greet") },
async ({ name }): Promise<CallToolResult> => {
return { content: [{ type: "text", text: `Hello, ${name}!` }] };
}
);
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: config.sessionIdGenerator ?? (() => randomUUID()),
enableJsonResponse: config.enableJsonResponse ?? false,
eventStore: config.eventStore
});
await mcpServer.connect(transport);
const server = createServer(async (req, res) => {
try {
if (config.customRequestHandler) {
await config.customRequestHandler(req, res);
} else {
await transport.handleRequest(req, res);
}
} catch (error) {
console.error("Error handling request:", error);
if (!res.headersSent) res.writeHead(500).end();
}
});
const baseUrl = await new Promise<URL>((resolve) => {
server.listen(0, "127.0.0.1", () => {
const addr = server.address() as AddressInfo;
resolve(new URL(`http://127.0.0.1:${addr.port}`));
});
});
return { server, transport, mcpServer, baseUrl };
}
/**
* Helper to stop test server
*/
async function stopTestServer({ server, transport }: { server: Server; transport: StreamableHTTPServerTransport }): Promise<void> {
// First close the transport to ensure all SSE streams are closed
await transport.close();
// Close the server without waiting indefinitely
server.close();
}
/**
* Common test messages
*/
const TEST_MESSAGES = {
initialize: {
jsonrpc: "2.0",
method: "initialize",
params: {
clientInfo: { name: "test-client", version: "1.0" },
protocolVersion: "2025-03-26",
capabilities: {
},
},
id: "init-1",
} as JSONRPCMessage,
toolsList: {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "tools-1",
} as JSONRPCMessage
};
/**
* Helper to extract text from SSE response
* Note: Can only be called once per response stream. For multiple reads,
* get the reader manually and read multiple times.
*/
async function readSSEEvent(response: Response): Promise<string> {
const reader = response.body?.getReader();
const { value } = await reader!.read();
return new TextDecoder().decode(value);
}
/**
* Helper to send JSON-RPC request
*/
async function sendPostRequest(baseUrl: URL, message: JSONRPCMessage | JSONRPCMessage[], sessionId?: string): Promise<Response> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
};
if (sessionId) {
headers["mcp-session-id"] = sessionId;
}
return fetch(baseUrl, {
method: "POST",
headers,
body: JSON.stringify(message),
});
}
function expectErrorResponse(data: unknown, expectedCode: number, expectedMessagePattern: RegExp): void {
expect(data).toMatchObject({
jsonrpc: "2.0",
error: expect.objectContaining({
code: expectedCode,
message: expect.stringMatching(expectedMessagePattern),
}),
});
}
describe("StreamableHTTPServerTransport", () => {
let server: Server;
let transport: StreamableHTTPServerTransport;
let baseUrl: URL;
let sessionId: string;
beforeEach(async () => {
const result = await createTestServer();
server = result.server;
transport = result.transport;
baseUrl = result.baseUrl;
});
afterEach(async () => {
await stopTestServer({ server, transport });
});
async function initializeServer(): Promise<string> {
const response = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize);
expect(response.status).toBe(200);
const newSessionId = response.headers.get("mcp-session-id");
expect(newSessionId).toBeDefined();
return newSessionId as string;
}
it("should initialize server and generate session ID", async () => {
const response = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream");
expect(response.headers.get("mcp-session-id")).toBeDefined();
});
it("should reject second initialization request", async () => {
// First initialize
const sessionId = await initializeServer();
expect(sessionId).toBeDefined();
// Try second initialize
const secondInitMessage: JSONRPCMessage = {
jsonrpc: "2.0",
method: "initialize",
params: {
clientInfo: { name: "test-client-2", version: "1.0" },
protocolVersion: "2025-03-26",
},
id: "init-2",
};
const response = await sendPostRequest(baseUrl, secondInitMessage);
expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32600, /Server already initialized/);
});
it("should reject batch initialize request", async () => {
const batchInitMessages: JSONRPCMessage[] = [
TEST_MESSAGES.initialize,
{
jsonrpc: "2.0",
method: "initialize",
params: {
clientInfo: { name: "test-client-2", version: "1.0" },
protocolVersion: "2025-03-26",
},
id: "init-2",
}
];
const response = await sendPostRequest(baseUrl, batchInitMessages);
expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32600, /Only one initialization request is allowed/);
});
it("should pandle post requests via sse response correctly", async () => {
sessionId = await initializeServer();
const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList, sessionId);
expect(response.status).toBe(200);
// Read the SSE stream for the response
const text = await readSSEEvent(response);
// Parse the SSE event
const eventLines = text.split("\n");
const dataLine = eventLines.find(line => line.startsWith("data:"));
expect(dataLine).toBeDefined();
const eventData = JSON.parse(dataLine!.substring(5));
expect(eventData).toMatchObject({
jsonrpc: "2.0",
result: expect.objectContaining({
tools: expect.arrayContaining([
expect.objectContaining({
name: "greet",
description: "A simple greeting tool",
}),
]),
}),
id: "tools-1",
});
});
it("should call a tool and return the result", async () => {
sessionId = await initializeServer();
const toolCallMessage: JSONRPCMessage = {
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "greet",
arguments: {
name: "Test User",
},
},
id: "call-1",
};
const response = await sendPostRequest(baseUrl, toolCallMessage, sessionId);
expect(response.status).toBe(200);
const text = await readSSEEvent(response);
const eventLines = text.split("\n");
const dataLine = eventLines.find(line => line.startsWith("data:"));
expect(dataLine).toBeDefined();
const eventData = JSON.parse(dataLine!.substring(5));
expect(eventData).toMatchObject({
jsonrpc: "2.0",
result: {
content: [
{
type: "text",
text: "Hello, Test User!",
},
],
},
id: "call-1",
});
});
it("should reject requests without a valid session ID", async () => {
const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList);
expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32000, /Bad Request/);
expect(errorData.id).toBeNull();
});
it("should reject invalid session ID", async () => {
// First initialize to be in valid state
await initializeServer();
// Now try with invalid session ID
const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList, "invalid-session-id");
expect(response.status).toBe(404);
const errorData = await response.json();
expectErrorResponse(errorData, -32001, /Session not found/);
});
it("should establish standalone SSE stream and receive server-initiated messages", async () => {
// First initialize to get a session ID
sessionId = await initializeServer();
// Open a standalone SSE stream
const sseResponse = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
expect(sseResponse.status).toBe(200);
expect(sseResponse.headers.get("content-type")).toBe("text/event-stream");
// Send a notification (server-initiated message) that should appear on SSE stream
const notification: JSONRPCMessage = {
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "Test notification" },
};
// Send the notification via transport
await transport.send(notification);
// Read from the stream and verify we got the notification
const text = await readSSEEvent(sseResponse);
const eventLines = text.split("\n");
const dataLine = eventLines.find(line => line.startsWith("data:"));
expect(dataLine).toBeDefined();
const eventData = JSON.parse(dataLine!.substring(5));
expect(eventData).toMatchObject({
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "Test notification" },
});
});
it("should not close GET SSE stream after sending multiple server notifications", async () => {
sessionId = await initializeServer();
// Open a standalone SSE stream
const sseResponse = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
expect(sseResponse.status).toBe(200);
const reader = sseResponse.body?.getReader();
// Send multiple notifications
const notification1: JSONRPCMessage = {
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "First notification" }
};
// Just send one and verify it comes through - then the stream should stay open
await transport.send(notification1);
const { value, done } = await reader!.read();
const text = new TextDecoder().decode(value);
expect(text).toContain("First notification");
expect(done).toBe(false); // Stream should still be open
});
it("should reject second SSE stream for the same session", async () => {
sessionId = await initializeServer();
// Open first SSE stream
const firstStream = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
expect(firstStream.status).toBe(200);
// Try to open a second SSE stream with the same session ID
const secondStream = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
// Should be rejected
expect(secondStream.status).toBe(409); // Conflict
const errorData = await secondStream.json();
expectErrorResponse(errorData, -32000, /Only one SSE stream is allowed per session/);
});
it("should reject GET requests without Accept: text/event-stream header", async () => {
sessionId = await initializeServer();
// Try GET without proper Accept header
const response = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "application/json",
"mcp-session-id": sessionId,
},
});
expect(response.status).toBe(406);
const errorData = await response.json();
expectErrorResponse(errorData, -32000, /Client must accept text\/event-stream/);
});
it("should reject POST requests without proper Accept header", async () => {
sessionId = await initializeServer();
// Try POST without Accept: text/event-stream
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json", // Missing text/event-stream
"mcp-session-id": sessionId,
},
body: JSON.stringify(TEST_MESSAGES.toolsList),
});
expect(response.status).toBe(406);
const errorData = await response.json();
expectErrorResponse(errorData, -32000, /Client must accept both application\/json and text\/event-stream/);
});
it("should reject unsupported Content-Type", async () => {
sessionId = await initializeServer();
// Try POST with text/plain Content-Type
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "text/plain",
Accept: "application/json, text/event-stream",
"mcp-session-id": sessionId,
},
body: "This is plain text",
});
expect(response.status).toBe(415);
const errorData = await response.json();
expectErrorResponse(errorData, -32000, /Content-Type must be application\/json/);
});
it("should handle JSON-RPC batch notification messages with 202 response", async () => {
sessionId = await initializeServer();
// Send batch of notifications (no IDs)
const batchNotifications: JSONRPCMessage[] = [
{ jsonrpc: "2.0", method: "someNotification1", params: {} },
{ jsonrpc: "2.0", method: "someNotification2", params: {} },
];
const response = await sendPostRequest(baseUrl, batchNotifications, sessionId);
expect(response.status).toBe(202);
});
it("should handle batch request messages with SSE stream for responses", async () => {
sessionId = await initializeServer();
// Send batch of requests
const batchRequests: JSONRPCMessage[] = [
{ jsonrpc: "2.0", method: "tools/list", params: {}, id: "req-1" },
{ jsonrpc: "2.0", method: "tools/call", params: { name: "greet", arguments: { name: "BatchUser" } }, id: "req-2" },
];
const response = await sendPostRequest(baseUrl, batchRequests, sessionId);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream");
const reader = response.body?.getReader();
// The responses may come in any order or together in one chunk
const { value } = await reader!.read();
const text = new TextDecoder().decode(value);
// Check that both responses were sent on the same stream
expect(text).toContain('"id":"req-1"');
expect(text).toContain('"tools"'); // tools/list result
expect(text).toContain('"id":"req-2"');
expect(text).toContain('Hello, BatchUser'); // tools/call result
});
it("should properly handle invalid JSON data", async () => {
sessionId = await initializeServer();
// Send invalid JSON
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
"mcp-session-id": sessionId,
},
body: "This is not valid JSON",
});
expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32700, /Parse error/);
});
it("should return 400 error for invalid JSON-RPC messages", async () => {
sessionId = await initializeServer();
// Invalid JSON-RPC (missing required jsonrpc version)
const invalidMessage = { method: "tools/list", params: {}, id: 1 }; // missing jsonrpc version
const response = await sendPostRequest(baseUrl, invalidMessage as JSONRPCMessage, sessionId);
expect(response.status).toBe(400);
const errorData = await response.json();
expect(errorData).toMatchObject({
jsonrpc: "2.0",
error: expect.anything(),
});
});
it("should reject requests to uninitialized server", async () => {
// Create a new HTTP server and transport without initializing
const { server: uninitializedServer, transport: uninitializedTransport, baseUrl: uninitializedUrl } = await createTestServer();
// Transport not used in test but needed for cleanup
// No initialization, just send a request directly
const uninitializedMessage: JSONRPCMessage = {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "uninitialized-test",
};
// Send a request to uninitialized server
const response = await sendPostRequest(uninitializedUrl, uninitializedMessage, "any-session-id");
expect(response.status).toBe(400);
const errorData = await response.json();
expectErrorResponse(errorData, -32000, /Server not initialized/);
// Cleanup
await stopTestServer({ server: uninitializedServer, transport: uninitializedTransport });
});
it("should send response messages to the connection that sent the request", async () => {
sessionId = await initializeServer();
const message1: JSONRPCMessage = {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "req-1"
};
const message2: JSONRPCMessage = {
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "greet",
arguments: { name: "Connection2" }
},
id: "req-2"
};
// Make two concurrent fetch connections for different requests
const req1 = sendPostRequest(baseUrl, message1, sessionId);
const req2 = sendPostRequest(baseUrl, message2, sessionId);
// Get both responses
const [response1, response2] = await Promise.all([req1, req2]);
const reader1 = response1.body?.getReader();
const reader2 = response2.body?.getReader();
// Read responses from each stream (requires each receives its specific response)
const { value: value1 } = await reader1!.read();
const text1 = new TextDecoder().decode(value1);
expect(text1).toContain('"id":"req-1"');
expect(text1).toContain('"tools"'); // tools/list result
const { value: value2 } = await reader2!.read();
const text2 = new TextDecoder().decode(value2);
expect(text2).toContain('"id":"req-2"');
expect(text2).toContain('Hello, Connection2'); // tools/call result
});
it("should keep stream open after sending server notifications", async () => {
sessionId = await initializeServer();
// Open a standalone SSE stream
const sseResponse = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
// Send several server-initiated notifications
await transport.send({
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "First notification" },
});
await transport.send({
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "Second notification" },
});
// Stream should still be open - it should not close after sending notifications
expect(sseResponse.bodyUsed).toBe(false);
});
// The current implementation will close the entire transport for DELETE
// Creating a temporary transport/server where we don't care if it gets closed
it("should properly handle DELETE requests and close session", async () => {
// Setup a temporary server for this test
const tempResult = await createTestServer();
const tempServer = tempResult.server;
const tempUrl = tempResult.baseUrl;
// Initialize to get a session ID
const initResponse = await sendPostRequest(tempUrl, TEST_MESSAGES.initialize);
const tempSessionId = initResponse.headers.get("mcp-session-id");
// Now DELETE the session
const deleteResponse = await fetch(tempUrl, {
method: "DELETE",
headers: { "mcp-session-id": tempSessionId || "" },
});
expect(deleteResponse.status).toBe(200);
// Clean up - don't wait indefinitely for server close
tempServer.close();
});
it("should reject DELETE requests with invalid session ID", async () => {
// Initialize the server first to activate it
sessionId = await initializeServer();
// Try to delete with invalid session ID
const response = await fetch(baseUrl, {
method: "DELETE",
headers: { "mcp-session-id": "invalid-session-id" },
});
expect(response.status).toBe(404);
const errorData = await response.json();
expectErrorResponse(errorData, -32001, /Session not found/);
});
});
// Test JSON Response Mode
describe("StreamableHTTPServerTransport with JSON Response Mode", () => {
let server: Server;
let transport: StreamableHTTPServerTransport;
let baseUrl: URL;
let sessionId: string;
beforeEach(async () => {
const result = await createTestServer({ enableJsonResponse: true });
server = result.server;
transport = result.transport;
baseUrl = result.baseUrl;
// Initialize and get session ID
const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize);
sessionId = initResponse.headers.get("mcp-session-id") as string;
});
afterEach(async () => {
await stopTestServer({ server, transport });
});
it("should return JSON response for a single request", async () => {
const toolsListMessage: JSONRPCMessage = {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "json-req-1",
};
const response = await sendPostRequest(baseUrl, toolsListMessage, sessionId);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("application/json");
const result = await response.json();
expect(result).toMatchObject({
jsonrpc: "2.0",
result: expect.objectContaining({
tools: expect.arrayContaining([
expect.objectContaining({ name: "greet" })
])
}),
id: "json-req-1"
});
});
it("should return JSON response for batch requests", async () => {
const batchMessages: JSONRPCMessage[] = [
{ jsonrpc: "2.0", method: "tools/list", params: {}, id: "batch-1" },
{ jsonrpc: "2.0", method: "tools/call", params: { name: "greet", arguments: { name: "JSON" } }, id: "batch-2" }
];
const response = await sendPostRequest(baseUrl, batchMessages, sessionId);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("application/json");
const results = await response.json();
expect(Array.isArray(results)).toBe(true);
expect(results).toHaveLength(2);
// Batch responses can come in any order
const listResponse = results.find((r: { id?: string }) => r.id === "batch-1");
const callResponse = results.find((r: { id?: string }) => r.id === "batch-2");
expect(listResponse).toEqual(expect.objectContaining({
jsonrpc: "2.0",
id: "batch-1",
result: expect.objectContaining({
tools: expect.arrayContaining([
expect.objectContaining({ name: "greet" })
])
})
}));
expect(callResponse).toEqual(expect.objectContaining({
jsonrpc: "2.0",
id: "batch-2",
result: expect.objectContaining({
content: expect.arrayContaining([
expect.objectContaining({ type: "text", text: "Hello, JSON!" })
])
})
}));
});
});
// Test pre-parsed body handling
describe("StreamableHTTPServerTransport with pre-parsed body", () => {
let server: Server;
let transport: StreamableHTTPServerTransport;
let baseUrl: URL;
let sessionId: string;
let parsedBody: unknown = null;
beforeEach(async () => {
const result = await createTestServer({
customRequestHandler: async (req, res) => {
try {
if (parsedBody !== null) {
await transport.handleRequest(req, res, parsedBody);
parsedBody = null; // Reset after use
} else {
await transport.handleRequest(req, res);
}
} catch (error) {
console.error("Error handling request:", error);
if (!res.headersSent) res.writeHead(500).end();
}
}
});
server = result.server;
transport = result.transport;
baseUrl = result.baseUrl;
// Initialize and get session ID
const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize);
sessionId = initResponse.headers.get("mcp-session-id") as string;
});
afterEach(async () => {
await stopTestServer({ server, transport });
});
it("should accept pre-parsed request body", async () => {
// Set up the pre-parsed body
parsedBody = {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "preparsed-1",
};
// Send an empty body since we'll use pre-parsed body
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
"mcp-session-id": sessionId,
},
// Empty body - we're testing pre-parsed body
body: ""
});
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream");
const reader = response.body?.getReader();
const { value } = await reader!.read();
const text = new TextDecoder().decode(value);
// Verify the response used the pre-parsed body
expect(text).toContain('"id":"preparsed-1"');
expect(text).toContain('"tools"');
});
it("should handle pre-parsed batch messages", async () => {
parsedBody = [
{ jsonrpc: "2.0", method: "tools/list", params: {}, id: "batch-1" },
{ jsonrpc: "2.0", method: "tools/call", params: { name: "greet", arguments: { name: "PreParsed" } }, id: "batch-2" }
];
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
"mcp-session-id": sessionId,
},
body: "" // Empty as we're using pre-parsed
});
expect(response.status).toBe(200);
const reader = response.body?.getReader();
const { value } = await reader!.read();
const text = new TextDecoder().decode(value);
expect(text).toContain('"id":"batch-1"');
expect(text).toContain('"tools"');
});
it("should prefer pre-parsed body over request body", async () => {
// Set pre-parsed to tools/list
parsedBody = {
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: "preparsed-wins",
};
// Send actual body with tools/call - should be ignored
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
"mcp-session-id": sessionId,
},
body: JSON.stringify({
jsonrpc: "2.0",
method: "tools/call",
params: { name: "greet", arguments: { name: "Ignored" } },
id: "ignored-id"
})
});
expect(response.status).toBe(200);
const reader = response.body?.getReader();
const { value } = await reader!.read();
const text = new TextDecoder().decode(value);
// Should have processed the pre-parsed body
expect(text).toContain('"id":"preparsed-wins"');
expect(text).toContain('"tools"');
expect(text).not.toContain('"ignored-id"');
});
});
// Test resumability support
describe("StreamableHTTPServerTransport with resumability", () => {
let server: Server;
let transport: StreamableHTTPServerTransport;
let baseUrl: URL;
let sessionId: string;
let mcpServer: McpServer;
const storedEvents: Map<string, { eventId: string, message: JSONRPCMessage }> = new Map();
// Simple implementation of EventStore
const eventStore: EventStore = {
async storeEvent(streamId: string, message: JSONRPCMessage): Promise<string> {
const eventId = `${streamId}_${randomUUID()}`;
storedEvents.set(eventId, { eventId, message });
return eventId;
},
async replayEventsAfter(lastEventId: EventId, { send }: {
send: (eventId: EventId, message: JSONRPCMessage) => Promise<void>
}): Promise<StreamId> {
const streamId = lastEventId.split('_')[0];
// Extract stream ID from the event ID
// For test simplicity, just return all events with matching streamId that aren't the lastEventId
for (const [eventId, { message }] of storedEvents.entries()) {
if (eventId.startsWith(streamId) && eventId !== lastEventId) {
await send(eventId, message);
}
}
return streamId;
},
};
beforeEach(async () => {
storedEvents.clear();
const result = await createTestServer({
sessionIdGenerator: () => randomUUID(),
eventStore
});
server = result.server;
transport = result.transport;
baseUrl = result.baseUrl;
mcpServer = result.mcpServer;
// Verify resumability is enabled on the transport
expect((transport)['_eventStore']).toBeDefined();
// Initialize the server
const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize);
sessionId = initResponse.headers.get("mcp-session-id") as string;
expect(sessionId).toBeDefined();
});
afterEach(async () => {
await stopTestServer({ server, transport });
storedEvents.clear();
});
it("should store and include event IDs in server SSE messages", async () => {
// Open a standalone SSE stream
const sseResponse = await fetch(baseUrl, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sessionId,
},
});
expect(sseResponse.status).toBe(200);
expect(sseResponse.headers.get("content-type")).toBe("text/event-stream");
// Send a notification that should be stored with an event ID
const notification: JSONRPCMessage = {
jsonrpc: "2.0",
method: "notifications/message",
params: { level: "info", data: "Test notification with event ID" },
};
// Send the notification via transport
await transport.send(notification);
// Read from the stream and verify we got the notification with an event ID
const reader = sseResponse.body?.getReader();
const { value } = await reader!.read();
const text = new TextDecoder().decode(value);
// The response should contain an event ID
expect(text).toContain('id: ');
expect(text).toContain('"method":"notifications/message"');
// Extract the event ID
const idMatch = text.match(/id: ([^\n]+)/);
expect(idMatch).toBeTruthy();
// Verify the event was stored
const eventId = idMatch![1];