diff --git a/changes.md b/changes.md index 82bb39b298..3c68d6824e 100644 --- a/changes.md +++ b/changes.md @@ -158,6 +158,13 @@ Changes log proxy. - Bugs fixed + - The MCP STDIO connector no longer treats a clean end of its input as a failure: the requests + already sent are answered before it closes (within the request timeout of the adapter, + plus 5 s), where they were aborted, so a client that half-closes stdin after its last request, or a + request piped into the server, lost its answer; a listen stream, which never ends by + itself, is cancelled at the end of the input. The end of the input is logged at `FINE` + instead of a `WARNING` with a stack trace, and `getFailure()` still reports it. An I/O + error on the input still aborts what is in flight (#1765). - A request whose preconditions fail ("If-Match", "If-None-Match"...) with a method that the resource does not support is now answered 405 (Method Not Allowed) with the "Allow" header, instead of 412 (Precondition Failed) or of the status of a custom precondition diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioServerHelper.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioServerHelper.java index 3a8353d6a2..535784932d 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioServerHelper.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioServerHelper.java @@ -12,6 +12,7 @@ import io.modelcontextprotocol.json.McpJsonMapper; import io.modelcontextprotocol.json.TypeRef; import java.io.ByteArrayOutputStream; +import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -24,7 +25,9 @@ import java.util.concurrent.CompletionException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.LockSupport; import java.util.logging.Level; import org.restlet.Request; import org.restlet.Response; @@ -76,6 +79,9 @@ public final class StdioServerHelper extends ServerHelper { private static final String CANCELLED = "notifications/cancelled"; + /** How long past the request timeout the end of the input waits for the requests sent. */ + private static final Duration END_OF_INPUT_GRACE = Duration.ofSeconds(5); + /** Request attribute marking a request the client cancelled, which gets no response. */ private static final String CANCELLED_ATTRIBUTE = "org.restlet.ext.mcp.stdio.cancelled"; @@ -130,6 +136,12 @@ public final class StdioServerHelper extends ServerHelper { */ private Semaphore legacyPending; + /** The slots of {@link #pending} and {@link #legacyPending}, and the time a call may take. */ + private volatile int pendingSlots; + + private volatile int legacyPendingSlots; + private volatile Duration requestTimeout; + private volatile Thread reader; private volatile boolean closed; @@ -160,14 +172,15 @@ public synchronized void start() throws IOException { stream.start(); workers = new McpWorkers(limits.maxConcurrentCalls(), limits.requestTimeout()); modernWorkers = new McpWorkers(Integer.MAX_VALUE, null, Duration.ofSeconds(30)); - legacyPending = new Semaphore(limits.maxConcurrentCalls()); - pending = - new Semaphore( - (int) - Math.min( - (long) limits.maxListenStreams() - + limits.maxConcurrentCalls(), - Integer.MAX_VALUE)); + requestTimeout = limits.requestTimeout(); + legacyPendingSlots = limits.maxConcurrentCalls(); + legacyPending = new Semaphore(legacyPendingSlots); + pendingSlots = + (int) + Math.min( + (long) limits.maxListenStreams() + limits.maxConcurrentCalls(), + Integer.MAX_VALUE); + pending = new Semaphore(pendingSlots); reader = Thread.ofVirtual().name("restlet-mcp-stdio-server").start(this::read); } @@ -182,7 +195,7 @@ private void read() { } } if (!closed) { - fail(new IOException("MCP STDIO input ended")); + endOfInput(); } } catch (IOException | RuntimeException e) { if (!closed) { @@ -191,6 +204,58 @@ private void read() { } } + /** + * Ends the connector at the end of its input, which is a client with nothing more to send, not + * a fault: the requests it already sent are answered first, within the request timeout, and the + * listen streams, which never end by themselves, are cancelled at once. + */ + private void endOfInput() { + // The request timeout, plus a grace for the refusal of a call that has just timed out + long deadline = System.nanoTime() + requestTimeout.plus(END_OF_INPUT_GRACE).toNanos(); + while (!closed && requestsInProgress() > 0 && System.nanoTime() - deadline < 0) { + cancelListens(); + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); + } + if (closed) { + return; + } + int unanswered = requestsInProgress(); + if (unanswered > 0) { + fail( + new EOFException( + "MCP STDIO input ended with " + unanswered + " request(s) unanswered"), + Level.WARNING); + } else { + fail(new EOFException("MCP STDIO input ended"), Level.FINE); + } + } + + /** How many requests hold a pending slot: running, or waiting to be refused or written. */ + private int requestsInProgress() { + return pendingSlots + - pending.availablePermits() + + legacyPendingSlots + - legacyPending.availablePermits(); + } + + /** + * Cancels the 2026-07-28 listen streams in flight, as a {@code notifications/cancelled}: also + * one with a duplicate or an invalid id, which no cancellation names. + */ + private void cancelListens() { + for (Request request : requests) { + if (!isCancelled(request) + && McpModernExchange.isListen( + request.getHeaders().getFirstValue("Mcp-Method", true))) { + synchronized (output) { + request.getAttributes().put(CANCELLED_ATTRIBUTE, Boolean.TRUE); + } + inFlight.values().remove(request); + request.abort(); + } + } + } + /** Builds the request of a frame, in reading order, and hands it to a worker. */ private void accept(byte[] bytes) { Map envelope = envelope(bytes); @@ -680,12 +745,22 @@ private void refuse(Request request, boolean answered, Object id, Throwable caus } private void fail(Throwable cause) { + fail(cause, Level.WARNING); + } + + /** + * Ends the connector, aborting what is in flight, and keeps the cause for {@link + * #getFailure()}. + * + * @param level How the end is logged: an end of input is not a warning. + */ + private void fail(Throwable cause, Level level) { if (stopped) { return; // Stopping cuts exchanges short: not a failure. } failure = cause; closed = true; - getLogger().log(Level.WARNING, "MCP STDIO server input/exchange failed", cause); + getLogger().log(level, "MCP STDIO server input/exchange failed", cause); requests.forEach(Request::abort); try { stream.stop(); @@ -838,6 +913,8 @@ private void addData(String value) throws IOException { /** * Terminal input/worker failure, if any; connector owners should monitor this for subprocesses. + * An {@link EOFException} is the clean end of the input, a client with nothing more to send, + * once the requests it sent were answered; any other cause is a fault. */ public Throwable getFailure() { return failure; diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernStdioTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernStdioTestCase.java index 6e15edf38a..e9c022157e 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernStdioTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernStdioTestCase.java @@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import io.modelcontextprotocol.json.McpJsonDefaults; @@ -34,6 +35,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; @@ -62,12 +65,22 @@ class McpModernStdioTestCase { private McpServerAdapter adapter; private Server server; private OutputStream toServer; + private Pipe requestPipe; + + /** Counted down once the server's output ended: the connector closed. */ + private final CountDownLatch outputClosed = new CountDownLatch(1); + + /** The {@code gated} tool has started, and ends when the gate completes. */ + private final CountDownLatch gateStarted = new CountDownLatch(1); + + private final CompletableFuture gate = new CompletableFuture<>(); private final java.util.concurrent.BlockingQueue lines = new java.util.concurrent.LinkedBlockingQueue<>(); @BeforeEach void start() throws Exception { Pipe requests = Pipe.open(); + requestPipe = requests; Pipe responses = Pipe.open(); org.restlet.util.StreamTransport stream = new org.restlet.util.StreamTransport( @@ -98,6 +111,8 @@ void start() throws Exception { } } catch (IOException _) { // The server output ended. + } finally { + outputClosed.countDown(); } }); adapter = new McpServerAdapter(); @@ -132,6 +147,23 @@ void start() throws Exception { .doOnCancel( cancelled ::countDown)))))); + adapter.getTools() + .add( + McpAsyncTool.of( + Tool.builder("gated", Map.of("type", "object")).build(), + (ctx, request) -> + Mono.defer( + () -> { + gateStarted.countDown(); + return Mono.fromFuture(gate) + .map( + ignored -> + McpAsyncResponse + . + result( + text( + "released"))); + }))); adapter.getMethods() .add( McpMethod.of( @@ -242,6 +274,151 @@ void aCancelledRequestEndsWithoutAResponse() throws Exception { assertEquals(5, ((Number) next.get("id")).intValue(), next.toString()); } + /** + * The end of the input is a client with nothing more to send: a request already sent is still + * answered, and the connector closes after it. + */ + @Test + void aRequestInFlightAtTheEndOfInputIsAnswered() throws Exception { + send(request(8, "tools/call", Map.of("name", "gated", "arguments", Map.of()), meta())); + assertTrue(gateStarted.await(10, TimeUnit.SECONDS), "the tool did not start"); + + toServer.close(); + + assertNull(lines.poll(300, TimeUnit.MILLISECONDS), "answered before the tool ended"); + assertEquals(1, outputClosed.getCount(), "closed with a request in flight"); + gate.complete("go"); + Map answer = read(); + assertEquals(8, ((Number) answer.get("id")).intValue(), answer.toString()); + assertEquals("released", firstText(result(answer))); + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + } + + /** A listen stream never ends by itself: the end of the input cancels it, and closes. */ + @Test + void aListenStreamIsCancelledAtTheEndOfInput() throws Exception { + send( + request( + 9, + McpSchema.METHOD_SUBSCRIPTIONS_LISTEN, + Map.of("notifications", Map.of("toolsListChanged", true)), + meta())); + assertEquals( + McpSchema.METHOD_NOTIFICATION_SUBSCRIPTIONS_ACKNOWLEDGED, read().get("method")); + + toServer.close(); + + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + assertNull(lines.poll(), "a frame followed the acknowledgement"); + } + + /** A listen with an id another request has is cancelled too: no cancellation names it. */ + @Test + void aListenWithADuplicateIdIsCancelledAtTheEndOfInput() throws Exception { + for (int i = 0; i < 2; i++) { + send( + request( + 11, + McpSchema.METHOD_SUBSCRIPTIONS_LISTEN, + Map.of("notifications", Map.of("toolsListChanged", true)), + meta())); + assertEquals( + McpSchema.METHOD_NOTIFICATION_SUBSCRIPTIONS_ACKNOWLEDGED, read().get("method")); + } + + toServer.close(); + + // not after the request timeout and its grace, which would be 35 seconds + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + } + + /** The same for a 2025-11-25 request, which the connector serves with its own slots. */ + @Test + void aLegacyRequestInFlightAtTheEndOfInputIsAnswered() throws Exception { + Map legacy = new LinkedHashMap<>(); + legacy.put(MetaKeys.PROTOCOL_VERSION, McpProtocol.VERSION); + send(request(12, "tools/call", Map.of("name", "gated", "arguments", Map.of()), legacy)); + assertTrue(gateStarted.await(10, TimeUnit.SECONDS), "the tool did not start"); + + toServer.close(); + + assertNull(lines.poll(300, TimeUnit.MILLISECONDS), "answered before the tool ended"); + assertEquals(1, outputClosed.getCount(), "closed with a request in flight"); + gate.complete("go"); + Map answer = read(); + assertEquals(12, ((Number) answer.get("id")).intValue(), answer.toString()); + assertEquals("released", firstText(result(answer))); + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + } + + /** A clean end of the input is not a warning. */ + @Test + void aCleanEndOfInputIsNotLoggedAsAWarning() throws Exception { + List warnings = new CopyOnWriteArrayList<>(); + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + java.util.logging.Handler handler = warningsOfTheConnector(warnings); + root.addHandler(handler); + try { + toServer.close(); + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + assertEquals(List.of(), warnings, "a clean end of the input was a warning"); + } finally { + root.removeHandler(handler); + } + } + + /** + * The control of the test above: the same handler does capture the warning of an error on the + * input, so an empty capture is not a handler that sees nothing. + */ + @Test + void anErrorOnTheInputIsLoggedAsAWarning() throws Exception { + List warnings = new CopyOnWriteArrayList<>(); + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + java.util.logging.Handler handler = warningsOfTheConnector(warnings); + root.addHandler(handler); + try { + requestPipe.source().close(); + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + assertEquals(1, warnings.size(), warnings.toString()); + } finally { + root.removeHandler(handler); + } + } + + /** A handler that keeps the warnings and worse of the STDIO connector. */ + private static java.util.logging.Handler warningsOfTheConnector( + List warnings) { + return new java.util.logging.Handler() { + @Override + public void publish(java.util.logging.LogRecord record) { + if (record.getLevel().intValue() >= java.util.logging.Level.WARNING.intValue() + && String.valueOf(record.getMessage()).contains("MCP STDIO")) { + warnings.add(record); + } + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + } + + /** An error on the input is a fault: what is in flight is aborted, and gets no answer. */ + @Test + void anInputErrorAbortsWhatIsInFlight() throws Exception { + send(request(10, "tools/call", Map.of("name", "gated", "arguments", Map.of()), meta())); + assertTrue(gateStarted.await(10, TimeUnit.SECONDS), "the tool did not start"); + + requestPipe.source().close(); + + assertTrue(outputClosed.await(10, TimeUnit.SECONDS), "the connector did not close"); + gate.complete("go"); + assertNull(lines.poll(300, TimeUnit.MILLISECONDS), "answered after the abort"); + } + /** A listen stream stays open over stdio, carrying changes between other responses. */ @Test void aListenStreamCarriesChanges() throws Exception {