|
| 1 | +/* |
| 2 | + * Copyright 2024-2025 the original author or authors. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.modelcontextprotocol.spec; |
| 6 | + |
| 7 | +import java.time.Duration; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.concurrent.CountDownLatch; |
| 11 | +import java.util.concurrent.CopyOnWriteArrayList; |
| 12 | +import java.util.concurrent.TimeUnit; |
| 13 | +import java.util.concurrent.atomic.AtomicReference; |
| 14 | + |
| 15 | +import io.modelcontextprotocol.json.TypeRef; |
| 16 | +import io.modelcontextprotocol.server.McpNotificationHandler; |
| 17 | +import io.modelcontextprotocol.server.McpRequestHandler; |
| 18 | +import io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage; |
| 19 | +import io.modelcontextprotocol.spec.McpSchema.JSONRPCRequest; |
| 20 | +import io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse; |
| 21 | +import org.junit.jupiter.api.Test; |
| 22 | +import reactor.core.publisher.Mono; |
| 23 | +import reactor.test.StepVerifier; |
| 24 | + |
| 25 | +import static org.assertj.core.api.Assertions.assertThat; |
| 26 | + |
| 27 | +/** |
| 28 | + * Verifies that server-initiated requests and notifications tolerate a not-yet registered |
| 29 | + * listening stream: they are retried until the client opens the GET /mcp stream and fail |
| 30 | + * after the grace period if it never appears. This is the race behind intermittent |
| 31 | + * {@code Stream unavailable for session} failures right after {@code initialize}. |
| 32 | + */ |
| 33 | +class McpStreamableServerSessionMissingStreamTests { |
| 34 | + |
| 35 | + private static final TypeRef<Map<String, Object>> MAP_TYPE = new TypeRef<Map<String, Object>>() { |
| 36 | + }; |
| 37 | + |
| 38 | + private final RecordingTransport transport = new RecordingTransport(); |
| 39 | + |
| 40 | + @Test |
| 41 | + void notificationIsRetriedUntilListeningStreamRegisters() throws Exception { |
| 42 | + var session = newSession(Map.of(), Map.of()); |
| 43 | + var delivered = new CountDownLatch(1); |
| 44 | + |
| 45 | + var disposable = session.sendNotification("notifications/test", Map.of()).subscribe(v -> { |
| 46 | + }, e -> delivered.countDown(), delivered::countDown); |
| 47 | + try { |
| 48 | + assertThat(this.transport.sent).isEmpty(); |
| 49 | + assertThat(delivered.getCount()).isEqualTo(1); |
| 50 | + |
| 51 | + session.listeningStream(this.transport); |
| 52 | + assertThat(delivered.await(2, TimeUnit.SECONDS)).isTrue(); |
| 53 | + } |
| 54 | + finally { |
| 55 | + disposable.dispose(); |
| 56 | + } |
| 57 | + |
| 58 | + assertThat(this.transport.sent).hasSize(1); |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + void requestIsRetriedAndResponseCorrelatedAfterRegistration() throws Exception { |
| 63 | + var session = newSession(Map.of(), Map.of()); |
| 64 | + var response = new AtomicReference<Map<String, Object>>(); |
| 65 | + var error = new AtomicReference<Throwable>(); |
| 66 | + var completed = new CountDownLatch(1); |
| 67 | + |
| 68 | + var disposable = session.sendRequest("sampling/createMessage", Map.of("messages", List.of()), MAP_TYPE) |
| 69 | + .subscribe(response::set, e -> { |
| 70 | + error.set(e); |
| 71 | + completed.countDown(); |
| 72 | + }, completed::countDown); |
| 73 | + try { |
| 74 | + assertThat(this.transport.sent).isEmpty(); |
| 75 | + session.listeningStream(this.transport); |
| 76 | + assertThat(this.transport.firstMessage.await(2, TimeUnit.SECONDS)).isTrue(); |
| 77 | + |
| 78 | + var request = (JSONRPCRequest) this.transport.sent.get(0); |
| 79 | + session.accept(JSONRPCResponse.result(request.id(), Map.of("stopReason", "endTurn"))) |
| 80 | + .block(Duration.ofSeconds(1)); |
| 81 | + |
| 82 | + assertThat(completed.await(2, TimeUnit.SECONDS)).isTrue(); |
| 83 | + if (error.get() != null) { |
| 84 | + throw new AssertionError("Request did not complete successfully", error.get()); |
| 85 | + } |
| 86 | + } |
| 87 | + finally { |
| 88 | + disposable.dispose(); |
| 89 | + } |
| 90 | + |
| 91 | + assertThat(response.get()).containsEntry("stopReason", "endTurn"); |
| 92 | + } |
| 93 | + |
| 94 | + @Test |
| 95 | + void sendRequestFailsAfterGracePeriodWithoutListeningStream() { |
| 96 | + var session = newSession(Map.of(), Map.of()); |
| 97 | + |
| 98 | + StepVerifier.withVirtualTime(() -> session.sendRequest("sampling/createMessage", Map.of(), MAP_TYPE)) |
| 99 | + .thenAwait(Duration.ofSeconds(6)) |
| 100 | + .expectErrorSatisfies(e -> assertThat(e).hasRootCauseMessage("Stream unavailable for session test-session")) |
| 101 | + .verify(Duration.ofSeconds(2)); |
| 102 | + } |
| 103 | + |
| 104 | + @Test |
| 105 | + void notificationHandlerCanPushRequestBeforeStreamRegistered() throws Exception { |
| 106 | + var delivered = new AtomicReference<McpSchema.ListRootsResult>(); |
| 107 | + McpNotificationHandler initializedHandler = (exchange, |
| 108 | + params) -> exchange.listRoots().doOnNext(delivered::set).then(); |
| 109 | + |
| 110 | + var session = newSession(Map.of(), Map.of("notifications/initialized", initializedHandler)); |
| 111 | + var handled = new CountDownLatch(1); |
| 112 | + var error = new AtomicReference<Throwable>(); |
| 113 | + |
| 114 | + var disposable = session.accept(new McpSchema.JSONRPCNotification("notifications/initialized", Map.of())) |
| 115 | + .subscribe(v -> { |
| 116 | + }, e -> { |
| 117 | + error.set(e); |
| 118 | + handled.countDown(); |
| 119 | + }, handled::countDown); |
| 120 | + try { |
| 121 | + assertThat(this.transport.sent).isEmpty(); |
| 122 | + session.listeningStream(this.transport); |
| 123 | + assertThat(this.transport.firstMessage.await(2, TimeUnit.SECONDS)).isTrue(); |
| 124 | + |
| 125 | + var request = this.transport.sent.stream() |
| 126 | + .filter(JSONRPCRequest.class::isInstance) |
| 127 | + .map(JSONRPCRequest.class::cast) |
| 128 | + .findFirst() |
| 129 | + .orElseThrow(); |
| 130 | + session |
| 131 | + .accept(JSONRPCResponse.result(request.id(), |
| 132 | + Map.of("roots", List.of(Map.of("name", "workspace", "uri", "file:///ws"))))) |
| 133 | + .block(Duration.ofSeconds(1)); |
| 134 | + |
| 135 | + assertThat(handled.await(2, TimeUnit.SECONDS)).isTrue(); |
| 136 | + if (error.get() != null) { |
| 137 | + throw new AssertionError("Handler did not complete successfully", error.get()); |
| 138 | + } |
| 139 | + } |
| 140 | + finally { |
| 141 | + disposable.dispose(); |
| 142 | + } |
| 143 | + |
| 144 | + assertThat(delivered.get().roots()).singleElement().satisfies(root -> { |
| 145 | + assertThat(root.name()).isEqualTo("workspace"); |
| 146 | + assertThat(root.uri()).isEqualTo("file:///ws"); |
| 147 | + }); |
| 148 | + } |
| 149 | + |
| 150 | + private McpStreamableServerSession newSession(Map<String, McpRequestHandler<?>> requests, |
| 151 | + Map<String, McpNotificationHandler> notifications) { |
| 152 | + return new McpStreamableServerSession("test-session", McpSchema.ClientCapabilities.builder().build(), |
| 153 | + new McpSchema.Implementation("test-client", "1.0"), Duration.ofSeconds(10), requests, notifications); |
| 154 | + } |
| 155 | + |
| 156 | + private static final class RecordingTransport implements McpStreamableServerTransport { |
| 157 | + |
| 158 | + final CopyOnWriteArrayList<JSONRPCMessage> sent = new CopyOnWriteArrayList<>(); |
| 159 | + |
| 160 | + final CountDownLatch firstMessage = new CountDownLatch(1); |
| 161 | + |
| 162 | + @Override |
| 163 | + public Mono<Void> sendMessage(JSONRPCMessage message, String messageId) { |
| 164 | + this.sent.add(message); |
| 165 | + this.firstMessage.countDown(); |
| 166 | + return Mono.empty(); |
| 167 | + } |
| 168 | + |
| 169 | + @Override |
| 170 | + public Mono<Void> sendMessage(JSONRPCMessage message) { |
| 171 | + return sendMessage(message, "ignored"); |
| 172 | + } |
| 173 | + |
| 174 | + @Override |
| 175 | + public Mono<Void> closeGracefully() { |
| 176 | + return Mono.empty(); |
| 177 | + } |
| 178 | + |
| 179 | + @Override |
| 180 | + @SuppressWarnings("unchecked") |
| 181 | + public <T> T unmarshalFrom(Object data, TypeRef<T> typeRef) { |
| 182 | + // Minimal hand-rolled conversion: mcp-core tests run without a JSON binding |
| 183 | + // module on the classpath, so McpJsonDefaults is unavailable here. |
| 184 | + if (typeRef.getType() == McpSchema.ListRootsResult.class) { |
| 185 | + var map = (Map<String, Object>) data; |
| 186 | + var roots = ((List<Map<String, Object>>) map.get("roots")).stream() |
| 187 | + .map(root -> new McpSchema.Root((String) root.get("uri"), (String) root.get("name"), null)) |
| 188 | + .toList(); |
| 189 | + return (T) new McpSchema.ListRootsResult(roots, (String) map.get("nextCursor"), null); |
| 190 | + } |
| 191 | + return (T) data; |
| 192 | + } |
| 193 | + |
| 194 | + } |
| 195 | + |
| 196 | +} |
0 commit comments