From 66959e20921287662eb11f9353aa8308776b0e68 Mon Sep 17 00:00:00 2001 From: Jerome Louvel <374450+jlouvel@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:53:12 -0500 Subject: [PATCH 1/3] Give the request customizer of an MCP call its Reactor context (#1770) Co-Authored-By: Claude Sonnet 5.5 --- changes.md | 5 ++ .../org/restlet/ext/mcp/McpClientAdapter.java | 24 +++++++++- .../mcp/internal/McpModernHttpTransport.java | 25 ++++++++-- .../ext/mcp/McpModernClientTestCase.java | 46 +++++++++++++++++++ .../mcp/McpModernHttpTransportTestCase.java | 6 ++- 5 files changed, 98 insertions(+), 8 deletions(-) diff --git a/changes.md b/changes.md index 2972531646..db80e21323 100644 --- a/changes.md +++ b/changes.md @@ -58,6 +58,11 @@ Changes log bracketed and without zone, other hosts must be ASCII host names, and user information and percent-encoding are refused. - Enhancements + - `McpClientAdapter.setCallCustomizer(BiConsumer)` gives the customizer + of a 2026-07-28 request over HTTP the Reactor context its call was subscribed with, so a + client passes per-call state, such as a credential computed from the call's parameters, + with `contextWrite` on the call; the request customizer runs on a worker thread, where + the state of the calling thread is not visible (#1770). - `Redirector.MODE_CLIENT_PERMANENT_STRICT` answers 308 (Permanent Redirect), which makes the client repeat the request with the same method and content, unlike `MODE_CLIENT_PERMANENT` (301) that lets a user agent turn a POST into a GET. It comes with 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 cbda1f57c9..bf6309644c 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 @@ -23,6 +23,7 @@ import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeoutException; +import java.util.function.BiConsumer; import java.util.function.Consumer; import org.restlet.Client; import org.restlet.Request; @@ -35,6 +36,7 @@ import org.restlet.ext.mcp.internal.McpStdioChannel; import reactor.core.Exceptions; import reactor.core.publisher.Mono; +import reactor.util.context.ContextView; /** * Lifecycle facade of an MCP client, on the SDK's {@code 2026-07-28} types. Borrowed Restlet @@ -93,6 +95,7 @@ public final class McpClientAdapter implements AutoCloseable { private int maxMessageBytes = McpProtocol.DEFAULT_MAX_MESSAGE_BYTES; private int maxConcurrentCalls = McpProtocol.DEFAULT_MAX_CONCURRENT_CALLS; private Consumer requestCustomizer = request -> {}; + private BiConsumer callCustomizer = (request, context) -> {}; private String protocolVersion = McpProtocol.VERSION; private McpAsyncElicitationHandler formElicitation; private McpAsyncElicitationHandler urlElicitation; @@ -171,6 +174,24 @@ public synchronized Consumer getRequestCustomizer() { return requestCustomizer; } + /** + * Sets what each request of a 2026-07-28 call over HTTP gets from the call itself, after the + * {@linkplain #setRequestCustomizer(Consumer) request customizer}: the Reactor context the call + * was subscribed with, so a caller passes per-call state, such as credentials rendered from the + * call's parameters, with {@code contextWrite} on the call, as the customizer runs on a worker + * thread of the transport. A legacy (2025-11-25) request is not given it. + * + * @param value The customizer, which gets the request and the context of its call. + */ + public synchronized void setCallCustomizer(BiConsumer value) { + requireConfigurable(); + callCustomizer = Objects.requireNonNull(value); + } + + public synchronized BiConsumer getCallCustomizer() { + return callCustomizer; + } + /** * Sets the MCP revision spoken: {@link McpProtocol#VERSION}, the default, through the SDK's * client; {@link McpProtocol#MODERN_VERSION} through {@link #getModernClient()}, over HTTP or @@ -623,7 +644,8 @@ private Modern createModern() { maxMessageBytes, maxConcurrentCalls, requestTimeout, - requestCustomizer); + requestCustomizer, + callCustomizer); return new Modern( modernBuilder(transport).build(), new McpTasksClient( diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java index 0b0e7d122f..c2bee3f123 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java @@ -30,6 +30,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import org.restlet.Client; @@ -49,6 +50,7 @@ import reactor.core.publisher.Operators; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; +import reactor.util.context.ContextView; /** * Sends MCP {@code 2026-07-28} requests over a borrowed, started Restlet HTTP connector, one POST @@ -79,6 +81,7 @@ public final class McpModernHttpTransport implements McpClientTransport { private final McpJsonMapper mapper; private final int maxMessageBytes; private final Consumer customizer; + private final BiConsumer callCustomizer; private final Duration timeout; private final McpWorkers calls; private final McpWorkers listeners; @@ -93,6 +96,8 @@ public final class McpModernHttpTransport implements McpClientTransport { * @param maxConcurrentCalls The number of calls in flight at once. * @param timeout The time limit of each call, listen streams excepted. * @param customizer Adds to each request, such as credentials. + * @param callCustomizer Adds to each request what its call carries: it gets the Reactor context + * the call was subscribed with. */ public McpModernHttpTransport( Client client, @@ -101,12 +106,14 @@ public McpModernHttpTransport( int maxMessageBytes, int maxConcurrentCalls, Duration timeout, - Consumer customizer) { + Consumer customizer, + BiConsumer callCustomizer) { this.client = Objects.requireNonNull(client, "client"); this.target = Objects.requireNonNull(target, "target"); this.mapper = Objects.requireNonNull(mapper, "mapper"); this.maxMessageBytes = maxMessageBytes; this.customizer = Objects.requireNonNull(customizer, "customizer"); + this.callCustomizer = Objects.requireNonNull(callCustomizer, "callCustomizer"); this.timeout = timeout; calls = new McpWorkers(maxConcurrentCalls, timeout); listeners = new McpWorkers(McpProtocol.DEFAULT_MAX_LISTEN_STREAMS, null, timeout); @@ -197,6 +204,7 @@ private Flux send( BiFunction failure) { return Flux.create( sink -> { + ContextView context = sink.contextView(); AtomicReference active = new AtomicReference<>(); AtomicBoolean dispatched = new AtomicBoolean(); Demand demand = new Demand(); @@ -217,7 +225,8 @@ private Flux send( params, active, dispatched, - emitter), + emitter, + context), () -> abort(active.get()), limit) .subscribe( @@ -245,12 +254,13 @@ private void exchange( Map params, AtomicReference active, AtomicBoolean dispatched, - Emitter sink) + Emitter sink, + ContextView context) throws IOException { if (closed) { throw new IOException("MCP client is closed"); } - Request request = request(rpc, version, name, params); + Request request = request(rpc, version, name, params, context); active.set(request); requests.add(request); Response response = null; @@ -282,7 +292,11 @@ private void exchange( } private Request request( - JsonRpc.JSONRPCRequest rpc, String version, String name, Map params) + JsonRpc.JSONRPCRequest rpc, + String version, + String name, + Map params, + ContextView context) throws IOException { Request request = new Request( @@ -292,6 +306,7 @@ private Request request( McpMessages.encode(mapper, rpc, maxMessageBytes), MediaType.APPLICATION_JSON)); customizer.accept(request); + callCustomizer.accept(request, context); request.getHeaders().set(McpProtocol.VERSION_HEADER, version); request.getHeaders().set("Mcp-Method", rpc.method()); if (name != null) { 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 3329bdf933..3f0906e8be 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 @@ -374,6 +374,52 @@ void modernModeLimits() throws Exception { } /** Starts the server, if needed, and a modern client with an optional form handler. */ + /** + * What a call subscribes with reaches the customizer of its request, which runs on a worker of + * the transport: per-call state such as a credential rendered from the call's parameters. + */ + @Test + void aCallCustomizerGetsTheReactorContextOfItsCall() throws Exception { + List seen = new CopyOnWriteArrayList<>(); + McpAsyncClient modern = + start( + "HTTP2", + null, + configured -> + configured.setCallCustomizer( + (request, context) -> + seen.add( + String.valueOf( + context.getOrDefault( + "caller", "none"))))); + + modern.tool("echo") + .arguments(Map.of("text", "a")) + .call() + .contextWrite(reactor.util.context.Context.of("caller", "alice")) + .block(WAIT); + modern.tool("echo").arguments(Map.of("text", "b")).call().block(WAIT); + modern.tool("echo") + .arguments(Map.of("text", "c")) + .call() + .contextWrite(reactor.util.context.Context.of("caller", "bob")) + .block(WAIT); + + // Each call may send more than one request, and the start sends a discovery: what matters + // is that a request gets the context of its own call and of no other. + assertEquals("none", seen.getFirst(), "the discovery of the start"); + int alice = seen.indexOf("alice"); + int bob = seen.indexOf("bob"); + assertTrue(0 < alice && alice < bob, seen.toString()); + List runs = new java.util.ArrayList<>(); + for (String value : seen.subList(1, seen.size())) { + if (runs.isEmpty() || !runs.getLast().equals(value)) { + runs.add(value); + } + } + assertEquals(List.of("alice", "none", "bob"), runs); + } + private McpAsyncClient start( String mode, McpAsyncElicitationHandler form) throws Exception { diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernHttpTransportTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernHttpTransportTestCase.java index cd2474fd81..9760b5ec0f 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernHttpTransportTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpModernHttpTransportTestCase.java @@ -194,7 +194,8 @@ void aConnectionLostBeforeTheResponseIsLost() throws Exception { 1024, 1, WAIT, - ignored -> {}); + ignored -> {}, + (ignored, context) -> {}); try { McpTransportRequest request = McpTransportRequest.builder( @@ -327,7 +328,8 @@ public void handle(Request request, Response response) { maxMessageBytes, maxCalls, WAIT, - ignored -> {}); + ignored -> {}, + (ignored, context) -> {}); } private Flux send(long id) { From 8da7694b621b02c3c2a063e587c548512780b6fd Mon Sep 17 00:00:00 2001 From: Jerome Louvel <374450+jlouvel@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:57:18 -0500 Subject: [PATCH 2/3] Keep the Javadoc of start() on start() in McpModernClientTestCase Co-Authored-By: Claude Sonnet 5.5 --- .../test/java/org/restlet/ext/mcp/McpModernClientTestCase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 3f0906e8be..1ea170a49c 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 @@ -373,7 +373,6 @@ void modernModeLimits() throws Exception { assertThrows(IllegalArgumentException.class, () -> unknown.setMaxInputRounds(0)); } - /** Starts the server, if needed, and a modern client with an optional form handler. */ /** * What a call subscribes with reaches the customizer of its request, which runs on a worker of * the transport: per-call state such as a credential rendered from the call's parameters. @@ -420,6 +419,7 @@ void aCallCustomizerGetsTheReactorContextOfItsCall() throws Exception { assertEquals(List.of("alice", "none", "bob"), runs); } + /** Starts the server, if needed, and a modern client with an optional form handler. */ private McpAsyncClient start( String mode, McpAsyncElicitationHandler form) throws Exception { From b0119d198da89379d66229111e155071e5eacfe3 Mon Sep 17 00:00:00 2001 From: Jerome Louvel <374450+jlouvel@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:16:05 -0500 Subject: [PATCH 3/3] Free the permit of an MCP call before handing over its answer (#1772) Co-Authored-By: Claude Sonnet 5.5 --- changes.md | 4 ++ .../mcp/internal/McpModernHttpTransport.java | 22 +++++-- .../restlet/ext/mcp/internal/McpWorkers.java | 41 +++++++++++-- .../restlet/ext/mcp/McpWorkersTestCase.java | 59 +++++++++++++++++++ 4 files changed, 116 insertions(+), 10 deletions(-) diff --git a/changes.md b/changes.md index db80e21323..f6357e248a 100644 --- a/changes.md +++ b/changes.md @@ -167,6 +167,10 @@ Changes log `503` and logged a `NullPointerException`, as an entity without content has no stream to read (#1768); the MCP client likewise fails with an `IOException`, not a `NullPointerException`, on a response without content. + - The MCP client no longer refuses, at random, a call made from a handler that answers the + result of another call, such as an elicitation handler, when `maxConcurrentCalls` leaves + no other slot: a call now frees its slot before it hands over its answer, where it freed + it a moment after, and the handler's call could find the slot still held (#1772). - The MCP STDIO connector no longer treats a clean end of its input as a failure: the requests already sent are answered before it closes (within the request timeout of the adapter, plus 5 s), where they were aborted, so a client that half-closes stdin after its last request, or a diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java index c2bee3f123..006c286460 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpModernHttpTransport.java @@ -217,7 +217,7 @@ private Flux send( Disposable running = (listen ? listeners : calls) .submit( - () -> + release -> exchange( rpc, version, @@ -226,7 +226,8 @@ private Flux send( active, dispatched, emitter, - context), + context, + release), () -> abort(active.get()), limit) .subscribe( @@ -255,7 +256,8 @@ private void exchange( AtomicReference active, AtomicBoolean dispatched, Emitter sink, - ContextView context) + ContextView context, + Runnable release) throws IOException { if (closed) { throw new IOException("MCP client is closed"); @@ -274,9 +276,13 @@ private void exchange( Representation entity = response.getEntity(); MediaType type = entity == null ? null : entity.getMediaType(); if (type != null && MediaType.TEXT_EVENT_STREAM.isCompatible(type)) { - stream(entity, rpc.id(), sink); + stream(entity, rpc.id(), sink, release); } else if (type != null && MediaType.APPLICATION_JSON.isCompatible(type)) { - sink.emit(single(entity, response, rpc.id())); + JsonRpc.JSONRPCMessage message = single(entity, response, rpc.id()); + // Before the answer is handed over: its subscriber may answer it with a call of its + // own, such as an elicitation handler, which would find the permit still held. + release.run(); + sink.emit(message); } else { throw new McpHttpStatusException( "MCP HTTP failure: " + response.getStatus(), @@ -359,7 +365,8 @@ private JsonRpc.JSONRPCMessage single(Representation entity, Response response, * other requests are dropped. The stream must be valid UTF-8, and each message within the * message size limit, in bytes. */ - private void stream(Representation entity, Object id, Emitter sink) throws IOException { + private void stream(Representation entity, Object id, Emitter sink, Runnable release) + throws IOException { InputStream stream = entity.getStream(); if (stream == null) { throw new IOException("MCP event stream without content"); @@ -391,6 +398,9 @@ private void stream(Representation entity, Object id, Emitter sink) throws IOExc JsonRpc.JSONRPCMessage message = JsonRpc.deserializeMessage(mapper, data); boolean response = message instanceof JsonRpc.JSONRPCResponse; boolean ours = response && sameId(((JsonRpc.JSONRPCResponse) message).id(), id); + if (ours) { + release.run(); // As for a single reply: the subscriber may call at once. + } if (!response || ours) { sink.emit(message); // Another request's response is dropped. } diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpWorkers.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpWorkers.java index 90411cdeda..3f40c48a36 100644 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpWorkers.java +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpWorkers.java @@ -84,12 +84,38 @@ public Mono submit(Operation operation, Runnable cancel) { * @return Completes when the call ends. */ public Mono submit(Operation operation, Runnable cancel, Duration limit) { + return submit(release -> operation.run(), cancel, limit); + } + + /** A call that may free its admission permit before it ends. */ + @FunctionalInterface + public interface ReleasingOperation { + /** + * Runs the call. + * + * @param release Frees the permit of the call, once: to run before handing over what a + * subscriber may answer with a call of its own, which would otherwise be refused for + * want of the permit this call still holds. The call may go on, cleaning up. + * @throws Exception When the call fails. + */ + void run(Runnable release) throws Exception; + } + + /** + * Submits a call that frees its admission permit when it chooses, at the latest when it ends. + * + * @param operation The call. + * @param cancel Run when the call is cancelled. + * @param limit The time limit of the call, or null for none. + * @return Completes when the call ends. + */ + public Mono submit(ReleasingOperation operation, Runnable cancel, Duration limit) { Mono call = Mono.create(sink -> admit(sink, operation, cancel)); return limit == null ? call : call.timeout(limit); } /** Admits a call, or refuses it at once; cancelling it interrupts its worker. */ - private void admit(MonoSink sink, Operation operation, Runnable cancel) { + private void admit(MonoSink sink, ReleasingOperation operation, Runnable cancel) { AtomicReference worker = new AtomicReference<>(); AtomicBoolean cancelled = new AtomicBoolean(); sink.onCancel( @@ -122,23 +148,30 @@ private void admit(MonoSink sink, Operation operation, Runnable cancel) { @SuppressWarnings("java:S1181") private void work( MonoSink sink, - Operation operation, + ReleasingOperation operation, AtomicReference worker, AtomicBoolean cancelled) { worker.set(Thread.currentThread()); + AtomicBoolean released = new AtomicBoolean(); + Runnable release = + () -> { + if (released.compareAndSet(false, true)) { + admission.release(); + } + }; Throwable error = null; try { boolean ran = false; try { if (!cancelled.get()) { ran = true; - operation.run(); + operation.run(release); } } catch (Exception | Error e) { // An Error, such as a failed assertion, ends the call too, and is rethrown. error = e; } finally { - admission.release(); + release.run(); } if (ran && !cancelled.get()) { if (error == null) { diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpWorkersTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpWorkersTestCase.java index d78e967cbe..c973aad992 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpWorkersTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpWorkersTestCase.java @@ -40,6 +40,65 @@ void aChainedCallIsAdmittedWithOneSlot() throws Exception { } } + /** + * A call that frees its permit early lets another in while it is still running: what answers + * its result with a call of its own is not refused for want of the permit. + */ + @Test + void aCallThatReleasesEarlyAdmitsAnotherWhileItRuns() throws Exception { + McpWorkers workers = new McpWorkers(1, Duration.ofSeconds(5)); + CountDownLatch released = new CountDownLatch(1); + CountDownLatch otherDone = new CountDownLatch(1); + try { + workers.submit( + (McpWorkers.ReleasingOperation) + release -> { + release.run(); + released.countDown(); + // Still running, as in cleaning up after its answer. + assertTrue(otherDone.await(5, TimeUnit.SECONDS)); + }, + () -> {}, + Duration.ofSeconds(5)) + .subscribe(); + assertTrue(released.await(5, TimeUnit.SECONDS)); + + workers.submit(otherDone::countDown, () -> {}).block(Duration.ofSeconds(5)); + + assertEquals(0, otherDone.getCount()); + assertTrue(workers.awaitIdle(Duration.ofSeconds(5))); + } finally { + workers.close(); + } + } + + /** Releasing twice, or releasing and then ending, frees one permit. */ + @Test + void aPermitIsReleasedOnce() throws Exception { + McpWorkers workers = new McpWorkers(1, Duration.ofSeconds(5)); + CountDownLatch hold = new CountDownLatch(1); + try { + workers.submit( + (McpWorkers.ReleasingOperation) + release -> { + release.run(); + release.run(); + }, + () -> {}, + Duration.ofSeconds(5)) + .block(Duration.ofSeconds(5)); + // One permit: a second concurrent call is refused, not admitted by a double release. + workers.submit(() -> hold.await(5, TimeUnit.SECONDS), () -> {}).subscribe(); + org.junit.jupiter.api.Assertions.assertThrows( + RuntimeException.class, + () -> workers.submit(() -> {}, () -> {}).block(Duration.ofSeconds(5))); + hold.countDown(); + assertTrue(workers.awaitIdle(Duration.ofSeconds(5))); + } finally { + workers.close(); + } + } + /** A call failing with an Error ends with it, and no longer counts as running. */ @Test void aCallFailingWithAnErrorEnds() throws Exception {