1414import java .util .List ;
1515import java .util .Set ;
1616import java .util .concurrent .Executors ;
17+ import java .util .concurrent .atomic .AtomicReference ;
1718import java .util .function .Consumer ;
1819import java .util .function .Function ;
1920import java .util .stream .IntStream ;
@@ -60,6 +61,10 @@ public class StdioClientTransport implements McpClientTransport {
6061 /** The server process being communicated with */
6162 private Process process ;
6263
64+ private final AtomicReference <McpStdioServerProcessExitException > unexpectedExitException = new AtomicReference <>();
65+
66+ private final AtomicReference <Consumer <Throwable >> exceptionHandler = new AtomicReference <>();
67+
6368 private McpJsonMapper jsonMapper ;
6469
6570 /** Scheduler for handling inbound messages from the server process */
@@ -78,6 +83,8 @@ public class StdioClientTransport implements McpClientTransport {
7883
7984 private volatile boolean isClosing = false ;
8085
86+ private volatile boolean closeRequested = false ;
87+
8188 // visible for tests
8289 private Consumer <String > stdErrorHandler = error -> logger .info ("STDERR Message received: {}" , error );
8390
@@ -146,6 +153,7 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
146153 startInboundProcessing ();
147154 startOutboundProcessing ();
148155 startErrorProcessing ();
156+ startExitMonitoring ();
149157 logger .info ("MCP server started" );
150158 }).subscribeOn (Schedulers .boundedElastic ());
151159 }
@@ -172,6 +180,11 @@ public void setStdErrorHandler(Consumer<String> errorHandler) {
172180 this .stdErrorHandler = errorHandler ;
173181 }
174182
183+ @ Override
184+ public void setExceptionHandler (Consumer <Throwable > handler ) {
185+ this .exceptionHandler .set (handler );
186+ }
187+
175188 /**
176189 * Waits for the server process to exit.
177190 * @throws RuntimeException if the process is interrupted while waiting
@@ -239,6 +252,14 @@ private void handleIncomingErrors() {
239252
240253 @ Override
241254 public Mono <Void > sendMessage (JSONRPCMessage message ) {
255+ McpStdioServerProcessExitException exitException = this .unexpectedExitException .get ();
256+ if (exitException != null ) {
257+ return Mono .error (exitException );
258+ }
259+ if (!this .closeRequested && this .process != null && !this .process .isAlive ()) {
260+ exitException = signalUnexpectedProcessExit (this .process .exitValue ());
261+ return Mono .error (exitException );
262+ }
242263 if (this .outboundSink .tryEmitNext (message ).isSuccess ()) {
243264 // TODO: essentially we could reschedule ourselves in some time and make
244265 // another attempt with the already read data but pause reading until
@@ -252,6 +273,32 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
252273 }
253274 }
254275
276+ private void startExitMonitoring () {
277+ this .process .onExit ().thenAccept (process -> {
278+ if (!closeRequested ) {
279+ signalUnexpectedProcessExit (process .exitValue ());
280+ }
281+ });
282+ }
283+
284+ private McpStdioServerProcessExitException signalUnexpectedProcessExit (int exitCode ) {
285+ McpStdioServerProcessExitException exception = new McpStdioServerProcessExitException (exitCode ,
286+ 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 ();
293+
294+ Consumer <Throwable > handler = this .exceptionHandler .get ();
295+ if (handler != null ) {
296+ handler .accept (exception );
297+ }
298+ }
299+ return this .unexpectedExitException .get ();
300+ }
301+
255302 /**
256303 * Starts the inbound processing thread that reads JSON-RPC messages from the
257304 * process's input stream. Messages are deserialized and emitted to the inbound sink.
@@ -347,6 +394,7 @@ protected void handleOutbound(Function<Flux<JSONRPCMessage>, Flux<JSONRPCMessage
347394 @ Override
348395 public Mono <Void > closeGracefully () {
349396 return Mono .fromRunnable (() -> {
397+ closeRequested = true ;
350398 isClosing = true ;
351399 logger .debug ("Initiating graceful shutdown" );
352400 }).then (Mono .<Void >defer (() -> {
0 commit comments