Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Request, ContextView>)` 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
Expand Down Expand Up @@ -162,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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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<Request> requestCustomizer = request -> {};
private BiConsumer<Request, ContextView> callCustomizer = (request, context) -> {};
private String protocolVersion = McpProtocol.VERSION;
private McpAsyncElicitationHandler<McpSchema.ElicitFormRequest> formElicitation;
private McpAsyncElicitationHandler<McpSchema.ElicitUrlRequest> urlElicitation;
Expand Down Expand Up @@ -171,6 +174,24 @@ public synchronized Consumer<Request> 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<Request, ContextView> value) {
requireConfigurable();
callCustomizer = Objects.requireNonNull(value);
}

public synchronized BiConsumer<Request, ContextView> 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
Expand Down Expand Up @@ -623,7 +644,8 @@ private Modern createModern() {
maxMessageBytes,
maxConcurrentCalls,
requestTimeout,
requestCustomizer);
requestCustomizer,
callCustomizer);
return new Modern(
modernBuilder(transport).build(),
new McpTasksClient(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -79,6 +81,7 @@ public final class McpModernHttpTransport implements McpClientTransport {
private final McpJsonMapper mapper;
private final int maxMessageBytes;
private final Consumer<Request> customizer;
private final BiConsumer<Request, ContextView> callCustomizer;
private final Duration timeout;
private final McpWorkers calls;
private final McpWorkers listeners;
Expand All @@ -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,
Expand All @@ -101,12 +106,14 @@ public McpModernHttpTransport(
int maxMessageBytes,
int maxConcurrentCalls,
Duration timeout,
Consumer<Request> customizer) {
Consumer<Request> customizer,
BiConsumer<Request, ContextView> 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);
Expand Down Expand Up @@ -197,6 +204,7 @@ private Flux<JsonRpc.JSONRPCMessage> send(
BiFunction<Throwable, Boolean, Throwable> failure) {
return Flux.<JsonRpc.JSONRPCMessage>create(
sink -> {
ContextView context = sink.contextView();
AtomicReference<Request> active = new AtomicReference<>();
AtomicBoolean dispatched = new AtomicBoolean();
Demand demand = new Demand();
Expand All @@ -209,15 +217,17 @@ private Flux<JsonRpc.JSONRPCMessage> send(
Disposable running =
(listen ? listeners : calls)
.submit(
() ->
release ->
exchange(
rpc,
version,
name,
params,
active,
dispatched,
emitter),
emitter,
context,
release),
() -> abort(active.get()),
limit)
.subscribe(
Expand Down Expand Up @@ -245,12 +255,14 @@ private void exchange(
Map<String, String> params,
AtomicReference<Request> active,
AtomicBoolean dispatched,
Emitter sink)
Emitter sink,
ContextView context,
Runnable release)
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;
Expand All @@ -264,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(),
Expand All @@ -282,7 +298,11 @@ private void exchange(
}

private Request request(
JsonRpc.JSONRPCRequest rpc, String version, String name, Map<String, String> params)
JsonRpc.JSONRPCRequest rpc,
String version,
String name,
Map<String, String> params,
ContextView context)
throws IOException {
Request request =
new Request(
Expand All @@ -292,6 +312,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) {
Expand Down Expand Up @@ -344,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");
Expand Down Expand Up @@ -376,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.
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,38 @@
* @return Completes when the call ends.
*/
public Mono<Void> 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;

Check warning on line 101 in org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/internal/McpWorkers.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace generic exceptions with specific library exceptions or a custom exception.

See more on https://sonarcloud.io/project/issues?id=restlet_restlet-framework-java&issues=AaIqdbXYA8dDtxJnaTqA&open=AaIqdbXYA8dDtxJnaTqA&pullRequest=1771
}

/**
* 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<Void> submit(ReleasingOperation operation, Runnable cancel, Duration limit) {
Mono<Void> call = Mono.<Void>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<Void> sink, Operation operation, Runnable cancel) {
private void admit(MonoSink<Void> sink, ReleasingOperation operation, Runnable cancel) {
AtomicReference<Thread> worker = new AtomicReference<>();
AtomicBoolean cancelled = new AtomicBoolean();
sink.onCancel(
Expand Down Expand Up @@ -122,23 +148,30 @@
@SuppressWarnings("java:S1181")
private void work(
MonoSink<Void> sink,
Operation operation,
ReleasingOperation operation,
AtomicReference<Thread> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,52 @@ void modernModeLimits() throws Exception {
assertThrows(IllegalArgumentException.class, () -> unknown.setMaxInputRounds(0));
}

/**
* 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<String> 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<String> 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);
}

/** Starts the server, if needed, and a modern client with an optional form handler. */
private McpAsyncClient start(
String mode, McpAsyncElicitationHandler<McpSchema.ElicitFormRequest> form)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ void aConnectionLostBeforeTheResponseIsLost() throws Exception {
1024,
1,
WAIT,
ignored -> {});
ignored -> {},
(ignored, context) -> {});
try {
McpTransportRequest request =
McpTransportRequest.builder(
Expand Down Expand Up @@ -327,7 +328,8 @@ public void handle(Request request, Response response) {
maxMessageBytes,
maxCalls,
WAIT,
ignored -> {});
ignored -> {},
(ignored, context) -> {});
}

private Flux<JsonRpc.JSONRPCMessage> send(long id) {
Expand Down
Loading