Skip to content

Commit 71fdb15

Browse files
committed
fix: make stdio process exit terminal
1 parent 10449f0 commit 71fdb15

9 files changed

Lines changed: 356 additions & 78 deletions

File tree

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

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111
import java.util.concurrent.atomic.AtomicReference;
1212
import java.util.function.Function;
1313

14-
import io.modelcontextprotocol.client.transport.McpStdioServerProcessExitException;
1514
import io.modelcontextprotocol.spec.McpClientSession;
1615
import io.modelcontextprotocol.spec.McpError;
1716
import io.modelcontextprotocol.spec.McpSchema;
1817
import io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;
18+
import io.modelcontextprotocol.spec.McpTransportTerminatedException;
1919
import io.modelcontextprotocol.util.Assert;
2020
import org.slf4j.Logger;
2121
import org.slf4j.LoggerFactory;
@@ -94,6 +94,9 @@ class LifecycleInitializer {
9494

9595
private final AtomicReference<DefaultInitialization> initializationRef = new AtomicReference<>();
9696

97+
/** Permanent transport failure that prevents any further initialization attempt. */
98+
private final AtomicReference<Throwable> terminalFailure = new AtomicReference<>();
99+
97100
/**
98101
* The max timeout to await for the client-server connection to be initialized.
99102
*/
@@ -226,13 +229,10 @@ private void close() {
226229
this.mcpSession().close();
227230
}
228231

229-
private void close(Throwable cause) {
232+
private void terminate(Throwable cause) {
230233
McpClientSession mcpClientSession = this.mcpSession();
231234
if (mcpClientSession != null) {
232-
mcpClientSession.close(cause);
233-
}
234-
else {
235-
this.error(cause);
235+
mcpClientSession.terminate(cause);
236236
}
237237
}
238238

@@ -243,10 +243,13 @@ private Mono<Void> closeGracefully() {
243243
}
244244

245245
public boolean isInitialized() {
246-
return this.currentInitializationResult() != null;
246+
return this.terminalFailure.get() == null && this.currentInitializationResult() != null;
247247
}
248248

249249
public McpSchema.InitializeResult currentInitializationResult() {
250+
if (this.terminalFailure.get() != null) {
251+
return null;
252+
}
250253
DefaultInitialization current = this.initializationRef.get();
251254
McpSchema.InitializeResult initializeResult = current != null ? current.result.get() : null;
252255
return initializeResult;
@@ -261,7 +264,15 @@ public McpSchema.InitializeResult currentInitializationResult() {
261264
* @param t The exception to handle
262265
*/
263266
public void handleException(Throwable t) {
264-
if (t instanceof McpTransportSessionNotFoundException) {
267+
if (t instanceof McpTransportTerminatedException) {
268+
if (this.terminalFailure.compareAndSet(null, t)) {
269+
DefaultInitialization current = this.initializationRef.get();
270+
if (current != null) {
271+
current.terminate(t);
272+
}
273+
}
274+
}
275+
else if (t instanceof McpTransportSessionNotFoundException && this.terminalFailure.get() == null) {
265276
DefaultInitialization previous = this.initializationRef.getAndSet(null);
266277
if (previous != null) {
267278
previous.close();
@@ -270,13 +281,6 @@ public void handleException(Throwable t) {
270281
// the implicit initialization step.
271282
this.withInitialization("re-initializing", result -> Mono.empty()).subscribe();
272283
}
273-
else if (t instanceof McpStdioServerProcessExitException) {
274-
DefaultInitialization previous = this.initializationRef.get();
275-
if (previous != null && previous.initializeResult() == null
276-
&& this.initializationRef.compareAndSet(previous, null)) {
277-
previous.close(t);
278-
}
279-
}
280284
}
281285

282286
/**
@@ -289,6 +293,11 @@ else if (t instanceof McpStdioServerProcessExitException) {
289293
*/
290294
public <T> Mono<T> withInitialization(String actionName, Function<Initialization, Mono<T>> operation) {
291295
return Mono.deferContextual(ctx -> {
296+
Throwable terminal = this.terminalFailure.get();
297+
if (terminal != null) {
298+
return Mono.error(terminal);
299+
}
300+
292301
DefaultInitialization newInit = new DefaultInitialization();
293302
DefaultInitialization previous = this.initializationRef.compareAndExchange(null, newInit);
294303

@@ -316,6 +325,11 @@ private Mono<McpSchema.InitializeResult> doInitialize(DefaultInitialization init
316325
initialization.setMcpClientSession(this.sessionSupplier.apply(ctx));
317326

318327
McpClientSession mcpClientSession = initialization.mcpSession();
328+
Throwable terminal = this.terminalFailure.get();
329+
if (terminal != null) {
330+
mcpClientSession.terminate(terminal);
331+
return Mono.error(terminal);
332+
}
319333

320334
String latestVersion = this.protocolVersions.get(this.protocolVersions.size() - 1);
321335

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44

55
package io.modelcontextprotocol.client.transport;
66

7-
import io.modelcontextprotocol.spec.McpTransportException;
7+
import io.modelcontextprotocol.spec.McpTransportTerminatedException;
88
import io.modelcontextprotocol.util.Assert;
99

1010
/**
1111
* Thrown when an MCP stdio server process exits unexpectedly.
1212
*
1313
* @author Dongliang Xie
1414
*/
15-
public class McpStdioServerProcessExitException extends McpTransportException {
15+
public class McpStdioServerProcessExitException extends McpTransportTerminatedException {
1616

1717
private static final long serialVersionUID = 1L;
1818

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

Lines changed: 102 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,12 @@
1010
import java.nio.charset.StandardCharsets;
1111
import java.time.Duration;
1212
import java.util.ArrayList;
13-
import java.util.EnumSet;
1413
import java.util.List;
1514
import java.util.Set;
1615
import java.util.concurrent.Executors;
1716
import java.util.concurrent.atomic.AtomicReference;
1817
import java.util.function.Consumer;
1918
import java.util.function.Function;
20-
import java.util.stream.IntStream;
2119

2220
import io.modelcontextprotocol.json.TypeRef;
2321
import io.modelcontextprotocol.json.McpJsonMapper;
@@ -43,6 +41,16 @@
4341
*/
4442
public class StdioClientTransport implements McpClientTransport {
4543

44+
private enum State {
45+
46+
NEW, STARTING, RUNNING, CLOSING, TERMINATED
47+
48+
}
49+
50+
private record Lifecycle(State state, McpStdioServerProcessExitException terminalCause) {
51+
52+
}
53+
4654
private static final Logger logger = LoggerFactory.getLogger(StdioClientTransport.class);
4755

4856
// @formatter:off
@@ -59,9 +67,9 @@ public class StdioClientTransport implements McpClientTransport {
5967
private final Sinks.Many<JSONRPCMessage> outboundSink;
6068

6169
/** The server process being communicated with */
62-
private Process process;
70+
private volatile Process process;
6371

64-
private final AtomicReference<McpStdioServerProcessExitException> unexpectedExitException = new AtomicReference<>();
72+
private final AtomicReference<Lifecycle> lifecycle = new AtomicReference<>(new Lifecycle(State.NEW, null));
6573

6674
private final AtomicReference<Consumer<Throwable>> exceptionHandler = new AtomicReference<>();
6775

@@ -83,8 +91,6 @@ public class StdioClientTransport implements McpClientTransport {
8391

8492
private volatile boolean isClosing = false;
8593

86-
private volatile boolean closeRequested = false;
87-
8894
// visible for tests
8995
private Consumer<String> stdErrorHandler = error -> logger.info("STDERR Message received: {}", error);
9096

@@ -122,9 +128,18 @@ public StdioClientTransport(ServerParameters params, McpJsonMapper jsonMapper) {
122128
@Override
123129
public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> handler) {
124130
return Mono.<Void>fromRunnable(() -> {
131+
Lifecycle current = this.lifecycle.get();
132+
Lifecycle starting = new Lifecycle(State.STARTING, null);
133+
if (current.state() != State.NEW || !this.lifecycle.compareAndSet(current, starting)) {
134+
current = this.lifecycle.get();
135+
if (current.terminalCause() != null) {
136+
throw current.terminalCause();
137+
}
138+
throw new IllegalStateException(
139+
"Stdio client transport cannot be connected from state " + current.state());
140+
}
141+
125142
logger.info("MCP server starting.");
126-
handleIncomingMessages(handler);
127-
handleIncomingErrors();
128143

129144
// Prepare command and environment
130145
List<String> fullCommand = new ArrayList<>();
@@ -140,20 +155,41 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
140155
this.process = processBuilder.start();
141156
}
142157
catch (IOException e) {
158+
this.lifecycle.compareAndSet(starting, new Lifecycle(State.NEW, null));
143159
throw new RuntimeException("Failed to start process with command: " + fullCommand, e);
144160
}
145161

146162
// Validate process streams
147163
if (this.process.getInputStream() == null || process.getOutputStream() == null) {
148164
this.process.destroy();
165+
this.lifecycle.compareAndSet(starting, new Lifecycle(State.NEW, null));
149166
throw new RuntimeException("Process input or output stream is null");
150167
}
151168

169+
Lifecycle running = new Lifecycle(State.RUNNING, null);
170+
if (!this.lifecycle.compareAndSet(starting, running)) {
171+
this.process.destroy();
172+
current = this.lifecycle.get();
173+
if (current.terminalCause() != null) {
174+
throw current.terminalCause();
175+
}
176+
throw new IllegalStateException(
177+
"Stdio client transport startup interrupted in state " + current.state());
178+
}
179+
handleIncomingMessages(handler);
180+
handleIncomingErrors();
181+
152182
// Start threads
153183
startInboundProcessing();
154184
startOutboundProcessing();
155185
startErrorProcessing();
156186
startExitMonitoring();
187+
if (!this.process.isAlive()) {
188+
McpStdioServerProcessExitException terminal = signalUnexpectedProcessExit(this.process.exitValue());
189+
if (terminal != null) {
190+
throw terminal;
191+
}
192+
}
157193
logger.info("MCP server started");
158194
}).subscribeOn(Schedulers.boundedElastic());
159195
}
@@ -252,13 +288,16 @@ private void handleIncomingErrors() {
252288

253289
@Override
254290
public Mono<Void> sendMessage(JSONRPCMessage message) {
255-
McpStdioServerProcessExitException exitException = this.unexpectedExitException.get();
256-
if (exitException != null) {
257-
return Mono.error(exitException);
291+
Lifecycle current = this.lifecycle.get();
292+
if (current.terminalCause() != null) {
293+
return Mono.error(current.terminalCause());
258294
}
259-
if (!this.closeRequested && this.process != null && !this.process.isAlive()) {
260-
exitException = signalUnexpectedProcessExit(this.process.exitValue());
261-
return Mono.error(exitException);
295+
if ((current.state() == State.STARTING || current.state() == State.RUNNING) && this.process != null
296+
&& !this.process.isAlive()) {
297+
McpStdioServerProcessExitException exitException = signalUnexpectedProcessExit(this.process.exitValue());
298+
if (exitException != null) {
299+
return Mono.error(exitException);
300+
}
262301
}
263302
if (this.outboundSink.tryEmitNext(message).isSuccess()) {
264303
// TODO: essentially we could reschedule ourselves in some time and make
@@ -269,34 +308,65 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
269308
return Mono.empty();
270309
}
271310
else {
311+
current = this.lifecycle.get();
312+
if (current.terminalCause() != null) {
313+
return Mono.error(current.terminalCause());
314+
}
272315
return Mono.error(new RuntimeException("Failed to enqueue message"));
273316
}
274317
}
275318

276319
private void startExitMonitoring() {
277320
this.process.onExit().thenAccept(process -> {
278-
if (!closeRequested) {
321+
while (true) {
322+
Lifecycle current = this.lifecycle.get();
323+
if (current.state() == State.TERMINATED) {
324+
return;
325+
}
326+
if (current.state() == State.CLOSING) {
327+
if (this.lifecycle.compareAndSet(current, new Lifecycle(State.TERMINATED, null))) {
328+
return;
329+
}
330+
continue;
331+
}
279332
signalUnexpectedProcessExit(process.exitValue());
333+
return;
280334
}
281335
});
282336
}
283337

284338
private McpStdioServerProcessExitException signalUnexpectedProcessExit(int exitCode) {
285339
McpStdioServerProcessExitException exception = new McpStdioServerProcessExitException(exitCode,
286340
this.params.getCommand());
287-
if (this.unexpectedExitException.compareAndSet(null, exception)) {
288-
logger.warn(exception.getMessage());
289-
isClosing = true;
290-
inboundSink.tryEmitComplete();
291-
outboundSink.tryEmitComplete();
292-
errorSink.tryEmitComplete();
341+
while (true) {
342+
Lifecycle current = this.lifecycle.get();
343+
if (current.terminalCause() != null) {
344+
return current.terminalCause();
345+
}
346+
if (current.state() == State.CLOSING || current.state() == State.TERMINATED) {
347+
return null;
348+
}
349+
if (this.lifecycle.compareAndSet(current, new Lifecycle(State.TERMINATED, exception))) {
350+
break;
351+
}
352+
}
293353

294-
Consumer<Throwable> handler = this.exceptionHandler.get();
295-
if (handler != null) {
354+
logger.warn(exception.getMessage());
355+
this.isClosing = true;
356+
this.inboundSink.tryEmitComplete();
357+
this.outboundSink.tryEmitComplete();
358+
this.errorSink.tryEmitComplete();
359+
360+
Consumer<Throwable> handler = this.exceptionHandler.get();
361+
if (handler != null) {
362+
try {
296363
handler.accept(exception);
297364
}
365+
catch (RuntimeException handlerFailure) {
366+
logger.error("Transport exception handler failed", handlerFailure);
367+
}
298368
}
299-
return this.unexpectedExitException.get();
369+
return exception;
300370
}
301371

302372
/**
@@ -394,8 +464,9 @@ protected void handleOutbound(Function<Flux<JSONRPCMessage>, Flux<JSONRPCMessage
394464
@Override
395465
public Mono<Void> closeGracefully() {
396466
return Mono.fromRunnable(() -> {
397-
closeRequested = true;
398-
isClosing = true;
467+
this.lifecycle.updateAndGet(
468+
current -> current.state() == State.TERMINATED ? current : new Lifecycle(State.CLOSING, null));
469+
this.isClosing = true;
399470
logger.debug("Initiating graceful shutdown");
400471
}).then(Mono.<Void>defer(() -> {
401472
// First complete all sinks to stop accepting new messages
@@ -436,7 +507,11 @@ public Mono<Void> closeGracefully() {
436507
catch (Exception e) {
437508
logger.error("Error during graceful shutdown", e);
438509
}
439-
})).then().subscribeOn(Schedulers.boundedElastic());
510+
}))
511+
.doFinally(signalType -> this.lifecycle.updateAndGet(
512+
current -> current.state() == State.CLOSING ? new Lifecycle(State.TERMINATED, null) : current))
513+
.then()
514+
.subscribeOn(Schedulers.boundedElastic());
440515
}
441516

442517
public Sinks.Many<String> getErrorSink() {

0 commit comments

Comments
 (0)