Repository navigation
Expand file tree
/
Copy pathHttpServletStreamableIntegrationTests.java
More file actions
841 lines (730 loc) · 31.6 KB
/
Copy pathHttpServletStreamableIntegrationTests.java
File metadata and controls
841 lines (730 loc) · 31.6 KB
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
/*
* Copyright 2024 - 2026 the original author or authors.
*/
package io.modelcontextprotocol.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Stream;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import io.modelcontextprotocol.AbstractMcpClientServerIntegrationTests;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.json.McpJsonDefaults;
import io.modelcontextprotocol.server.McpServer.AsyncSpecification;
import io.modelcontextprotocol.server.McpServer.SyncSpecification;
import io.modelcontextprotocol.server.transport.HttpServletStreamableServerTransportProvider;
import io.modelcontextprotocol.server.transport.TomcatTestUtil;
import io.modelcontextprotocol.spec.HttpHeaders;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.util.KeepAliveScheduler;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.startup.Tomcat;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.test.scheduler.VirtualTimeScheduler;
import static io.modelcontextprotocol.util.ToolsUtils.EMPTY_JSON_SCHEMA;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
/**
* Based on {@link AbstractMcpClientServerIntegrationTests} for basic client <> server
* integration tests. Also contains some tests specific to streamable HTTP, around
* resumability, connection lifecycle and session management.
*/
@Timeout(15)
class HttpServletStreamableIntegrationTests extends AbstractMcpClientServerIntegrationTests {
private static final int PORT = TomcatTestUtil.findAvailablePort();
private static final String MESSAGE_ENDPOINT = "/mcp/message";
// Tomcat is started once for the whole class; each test swaps in its own transport
private static final TomcatTestUtil.DelegatingServlet MCP_SERVLET = new TomcatTestUtil.DelegatingServlet();
private static Tomcat tomcat;
private HttpServletStreamableServerTransportProvider mcpServerTransportProvider;
// Keep alive is fast. A ping failure releases the stream, so listening
// steams are released quickly.
private final Duration KEEP_ALIVE_INTERVAL = Duration.ofMillis(150);
// Sweeping is slower than keep-alive, so that a failed ping doesn't immediately
// result in a session sweep
private final Duration SESSION_SWEEP_INTERVAL = KEEP_ALIVE_INTERVAL.multipliedBy(2);
protected static final int MAX_REQUEST_SIZE = 2048;
private final HttpClient httpClient = HttpClient.newHttpClient();
@Override
protected void awaitClientStreamEstablished() {
var timeout = Duration.ofSeconds(5);
await().atMost(timeout).untilAsserted(() -> {
assertThat(MCP_SERVLET.isStreamEstablished())
.withFailMessage("[Failed to observe MCP Client connection within %s]", timeout)
.isTrue();
});
}
static Stream<Arguments> clientsForTesting() {
return Stream.of(Arguments.of("httpclient"));
}
@BeforeAll
public static void beforeAll() {
tomcat = TomcatTestUtil.createTomcatServer("", PORT, MCP_SERVLET);
try {
tomcat.start();
assertThat(tomcat.getServer().getState()).isEqualTo(LifecycleState.STARTED);
}
catch (Exception e) {
throw new RuntimeException("Failed to start Tomcat", e);
}
}
@AfterAll
public static void afterAll() {
if (tomcat != null) {
try {
tomcat.stop();
tomcat.destroy();
}
catch (LifecycleException e) {
throw new RuntimeException("Failed to stop Tomcat", e);
}
}
}
@BeforeEach
public void before() {
// Create and configure the transport provider
mcpServerTransportProvider = HttpServletStreamableServerTransportProvider.builder()
.contextExtractor(TEST_CONTEXT_EXTRACTOR)
.mcpEndpoint(MESSAGE_ENDPOINT)
.keepAliveInterval(KEEP_ALIVE_INTERVAL)
.maxRequestSize(MAX_REQUEST_SIZE)
.sessionSweepInterval(SESSION_SWEEP_INTERVAL)
.build();
MCP_SERVLET.setDelegate(mcpServerTransportProvider);
clientBuilders
.put("httpclient",
McpClient.sync(HttpClientStreamableHttpTransport.builder("http://localhost:" + PORT)
.endpoint(MESSAGE_ENDPOINT)
.build()).requestTimeout(Duration.ofHours(10)));
}
@Override
protected AsyncSpecification<?> prepareAsyncServerBuilder() {
return McpServer.async(this.mcpServerTransportProvider);
}
@Override
protected SyncSpecification<?> prepareSyncServerBuilder() {
return McpServer.sync(this.mcpServerTransportProvider);
}
@AfterEach
public void after() {
if (mcpServerTransportProvider != null) {
mcpServerTransportProvider.closeGracefully().block();
}
}
@Test
void testMissingHandlerReturnsMethodNotFoundError() {
var mcpServer = prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.build();
var clientTransport = HttpClientStreamableHttpTransport.builder("http://localhost:" + PORT)
.endpoint(MESSAGE_ENDPOINT)
.build();
try (var mcpClient = McpClient.sync(clientTransport).build()) {
// Create a session using an MCP client
McpSchema.InitializeResult initResult = mcpClient.initialize();
assertThat(initResult).isNotNull();
// Override the response handler in the client to capture responses
AtomicReference<McpSchema.JSONRPCResponse> response = new AtomicReference<>();
var handler = (Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchema.JSONRPCMessage>>) (
message) -> message.doOnNext(r -> {
if (r instanceof McpSchema.JSONRPCResponse resp) {
response.set(resp);
}
});
StepVerifier.create(clientTransport.connect(handler)).verifyComplete();
// Send an incorrect request through the transport
StepVerifier
.create(clientTransport.sendMessage(new McpSchema.JSONRPCRequest("foo/bar", "test-request-123")))
.verifyComplete();
// Wait until we've received the response
await().atMost(Duration.ofSeconds(1)).until(() -> response.get() != null);
assertThat(response.get().error().code()).isEqualTo(McpSchema.ErrorCodes.METHOD_NOT_FOUND);
assertThat(response.get().error().message()).isEqualTo("Method not found: foo/bar");
}
finally {
mcpServer.close();
}
}
@Test
void listeningStreamHasStreamingHeaders() throws Exception {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
var sessionId = initializeSession(httpClient);
var get = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Accept", "text/event-stream")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.GET()
.build();
var response = httpClient.send(get, HttpResponse.BodyHandlers.ofInputStream());
try {
assertSseHeaders(response);
}
finally {
response.body().close();
}
}
@Test
void toolCallSseResponseHasStreamingHeaders() throws Exception {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.tools(McpServerFeatures.AsyncToolSpecification.builder()
.tool(McpSchema.Tool.builder("echo", EMPTY_JSON_SCHEMA).description("returns immediately").build())
.callHandler((exchange,
request) -> Mono.just(McpSchema.CallToolResult.builder()
.content(List.of(McpSchema.TextContent.builder("ok").build()))
.isError(false)
.build()))
.build())
.build();
var sessionId = initializeSession(httpClient);
var post = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream, application/json")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.POST(HttpRequest.BodyPublishers
.ofString("{\"jsonrpc\":\"2.0\",\"id\":\"call-1\",\"method\":\"tools/call\","
+ "\"params\":{\"name\":\"echo\",\"arguments\":{}}}"))
.build();
var response = httpClient.send(post, HttpResponse.BodyHandlers.ofInputStream());
try {
assertSseHeaders(response);
}
finally {
response.body().close();
}
}
@Override
protected void prepareClients(int port, String mcpEndpoint) {
}
private static void assertSseHeaders(HttpResponse<?> response) {
assertThat(response.headers().firstValue("Content-Type")).contains("text/event-stream;charset=UTF-8");
assertThat(response.headers().firstValue("Cache-Control")).contains("no-cache, no-transform");
assertThat(response.headers().firstValue("X-Accel-Buffering")).contains("no");
assertThat(response.headers().firstValue("Connection")).isEmpty();
}
static McpTransportContextExtractor<HttpServletRequest> TEST_CONTEXT_EXTRACTOR = (r) -> McpTransportContext
.create(Map.of("important", "value"));
@Test
void rejectsWhenBodyBytesExceedLimitWithoutContentLengthHeader() throws Exception {
// A publisher with unknown content length forces chunked transfer encoding,
// bypassing the Content-Length header check and exercising the body byte
// count
byte[] oversizedBody = "a".repeat(MAX_REQUEST_SIZE + 1).getBytes(UTF_8);
HttpRequest.BodyPublisher chunkedPublisher = new HttpRequest.BodyPublisher() {
@Override
public long contentLength() {
return -1;
}
@Override
public void subscribe(java.util.concurrent.Flow.Subscriber<? super ByteBuffer> subscriber) {
subscriber.onSubscribe(new java.util.concurrent.Flow.Subscription() {
@Override
public void request(long n) {
subscriber.onNext(ByteBuffer.wrap(oversizedBody));
subscriber.onComplete();
}
@Override
public void cancel() {
}
});
}
};
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream, application/json")
.POST(chunkedPublisher)
.build();
var response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
assertThat(response.statusCode()).isEqualTo(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
}
@ParameterizedTest(name = "{0} : {displayName} ")
@MethodSource("clientsForTesting")
void testRejectsWhenContentLengthHeaderExceedsLimit(String clientType) {
var clientBuilder = clientBuilders.get(clientType);
String inputSchema = """
{
"type": "object",
"properties": {
"message": { "type": "string" }
},
"required": ["message"]
}
""";
McpServerFeatures.SyncToolSpecification tool1 = McpServerFeatures.SyncToolSpecification.builder()
.tool(McpSchema.Tool.builder("tool1", McpJsonDefaults.getMapper(), inputSchema)
.description("tool1 description")
.build())
.callHandler((exchange, request) -> McpSchema.CallToolResult.builder()
.addContent(McpSchema.TextContent.builder(request.arguments().get("message").toString()).build())
.build())
.build();
var mcpServer = prepareSyncServerBuilder()
.capabilities(McpSchema.ServerCapabilities.builder().tools(false).build())
.tools(tool1)
.build();
try (var mcpClient = clientBuilder.build()) {
String oversizedBody = "a".repeat(MAX_REQUEST_SIZE + 1);
mcpClient.initialize();
assertThat(mcpClient.listTools().tools()).contains(tool1.tool());
assertThatThrownBy(() -> mcpClient.callTool(
McpSchema.CallToolRequest.builder("tool1").arguments(Map.of("message", oversizedBody)).build()))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("413");
}
finally {
mcpServer.closeGracefully();
}
}
@ParameterizedTest
@ValueSource(strings = { "text/plain;charset=UTF-8", "application/x-www-form-urlencoded", "multipart/form-data" })
void rejectsInitializeWithNonJsonContentType(String contentType) throws Exception {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
// CORS-safelisted content types can be sent cross-origin by a browser without a
// preflight, so they must be rejected before a session is created
var initialize = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", contentType)
.header("Accept", "text/event-stream, application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{"jsonrpc":"2.0","id":"init","method":"initialize","params":{
"protocolVersion":"2025-06-18","capabilities":{},
"clientInfo":{"name":"test-client","version":"1.0.0"}}}"""))
.build();
var response = httpClient.send(initialize, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
assertThat(response.body()).contains("Unsupported Media Type: Content-Type must be application/json");
assertThat(response.headers().firstValue(HttpHeaders.MCP_SESSION_ID)).isEmpty();
}
@Test
void rejectsToolCallWithNonJsonContentType() throws Exception {
var toolCalled = new AtomicBoolean();
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.tools(McpServerFeatures.AsyncToolSpecification.builder()
.tool(McpSchema.Tool.builder("tool1", EMPTY_JSON_SCHEMA).build())
.callHandler((exchange, request) -> {
toolCalled.set(true);
return Mono.just(McpSchema.CallToolResult.builder().build());
})
.build())
.build();
var sessionId = initializeSession(httpClient);
var toolCall = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "text/plain;charset=UTF-8")
.header("Accept", "text/event-stream, application/json")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.POST(HttpRequest.BodyPublishers.ofString("""
{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"tool1","arguments":{}}}"""))
.build();
var response = httpClient.send(toolCall, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
assertThat(response.body()).contains("Unsupported Media Type: Content-Type must be application/json");
assertThat(toolCalled).isFalse();
}
@Test
void resumedStreamReceivesServerNotifications() {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
var sessionId = initializeSession(httpClient);
// Resume the stream the way a client does once its SSE connection broke. The
// resumed stream must become the session listening stream, otherwise the
// reconnected client never receives anything again.
var stream = openListeningStream(httpClient, sessionId, sessionId + "_0");
awaitClientStreamEstablished();
awaitNotification(stream.events());
}
@Test
void replacedListeningStreamIsClosed() {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
var sessionId = initializeSession(httpClient);
var firstStream = openListeningStream(httpClient, sessionId, null);
awaitClientStreamEstablished();
awaitNotification(firstStream.events());
// stream keeps receiving pings, so we just ensure we've removed the notification
firstStream.events().clear();
assertThat(firstStream.events()).noneMatch(line -> line.contains("notifications/resources/list_changed"));
// Resuming installs a new listening stream. The session can no longer address the
// first one, so it must not be left open. the first stream is only closed when
// the second stream is turned on, so we don't need to wait for a client stream to
// be established
var secondStream = openListeningStream(httpClient, sessionId, sessionId + "_0");
assertThat(firstStream.streamFuture()).succeedsWithin(Duration.ofSeconds(5));
mcpServerTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED, null).block();
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
assertThat(secondStream.events()).anyMatch(line -> line.contains("notifications/resources/list_changed"));
assertThat(firstStream.events()).noneMatch(line -> line.contains("notifications/resources/list_changed"));
});
}
@Test
void keepAliveSkipsSessionsWithoutListeningStream() {
var keepAliveLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(KeepAliveScheduler.class);
ListAppender<ILoggingEvent> logAppender = new ListAppender<>();
logAppender.start();
keepAliveLogger.addAppender(logAppender);
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(KEEP_ALIVE_INTERVAL, null);
initializeSession(httpClient);
// go through multiple keep-alive-rounds
virtualTime.advanceTimeBy(KEEP_ALIVE_INTERVAL.multipliedBy(3));
assertThat(logAppender.list).as("Should not display any Keep-Alive warning log")
.noneMatch(event -> event.getLevel() == Level.WARN);
}
finally {
keepAliveLogger.detachAppender(logAppender);
logAppender.stop();
VirtualTimeScheduler.reset();
}
}
@Test
void keepAlivePingsSessionsWithListeningStream() {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
var sessionId = initializeSession(httpClient);
var stream = openListeningStream(httpClient, sessionId, null);
awaitClientStreamEstablished();
// Sessions with a listening stream are still pinged
await().atMost(Duration.ofSeconds(1))
.untilAsserted(() -> assertThat(stream.events()).anyMatch(line -> line.contains("\"method\":\"ping\"")));
}
@Test
void unansweredKeepAlivePingReleasesTheStreamButKeepsTheSession() {
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
var sessionId = initializeSession(httpClient);
var stream = openListeningStream(httpClient, sessionId, null);
awaitClientStreamEstablished();
// Nothing answers the pings the server writes to this stream, which is how a
// connection whose client is gone looks: the writes keep succeeding until the
// peer resets. The server must not hold on to it.
assertThat(stream.streamFuture()).succeedsWithin(Duration.ofSeconds(10));
assertThat(stream.events()).anyMatch(line -> line.contains("\"method\":\"ping\""));
// The session itself survives, so a client can come back to it
assertThat(postNotification(httpClient, sessionId)).isEqualTo(HttpServletResponse.SC_ACCEPTED);
}
@Test
void sessionEviction() {
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(null, SESSION_SWEEP_INTERVAL);
var sessionId = initializeSession(httpClient);
// One client request every sweep interval/2, the session remains active
// We do 5 total requests so the total time is > 2 sweep intervals, verifying
// that the sweeper does not reclaim a session
for (int i = 1; i < 6; i++) {
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.dividedBy(2));
assertThat(postNotification(httpClient, sessionId)).as("Session should be active for request #%s", i)
.isEqualTo(HttpServletResponse.SC_ACCEPTED);
}
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(2));
assertThat(postNotification(httpClient, sessionId)).as("Session should be sweeped after SWEEP_INTERVAL * 2")
.isEqualTo(HttpServletResponse.SC_NOT_FOUND);
}
finally {
VirtualTimeScheduler.reset();
}
}
@Test
void sessionHoldingAnOpenStreamIsNotEvicted() {
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(null, SESSION_SWEEP_INTERVAL);
var sessionId = initializeSession(httpClient);
openListeningStream(httpClient, sessionId, null);
awaitClientStreamEstablished();
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(2));
assertThat(postNotification(httpClient, sessionId))
.as("Session should not be sweeped when a GET SSE stream is open")
.isEqualTo(HttpServletResponse.SC_ACCEPTED);
}
finally {
VirtualTimeScheduler.reset();
}
}
@Test
void sessionEvictionAfterReleasingStream() {
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(null, SESSION_SWEEP_INTERVAL);
var sessionId = initializeSession(httpClient);
var clientStream = openListeningStream(httpClient, sessionId, null);
awaitClientStreamEstablished();
// "prep" the client so we can close the stream by sending data: the
// subscription
// in the clientStream is only present when the client has received data
awaitNotification(clientStream.events());
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(2));
assertThat(postNotification(httpClient, sessionId)).as("Session should be active when a stream is open")
.isEqualTo(HttpServletResponse.SC_ACCEPTED);
// Close the client stream
clientStream.closeStream();
await().atMost(Duration.ofSeconds(5))
.pollDelay(Duration.ZERO)
.pollInterval(Duration.ZERO)
.untilAsserted(() -> {
// send a message so the server realizes the client is gone might take
// a few tries before the internal buffer fills up and the connection
// errors
mcpServerTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED, null)
.block();
// eventually, the session should be sweepable
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(2));
assertThat(postNotification(httpClient, sessionId))
.as("Session should be sweeped after a stream is released")
.isEqualTo(HttpServletResponse.SC_NOT_FOUND);
});
}
finally {
VirtualTimeScheduler.reset();
}
}
@Test
void sessionIsNotEvictedWithoutSweepInterval() {
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(KEEP_ALIVE_INTERVAL, null);
var sessionId = initializeSession(httpClient);
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(10));
assertThat(postNotification(httpClient, sessionId))
.as("Session should never be sweeped when there is no sessionSweepInterval")
.isEqualTo(HttpServletResponse.SC_ACCEPTED);
}
finally {
VirtualTimeScheduler.reset();
}
}
@Test
void getStreamSendsHeadersBeforeFirstEvent() throws Exception {
withTransportProvider(null, null);
String sessionId = initializeSession(httpClient);
var get = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Accept", "text/event-stream")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.GET()
.build();
HttpResponse<InputStream> response = httpClient.sendAsync(get, HttpResponse.BodyHandlers.ofInputStream())
.get(5, TimeUnit.SECONDS);
assertThat(response.statusCode()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(response.headers().firstValue("Content-Type").orElse("")).startsWith("text/event-stream");
response.body().close();
}
/**
* A client which aborts a tool call must not leave its session behind.
*/
@Test
void sessionIsEvictedWhenTheClientAbortsAResponseStream() {
var virtualTime = VirtualTimeScheduler.getOrSet();
try {
withTransportProvider(null, SESSION_SWEEP_INTERVAL);
var toolEmissionInterval = Duration.ofMillis(10);
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.tools(McpServerFeatures.AsyncToolSpecification.builder()
.tool(McpSchema.Tool.builder("hangs", EMPTY_JSON_SCHEMA).description("never returns").build())
.callHandler((exchange, request) -> Flux
.interval(toolEmissionInterval, toolEmissionInterval, Schedulers.newSingle("test-tool"))
.flatMap(tick -> exchange.loggingNotification(McpSchema.LoggingMessageNotification.builder()
.level(McpSchema.LoggingLevel.INFO)
.data("x".repeat(64 * 1024))
.build()))
.then(Mono.<McpSchema.CallToolResult>never()))
.build())
.build();
var sessionId = initializeSession(httpClient);
// The POST opens a response SSE stream, which the session counts as an open
// stream for as long as the call is in flight
var responseStream = postToolCall(httpClient, sessionId, "hangs");
await().atMost(Duration.ofSeconds(5))
.pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(10))
.untilAsserted(() -> {
// We do this in a loop for the wire-side of the connection - data has
// to be buffered then flushed
// Advance time so the tool emits some data
virtualTime.advanceTimeBy(toolEmissionInterval);
// Verify the data is received
assertThat(responseStream.events()).anyMatch(line -> line.contains("notifications/message"));
});
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(2));
assertThat(postNotification(httpClient, sessionId)).as("Session with POST stream is active")
.isEqualTo(HttpServletResponse.SC_ACCEPTED);
// The client gives up on the call and disconnects
responseStream.closeStream();
// Nothing is connected to the session anymore, so the sweeper must reclaim
// it.
// Probing only once: any request would count as activity and reset the clock.
virtualTime.advanceTimeBy(SESSION_SWEEP_INTERVAL.multipliedBy(5));
assertThat(postNotification(httpClient, sessionId)).isEqualTo(HttpServletResponse.SC_NOT_FOUND);
}
finally {
VirtualTimeScheduler.reset();
}
}
/**
* Calls a tool with a POST request, returning a handle on the SSE response stream it
* opens.
*/
private StreamResponse postToolCall(HttpClient httpClient, String sessionId, String toolName) {
var post = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream, application/json")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"id\":\"call-1\","
+ "\"method\":\"tools/call\",\"params\":{\"name\":\"" + toolName + "\",\"arguments\":{}}}"))
.build();
Queue<String> events = new ConcurrentLinkedQueue<>();
var streamRef = new AtomicReference<InputStream>();
var clientFuture = httpClient.sendAsync(post, HttpResponse.BodyHandlers.ofInputStream())
.thenAccept(response -> {
streamRef.set(response.body());
try (var r = new BufferedReader(new InputStreamReader(response.body(), UTF_8))) {
String l;
while ((l = r.readLine()) != null) {
events.add(l);
}
}
catch (IOException e) {
// "closed" here is our own closeStream(), not a failure
}
});
return new StreamResponse(clientFuture, events, streamRef);
}
private int postNotification(HttpClient httpClient, String sessionId) {
var notification = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream, application/json")
.header(HttpHeaders.MCP_SESSION_ID, sessionId)
.POST(HttpRequest.BodyPublishers.ofString("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"))
.build();
try {
return httpClient.send(notification, HttpResponse.BodyHandlers.ofString()).statusCode();
}
catch (IOException | InterruptedException e) {
return -1;
}
}
private String initializeSession(HttpClient httpClient) {
var initialize = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream, application/json")
.POST(HttpRequest.BodyPublishers.ofString("""
{"jsonrpc":"2.0","id":"init","method":"initialize","params":{
"protocolVersion":"2025-06-18","capabilities":{},
"clientInfo":{"name":"test-client","version":"1.0.0"}}}"""))
.build();
HttpResponse<String> response = null;
try {
response = httpClient.send(initialize, HttpResponse.BodyHandlers.ofString());
}
catch (IOException | InterruptedException e) {
return null;
}
assertThat(response.statusCode()).isEqualTo(HttpServletResponse.SC_OK);
return response.headers().firstValue(HttpHeaders.MCP_SESSION_ID).orElse(null);
}
/**
* Opens an SSE listening stream with a GET request, collecting the received lines.
* @return a handle on the stream, whose future completes once the server closes it
*/
private StreamResponse openListeningStream(HttpClient httpClient, String sessionId, String lastEventId) {
var get = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + PORT + MESSAGE_ENDPOINT))
.header("Accept", "text/event-stream")
.header(HttpHeaders.MCP_SESSION_ID, sessionId);
if (lastEventId != null) {
get.header(HttpHeaders.LAST_EVENT_ID, lastEventId);
}
Queue<String> events = new ConcurrentLinkedQueue<>();
var streamRef = new AtomicReference<InputStream>();
var clientFuture = httpClient.sendAsync(get.GET().build(), HttpResponse.BodyHandlers.ofInputStream())
.thenAccept(response -> {
streamRef.set(response.body());
try (var r = new BufferedReader(new InputStreamReader(response.body(), UTF_8))) {
String l;
while ((l = r.readLine()) != null) {
events.add(l);
}
}
catch (IOException e) {
// "closed" here is our own stop(), not a failure
}
});
return new StreamResponse(clientFuture, events, streamRef);
}
private void awaitNotification(Queue<String> events) {
mcpServerTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED, null).block();
await().atMost(Duration.ofSeconds(5)).pollDelay(Duration.ofMillis(100)).untilAsserted(() -> {
assertThat(events).anyMatch(line -> line.contains("notifications/resources/list_changed"));
});
}
record StreamResponse(CompletableFuture<Void> streamFuture, Queue<String> events,
AtomicReference<InputStream> streamRef) {
void closeStream() {
// Close listening stream. We retry a few times in case the stream was not
// established on the first try
await().pollDelay(Duration.ZERO).atMost(Duration.ofSeconds(1)).until(() -> {
var stream = streamRef.get();
if (stream != null) {
stream.close();
return true;
}
return false;
});
}
}
private void withTransportProvider(Duration keepAliveInterval, Duration sessionSweepInterval) {
mcpServerTransportProvider.closeGracefully().block();
mcpServerTransportProvider = HttpServletStreamableServerTransportProvider.builder()
.contextExtractor(TEST_CONTEXT_EXTRACTOR)
.mcpEndpoint(MESSAGE_ENDPOINT)
.keepAliveInterval(keepAliveInterval)
// no sweeping: the session must survive every keep-alive round
.sessionSweepInterval(sessionSweepInterval)
.build();
MCP_SERVLET.setDelegate(mcpServerTransportProvider);
prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").build();
}
}