Skip to content

MCP: AUTO mode over STDIO, probing with server/discover (#1670) - #1729

Merged
jlouvel merged 4 commits into
feature/mcp-sdk-modern-clientfrom
feature/1670-mcp-stdio-auto
Nov 28, 2026
Merged

jlouvel merged 4 commits into
feature/mcp-sdk-modern-clientfrom
feature/1670-mcp-stdio-auto

Conversation

@jlouvel

@jlouvel jlouvel commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

Last open part of #1670 (item 2 over stdio): McpClientAdapter in auto mode now probes stdio servers with server/discover instead of always falling back to legacy, and the 2026-07-28 client works over stdio.

Stacked on #1728 (base feature/mcp-sdk-modern-client). Retarget to 3.0 once #1728 merges.

What it does

  • AUTO over stdio (own StreamTransport or a stdio: connector): sends server/discover through the SDK's modern client within requestTimeout.
    • A DiscoverResult naming 2026-07-28 → modern client.
    • A recognized modern error (header mismatch, missing client capability) → modern, and the failure is thrown, as over HTTP.
    • -32022 → legacy only if data.supported offers a legacy revision, else "No MCP revision supported by both..." (reuses isLegacy / offersLegacy).
    • Any other JSON-RPC error, or a timeout (stdio only: a legacy server may just ignore the request) → the modern side detaches, and the legacy initialize runs on the same stream, offering McpProtocol.LEGACY_VERSIONS as HTTP auto does.
    • A late answer to the abandoned probe is dropped, so it can't reach the legacy client, which would otherwise end the session on an unsolicited id.
  • Explicit MODERN_VERSION over stdio now works (it threw UnsupportedOperationException before). It discovers first, as startModern does over HTTP.
  • No era cache for stdio. McpEras stays per HTTP origin. A stdio process or connector serves one client, so each start probes once. The class javadoc says so.
  • getTasksClient() over stdio throws UnsupportedOperationException ("HTTP only for now"). Adapting it isn't trivial: McpTasksClient calls McpModernHttpTransport.send directly and numbers its own request ids from 1, which would collide with the SDK client's ids on a shared stdio stream (the SDK transport rejects duplicate ids).

Design

  • internal/McpStdioChannel (new): one per StreamTransport. It owns the single reader (a virtual thread) and the serialized frame writes, and applies maxMessageBytes (setMaxOperationBytes(max+1), starting the stream once; later opens must use the same limit). Frames go to the attached sink, in order. Frames read while no sink is attached are queued (at most 64, oldest dropped) and delivered on attach. It records the ids of requests a sink wrote and left unanswered when it detached, and of requests it cancelled (notifications/cancelled), and drops later responses with those ids (at most 1024 remembered). EOF and read errors go to the attached sink, or to the next one.
    • Writes run on the channel's own writer thread, and the caller waits for them even if interrupted. Reason: the SDK's stdio transport writes from a Reactor scheduler thread that it interrupts when it closes, and an interrupted write closes an interruptible stream such as a Pipe for the client that comes next. Under load this broke the legacy fallback in the tests, so it is part of the design now.
  • Modern stdio transport (internal/McpModernStdioTransport): the SDK's StdioMcpClientTransport.builder(InputStream, OutputStream), with jsonMapper, inputMaxSize(maxMessageBytes) and shutdownTimeout, over stream views of the channel. Input is the attached frames, each followed by \n, and ends on detach or close. Output is split on \n into channel frames, within maxMessageBytes. I kept the SDK transport rather than writing our own McpClientTransport: it already routes responses, progress and subscriptions/listen notifications by id or token, and sends notifications/cancelled. Closing it closes its output, which detaches from the channel. The wrapper adds the maxConcurrentCalls limit on calls (listen streams excepted), as HTTP has.
  • Legacy StdioMcpClientTransport is now a channel sink and no longer runs its own read loop. Its correlation, expiry, reject-server-requests logic and limits are unchanged. It takes the versions to offer (non-auto: VERSION only, as before), and owned decides whether closing it closes the channel or only detaches. The public constructor over a StreamTransport used by McpStdioTestCase is kept. McpLegacyEdge.StdioTransport and the Borrowed wrapper are gone (all internal).
  • StdioClientHelper keeps one channel per connector instead of a legacy transport, so one adapter can probe and then bind either era on it. Stopping the helper still ends the stream. The non-auto bind keeps its behavior, including "limits fixed once connected".
  • McpClientAdapter closes its own stream's channel on stop(), or when start() fails, as the owned legacy transport did before.

Tests

New McpStdioAutoTestCase (pipes):

  • (a) AUTO through a stdio: connector against a Restlet StdioServerHelper + McpServerAdapter → modern, tool call and listing work, connector stays started after stop().
  • (b) a legacy-only fake answering server/discover with -32601 → legacy, negotiated 2025-06-18, tool call works.
  • (c) a fake that ignores server/discover (2 s request timeout) → legacy, and its late answer to the probe, sent just before it answers initialize, is dropped without breaking the session.
  • (d) -32022 offering only 2099-01-01 → fails with no shared revision, no initialize sent. Also -32022 offering 2025-06-18 → legacy.
  • (e) explicit MODERN over the adapter's own stream: discover, calls through getModernClient() and callTool, getTasksClient() → UnsupportedOperationException.
  • (f) on the wire, in (b): after the probe come only initialize (offering 2025-11-25, empty capabilities), notifications/initialized and tools/call. No second server/discover, and no message mentions 2026-07-28.
  • A channel test: queueing before attach, abandoned and cancelled ids dropped, EOF told to the next sink, limit fixed once opened.

McpModernClientTestCase.modernModeLimits changes: a MODERN stdio: target on an HTTP connector now fails with IllegalStateException (no stdio helper), not UnsupportedOperationException. Existing stdio tests (McpStdioTestCase, McpModernStdioTestCase) are unchanged and pass.

./mvnw -B verify -P default,test -pl org.restlet.ext.mcp: 213 tests, 0 failures, BUILD SUCCESS (Spotless, JaCoCo coverage checks met, SpotBugs 0). A first full run failed only on the modernModeLimits expectation above, before I updated it; no flakes seen.

Out of scope

  • The Tasks extension client over stdio (see above).
  • Server-initiated requests over stdio: legacy still answers them "method not found". The SDK's modern stdio transport ignores them, as 2026-07-28 servers send none.
  • Making auto the default (the issue's open question).

Issue #1670 must be closed by hand once this reaches 3.0, which isn't the default branch.

🤖 Generated with Claude Code

@jlouvel jlouvel left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1.

I reviewed only this PR's diff on top of feature/mcp-sdk-modern-client. The probe classification over stdio matches the 2026-07-28 Versioning and Compatibility rules and the HTTP path: a DiscoverResult naming 2026-07-28 or a recognized modern error means modern, -32022 reuses offersLegacy, and any other JSON-RPC error or a timeout (stdio only) means legacy. Transport failures such as EOF are not treated as legacy. The legacy refactor keeps the version order (versions.reversed(), as RestletMcpClientTransport does), and non-auto stdio still offers VERSION only. The tests are strong where it counts. The ignored-probe test would fail if the late answer reached the legacy transport, because correlate throws on an unsolicited id. The -32601 test proves LEGACY_VERSIONS is offered, since a VERSION-only offer would reject 2025-06-18.

Two findings, both about the stream's lifecycle:

  1. Medium: detach waits on the write lock, so closing a client over a server that has stopped reading stdin hangs before the stream is ever stopped. This is a regression for the plain legacy stdio client over the adapter's own stream.
  2. Low: stop() closes the adapter's own channel only if the client closed without throwing.

Review assisted by Claude Code.

@jlouvel
jlouvel force-pushed the feature/1670-mcp-stdio-auto branch from 113d5e6 to 181b19b Compare November 28, 2026 06:15

@jlouvel jlouvel left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2.

Both round-1 points hold in 181b19b:

  1. McpStdioChannel.detach takes only the channel's own monitor now, so a write stuck on a peer that stopped reading no longer holds it. aServerThatStopsReadingDoesNotHoldTheStop pins this: without the fix, stop() never gets past detach.
  2. McpClientAdapter.stop() closes the adapter's own channel in a finally. The same test pins this too: the legacy close throws there, so without the finally the stuck call would never end and call.join would fail.

The fix adds no new race that I can find. A write that races detach already has its id in pending, so its id moves to abandoned. If that write then fails, its id stays in abandoned, which is bounded and cleared when the id is reused, so nothing is misrouted. The next sink's writes wait on writing, so frames never interleave. On the modern side, sdk.close() closes FrameOutput without its monitor, so it doesn't block behind the SDK's stuck writer either.

I also checked what round 1 may have missed:

  • McpModernStdioTransport: the stream views give one frame per line, end on close or on the channel's end, and keep a read failure distinct from EOF. The SDK writes each line in one write, so the output limit can't send a truncated frame.
  • Consistency with the current base: the SDK's stdio transport already fails open exchanges with McpResponseLostException and applies the round timeout itself, so the stdio side matches the HTTP transport, which has no exchange timeout of its own.
  • Probe classification over stdio matches the HTTP path, plus the timeout case.
  • StdioClientHelper ownership and the docs in changes.md look right.

One Low inline, about how stop() behaves in the case the fix targets.

Review assisted by Claude Code.

@jlouvel jlouvel left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3.

The round-2 point holds in b9168e1. stop() stops the adapter's own stream first, so a write stuck on a full pipe fails at once and writers.close() ends in time. A failure from the channel or from either client is kept, the first one thrown with the later ones suppressed. aServerThatStopsReadingDoesNotHoldTheStop now calls client::stop directly, so it fails if stop() throws.

I checked the new order for regressions:

  • Legacy client after the stream has stopped: closeGracefully -> detach does nothing on a closed channel (no sink attached), and the writers end once the write fails. Over the adapter's own stream this is the order the owned transport used before this PR.
  • Modern client after the stream has stopped: the SDK's StdioMcpClientTransport.close() fails open exchanges, disposes its writer, and closes FrameOutput, which closes Frames and wakes the SDK's reader in take(). It waits on nothing (no process to wait for), so it hits no error or delay.
  • HTTP path and stdio: connector: ownChannel is null there, so closeOwnChannel() does nothing and the order is the same as before.
  • stop() during or right after a failed start: start() already closed and cleared ownChannel, and startModern / probe close the candidate. stop() finds nothing left to close and doesn't throw.

One Low inline, about a case the new order handles worse than the previous commit did. A final pass over the rest of the diff found nothing new.

Review assisted by Claude Code.

@jlouvel jlouvel left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 4.

The round-3 point holds in b00dce5. stop() now closes the modern client first, then the adapter's own stream, then the legacy client. Every failure is kept: the first one is thrown and the later ones are added as suppressed. Closing the modern client calls frames.close(), which wakes a channel reader waiting in Frames.receive. So the stream's reader no longer runs out its join, and stop() no longer throws "MCP STDIO reader shutdown timed out".

The new order keeps the earlier fixes:

  • Round 1 (detach without the writing lock): unchanged. McpStdioChannel.detach takes only the channel's monitor.
  • Round 2 (own stream stopped before the legacy close): it still holds, since closeOwnChannel() runs before legacy.close(). With no modern client attached, the order is the same as in b9168e1, so aServerThatStopsReadingDoesNotHoldTheStop still covers it.
  • Modern close with the SDK's writer stuck on a full pipe: I checked SDK 2.2.0's StdioMcpClientTransport.close(). It fails the open exchanges, calls writer.dispose() (an interrupt, which writeFrame ignores, and no wait), closes out with closeQuietly, and disposes its schedulers. None of these wait. awaitExit runs only with a process, and there is none here. FrameOutput.close() isn't synchronized, so it doesn't wait behind the writer thread, which holds FrameOutput's monitor and writing. It calls Frames.close(), which takes only the monitor of Frames, which receive and take release in wait(), and then detach. So the modern close returns before the stream stops, and closeOwnChannel() then ends the stuck write. The writer thread then holds no lock that the rest of stop() needs.
  • The case of round 3: failOpenExchanges signals the error while the reader thread is inside next. The serialized sink queues that error and returns, and readerScheduler.dispose() interrupts the progress handler that is blocking. Nothing in the close waits on that subscriber.

The test is strong. The SDK runs the progress handler on its reader thread, inside concatMap through deliverProgress. So a blocked handler stops take(), and 256 notifications fill the 64-frame queue. On the previous order, the reader stays in wait() after the stream stops, and the 30 s join fails the 10 s bound. Under load, the test isn't flaky: the 500 ms sleep only affects whether it would catch a regression, not whether it passes on this commit. With this order, stop() waits on nothing slow. Cleanup ends the fake server's sender, which may be blocked on the full pipe, by closing responses.sink().

A final pass over the rest of the diff found nothing new. Round 4 is clean.

Review assisted by Claude Code.

@jlouvel
jlouvel added this pull request to stack #1750 November 28, 2026 16:19
jlouvel and others added 4 commits November 28, 2026 11:20
In auto mode, the MCP client now probes stdio servers with server/discover
within the request timeout, over its own stream or a stdio: connector, and
falls back to a legacy initialize offering the legacy revisions on the same
stream when the server rejects the probe or leaves it unanswered. A late
answer to the abandoned probe is dropped. The 2026-07-28 client, also when
asked for explicitly, speaks over stdio through the SDK's stdio transport;
the Tasks client stays HTTP only.

A new McpStdioChannel owns the stream's reader and serialized writes, and
hands frames to one sink at a time. The legacy stdio transport reads from
it instead of owning its own loop, and StdioClientHelper keeps one channel
per connector.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…m even if a client fails to close

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ber's reader may wait on

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jlouvel
jlouvel force-pushed the feature/1670-mcp-stdio-auto branch from b00dce5 to ebd074d Compare November 28, 2026 16:29
@jlouvel
jlouvel merged commit 8f1731d into 3.0 Nov 28, 2026
1 check passed
@jlouvel
jlouvel deleted the feature/1670-mcp-stdio-auto branch November 28, 2026 16:30
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant