1212import java .util .ArrayList ;
1313import java .util .List ;
1414import java .util .concurrent .Executors ;
15+ import java .util .concurrent .atomic .AtomicReference ;
1516import java .util .function .Consumer ;
1617import java .util .function .Function ;
1718
@@ -48,6 +49,10 @@ public class StdioClientTransport implements McpClientTransport {
4849 /** The server process being communicated with */
4950 private Process process ;
5051
52+ private final AtomicReference <McpStdioServerProcessExitException > unexpectedExitException = new AtomicReference <>();
53+
54+ private final AtomicReference <Consumer <Throwable >> exceptionHandler = new AtomicReference <>();
55+
5156 private McpJsonMapper jsonMapper ;
5257
5358 /** Scheduler for handling inbound messages from the server process */
@@ -66,6 +71,8 @@ public class StdioClientTransport implements McpClientTransport {
6671
6772 private volatile boolean isClosing = false ;
6873
74+ private volatile boolean closeRequested = false ;
75+
6976 // visible for tests
7077 private Consumer <String > stdErrorHandler = error -> logger .info ("STDERR Message received: {}" , error );
7178
@@ -134,6 +141,7 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
134141 startInboundProcessing ();
135142 startOutboundProcessing ();
136143 startErrorProcessing ();
144+ startExitMonitoring ();
137145 logger .info ("MCP server started" );
138146 }).subscribeOn (Schedulers .boundedElastic ());
139147 }
@@ -160,6 +168,11 @@ public void setStdErrorHandler(Consumer<String> errorHandler) {
160168 this .stdErrorHandler = errorHandler ;
161169 }
162170
171+ @ Override
172+ public void setExceptionHandler (Consumer <Throwable > handler ) {
173+ this .exceptionHandler .set (handler );
174+ }
175+
163176 /**
164177 * Waits for the server process to exit.
165178 * @throws RuntimeException if the process is interrupted while waiting
@@ -227,6 +240,14 @@ private void handleIncomingErrors() {
227240
228241 @ Override
229242 public Mono <Void > sendMessage (JSONRPCMessage message ) {
243+ McpStdioServerProcessExitException exitException = this .unexpectedExitException .get ();
244+ if (exitException != null ) {
245+ return Mono .error (exitException );
246+ }
247+ if (!this .closeRequested && this .process != null && !this .process .isAlive ()) {
248+ exitException = signalUnexpectedProcessExit (this .process .exitValue ());
249+ return Mono .error (exitException );
250+ }
230251 if (this .outboundSink .tryEmitNext (message ).isSuccess ()) {
231252 // TODO: essentially we could reschedule ourselves in some time and make
232253 // another attempt with the already read data but pause reading until
@@ -240,6 +261,32 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
240261 }
241262 }
242263
264+ private void startExitMonitoring () {
265+ this .process .onExit ().thenAccept (process -> {
266+ if (!closeRequested ) {
267+ signalUnexpectedProcessExit (process .exitValue ());
268+ }
269+ });
270+ }
271+
272+ private McpStdioServerProcessExitException signalUnexpectedProcessExit (int exitCode ) {
273+ McpStdioServerProcessExitException exception = new McpStdioServerProcessExitException (exitCode ,
274+ this .params .getCommand ());
275+ if (this .unexpectedExitException .compareAndSet (null , exception )) {
276+ logger .warn (exception .getMessage ());
277+ isClosing = true ;
278+ inboundSink .tryEmitComplete ();
279+ outboundSink .tryEmitComplete ();
280+ errorSink .tryEmitComplete ();
281+
282+ Consumer <Throwable > handler = this .exceptionHandler .get ();
283+ if (handler != null ) {
284+ handler .accept (exception );
285+ }
286+ }
287+ return this .unexpectedExitException .get ();
288+ }
289+
243290 /**
244291 * Starts the inbound processing thread that reads JSON-RPC messages from the
245292 * process's input stream. Messages are deserialized and emitted to the inbound sink.
@@ -335,6 +382,7 @@ protected void handleOutbound(Function<Flux<JSONRPCMessage>, Flux<JSONRPCMessage
335382 @ Override
336383 public Mono <Void > closeGracefully () {
337384 return Mono .fromRunnable (() -> {
385+ closeRequested = true ;
338386 isClosing = true ;
339387 logger .debug ("Initiating graceful shutdown" );
340388 }).then (Mono .<Void >defer (() -> {
0 commit comments