Skip to content

Commit b563e31

Browse files
fix: allow StdioClientTransport to reconnect without a new process
The client creates a new session, which connects the transport again, whenever it re-initializes, for instance after an initialize request timed out. StdioClientTransport started a second server process on each connect and subscribed its single-subscriber sinks again, which failed. The first process was left running, and replies still went to the abandoned session, so the client could never initialize. connect now only replaces the inbound message handler once the server process is running.
1 parent 54e8b61 commit b563e31

3 files changed

Lines changed: 139 additions & 3 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/client/transport/StdioClientTransport.java‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import java.util.List;
1515
import java.util.Set;
1616
import java.util.concurrent.Executors;
17+
import java.util.concurrent.atomic.AtomicBoolean;
18+
import java.util.concurrent.atomic.AtomicReference;
1719
import java.util.function.Consumer;
1820
import java.util.function.Function;
1921
import java.util.stream.IntStream;
@@ -82,6 +84,12 @@ public class StdioClientTransport implements McpClientTransport {
8284

8385
private volatile boolean isClosing = false;
8486

87+
/** Whether the server process has been started by {@link #connect(Function)} */
88+
private final AtomicBoolean started = new AtomicBoolean(false);
89+
90+
/** Handler of the messages received from the server process */
91+
private final AtomicReference<Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>>> inboundMessageHandler = new AtomicReference<>();
92+
8593
// visible for tests
8694
private Consumer<String> stdErrorHandler = error -> logger.info("STDERR Message received: {}", error);
8795

@@ -134,8 +142,17 @@ public StdioClientTransport(ServerParameters params, McpJsonMapper jsonMapper, i
134142
@Override
135143
public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> handler) {
136144
return Mono.<Void>fromRunnable(() -> {
145+
// A client session connects again when it re-initializes, for instance after
146+
// a
147+
// failed initialization: hand it the messages of the already running server
148+
// rather than starting another one.
149+
this.inboundMessageHandler.set(handler);
150+
if (!this.started.compareAndSet(false, true)) {
151+
logger.debug("MCP server already started, replacing the inbound message handler");
152+
return;
153+
}
137154
logger.info("MCP server starting.");
138-
handleIncomingMessages(handler);
155+
handleIncomingMessages();
139156
handleIncomingErrors();
140157

141158
// Prepare command and environment
@@ -242,10 +259,10 @@ private void startErrorProcessing() {
242259
});
243260
}
244261

245-
private void handleIncomingMessages(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> inboundMessageHandler) {
262+
private void handleIncomingMessages() {
246263
this.inboundSink.asFlux()
247264
.flatMap(message -> Mono.just(message)
248-
.transform(inboundMessageHandler)
265+
.transform(this.inboundMessageHandler.get())
249266
.contextWrite(ctx -> ctx.put("observation", "myObservation")))
250267
.subscribe();
251268
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.client.transport;
6+
7+
import java.io.BufferedReader;
8+
import java.io.FileDescriptor;
9+
import java.io.FileOutputStream;
10+
import java.io.IOException;
11+
import java.io.InputStreamReader;
12+
import java.io.PrintStream;
13+
import java.nio.charset.StandardCharsets;
14+
import java.util.regex.Matcher;
15+
import java.util.regex.Pattern;
16+
17+
/**
18+
* Minimal stdio MCP server that never answers the first {@code initialize} request, like
19+
* a server that is too slow to start, and answers every later one.
20+
*/
21+
public final class FirstInitializeIgnoringStdioServer {
22+
23+
private static final Pattern ID = Pattern.compile("\"id\"\\s*:\\s*(\"[^\"]*\"|-?\\d+)");
24+
25+
private FirstInitializeIgnoringStdioServer() {
26+
}
27+
28+
public static void main(String[] args) throws IOException {
29+
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
30+
PrintStream out = new PrintStream(new FileOutputStream(FileDescriptor.out), true, StandardCharsets.UTF_8);
31+
boolean ignoredFirstInitialize = false;
32+
String line;
33+
while ((line = in.readLine()) != null) {
34+
if (!line.contains("\"initialize\"")) {
35+
continue;
36+
}
37+
if (!ignoredFirstInitialize) {
38+
ignoredFirstInitialize = true;
39+
continue;
40+
}
41+
Matcher id = ID.matcher(line);
42+
if (id.find()) {
43+
out.println("{\"jsonrpc\":\"2.0\",\"id\":" + id.group(1)
44+
+ ",\"result\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},"
45+
+ "\"serverInfo\":{\"name\":\"test-server\",\"version\":\"1.0.0\"}}}");
46+
}
47+
}
48+
}
49+
50+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.client.transport;
6+
7+
import java.nio.file.Path;
8+
import java.time.Duration;
9+
import java.util.concurrent.atomic.AtomicInteger;
10+
11+
import io.modelcontextprotocol.client.McpAsyncClient;
12+
import io.modelcontextprotocol.client.McpClient;
13+
import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
14+
import io.modelcontextprotocol.spec.json.gson.GsonMcpJsonMapper;
15+
import org.junit.jupiter.api.AfterEach;
16+
import org.junit.jupiter.api.Test;
17+
import reactor.test.StepVerifier;
18+
19+
import static org.assertj.core.api.Assertions.assertThat;
20+
import static org.mockito.Mockito.mock;
21+
22+
/**
23+
* Tests that a {@link StdioClientTransport} can initialize again after a failed
24+
* initialization, without starting another server process.
25+
*/
26+
class StdioClientTransportReinitializationTests {
27+
28+
private McpAsyncClient client;
29+
30+
@AfterEach
31+
void tearDown() {
32+
if (this.client != null) {
33+
this.client.close();
34+
}
35+
}
36+
37+
@Test
38+
void initializeAgainAfterTimeoutReusesTheServerProcess() {
39+
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
40+
ServerParameters params = ServerParameters.builder(java)
41+
.args("-cp", System.getProperty("java.class.path"), FirstInitializeIgnoringStdioServer.class.getName())
42+
.build();
43+
44+
AtomicInteger startedProcesses = new AtomicInteger();
45+
StdioClientTransport transport = new StdioClientTransport(params, new GsonMcpJsonMapper()) {
46+
@Override
47+
protected ProcessBuilder getProcessBuilder() {
48+
startedProcesses.incrementAndGet();
49+
return super.getProcessBuilder();
50+
}
51+
};
52+
53+
this.client = McpClient.async(transport)
54+
.jsonSchemaValidator(mock(JsonSchemaValidator.class))
55+
.initializationTimeout(Duration.ofSeconds(5))
56+
.build();
57+
58+
// The server does not answer the first initialize request
59+
StepVerifier.create(this.client.initialize()).expectError().verify(Duration.ofSeconds(30));
60+
61+
// Retrying must reach the same, still running, server
62+
StepVerifier.create(this.client.initialize())
63+
.assertNext(result -> assertThat(result.serverInfo().name()).isEqualTo("test-server"))
64+
.verifyComplete();
65+
66+
assertThat(startedProcesses).hasValue(1);
67+
}
68+
69+
}

0 commit comments

Comments
 (0)