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 ;
@@ -62,6 +63,10 @@ public class StdioClientTransport implements McpClientTransport {
6263 /** The server process being communicated with */
6364 private Process process ;
6465
66+ private final AtomicReference <McpStdioServerProcessExitException > unexpectedExitException = new AtomicReference <>();
67+
68+ private final AtomicReference <Consumer <Throwable >> exceptionHandler = new AtomicReference <>();
69+
6570 private McpJsonMapper jsonMapper ;
6671
6772 /** Scheduler for handling inbound messages from the server process */
@@ -82,6 +87,8 @@ public class StdioClientTransport implements McpClientTransport {
8287
8388 private volatile boolean isClosing = false ;
8489
90+ private volatile boolean closeRequested = false ;
91+
8592 // visible for tests
8693 private Consumer <String > stdErrorHandler = error -> logger .info ("STDERR Message received: {}" , error );
8794
@@ -165,6 +172,7 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
165172 startInboundProcessing ();
166173 startOutboundProcessing ();
167174 startErrorProcessing ();
175+ startExitMonitoring ();
168176 logger .info ("MCP server started" );
169177 }).subscribeOn (Schedulers .boundedElastic ());
170178 }
@@ -191,6 +199,11 @@ public void setStdErrorHandler(Consumer<String> errorHandler) {
191199 this .stdErrorHandler = errorHandler ;
192200 }
193201
202+ @ Override
203+ public void setExceptionHandler (Consumer <Throwable > handler ) {
204+ this .exceptionHandler .set (handler );
205+ }
206+
194207 /**
195208 * Waits for the server process to exit.
196209 * @throws RuntimeException if the process is interrupted while waiting
@@ -258,6 +271,14 @@ private void handleIncomingErrors() {
258271
259272 @ Override
260273 public Mono <Void > sendMessage (JSONRPCMessage message ) {
274+ McpStdioServerProcessExitException exitException = this .unexpectedExitException .get ();
275+ if (exitException != null ) {
276+ return Mono .error (exitException );
277+ }
278+ if (!this .closeRequested && this .process != null && !this .process .isAlive ()) {
279+ exitException = signalUnexpectedProcessExit (this .process .exitValue ());
280+ return Mono .error (exitException );
281+ }
261282 if (this .outboundSink .tryEmitNext (message ).isSuccess ()) {
262283 // TODO: essentially we could reschedule ourselves in some time and make
263284 // another attempt with the already read data but pause reading until
@@ -271,6 +292,32 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
271292 }
272293 }
273294
295+ private void startExitMonitoring () {
296+ this .process .onExit ().thenAccept (process -> {
297+ if (!closeRequested ) {
298+ signalUnexpectedProcessExit (process .exitValue ());
299+ }
300+ });
301+ }
302+
303+ private McpStdioServerProcessExitException signalUnexpectedProcessExit (int exitCode ) {
304+ McpStdioServerProcessExitException exception = new McpStdioServerProcessExitException (exitCode ,
305+ this .params .getCommand ());
306+ if (this .unexpectedExitException .compareAndSet (null , exception )) {
307+ logger .warn (exception .getMessage ());
308+ isClosing = true ;
309+ inboundSink .tryEmitComplete ();
310+ outboundSink .tryEmitComplete ();
311+ errorSink .tryEmitComplete ();
312+
313+ Consumer <Throwable > handler = this .exceptionHandler .get ();
314+ if (handler != null ) {
315+ handler .accept (exception );
316+ }
317+ }
318+ return this .unexpectedExitException .get ();
319+ }
320+
274321 /**
275322 * Starts the inbound processing thread that reads JSON-RPC messages from the
276323 * process's input stream. Messages are deserialized and emitted to the inbound sink.
@@ -402,6 +449,7 @@ protected void handleOutbound(Function<Flux<JSONRPCMessage>, Flux<JSONRPCMessage
402449 @ Override
403450 public Mono <Void > closeGracefully () {
404451 return Mono .fromRunnable (() -> {
452+ closeRequested = true ;
405453 isClosing = true ;
406454 logger .debug ("Initiating graceful shutdown" );
407455 }).then (Mono .<Void >defer (() -> {
0 commit comments