1010import java .nio .charset .StandardCharsets ;
1111import java .time .Duration ;
1212import java .util .ArrayList ;
13- import java .util .EnumSet ;
1413import java .util .List ;
1514import java .util .Set ;
1615import java .util .concurrent .Executors ;
1716import java .util .concurrent .atomic .AtomicReference ;
1817import java .util .function .Consumer ;
1918import java .util .function .Function ;
20- import java .util .stream .IntStream ;
2119
2220import io .modelcontextprotocol .json .TypeRef ;
2321import io .modelcontextprotocol .json .McpJsonMapper ;
4341 */
4442public 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