Skip to content
Open
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
7 changes: 7 additions & 0 deletions changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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";

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
}

Expand All @@ -182,7 +195,7 @@ private void read() {
}
}
if (!closed) {
fail(new IOException("MCP STDIO input ended"));
endOfInput();
}
} catch (IOException | RuntimeException e) {
if (!closed) {
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Comment thread
jlouvel marked this conversation as resolved.
Resolved
requests.forEach(Request::abort);
try {
stream.stop();
Expand Down Expand Up @@ -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;
Expand Down
Loading