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> MAP = new TypeRef<>() {}; + + private final StreamTransport stream; + private final McpJsonMapper mapper = McpJsonDefaults.getMapper(); + private final ReentrantLock delivery = new ReentrantLock(); + private final Object writing = new Object(); + private final ExecutorService writer = + Executors.newSingleThreadExecutor( + Thread.ofVirtual().name("restlet-mcp-stdio-writer").factory()); + private final ArrayDeque queued = new ArrayDeque<>(); + private final SequencedSet pending = new LinkedHashSet<>(); + private final SequencedSet abandoned = new LinkedHashSet<>(); + private int maxMessageBytes; + private Sink sink; + private IOException ended; + private Thread reader; + private volatile boolean closed; + + /** + * @param stream The unstarted stream, which {@link #close(Duration)} stops. + */ + public McpStdioChannel(StreamTransport stream) { + this.stream = Objects.requireNonNull(stream, "stream"); + } + + /** + * Starts the stream and its reader, once, with a message limit, which later calls must repeat. + * + * @param limit The largest message, in bytes. + * @throws IOException If the stream fails to start. + * @throws IllegalStateException If closed, or already opened with another limit. + */ + public synchronized void open(int limit) throws IOException { + if (closed) { + throw new IllegalStateException("MCP STDIO channel is closed"); + } + if (reader != null) { + if (limit != maxMessageBytes) { + throw new IllegalStateException("MCP STDIO limits are fixed once connected"); + } + return; + } + if (limit <= 0 || limit == Integer.MAX_VALUE) { + throw new IllegalArgumentException("Positive finite MCP byte limit required"); + } + stream.setMaxOperationBytes(limit + 1); + stream.start(); + maxMessageBytes = limit; + reader = Thread.ofVirtual().name("restlet-mcp-stdio-reader").start(() -> read(limit)); + } + + /** + * The message limit, once opened. + * + * @return The largest message, in bytes, or zero before {@link #open(int)}. + */ + public synchronized int maxMessageBytes() { + return maxMessageBytes; + } + + /** + * Attaches the sink of the frames, then delivers it those queued, or the end of the stream. + * + * @param next The sink. + * @throws IllegalStateException If another sink is attached. + */ + public void attach(Sink next) { + Objects.requireNonNull(next, "sink"); + delivery.lock(); + try { + List backlog; + IOException end; + synchronized (this) { + if (sink != null) { + throw new IllegalStateException("MCP STDIO channel is already in use"); + } + sink = next; + backlog = new ArrayList<>(queued); + queued.clear(); + end = ended; + } + for (byte[] frame : backlog) { + next.receive(frame); + } + if (end != null) { + next.end(end); + } + } finally { + delivery.unlock(); + } + } + + /** + * Detaches a sink, if attached: the responses to its unanswered requests will be dropped. It + * doesn't wait for a write in progress, which a peer that stops reading may block until the + * stream stops: that request's id is already pending, so its response is dropped too. + * + * @param current The sink. + */ + public synchronized void detach(Sink current) { + if (sink != current) { + return; + } + sink = null; + for (Object id : pending) { + remember(abandoned, id); + } + pending.clear(); + } + + /** + * Writes a frame for the attached sink, remembering the id of a request until it is answered. + * + * @param owner The sink writing. + * @param bytes The message, without newline. + * @throws IOException If the sink is not attached, the message too large, or the write fails. + */ + public void write(Sink owner, byte[] bytes) throws IOException { + synchronized (writing) { + Object id = null; + synchronized (this) { + if (closed || sink != owner) { + throw new IOException("MCP STDIO channel is not attached"); + } + if (ended != null) { + throw new IOException("MCP STDIO stream ended", ended); + } + Map message = parse(bytes); + if (message != null && message.get("method") instanceof String method) { + if (message.get("id") != null) { + id = McpMessages.idKey(message.get("id")); + abandoned.remove(id); // Its id reused: the next response is for it. + remember(pending, id); + } else if ("notifications/cancelled".equals(method) + && message.get("params") instanceof Map params + && params.get("requestId") != null) { + // Its sink no longer awaits a response, which may never come. + Object cancelled = McpMessages.idKey(params.get("requestId")); + if (pending.remove(cancelled)) { + remember(abandoned, cancelled); + } + } + } + } + try { + writeFrame(bytes); + } catch (IOException | RuntimeException e) { + if (id != null) { + synchronized (this) { + pending.remove(id); + } + } + throw e; + } + } + } + + /** + * Writes a frame on the writer thread, waiting for it even if interrupted: the calling thread, + * such as a scheduler's that an SDK transport disposes of, may be interrupted, which would + * close an interruptible stream, such as a pipe, for the clients to come. + */ + private void writeFrame(byte[] bytes) throws IOException { + Future written; + try { + written = + writer.submit( + () -> { + McpMessages.writeFrame(stream, bytes); + return null; + }); + } catch (RejectedExecutionException e) { + throw new IOException("MCP STDIO channel is closed", e); + } + boolean interrupted = false; + try { + while (true) { + try { + written.get(); + return; + } catch (InterruptedException e) { + interrupted = true; + } catch (ExecutionException e) { + if (e.getCause() instanceof IOException io) { + throw io; + } + if (e.getCause() instanceof RuntimeException runtime) { + throw runtime; + } + throw new IOException(e.getCause()); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** Adds to a bounded set of ids, forgetting the oldest beyond {@link #MAX_IDS}. */ + private static void remember(SequencedSet ids, Object id) { + ids.add(id); + if (ids.size() > MAX_IDS) { + ids.removeFirst(); + } + } + + private Map parse(byte[] bytes) { + try { + return mapper.readValue(McpMessages.utf8(bytes), MAP); + } catch (IOException | RuntimeException e) { + return null; // Not a JSON object: the sink tells what it makes of it. + } + } + + private void read(int limit) { + IOException end; + try { + byte[] frame; + while ((frame = McpMessages.readFrame(stream, limit)) != null) { + dispatch(frame); + } + end = new EOFException("MCP subprocess or pipe ended"); + } catch (IOException e) { + end = e; + } catch (RuntimeException e) { + end = new IOException(e); + } + if (closed) { + return; + } + delivery.lock(); + try { + Sink current; + synchronized (this) { + ended = end; + current = sink; + } + if (current != null) { + current.end(end); + } + } finally { + delivery.unlock(); + } + } + + /** Delivers a frame to the attached sink, queues it, or drops an abandoned response. */ + private void dispatch(byte[] frame) { + delivery.lock(); + try { + Sink current; + synchronized (this) { + if (!pending.isEmpty() || !abandoned.isEmpty()) { + Map message = parse(frame); + if (message != null + && !message.containsKey("method") + && message.get("id") != null) { + Object id = McpMessages.idKey(message.get("id")); + if (!pending.remove(id) && abandoned.remove(id)) { + LOGGER.log( + Level.FINE, + "Dropped the late MCP STDIO response to abandoned request {0}", + id); + return; + } + } + } + current = sink; + if (current == null) { + if (queued.size() == MAX_QUEUED) { + LOGGER.warning("Dropped an MCP STDIO message no client was ready for"); + queued.removeFirst(); + } + queued.add(frame); + return; + } + } + current.receive(frame); + } finally { + delivery.unlock(); + } + } + + /** + * Stops the stream, and waits for the reader to end. + * + * @param timeout The time to wait for the reader. + * @throws IOException If the stream fails to stop, or the reader to end in time. + */ + public void close(Duration timeout) throws IOException { + Thread current; + synchronized (this) { + if (closed) { + return; + } + closed = true; + current = reader; + sink = null; + queued.clear(); + pending.clear(); + abandoned.clear(); + } + writer.shutdown(); + IOException error = null; + try { + stream.stop(); + } catch (IOException e) { + error = e; + } + try { + if (current != null && !current.join(timeout)) { + IOException join = new IOException("MCP STDIO reader shutdown timed out"); + if (error == null) { + error = join; + } else { + error.addSuppressed(join); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + IOException interrupted = new InterruptedIOException("Interrupted"); + if (error == null) { + error = interrupted; + } else { + error.addSuppressed(interrupted); + } + } + if (error != null) { + throw error; + } + } +} diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/McpLegacyClient.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/McpLegacyClient.java index 5970e750f9..d3a37d9b0f 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/McpLegacyClient.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/McpLegacyClient.java @@ -19,9 +19,6 @@ import java.time.Duration; import java.util.List; import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; -import org.restlet.ext.mcp.McpProtocol; import org.restlet.ext.mcp.internal.McpHttpStatusException; import org.restlet.ext.mcp.internal.McpLegacyEdge; import reactor.core.publisher.Mono; @@ -76,18 +73,12 @@ public static McpLegacyClient http(McpLegacyEdge.HttpOptions options) { /** * Starts a client over stdio. * - * @param transport The transport. - * @param owned Whether the client closes the transport, rather than its connector. + * @param transport The transport, offering the revisions accepted. * @param timeout The request timeout. * @return The started client. */ - public static McpLegacyClient stdio( - StdioMcpClientTransport transport, boolean owned, Duration timeout) { - return start( - owned ? transport : new Borrowed(transport), - null, - List.of(McpProtocol.VERSION), - timeout); + public static McpLegacyClient stdio(StdioMcpClientTransport transport, Duration timeout) { + return start(transport, null, transport.protocolVersions(), timeout); } /** Initializes the SDK client, closing the transport if that fails. */ @@ -218,42 +209,4 @@ private T modern(Object result, Class type) { public void close() { sdk.closeGracefully().block(timeout); } - - /** A connector's transport, which the client uses but doesn't close. */ - private record Borrowed(StdioMcpClientTransport delegate) implements McpClientTransport { - @Override - public Mono connect( - Function< - Mono, - Mono> - handler) { - return delegate.connect(handler); - } - - @Override - public void setExceptionHandler(Consumer handler) { - delegate.setExceptionHandler(handler); - } - - @Override - public List protocolVersions() { - return delegate.protocolVersions(); - } - - @Override - public Mono sendMessage( - io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage message) { - return delegate.sendMessage(message); - } - - @Override - public T unmarshalFrom(Object data, TypeRef type) { - return delegate.unmarshalFrom(data, type); - } - - @Override - public Mono closeGracefully() { - return Mono.empty(); - } - } } diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/StdioMcpClientTransport.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/StdioMcpClientTransport.java index 2fa9cf9cf0..7a8a34deb8 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/StdioMcpClientTransport.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/legacy/StdioMcpClientTransport.java @@ -13,7 +13,6 @@ import io.modelcontextprotocol.json.TypeRef; import io.modelcontextprotocol.spec.McpClientTransport; import io.modelcontextprotocol.spec.McpSchema; -import java.io.EOFException; import java.io.IOException; import java.time.Duration; import java.util.HashMap; @@ -27,24 +26,26 @@ import java.util.logging.Level; import java.util.logging.Logger; import org.restlet.ext.mcp.McpProtocol; -import org.restlet.ext.mcp.internal.McpLegacyEdge; import org.restlet.ext.mcp.internal.McpMessages; +import org.restlet.ext.mcp.internal.McpStdioChannel; import org.restlet.ext.mcp.internal.McpWorkers; import reactor.core.publisher.Mono; /** - * One reader per pipe, finite outstanding IDs for admission only; the SDK owns correlation. An ID - * left unanswered past the call timeout frees its slot, and its late reply is dropped. Requests the + * Reads its frames from a stdio channel, whose reader it shares with the client that probed the + * server before; finite outstanding IDs for admission only; the SDK owns correlation. An ID left + * unanswered past the call timeout frees its slot, and its late reply is dropped. Requests the * server sends, such as sampling, roots or elicitation, are answered as not found without reaching * the SDK client: the legacy edge declares no capability and answers none. */ -public final class StdioMcpClientTransport - implements McpClientTransport, McpLegacyEdge.StdioTransport { +public final class StdioMcpClientTransport implements McpClientTransport, McpStdioChannel.Sink { private final McpJsonMapper mapper = McpJsonDefaults.getMapper(); - private final org.restlet.util.StreamTransport stream; - private volatile int maxMessageBytes; - private volatile int maxPendingCalls; - private volatile Duration timeout; + private final McpStdioChannel channel; + private final boolean owned; + private final List versions; + private final int maxMessageBytes; + private final int maxPendingCalls; + private final Duration timeout; private volatile McpWorkers writers; private final Map outstanding = new HashMap<>(); private final Set expired = new HashSet<>(); @@ -56,23 +57,40 @@ public final class StdioMcpClientTransport .log(Level.WARNING, "MCP STDIO failure", error); private volatile Throwable failure; private volatile boolean closed; - private Thread reader; + /** Over a stream it owns, offering {@link McpProtocol#VERSION}. */ public StdioMcpClientTransport( org.restlet.util.StreamTransport stream, int maxMessageBytes, int maxPendingCalls, Duration timeout) { - this.stream = Objects.requireNonNull(stream, "stream"); - setLimits(maxMessageBytes, maxPendingCalls, timeout); + this( + new McpStdioChannel(stream), + true, + List.of(McpProtocol.VERSION), + maxMessageBytes, + maxPendingCalls, + timeout); } - /** Replaces the byte, call and timeout limits; only allowed before connecting. */ - @Override - public synchronized void setLimits(int maxMessageBytes, int maxPendingCalls, Duration timeout) { - if (closed || incoming != null) { - throw new IllegalStateException("MCP STDIO limits are fixed once connected"); - } + /** + * @param channel The channel. + * @param owned Whether closing the transport closes the channel, rather than detaching from it. + * @param versions The revisions offered, newest first. + * @param maxMessageBytes The largest message. + * @param maxPendingCalls The most requests awaiting a response. + * @param timeout The request timeout. + */ + public StdioMcpClientTransport( + McpStdioChannel channel, + boolean owned, + List versions, + int maxMessageBytes, + int maxPendingCalls, + Duration timeout) { + this.channel = Objects.requireNonNull(channel, "channel"); + this.owned = owned; + this.versions = List.copyOf(versions); if (maxMessageBytes <= 0 || maxMessageBytes == Integer.MAX_VALUE || maxPendingCalls <= 0 @@ -93,11 +111,10 @@ public synchronized Mono connect( return Mono.error(new IllegalStateException("MCP STDIO is single-use")); } try { - stream.setMaxOperationBytes(maxMessageBytes + 1); - stream.start(); + channel.open(maxMessageBytes); writers = new McpWorkers(maxPendingCalls, timeout); incoming = Objects.requireNonNull(handler, "handler"); - reader = Thread.ofVirtual().name("restlet-mcp-stdio-reader").start(this::read); + channel.attach(this); return Mono.empty(); } catch (IOException | RuntimeException e) { return Mono.error(e); @@ -111,7 +128,7 @@ public void setExceptionHandler(Consumer handler) { @Override public List protocolVersions() { - return List.of(McpProtocol.VERSION); + return versions.reversed(); // The SDK takes the last one as the newest. } @Override @@ -130,8 +147,7 @@ public Mono sendMessage(McpSchema.JSONRPCMessage message) { admit(id); } try { - McpMessages.writeFrame( - stream, McpMessages.encode(mapper, message, maxMessageBytes)); + channel.write(this, McpMessages.encode(mapper, message, maxMessageBytes)); } catch (IOException | RuntimeException e) { if (id != null) { synchronized (outstanding) { @@ -180,27 +196,35 @@ private boolean correlate(McpSchema.JSONRPCResponse response) throws IOException throw new IOException("Unsolicited MCP STDIO response id"); } - private void read() { + /** Handles a frame of the channel, until the transport fails or closes. */ + @Override + public void receive(byte[] bytes) { + if (closed || failure != null) { + return; + } try { - byte[] bytes; - while (!closed && (bytes = McpMessages.readFrame(stream, maxMessageBytes)) != null) { - McpSchema.JSONRPCMessage message = - McpSchema.deserializeJsonRpcMessage(mapper, McpMessages.utf8(bytes)); - if (message instanceof McpSchema.JSONRPCRequest request) { - reject(request); - } else if (!(message instanceof McpSchema.JSONRPCResponse response) - || correlate(response)) { - incoming.apply(Mono.just(message)).block(timeout); - } - } - if (!closed) { - throw new EOFException("MCP subprocess or pipe ended"); + McpSchema.JSONRPCMessage message = + McpSchema.deserializeJsonRpcMessage(mapper, McpMessages.utf8(bytes)); + if (message instanceof McpSchema.JSONRPCRequest request) { + reject(request); + } else if (!(message instanceof McpSchema.JSONRPCResponse response) + || correlate(response)) { + incoming.apply(Mono.just(message)).block(timeout); } } catch (IOException | RuntimeException e) { - if (!closed) { - failure = e; - exceptionHandler.accept(e); - } + fail(e); + } + } + + @Override + public void end(IOException cause) { + fail(cause); + } + + private void fail(Exception cause) { + if (!closed && failure == null) { + failure = cause; + exceptionHandler.accept(cause); } } @@ -222,11 +246,6 @@ private void reject(McpSchema.JSONRPCRequest request) { .log(Level.FINE, "MCP server request not answered", error)); } - @Override - public void close(Duration timeout) { - closeGracefully().block(timeout); - } - @Override public T unmarshalFrom(Object data, TypeRef type) { return mapper.convertValue(data, type); @@ -239,7 +258,11 @@ public Mono closeGracefully() { closed = true; IOException error = null; try { - stream.stop(); + if (owned) { + channel.close(timeout); + } else { + channel.detach(this); + } } catch (IOException e) { error = e; } @@ -254,15 +277,6 @@ public Mono closeGracefully() { error.addSuppressed(e); } } - if (reader != null && !reader.join(timeout)) { - IOException join = - new IOException("MCP STDIO reader shutdown timed out"); - if (error == null) { - error = join; - } else { - error.addSuppressed(join); - } - } synchronized (outstanding) { outstanding.clear(); expired.clear(); diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernClientTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernClientTestCase.java index 6fd85ad011..3329bdf933 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernClientTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernClientTestCase.java @@ -352,7 +352,10 @@ void anErrorResponseFails() throws Exception { assertEquals(McpSchema.ErrorCodes.INVALID_PARAMS, error.error().code().intValue()); } - /** The modern client is reached through getModernClient() only, over HTTP for now. */ + /** + * The modern client is reached through getModernClient() only; over stdio, it needs a stdio + * connector. + */ @Test void modernModeLimits() throws Exception { start("HTTP2", null); @@ -363,7 +366,7 @@ void modernModeLimits() throws Exception { McpClientAdapter stdio = new McpClientAdapter(connector, "stdio://localhost/mcp"); stdio.setProtocolVersion(McpProtocol.MODERN_VERSION); - assertThrows(UnsupportedOperationException.class, stdio::start); + assertThrows(IllegalStateException.class, stdio::start); McpClientAdapter unknown = new McpClientAdapter(connector, "http://localhost/mcp"); assertThrows( IllegalArgumentException.class, () -> unknown.setProtocolVersion("2024-11-05")); diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpStdioAutoTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpStdioAutoTestCase.java new file mode 100644 index 0000000000..aefabc00a7 --- /dev/null +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpStdioAutoTestCase.java @@ -0,0 +1,684 @@ +/** + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.modelcontextprotocol.json.McpJsonDefaults; +import io.modelcontextprotocol.json.McpJsonMapper; +import io.modelcontextprotocol.json.TypeRef; +import io.modelcontextprotocol.modern.McpSchema; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.channels.Channels; +import java.nio.channels.Pipe; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.restlet.Client; +import org.restlet.Context; +import org.restlet.Server; +import org.restlet.data.Protocol; +import org.restlet.engine.Engine; +import org.restlet.ext.mcp.internal.McpStdioChannel; +import org.restlet.util.StreamTransport; + +/** + * {@link McpProtocol#AUTO} over stdio: the client probes with {@code server/discover} on the stream + * it then keeps, selecting the modern client for a {@code 2026-07-28} server and falling back to a + * legacy {@code initialize} for a legacy one, which answers the probe with an error or not at all. + */ +class McpStdioAutoTestCase { + private static final McpJsonMapper MAPPER = McpJsonDefaults.getMapper(); + private static final TypeRef> MAP = new TypeRef<>() {}; + + private final List cleanup = new ArrayList<>(); + + @AfterEach + void stop() throws Exception { + Exception failure = null; + for (AutoCloseable closeable : cleanup.reversed()) { + try { + closeable.close(); + } catch (Exception e) { + if (failure == null) { + failure = e; + } + } + } + if (failure != null) { + throw failure; + } + } + + /** A stream over two pipes, from one and to the other. */ + private static StreamTransport stream(Pipe in, Pipe out) { + return new StreamTransport( + Channels.newInputStream(in.source()), + Channels.newOutputStream(out.sink()), + () -> { + try { + in.source().close(); + out.sink().close(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + } + + /** A Restlet server on stdio, serving both eras, and the client's end of its stream. */ + private StreamTransport restletServer() throws Exception { + Pipe requests = Pipe.open(); + Pipe responses = Pipe.open(); + McpServerAdapter adapter = new McpServerAdapter(); + McpServerAdapterTestCase.addEcho(adapter); + adapter.start(); + cleanup.add(adapter::stop); + StdioServerHelper prototype = new StdioServerHelper(null); + Engine.getInstance().getRegisteredServers().add(prototype); + cleanup.add(() -> Engine.getInstance().getRegisteredServers().remove(prototype)); + Context context = new Context(); + context.getAttributes() + .put(McpProtocol.STREAM_TRANSPORT_ATTRIBUTE, stream(requests, responses)); + Server server = + new Server( + context, + List.of(Protocol.STDIO), + null, + -1, + adapter, + StdioServerHelper.class.getCanonicalName()); + server.start(); + cleanup.add(server::stop); + return stream(responses, requests); + } + + private McpClientAdapter client(StreamTransport stream, String version, Duration timeout) { + McpClientAdapter client = new McpClientAdapter(stream); + client.setProtocolVersion(version); + client.setRequestTimeout(timeout); + cleanup.add(client::stop); + return client; + } + + private static String text(McpSchema.CallToolResult result) { + return ((McpSchema.TextContent) result.content().getFirst()).text(); + } + + /** A dual-era Restlet server, on a stdio connector, gets the modern client. */ + @Test + void aDualEraServerGetsTheModernClient() throws Exception { + StreamTransport stream = restletServer(); + StdioClientHelper prototype = new StdioClientHelper(null); + Engine.getInstance().getRegisteredClients().add(prototype); + cleanup.add(() -> Engine.getInstance().getRegisteredClients().remove(prototype)); + Context context = new Context(); + context.getAttributes().put(McpProtocol.STREAM_TRANSPORT_ATTRIBUTE, stream); + Client connector = + new Client( + context, + List.of(Protocol.STDIO), + StdioClientHelper.class.getCanonicalName()); + connector.start(); + cleanup.add(connector::stop); + McpClientAdapter client = new McpClientAdapter(connector, "stdio://localhost/mcp"); + client.setProtocolVersion(McpProtocol.AUTO); + cleanup.add(client::stop); + + client.start(); + + assertEquals(McpProtocol.MODERN_VERSION, client.getNegotiatedVersion()); + assertEquals("echo:auto", text(client.callTool("echo", Map.of("text", "auto")))); + assertEquals(1, client.listTools(null).tools().size()); + client.stop(); + assertTrue(connector.isStarted()); + } + + /** + * Explicit {@code 2026-07-28} over the client's own stream discovers and calls; the Tasks + * client is HTTP only. + */ + @Test + void theModernClientSpeaksOverItsOwnStream() throws Exception { + McpClientAdapter client = + client(restletServer(), McpProtocol.MODERN_VERSION, Duration.ofSeconds(30)); + + client.start(); + + assertEquals(McpProtocol.MODERN_VERSION, client.getNegotiatedVersion()); + assertEquals( + "echo:modern", + text( + client.getModernClient() + .tool("echo") + .arguments(Map.of("text", "modern")) + .call() + .block(Duration.ofSeconds(30)))); + assertEquals("echo:again", text(client.callTool("echo", Map.of("text", "again")))); + assertThrows(UnsupportedOperationException.class, client::getTasksClient); + client.stop(); + assertFalse(client.isStarted()); + } + + /** + * A legacy server answering the probe with method not found gets an {@code initialize} offering + * the legacy revisions, and after the probe, nothing 2026-07-28 introduced or removed. + */ + @Test + void aLegacyServerRejectingTheProbeGetsTheLegacyClient() throws Exception { + FakeServer fake = + new FakeServer( + (message, server) -> { + if ("server/discover".equals(message.get("method"))) { + server.error(message.get("id"), -32601, "Method not found"); + } else { + server.legacy(message); + } + }); + McpClientAdapter client = + client(fake.clientStream(), McpProtocol.AUTO, Duration.ofSeconds(30)); + + client.start(); + + assertEquals("2025-06-18", client.getNegotiatedVersion()); + assertEquals("echo:legacy", text(client.callTool("echo", Map.of("text", "legacy")))); + List> received = List.copyOf(fake.received); + assertEquals("server/discover", received.getFirst().get("method")); + List> after = received.subList(1, received.size()); + assertEquals( + List.of("initialize", "notifications/initialized", "tools/call"), + after.stream().map(message -> message.get("method")).toList()); + Map initialize = (Map) after.getFirst().get("params"); + assertEquals(McpProtocol.VERSION, initialize.get("protocolVersion")); + assertEquals(Map.of(), initialize.get("capabilities")); + for (Map message : after) { + assertFalse( + MAPPER.writeValueAsString(message).contains(McpProtocol.MODERN_VERSION), + () -> "2026-07-28 sent to a legacy server: " + message); + } + } + + /** + * A legacy server ignoring the probe gets the legacy client once the probe times out, and the + * late answer it then sends to the probe is dropped without ending the session. + */ + @Test + void aLegacyServerIgnoringTheProbeGetsTheLegacyClient() throws Exception { + List probes = new CopyOnWriteArrayList<>(); + FakeServer fake = + new FakeServer( + (message, server) -> { + if ("server/discover".equals(message.get("method"))) { + probes.add(message.get("id")); + } else { + if ("initialize".equals(message.get("method"))) { + for (Object id : probes) { + server.send( + Map.of( + "jsonrpc", + "2.0", + "id", + id, + "result", + Map.of( + "supportedVersions", + List.of("2026-07-28")))); + } + } + server.legacy(message); + } + }); + McpClientAdapter client = + client(fake.clientStream(), McpProtocol.AUTO, Duration.ofSeconds(2)); + + client.start(); + + assertEquals(1, probes.size()); + assertEquals("2025-06-18", client.getNegotiatedVersion()); + assertEquals("echo:late", text(client.callTool("echo", Map.of("text", "late")))); + assertEquals("echo:still", text(client.callTool("echo", Map.of("text", "still")))); + assertEquals( + 1, + fake.received.stream() + .filter(message -> "server/discover".equals(message.get("method"))) + .count()); + } + + /** A server offering only revisions this client doesn't speak fails the start. */ + @Test + void noSharedRevisionFailsTheStart() throws Exception { + FakeServer fake = + new FakeServer( + (message, server) -> { + if ("server/discover".equals(message.get("method"))) { + server.send( + Map.of( + "jsonrpc", + "2.0", + "id", + message.get("id"), + "error", + Map.of( + "code", + McpProtocol.UNSUPPORTED_PROTOCOL_VERSION, + "message", + "Unsupported protocol version", + "data", + Map.of( + "supported", + List.of("2099-01-01"))))); + } else { + server.legacy(message); + } + }); + McpClientAdapter client = + client(fake.clientStream(), McpProtocol.AUTO, Duration.ofSeconds(30)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, client::start); + + assertTrue(failure.getMessage().contains("No MCP revision supported"), failure::getMessage); + assertFalse(client.isStarted()); + assertTrue( + fake.received.stream().noneMatch(m -> "initialize".equals(m.get("method"))), + "No initialize after a no-shared-revision error"); + } + + /** + * A server answering {@code -32022} with a legacy revision among those it supports gets the + * legacy client. + */ + @Test + void anUnsupportedVersionOfferingALegacyRevisionGetsTheLegacyClient() throws Exception { + FakeServer fake = + new FakeServer( + (message, server) -> { + if ("server/discover".equals(message.get("method"))) { + server.send( + Map.of( + "jsonrpc", + "2.0", + "id", + message.get("id"), + "error", + Map.of( + "code", + McpProtocol.UNSUPPORTED_PROTOCOL_VERSION, + "message", + "Unsupported protocol version", + "data", + Map.of( + "supported", + List.of("2025-06-18"))))); + } else { + server.legacy(message); + } + }); + McpClientAdapter client = + client(fake.clientStream(), McpProtocol.AUTO, Duration.ofSeconds(30)); + + client.start(); + + assertEquals("2025-06-18", client.getNegotiatedVersion()); + assertEquals(1, client.listTools(null).tools().size()); + } + + /** + * The channel queues what it reads while no sink is attached, drops the late response to a + * request its sink left unanswered, and tells the next sink that the stream ended. + */ + @Test + void theChannelQueuesFramesAndDropsAbandonedResponses() throws Exception { + Pipe requests = Pipe.open(); + Pipe responses = Pipe.open(); + McpStdioChannel channel = new McpStdioChannel(stream(responses, requests)); + cleanup.add(() -> channel.close(Duration.ofSeconds(5))); + OutputStream peer = Channels.newOutputStream(responses.sink()); + channel.open(1024); + channel.open(1024); + assertEquals(1024, channel.maxMessageBytes()); + assertThrows(IllegalStateException.class, () -> channel.open(2048)); + + BlockingQueue first = new LinkedBlockingQueue<>(); + McpStdioChannel.Sink probe = sink(first, new LinkedBlockingQueue<>()); + channel.attach(probe); + assertThrows(IllegalStateException.class, () -> channel.attach(probe)); + channel.write( + probe, + "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"server/discover\"}" + .getBytes(StandardCharsets.UTF_8)); + channel.write( + probe, + "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"ping\"}" + .getBytes(StandardCharsets.UTF_8)); + channel.write( + probe, + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":8}}" + .getBytes(StandardCharsets.UTF_8)); + channel.detach(probe); + assertThrows( + IOException.class, + () -> channel.write(probe, "{}".getBytes(StandardCharsets.UTF_8))); + + peer.write( + ("{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":{}}\n" + + "{\"jsonrpc\":\"2.0\",\"id\":8,\"result\":{}}\n" + + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\n") + .getBytes(StandardCharsets.UTF_8)); + peer.flush(); + peer.close(); + TimeUnit.MILLISECONDS.sleep(200); + + BlockingQueue second = new LinkedBlockingQueue<>(); + BlockingQueue ends = new LinkedBlockingQueue<>(); + channel.attach(sink(second, ends)); + assertEquals( + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}", + second.poll(5, TimeUnit.SECONDS)); + assertTrue(ends.poll(5, TimeUnit.SECONDS) instanceof java.io.EOFException); + assertTrue(second.isEmpty()); + assertTrue(first.isEmpty()); + } + + /** + * A server that stops reading its input doesn't keep the client from stopping, nor makes it + * fail: a write stuck on the full pipe doesn't hold the detach, and stopping the stream first + * ends it. + */ + @Test + void aServerThatStopsReadingDoesNotHoldTheStop() throws Exception { + java.util.concurrent.CountDownLatch stalled = new java.util.concurrent.CountDownLatch(1); + FakeServer fake = + new FakeServer( + (message, server) -> { + if ("server/discover".equals(message.get("method"))) { + server.error(message.get("id"), -32601, "Method not found"); + } else if ("notifications/initialized".equals(message.get("method"))) { + try { + stalled.await(); // Reads nothing more. + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + server.legacy(message); + } + }); + cleanup.add(stalled::countDown); + McpClientAdapter client = new McpClientAdapter(fake.clientStream()); + client.setProtocolVersion(McpProtocol.AUTO); + client.setRequestTimeout(Duration.ofSeconds(2)); + client.setMaxMessageBytes(32 * 1024 * 1024); + client.start(); + assertEquals("2025-06-18", client.getNegotiatedVersion()); + + // Larger than the pipe holds: the write waits for a reader that never comes. + String large = "x".repeat(16 * 1024 * 1024); + Thread call = + Thread.ofVirtual() + .start( + () -> { + try { + client.callTool("echo", Map.of("text", large)); + } catch (RuntimeException _) { + // Timed out, or ended by the stop. + } + }); + TimeUnit.MILLISECONDS.sleep(500); + + // The stream stops first, which ends the write: the client then closes without error. + org.junit.jupiter.api.Assertions.assertTimeoutPreemptively( + Duration.ofSeconds(20), client::stop); + assertFalse(client.isStarted()); + assertTrue(call.join(Duration.ofSeconds(10)), "the stuck call did not end"); + } + + /** + * A modern subscriber slow to take its messages doesn't hold the stop: the client is closed + * before the stream, which frees the reader waiting for that subscriber. + */ + @Test + void aSlowModernSubscriberDoesNotHoldTheStop() throws Exception { + java.util.concurrent.CountDownLatch first = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.CountDownLatch released = new java.util.concurrent.CountDownLatch(1); + FakeServer fake = + new FakeServer( + (message, server) -> { + Object id = message.get("id"); + switch (String.valueOf(message.get("method"))) { + case "server/discover" -> + server.send( + Map.of( + "jsonrpc", + "2.0", + "id", + id, + "result", + Map.of( + "supportedVersions", + List.of(McpProtocol.MODERN_VERSION), + "capabilities", + Map.of("tools", Map.of()), + "serverInfo", + Map.of( + "name", "modern", "version", + "1")))); + case "tools/list" -> + server.send( + Map.of( + "jsonrpc", + "2.0", + "id", + id, + "result", + Map.of( + "tools", + List.of( + Map.of( + "name", + "slow", + "inputSchema", + Map.of( + "type", + "object")))))); + case "tools/call" -> { + Object token = + ((Map) + ((Map) message.get("params")) + .get("_meta")) + .get("progressToken"); + // More than the channel queues (64): its reader then waits. + for (int i = 0; i < 256; i++) { + server.send( + Map.of( + "jsonrpc", + "2.0", + "method", + "notifications/progress", + "params", + Map.of( + "progressToken", + token, + "progress", + i))); + } + } + default -> {} + } + }); + cleanup.add(released::countDown); + McpClientAdapter client = + client(fake.clientStream(), McpProtocol.MODERN_VERSION, Duration.ofSeconds(30)); + client.start(); + client.getModernClient() + .tool("slow") + .arguments(Map.of()) + .progress( + progress -> { + first.countDown(); + try { + released.await(); // Takes nothing more. + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return reactor.core.publisher.Mono.empty(); + }) + .call() + .subscribe(null, error -> {}); + assertTrue(first.await(10, TimeUnit.SECONDS), "no progress arrived"); + TimeUnit.MILLISECONDS.sleep(500); + + // Well within the request timeout, which a reader left waiting would take. + org.junit.jupiter.api.Assertions.assertTimeoutPreemptively( + Duration.ofSeconds(10), client::stop); + assertFalse(client.isStarted()); + } + + private static McpStdioChannel.Sink sink( + BlockingQueue frames, BlockingQueue ends) { + return new McpStdioChannel.Sink() { + @Override + public void receive(byte[] frame) { + frames.add(new String(frame, StandardCharsets.UTF_8)); + } + + @Override + public void end(IOException failure) { + ends.add(failure); + } + }; + } + + /** A scripted server at the other end of a pair of pipes, one JSON-RPC message per line. */ + private final class FakeServer { + private final List> received = new CopyOnWriteArrayList<>(); + private final OutputStream out; + private final StreamTransport clientStream; + + FakeServer(BiConsumer, FakeServer> script) throws IOException { + Pipe requests = Pipe.open(); + Pipe responses = Pipe.open(); + clientStream = stream(responses, requests); + out = Channels.newOutputStream(responses.sink()); + BufferedReader in = + new BufferedReader( + new InputStreamReader( + Channels.newInputStream(requests.source()), + StandardCharsets.UTF_8)); + Thread reader = + Thread.ofVirtual() + .start( + () -> { + try { + for (String line = in.readLine(); + line != null; + line = in.readLine()) { + Map message = + MAPPER.readValue(line, MAP); + received.add(message); + script.accept(message, this); + } + } catch (IOException | RuntimeException _) { + // The client closed its end. + } + }); + cleanup.add( + () -> { + requests.source().close(); + responses.sink().close(); + reader.join(Duration.ofSeconds(5)); + }); + } + + StreamTransport clientStream() { + return clientStream; + } + + synchronized void send(Map message) { + try { + out.write( + (MAPPER.writeValueAsString(message) + "\n") + .getBytes(StandardCharsets.UTF_8)); + out.flush(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + void error(Object id, int code, String text) { + send( + Map.of( + "jsonrpc", + "2.0", + "id", + id, + "error", + Map.of("code", code, "message", text))); + } + + private void result(Object id, Map result) { + send(Map.of("jsonrpc", "2.0", "id", id, "result", result)); + } + + /** Answers as a legacy server negotiating 2025-06-18, with an echo tool. */ + void legacy(Map message) { + Object id = message.get("id"); + Object method = message.get("method"); + if (id == null || method == null) { + return; // A notification, or a response. + } + Map params = message.get("params") instanceof Map map ? map : Map.of(); + switch (String.valueOf(method)) { + case "initialize" -> + result( + id, + Map.of( + "protocolVersion", + "2025-06-18", + "capabilities", + Map.of("tools", Map.of()), + "serverInfo", + Map.of("name", "legacy", "version", "1"))); + case "tools/list" -> + result( + id, + Map.of( + "tools", + List.of( + Map.of( + "name", + "echo", + "inputSchema", + Map.of("type", "object"))))); + case "tools/call" -> { + Map arguments = (Map) params.get("arguments"); + Map content = new LinkedHashMap<>(); + content.put("type", "text"); + content.put("text", "echo:" + arguments.get("text")); + result(id, Map.of("content", List.of(content))); + } + default -> error(id, -32601, "Method not found"); + } + } + } +}