diff --git a/changes.md b/changes.md
index 0a4b3d5451..16244c2511 100644
--- a/changes.md
+++ b/changes.md
@@ -53,6 +53,13 @@ Changes log
`Response.redirectPermanentStrict(...)`, `ServerResource.redirectPermanentStrict(...)` and
`Router.redirectPermanentStrict(...)`. The Javadoc of the 301 helpers no longer promises
that the method is kept (#1746).
+ - `McpClientAdapter` in `auto` mode now probes stdio servers too (#1670), over its own
+ stream or a `stdio:` connector: it sends `server/discover` within the request timeout and
+ keeps the 2026-07-28 client when the server names that revision, or falls back to a
+ legacy `initialize`, offering the legacy revisions, on the same stream when the server
+ rejects the probe or leaves it unanswered, dropping a late answer to the probe. The
+ 2026-07-28 client, also when asked for explicitly, now speaks over stdio through the SDK's
+ stdio transport; `getTasksClient()` stays HTTP only.
- `McpServerAdapter.setJsonMapper` and `McpClientAdapter.setJsonMapper` (for the
2026-07-28 client) let the application supply the JSON mapper of the MCP messages, the
SDK's Jackson 3 one by default (#1705).
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpClientAdapter.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpClientAdapter.java
index 2fc93aa33b..cbda1f57c9 100644
--- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpClientAdapter.java
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpClientAdapter.java
@@ -14,6 +14,7 @@
import io.modelcontextprotocol.modern.client.McpAsyncClient;
import io.modelcontextprotocol.modern.client.McpAsyncElicitationHandler;
import io.modelcontextprotocol.modern.client.McpClient;
+import io.modelcontextprotocol.modern.client.McpTimeoutException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
@@ -21,6 +22,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import org.restlet.Client;
import org.restlet.Request;
@@ -28,8 +30,11 @@
import org.restlet.ext.mcp.internal.McpHttpStatusException;
import org.restlet.ext.mcp.internal.McpLegacyEdge;
import org.restlet.ext.mcp.internal.McpModernHttpTransport;
+import org.restlet.ext.mcp.internal.McpModernStdioTransport;
import org.restlet.ext.mcp.internal.McpServerErrorException;
+import org.restlet.ext.mcp.internal.McpStdioChannel;
import reactor.core.Exceptions;
+import reactor.core.publisher.Mono;
/**
* Lifecycle facade of an MCP client, on the SDK's {@code 2026-07-28} types. Borrowed Restlet
@@ -37,9 +42,10 @@
*
*
By default it speaks MCP {@link McpProtocol#VERSION} through the SDK's client, behind a legacy
* edge. With {@link #setProtocolVersion(String)} set to {@link McpProtocol#MODERN_VERSION}, it
- * speaks {@code 2026-07-28} over HTTP instead, experimentally: {@link #start()} discovers the
- * server, and {@link #getModernClient()}, the SDK's client over this adapter's HTTP connector,
- * makes the requests, the task-augmented ones excepted, which {@link #getTasksClient()} makes.
+ * speaks {@code 2026-07-28} instead, experimentally, over HTTP or stdio: {@link #start()} discovers
+ * the server, and {@link #getModernClient()}, the SDK's client over this adapter's connector or
+ * stream, makes the requests, the task-augmented ones excepted, which {@link #getTasksClient()}
+ * makes, over HTTP only for now.
*
*
With {@link McpProtocol#AUTO}, also experimental, it speaks whichever era the server does, as
* the 2026-07-28 revision specifies for a dual-era client. Over HTTP, {@link #start()} sends {@code
@@ -51,8 +57,15 @@
* a later start skips the probe, and probes again only if the server contradicts that era, with a
* {@code 4xx} or a JSON-RPC error that the other era would answer with, not with a timeout or a
* {@code 5xx}. A started client keeps its era: requests are never replayed on the other one, so
- * when a server changes era, stop the client and start a new one. Over stdio, it speaks {@link
- * McpProtocol#VERSION}, the modern client being HTTP only.
+ * when a server changes era, stop the client and start a new one.
+ *
+ *
Over stdio, whether its own stream or a {@code stdio:} connector's, {@link McpProtocol#AUTO}
+ * probes the same way, within the request timeout, on the stream it then keeps using: a discovery
+ * result naming {@code 2026-07-28}, or a recognized modern error, selects the modern client; an
+ * unsupported version error offering a legacy revision, any other JSON-RPC error, or a timeout
+ * selects the legacy one, whose {@code initialize} offers {@link McpProtocol#LEGACY_VERSIONS}. A
+ * late answer to the probe is dropped. No era is remembered: the process at the other end of the
+ * stream serves this client only, and is probed once per start.
*
*
With a legacy server, the client exposes nothing 2026-07-28 deprecates or removes: it declares
* no roots, sampling or elicitation capability, never sets a logging level, refuses the requests a
@@ -87,6 +100,7 @@ public final class McpClientAdapter implements AutoCloseable {
private McpJsonMapper jsonMapper = McpJsonDefaults.getMapper();
private boolean legacySessions;
private String legacySessionId;
+ private McpStdioChannel ownChannel;
private Modern modern;
private McpLegacyEdge.Client legacy;
private String negotiatedVersion;
@@ -159,8 +173,8 @@ public synchronized Consumer getRequestCustomizer() {
/**
* Sets the MCP revision spoken: {@link McpProtocol#VERSION}, the default, through the SDK's
- * client; {@link McpProtocol#MODERN_VERSION} through {@link #getModernClient()}, over HTTP only
- * for now; or {@link McpProtocol#AUTO}, whichever the server speaks. Experimental for {@code
+ * client; {@link McpProtocol#MODERN_VERSION} through {@link #getModernClient()}, over HTTP or
+ * stdio; or {@link McpProtocol#AUTO}, whichever the server speaks. Experimental for {@code
* 2026-07-28} and {@code auto}.
*
* @param value The revision, or {@link McpProtocol#AUTO}.
@@ -324,15 +338,61 @@ public synchronized void start() {
}
requireConfigurable();
configured = true;
- if (McpProtocol.MODERN_VERSION.equals(protocolVersion)) {
- startModern(createModern());
- return;
+ try {
+ if (McpProtocol.MODERN_VERSION.equals(protocolVersion)) {
+ startModern(createModern());
+ } else if (McpProtocol.AUTO.equals(protocolVersion)) {
+ startAuto();
+ } else {
+ startLegacy(List.of(McpProtocol.VERSION));
+ }
+ } catch (RuntimeException e) {
+ try {
+ closeOwnChannel();
+ } catch (RuntimeException cleanup) {
+ e.addSuppressed(cleanup);
+ }
+ throw e;
}
- if (McpProtocol.AUTO.equals(protocolVersion)) {
- startAuto();
- return;
+ }
+
+ /** Whether this client speaks over stdio: its own stream, or a {@code stdio:} connector. */
+ private boolean isStdio() {
+ return stream != null || target.startsWith("stdio:");
+ }
+
+ /**
+ * The framing of the stdio stream: this adapter's own, or the connector's, which the clients of
+ * either era attach to in turn.
+ */
+ private McpStdioChannel stdioChannel() {
+ if (stream != null) {
+ if (ownChannel == null) {
+ ownChannel = new McpStdioChannel(stream);
+ }
+ return ownChannel;
+ }
+ if (!client.isStarted()
+ || client.getContext() == null
+ || !(client.getContext().getAttributes().get(StdioClientHelper.TRANSPORT_ATTRIBUTE)
+ instanceof StdioClientHelper helper)) {
+ throw new IllegalStateException(
+ "A started explicitly selected MCP STDIO helper is required");
+ }
+ return helper.channel();
+ }
+
+ /** Stops this adapter's own stream, if it has one. */
+ private void closeOwnChannel() {
+ if (ownChannel != null) {
+ try {
+ ownChannel.close(requestTimeout);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } finally {
+ ownChannel = null;
+ }
}
- startLegacy(List.of(McpProtocol.VERSION));
}
/** Starts the legacy client: an {@code initialize} handshake offering these revisions. */
@@ -347,8 +407,14 @@ private void startLegacy(List versions) {
* the server contradicts it, else the one a {@code server/discover} probe tells.
*/
private void startAuto() {
- if (stream != null || target.startsWith("stdio:")) {
- startLegacy(List.of(McpProtocol.VERSION));
+ if (isStdio()) {
+ // One client per process or connector: there is no era to remember.
+ if (probe(createModern())) {
+ negotiatedVersion = McpProtocol.MODERN_VERSION;
+ started = true;
+ } else {
+ startLegacy(McpProtocol.LEGACY_VERSIONS);
+ }
return;
}
String cached = McpEras.get(target);
@@ -369,9 +435,7 @@ private void startAuto() {
McpEras.remove(target);
}
}
- Modern candidate = createModern();
- if (probe(candidate)) {
- modern = candidate;
+ if (probe(createModern())) {
negotiatedVersion = McpProtocol.MODERN_VERSION;
started = true;
McpEras.put(target, McpEras.MODERN);
@@ -412,16 +476,20 @@ private NotModern() {
}
/**
- * Probes the server with {@code server/discover}.
+ * Probes the server with {@code server/discover}. Over stdio, where a legacy server may leave
+ * the request unanswered, a timeout marks a legacy server too.
*
* @return True for a modern server, which the candidate then serves; false for a legacy one,
- * for which the candidate is closed.
+ * for which the candidate is closed, and detached from the stdio stream.
*/
private boolean probe(Modern candidate) {
boolean kept = false;
try {
+ Mono discover = candidate.client().discover();
McpSchema.DiscoverResult discovered =
- candidate.client().discover().block(requestTimeout);
+ isStdio()
+ ? discover.timeout(requestTimeout).block()
+ : discover.block(requestTimeout);
List supported =
discovered == null || discovered.supportedVersions() == null
? List.of()
@@ -431,9 +499,13 @@ private boolean probe(Modern candidate) {
throw new IllegalStateException(
"No MCP revision supported by both the client and the peer: " + supported);
}
+ if (kept) {
+ modern = candidate;
+ }
return kept;
} catch (RuntimeException e) {
- if (!isLegacy(Exceptions.unwrap(e))) {
+ Throwable cause = Exceptions.unwrap(e);
+ if (!(isStdio() && isTimeout(cause)) && !isLegacy(cause)) {
throw e;
}
return false;
@@ -449,6 +521,11 @@ private boolean probe(Modern candidate) {
}
}
+ /** Whether a failure is a timeout: the probe's, or the SDK's round timeout. */
+ private static boolean isTimeout(Throwable failure) {
+ return failure instanceof TimeoutException || failure instanceof McpTimeoutException;
+ }
+
/**
* Whether a failed {@code server/discover} marks a legacy server: a JSON-RPC error that isn't a
* recognized modern one and doesn't come with a {@code 5xx}, or a {@code 4xx} without a
@@ -493,10 +570,10 @@ private static boolean offersLegacy(List supported) {
}
/**
- * The {@code 2026-07-28} clients over one HTTP transport: the SDK's and the Tasks extension's.
+ * The {@code 2026-07-28} clients over one transport: the SDK's and, over HTTP, the Tasks
+ * extension's.
*/
- private record Modern(
- McpAsyncClient client, McpTasksClient tasks, McpModernHttpTransport transport) {
+ private record Modern(McpAsyncClient client, McpTasksClient tasks, AutoCloseable transport) {
/** Ends the exchanges in flight and listen streams. */
void close() {
@@ -504,14 +581,29 @@ void close() {
transport.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
}
}
}
private Modern createModern() {
- if (stream != null || target.startsWith("stdio:")) {
- throw new UnsupportedOperationException(
- "The MCP 2026-07-28 client supports HTTP only for now");
+ if (isStdio()) {
+ McpModernStdioTransport transport;
+ try {
+ transport =
+ new McpModernStdioTransport(
+ stdioChannel(),
+ jsonMapper,
+ maxMessageBytes,
+ maxConcurrentCalls,
+ requestTimeout);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return new Modern(modernBuilder(transport).build(), null, transport);
}
if (!client.isStarted()
|| client.getContext() == null
@@ -532,6 +624,16 @@ private Modern createModern() {
maxConcurrentCalls,
requestTimeout,
requestCustomizer);
+ return new Modern(
+ modernBuilder(transport).build(),
+ new McpTasksClient(
+ transport, jsonMapper, formElicitation, urlElicitation, maxInputRounds),
+ transport::close);
+ }
+
+ /** The builder of the SDK's modern client over a transport, with this adapter's settings. */
+ private McpClient.AsyncBuilder modernBuilder(
+ io.modelcontextprotocol.modern.client.transport.McpClientTransport transport) {
McpClient.AsyncBuilder builder =
McpClient.async(transport)
.jsonMapper(jsonMapper)
@@ -543,11 +645,7 @@ private Modern createModern() {
if (urlElicitation != null) {
builder.urlElicitation(urlElicitation);
}
- return new Modern(
- builder.build(),
- new McpTasksClient(
- transport, jsonMapper, formElicitation, urlElicitation, maxInputRounds),
- transport);
+ return builder;
}
/** Starts a {@code 2026-07-28} client, and discovers the server's support of it. */
@@ -575,9 +673,10 @@ private void startModern(Modern candidate) {
/**
* The SDK's {@link McpProtocol#MODERN_VERSION} client, once that is the revision spoken. It
- * sends its requests over this adapter's HTTP connector, within its limits, and answers their
- * {@code input_required} results with its elicitation handlers. It declares the capabilities of
- * those handlers only: task-augmented calls go through {@link #getTasksClient()}.
+ * sends its requests over this adapter's HTTP connector or stdio stream, within its limits, and
+ * answers their {@code input_required} results with its elicitation handlers. It declares the
+ * capabilities of those handlers only: task-augmented calls go through {@link
+ * #getTasksClient()}.
*
* @return The client.
*/
@@ -587,12 +686,18 @@ public synchronized McpAsyncClient getModernClient() {
/**
* The client of the Tasks extension, once {@link McpProtocol#MODERN_VERSION} is the revision
- * spoken.
+ * spoken, over HTTP only for now.
*
* @return The client.
+ * @throws UnsupportedOperationException Over stdio.
*/
public synchronized McpTasksClient getTasksClient() {
- return modern().tasks();
+ McpTasksClient tasks = modern().tasks();
+ if (tasks == null) {
+ throw new UnsupportedOperationException(
+ "The MCP Tasks extension client supports HTTP only for now");
+ }
+ return tasks;
}
private Modern modern() {
@@ -604,20 +709,9 @@ private Modern modern() {
/** Starts a legacy client, over the stream, the stdio connector or HTTP. */
private McpLegacyEdge.Client createLegacy(List versions) {
- if (stream != null) {
- return McpLegacyEdge.stdio(stream, maxMessageBytes, maxConcurrentCalls, requestTimeout);
- }
- if (target.startsWith("stdio:")) {
- if (!client.isStarted()
- || client.getContext() == null
- || !(client.getContext()
- .getAttributes()
- .get(StdioClientHelper.TRANSPORT_ATTRIBUTE)
- instanceof StdioClientHelper helper)) {
- throw new IllegalStateException(
- "A started explicitly selected MCP STDIO helper is required");
- }
- return helper.bind(maxMessageBytes, maxConcurrentCalls, requestTimeout);
+ if (isStdio()) {
+ return McpLegacyEdge.stdio(
+ stdioChannel(), versions, maxMessageBytes, maxConcurrentCalls, requestTimeout);
}
return McpLegacyEdge.http(
new McpLegacyEdge.HttpOptions(
@@ -721,22 +815,48 @@ private synchronized McpLegacyEdge.Client legacy() {
}
public synchronized void stop() {
+ RuntimeException failure = null;
+ // The modern client first: closing it frees the stream's reader, which a subscriber slow
+ // to take its messages may hold.
if (modern != null) {
started = false;
try {
modern.close();
+ } catch (RuntimeException e) {
+ failure = e;
} finally {
modern = null;
}
}
+ // Then the adapter's own stream: a write stuck on a server that stopped reading ends at
+ // once, instead of holding the legacy client's close until it times out.
+ try {
+ closeOwnChannel();
+ } catch (RuntimeException e) {
+ failure = suppress(failure, e);
+ }
if (legacy != null) {
started = false;
try {
legacy.close();
+ } catch (RuntimeException e) {
+ failure = suppress(failure, e);
} finally {
legacy = null;
}
}
+ if (failure != null) {
+ throw failure;
+ }
+ }
+
+ /** The first failure, with a later one suppressed in it. */
+ private static RuntimeException suppress(RuntimeException first, RuntimeException later) {
+ if (first == null) {
+ return later;
+ }
+ first.addSuppressed(later);
+ return first;
}
@Override
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpProtocol.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpProtocol.java
index 7daa3804bb..ca71f56a20 100644
--- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpProtocol.java
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpProtocol.java
@@ -23,9 +23,9 @@ public final class McpProtocol {
public static final String MODERN_VERSION = "2026-07-28";
/**
- * Makes {@link McpClientAdapter} speak whichever revision the server does, experimentally: over
- * HTTP, {@link #MODERN_VERSION} when the server answers {@code server/discover}, else one of
- * {@link #LEGACY_VERSIONS} through an {@code initialize} handshake.
+ * Makes {@link McpClientAdapter} speak whichever revision the server does, experimentally, over
+ * HTTP or stdio: {@link #MODERN_VERSION} when the server answers {@code server/discover}, else
+ * one of {@link #LEGACY_VERSIONS} through an {@code initialize} handshake.
*/
public static final String AUTO = "auto";
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioClientHelper.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioClientHelper.java
index dd53152b66..91585d3c4a 100644
--- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioClientHelper.java
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/StdioClientHelper.java
@@ -8,24 +8,34 @@
*/
package org.restlet.ext.mcp;
+import java.io.IOException;
+import java.io.UncheckedIOException;
import java.time.Duration;
+import java.util.List;
import org.restlet.Client;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Protocol;
import org.restlet.engine.connector.ClientHelper;
import org.restlet.ext.mcp.internal.McpLegacyEdge;
+import org.restlet.ext.mcp.internal.McpStdioChannel;
/**
* Explicit MCP STDIO connector helper. Its owner supplies an unstarted StreamTransport in the
* connector context under STREAM_TRANSPORT_ATTRIBUTE and stops the connector after the {@link
* McpClientAdapter} using it. No executable is inferred from the stdio URI and no system stream is
- * installed by default. The connector speaks MCP {@link McpProtocol#VERSION}, the modern client
- * being HTTP only for now.
+ * installed by default.
+ *
+ *
The connector frames the stream, one JSON-RPC message per line, for one {@link
+ * McpClientAdapter} at a time, which speaks MCP {@link McpProtocol#VERSION}, {@link
+ * McpProtocol#MODERN_VERSION} or, with {@link McpProtocol#AUTO}, probes with {@code
+ * server/discover} first and falls back to a legacy {@code initialize} on the same stream. The
+ * first client to use the connector fixes its message limit. Stopping the connector ends the
+ * stream.
*/
public final class StdioClientHelper extends ClientHelper {
static final String TRANSPORT_ATTRIBUTE = "org.restlet.ext.mcp.clientTransport";
- private McpLegacyEdge.StdioTransport transport;
+ private McpStdioChannel channel;
public StdioClientHelper(Client client) {
super(client);
@@ -39,27 +49,39 @@ public synchronized void start() {
throw new IllegalStateException(
"MCP STDIO requires an explicitly configured StreamTransport");
}
- transport = McpLegacyEdge.stdioTransport(stream);
+ channel = new McpStdioChannel(stream);
getContext().getAttributes().put(TRANSPORT_ATTRIBUTE, this);
}
/**
- * Starts a client on this connector's transport, with an MCP client's limits. One client may
- * bind it.
+ * The framing of this connector's stream, which the client adapter using it attaches to.
+ *
+ * @return The channel.
*/
- synchronized McpLegacyEdge.Client bind(int maxMessageBytes, int maxCalls, Duration timeout) {
- if (transport == null) {
+ synchronized McpStdioChannel channel() {
+ if (channel == null) {
throw new IllegalStateException("Start the MCP STDIO client connector first");
}
- return McpLegacyEdge.stdio(transport, maxMessageBytes, maxCalls, timeout);
+ return channel;
+ }
+
+ /**
+ * Starts a legacy client on this connector's stream, with an MCP client's limits, offering
+ * {@link McpProtocol#VERSION}.
+ */
+ McpLegacyEdge.Client bind(int maxMessageBytes, int maxCalls, Duration timeout) {
+ return McpLegacyEdge.stdio(
+ channel(), List.of(McpProtocol.VERSION), maxMessageBytes, maxCalls, timeout);
}
@Override
public synchronized void stop() {
try {
- if (transport != null) {
- transport.close(Duration.ofSeconds(30));
+ if (channel != null) {
+ channel.close(Duration.ofSeconds(30));
}
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
} finally {
getContext().getAttributes().remove(TRANSPORT_ATTRIBUTE, this);
}
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpLegacyEdge.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpLegacyEdge.java
index 2e132b9ed4..89246356d6 100644
--- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpLegacyEdge.java
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpLegacyEdge.java
@@ -11,6 +11,8 @@
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.modern.JsonRpc;
import io.modelcontextprotocol.modern.McpSchema;
+import java.io.IOException;
+import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.List;
import java.util.function.Consumer;
@@ -20,7 +22,6 @@
import org.restlet.ext.mcp.internal.legacy.McpLegacyClient;
import org.restlet.ext.mcp.internal.legacy.McpLegacyServer;
import org.restlet.ext.mcp.internal.legacy.StdioMcpClientTransport;
-import org.restlet.util.StreamTransport;
import reactor.core.publisher.Mono;
/**
@@ -144,16 +145,6 @@ record HttpOptions(
boolean sessions,
String sessionId) {}
- /** The transport a stdio client connector owns, for one legacy client to bind. */
- interface StdioTransport {
-
- /** Applies a client's limits, before it connects. */
- void setLimits(int maxMessageBytes, int maxConcurrentCalls, Duration timeout);
-
- /** Ends the transport. */
- void close(Duration timeout);
- }
-
/**
* Creates the server edge of an adapter.
*
@@ -190,52 +181,30 @@ static Client http(HttpOptions options) {
}
/**
- * Starts a legacy client over a stream it owns.
+ * Starts a legacy client over a stdio channel, opening it with the client's message limit if
+ * not yet open. The channel stays open when the client closes: the client detaches from it.
*
- * @param stream The stream.
- * @param maxMessageBytes The largest message.
- * @param maxConcurrentCalls The most exchanges at once.
- * @param timeout The request timeout.
- * @return The started client.
- */
- static Client stdio(
- StreamTransport stream, int maxMessageBytes, int maxConcurrentCalls, Duration timeout) {
- return McpLegacyClient.stdio(
- new StdioMcpClientTransport(stream, maxMessageBytes, maxConcurrentCalls, timeout),
- true,
- timeout);
- }
-
- /**
- * Starts a legacy client over the transport a stdio connector owns, which stays open when the
- * client closes.
- *
- * @param transport The connector's transport.
+ * @param channel The channel.
+ * @param versions The revisions offered, newest first.
* @param maxMessageBytes The largest message.
* @param maxConcurrentCalls The most exchanges at once.
* @param timeout The request timeout.
* @return The started client.
*/
static Client stdio(
- StdioTransport transport,
+ McpStdioChannel channel,
+ List versions,
int maxMessageBytes,
int maxConcurrentCalls,
Duration timeout) {
- transport.setLimits(maxMessageBytes, maxConcurrentCalls, timeout);
- return McpLegacyClient.stdio((StdioMcpClientTransport) transport, false, timeout);
- }
-
- /**
- * Creates the transport of a stdio client connector.
- *
- * @param stream The stream.
- * @return The transport.
- */
- static StdioTransport stdioTransport(StreamTransport stream) {
- return new StdioMcpClientTransport(
- stream,
- org.restlet.ext.mcp.McpProtocol.DEFAULT_MAX_MESSAGE_BYTES,
- org.restlet.ext.mcp.McpProtocol.DEFAULT_MAX_CONCURRENT_CALLS,
- Duration.ofSeconds(30));
+ try {
+ channel.open(maxMessageBytes);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return McpLegacyClient.stdio(
+ new StdioMcpClientTransport(
+ channel, false, versions, maxMessageBytes, maxConcurrentCalls, timeout),
+ timeout);
}
}
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernStdioTransport.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernStdioTransport.java
new file mode 100644
index 0000000000..260aa5bd3c
--- /dev/null
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernStdioTransport.java
@@ -0,0 +1,272 @@
+/**
+ * Copyright 2005-2026 Qlik
+ *
+ * The content of this file is subject to the terms of the Apache 2.0 open
+ * source license available at https://www.opensource.org/licenses/apache-2.0
+ *
+ * Restlet is a registered trademark of QlikTech International AB.
+ */
+package org.restlet.ext.mcp.internal;
+
+import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.modern.JsonRpc;
+import io.modelcontextprotocol.modern.McpSchema;
+import io.modelcontextprotocol.modern.client.transport.McpClientTransport;
+import io.modelcontextprotocol.modern.client.transport.McpTransportRequest;
+import io.modelcontextprotocol.modern.client.transport.StdioMcpClientTransport;
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
+import reactor.core.publisher.Flux;
+
+/**
+ * Sends MCP {@code 2026-07-28} requests over a stdio channel, through the SDK's stdio transport,
+ * which routes the responses, progress and subscription notifications to their requests, and sends
+ * {@code notifications/cancelled} when one is cancelled. The SDK's transport reads and writes
+ * streams that are views of the channel: its input gives the frames the channel delivers, each
+ * followed by a newline, and ends when this transport closes or the channel ends; its output splits
+ * what is written into frames at newlines. Closing this transport detaches it from the channel,
+ * which stays open for another client, and drops the late responses to the requests left
+ * unanswered. Calls in flight are limited, listen streams excepted.
+ */
+public final class McpModernStdioTransport implements McpClientTransport, AutoCloseable {
+
+ /** The most frames received but not yet read by the SDK's transport. */
+ private static final int MAX_BUFFERED = 64;
+
+ private final McpStdioChannel channel;
+ private final int maxConcurrentCalls;
+ private final AtomicInteger calls = new AtomicInteger();
+ private final Frames frames = new Frames();
+ private final StdioMcpClientTransport sdk;
+
+ /**
+ * Attaches to a channel, opening it with the message limit if not yet open.
+ *
+ * @param channel The channel.
+ * @param mapper The JSON mapper.
+ * @param maxMessageBytes The size limit of each message, sent or received.
+ * @param maxConcurrentCalls The number of calls in flight at once.
+ * @param shutdownTimeout How long closing waits.
+ * @throws IOException If the channel fails to open.
+ */
+ public McpModernStdioTransport(
+ McpStdioChannel channel,
+ McpJsonMapper mapper,
+ int maxMessageBytes,
+ int maxConcurrentCalls,
+ Duration shutdownTimeout)
+ throws IOException {
+ this.channel = Objects.requireNonNull(channel, "channel");
+ this.maxConcurrentCalls = maxConcurrentCalls;
+ channel.open(maxMessageBytes);
+ channel.attach(frames);
+ try {
+ sdk =
+ StdioMcpClientTransport.builder(
+ new FrameInput(), new FrameOutput(maxMessageBytes))
+ .jsonMapper(mapper)
+ .inputMaxSize(maxMessageBytes)
+ .shutdownTimeout(shutdownTimeout)
+ .start();
+ } catch (RuntimeException e) {
+ frames.close();
+ throw e;
+ }
+ }
+
+ @Override
+ public Flux exchange(McpTransportRequest request) {
+ if (McpSchema.METHOD_SUBSCRIPTIONS_LISTEN.equals(request.method())) {
+ return sdk.exchange(request);
+ }
+ return Flux.defer(
+ () -> {
+ if (calls.incrementAndGet() > maxConcurrentCalls) {
+ calls.decrementAndGet();
+ return Flux.error(
+ new IOException(
+ "MCP STDIO call limit of "
+ + maxConcurrentCalls
+ + " reached"));
+ }
+ return sdk.exchange(request).doFinally(signal -> calls.decrementAndGet());
+ });
+ }
+
+ /** Ends the requests in flight, and detaches from the channel. */
+ @Override
+ public void close() {
+ try {
+ sdk.close();
+ } finally {
+ frames.close();
+ }
+ }
+
+ /** The frames the channel delivers, until closed or the channel ends. */
+ private final class Frames implements McpStdioChannel.Sink {
+ private final ArrayDeque queue = new ArrayDeque<>();
+ private IOException failure;
+ private boolean ended;
+ private boolean closed;
+
+ @Override
+ public synchronized void receive(byte[] frame) {
+ // Holds back the channel's reader while the SDK's transport catches up.
+ while (!closed && queue.size() >= MAX_BUFFERED) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ }
+ if (!closed) {
+ queue.add(frame);
+ notifyAll();
+ }
+ }
+
+ @Override
+ public synchronized void end(IOException cause) {
+ ended = true;
+ if (!(cause instanceof EOFException)) {
+ failure = cause;
+ }
+ notifyAll();
+ }
+
+ /** The next frame, null at the end. */
+ synchronized byte[] take() throws IOException {
+ while (queue.isEmpty() && !ended && !closed) {
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("MCP STDIO read interrupted");
+ }
+ }
+ if (closed) {
+ return null;
+ }
+ byte[] frame = queue.poll();
+ if (frame == null && failure != null) {
+ throw new IOException("MCP STDIO read failed", failure);
+ }
+ notifyAll();
+ return frame;
+ }
+
+ void close() {
+ synchronized (this) {
+ if (closed) {
+ return;
+ }
+ closed = true;
+ queue.clear();
+ notifyAll();
+ }
+ channel.detach(this);
+ }
+ }
+
+ /** The input of the SDK's transport: each frame, then a newline. */
+ private final class FrameInput extends InputStream {
+ private byte[] current;
+ private int position;
+ private boolean done;
+
+ @Override
+ public int read() throws IOException {
+ byte[] single = new byte[1];
+ return read(single, 0, 1) == -1 ? -1 : single[0] & 0xff;
+ }
+
+ @Override
+ public synchronized int read(byte[] buffer, int offset, int length) throws IOException {
+ Objects.checkFromIndexSize(offset, length, buffer.length);
+ if (length == 0) {
+ return 0;
+ }
+ if (done) {
+ return -1;
+ }
+ if (current == null || position > current.length) {
+ current = frames.take();
+ position = 0;
+ if (current == null) {
+ done = true;
+ return -1;
+ }
+ }
+ if (position == current.length) {
+ buffer[offset] = '\n';
+ position++;
+ return 1;
+ }
+ int count = Math.min(length, current.length - position);
+ System.arraycopy(current, position, buffer, offset, count);
+ position += count;
+ return count;
+ }
+
+ @Override
+ public void close() {
+ frames.close();
+ }
+ }
+
+ /** The output of the SDK's transport: a frame written to the channel at each newline. */
+ private final class FrameOutput extends OutputStream {
+ private final int limit;
+ private final ByteArrayOutputStream pending;
+
+ FrameOutput(int limit) {
+ this.limit = limit;
+ pending = new ByteArrayOutputStream(Math.min(limit, 8192));
+ }
+
+ @Override
+ public void write(int value) throws IOException {
+ write(new byte[] {(byte) value}, 0, 1);
+ }
+
+ @Override
+ public synchronized void write(byte[] bytes, int offset, int length) throws IOException {
+ Objects.checkFromIndexSize(offset, length, bytes.length);
+ int start = offset;
+ int end = offset + length;
+ for (int i = offset; i < end; i++) {
+ if (bytes[i] == '\n') {
+ append(bytes, start, i - start);
+ byte[] frame = pending.toByteArray();
+ pending.reset();
+ channel.write(frames, frame);
+ start = i + 1;
+ }
+ }
+ append(bytes, start, end - start);
+ }
+
+ private void append(byte[] bytes, int offset, int length) throws IOException {
+ if (pending.size() + length > limit) {
+ pending.reset();
+ throw new IOException("MCP encoded message exceeds " + limit + " bytes");
+ }
+ pending.write(bytes, offset, length);
+ }
+
+ @Override
+ public void close() {
+ frames.close();
+ }
+ }
+}
diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpStdioChannel.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpStdioChannel.java
new file mode 100644
index 0000000000..6889ecdf11
--- /dev/null
+++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpStdioChannel.java
@@ -0,0 +1,405 @@
+/**
+ * Copyright 2005-2026 Qlik
+ *
+ * The content of this file is subject to the terms of the Apache 2.0 open
+ * source license available at https://www.opensource.org/licenses/apache-2.0
+ *
+ * Restlet is a registered trademark of QlikTech International AB.
+ */
+package org.restlet.ext.mcp.internal;
+
+import io.modelcontextprotocol.json.McpJsonDefaults;
+import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.json.TypeRef;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.SequencedSet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.restlet.util.StreamTransport;
+
+/**
+ * The MCP framing of one stdio stream, one JSON-RPC message per line, shared by the clients that
+ * use it in turn: a {@code 2026-07-28} client probing the server, then the legacy client if the
+ * probe fails. It owns the stream's only reader, a virtual thread, and serializes the writes.
+ *
+ *
Frames go to the attached sink, one at a time and in order, on the reader thread. Frames read
+ * while no sink is attached are queued, within a bound, and delivered to the next one. The ids of
+ * the requests a sink wrote and left unanswered when it detached are remembered, within a bound, so
+ * that their late responses are dropped rather than reaching the next sink, which never sent them.
+ * The end of the stream, or a read failure, is told to the attached sink, or else to the next one.
+ */
+public final class McpStdioChannel {
+
+ /** Receives the frames of a channel. */
+ public interface Sink {
+
+ /**
+ * Receives one frame, without its newline, on the reader thread.
+ *
+ * @param frame The frame.
+ */
+ void receive(byte[] frame);
+
+ /**
+ * Tells that no more frames will come.
+ *
+ * @param failure An {@link EOFException} for the end of the stream, or the read failure.
+ */
+ void end(IOException failure);
+ }
+
+ /** The most frames queued while no sink is attached. */
+ static final int MAX_QUEUED = 64;
+
+ /** The most request ids remembered, unanswered or abandoned. */
+ static final int MAX_IDS = 1024;
+
+ private static final Logger LOGGER = Logger.getLogger(McpStdioChannel.class.getName());
+
+ private static final TypeRef