Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import io.modelcontextprotocol.modern.server.feature.ToolsFeature;
import io.modelcontextprotocol.modern.server.transport.StdioMcpTransport;
import org.jspecify.annotations.Nullable;
import reactor.core.publisher.Mono;
import tools.jackson.databind.json.JsonMapper;

import org.springframework.ai.mcp.customizer.McpServerCustomizer;
Expand Down Expand Up @@ -421,22 +422,50 @@ static RequestStateCodec requestStateCodec(McpServerModernProperties properties,

/**
* Starts the stdio transport with the application and closes it on shutdown.
* <p>
* The threads of the transport are daemon threads, so they do not keep the JVM alive.
* A thread of this lifecycle, which is not a daemon, waits while the transport
* serves: until the standard input ends or the application is closed. A server on the
* standard streams therefore stays up for its client. When the input ends, the JVM
* ends as well, unless something else keeps it running.
* <p>
* The transport can be started once, so the lifecycle is not pauseable.
*/
public static final class StdioMcpTransportLifecycle implements SmartLifecycle {

private final StdioMcpTransport transport;

private volatile boolean running;

private volatile @Nullable Thread servingThread;

StdioMcpTransportLifecycle(StdioMcpTransport transport) {
this.transport = transport;
}

@Override
public void start() {
if (!this.running) {
Mono<Void> served = this.transport.start();
this.running = true;
this.transport.start().subscribe();
Thread thread = new Thread(() -> awaitEndOfServing(served), "mcp-stdio-server");
thread.setDaemon(false);
this.servingThread = thread;
thread.start();
}
}

private void awaitEndOfServing(Mono<Void> served) {
try {
served.block();
}
catch (RuntimeException ex) {
logger.error(ex, "The MCP server on the standard streams failed");
}
if (this.running) {
// Not closed by stop(): the transport has ended by itself.
this.running = false;
logger.info("The standard input has ended: the MCP server on the standard streams no longer serves");
}
}

Expand All @@ -453,6 +482,19 @@ public boolean isRunning() {
return this.running;
}

@Override
public boolean isPauseable() {
return false;
}

/**
* The thread that waits while the transport serves.
* @return the thread, or {@code null} before the lifecycle is started
*/
@Nullable Thread servingThread() {
return this.servingThread;
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
* Copyright 2023-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.mcp.server.common.autoconfigure;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.atomic.AtomicReference;

import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
import io.modelcontextprotocol.modern.server.McpServer;
import io.modelcontextprotocol.modern.server.transport.StdioMcpTransport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import tools.jackson.databind.json.JsonMapper;

import org.springframework.ai.mcp.server.common.autoconfigure.McpServerModernAutoConfiguration.StdioMcpTransportLifecycle;
import org.springframework.ai.mcp.server.common.autoconfigure.annotations.McpServerAnnotationScannerAutoConfiguration;
import org.springframework.ai.mcp.server.common.autoconfigure.annotations.ModernServerSpecificationFactoryAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for the lifetime of a modern MCP server on the standard streams: the application
* stays up while the input is open, and ends with it.
*
* @author Christian Tzolov
*/
@ExtendWith(OutputCaptureExtension.class)
class McpServerModernStdioLifecycleTests {

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.mcp.server.protocol=MODERN", "spring.ai.mcp.server.stdio=true")
.withConfiguration(AutoConfigurations.of(McpServerJsonMapperAutoConfiguration.class,
McpServerAnnotationScannerAutoConfiguration.class,
ModernServerSpecificationFactoryAutoConfiguration.class,
ModernToolCallbackConverterAutoConfiguration.class, McpServerModernAutoConfiguration.class))
.withUserConfiguration(PipedInputConfiguration.class);

@Test
void threadThatIsNotADaemonWaitsUntilTheInputEnds(CapturedOutput output) {
this.contextRunner.run(context -> {
assertThat(context).hasNotFailed();
StdioMcpTransportLifecycle lifecycle = context.getBean(StdioMcpTransportLifecycle.class);
Thread servingThread = lifecycle.servingThread();

// The threads of the transport are daemon threads: this one keeps the JVM
// alive while the client may still send a request.
assertThat(servingThread).isNotNull();
assertThat(servingThread.isDaemon()).isFalse();
servingThread.join(100);
assertThat(servingThread.isAlive()).isTrue();
assertThat(lifecycle.isRunning()).isTrue();

// The client closes its end of the input.
context.getBean(PipedOutputStream.class).close();

servingThread.join(10_000);
assertThat(servingThread.isAlive()).isFalse();
assertThat(lifecycle.isRunning()).isFalse();
assertThat(output).contains("The standard input has ended");
});
}

@Test
void threadEndsWhenTheApplicationIsClosedWhileTheInputIsOpen(CapturedOutput output) throws InterruptedException {
AtomicReference<Thread> servingThread = new AtomicReference<>();

this.contextRunner.run(context -> {
servingThread.set(context.getBean(StdioMcpTransportLifecycle.class).servingThread());
assertThat(servingThread.get()).isNotNull();
assertThat(servingThread.get().isAlive()).isTrue();
});

servingThread.get().join(10_000);
assertThat(servingThread.get().isAlive()).isFalse();
assertThat(output).doesNotContain("The standard input has ended");
}

@Test
void lifecycleIsNotPauseableAsTheTransportStartsOnce() {
this.contextRunner
.run(context -> assertThat(context.getBean(StdioMcpTransportLifecycle.class).isPauseable()).isFalse());
}

/**
* The transport reads from a pipe in place of the standard input, so that a test can
* end the input.
*/
@Configuration(proxyBeanMethods = false)
static class PipedInputConfiguration {

@Bean
PipedOutputStream clientEndOfTheInput() {
return new PipedOutputStream();
}

@Bean
StdioMcpTransport stdioTransport(McpServer mcpServer, PipedOutputStream clientEndOfTheInput)
throws IOException {
return new StdioMcpTransport(mcpServer, new JacksonMcpJsonMapper(JsonMapper.shared()),
new PipedInputStream(clientEndOfTheInput), new ByteArrayOutputStream());
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ spring:
stdio: true
----

The server serves while the standard input of the application is open.
When the input ends, which is when its client closes the connection or goes away, the server stops serving, and the application ends unless something else keeps it running, such as a web server or `spring.main.keep-alive=true`.

== Configuration Properties

The common properties (`spring.ai.mcp.server.name`, `version`, `instructions`, `type`, `capabilities.*`, `tool-callback-converter`, `tool-response-mime-type`) and the MCP annotation scanner properties apply as they do for the other protocols.
Expand Down
Loading