diff --git a/changes.md b/changes.md index 8c689424a2..0a4b3d5451 100644 --- a/changes.md +++ b/changes.md @@ -23,6 +23,20 @@ Changes log - The MCP extension depends on Jackson 3, as `org.restlet.ext.jackson` does, through the SDK's `mcp-json-jackson3` module, instead of Jackson 2 (#1705). An application that got Jackson 2 through it must now declare it. + - The MCP 2026-07-28 client is the SDK's: `McpClientAdapter.getModernClient()` returns + its `McpAsyncClient`, which sends its requests over the adapter's Restlet HTTP + connector, within the adapter's limits, and `McpModernClient` is removed. The SDK's + client lists the tools it doesn't know before calling one with `x-mcp-header` + arguments, leaves out of its listings, and refuses to call, a tool whose header + argument is a number, and fails an `input_required` request it can't answer instead of + returning the result; its `callOnce`, `readOnce` and `getOnce` return it. + `McpInputHandler`, `setInputHandler` and `setModernCapabilities` give way to + `setFormElicitation` and `setUrlElicitation`, whose handlers also set the declared + elicitation capabilities, and `setMaxInputRounds` requires at least one round. + Task-augmented calls, which the SDK's client can't declare, go through + `McpClientAdapter.getTasksClient()`, an `McpTasksClient`: its `callTool` takes the + tool's definition, from which it mirrors the annotated arguments, no longer takes a + progress listener, and still returns an `input_required` result it can't answer. - `DefaultSslContextFactory` now uses the JVM default algorithms for the trust manager (`TrustManagerFactory.getDefaultAlgorithm()`, `PKIX`) and the key manager (`KeyManagerFactory.getDefaultAlgorithm()`) instead of the obsolete `SunX509`, unless the @@ -95,9 +109,9 @@ Changes log `tasks/cancel` on the application's tasks, scoped to the principal that created them (`McpRequestContext.principal()`), and advertises the extension. A tool returns an `McpTaskResult` to run a call as a task, only to clients declaring the extension - (`McpTaskResult.isDeclared`). `McpModernClient.callTool` returns that task, and - `awaitTask` polls it to its result, answering its questions through the input handler; - `getTask`, `updateTask` and `cancelTask` drive it directly. + (`McpTaskResult.isDeclared`). `McpTasksClient.callTool` returns that task, and + `awaitTask` polls it to its result, answering its questions through the elicitation + handlers; `getTask`, `updateTask` and `cancelTask` drive it directly. - The sealed `requestState` of MCP `input_required` results can be sealed by the application's codec, `McpServerAdapter.setRequestStateCodec(RequestStateCodec)` (#1701). `McpAeadRequestStateCodec` seals it with AES-256-GCM, so the client can't read it, with a 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 e1e046146b..2fc93aa33b 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 @@ -11,6 +11,9 @@ import io.modelcontextprotocol.json.McpJsonDefaults; import io.modelcontextprotocol.json.McpJsonMapper; import io.modelcontextprotocol.modern.McpSchema; +import io.modelcontextprotocol.modern.client.McpAsyncClient; +import io.modelcontextprotocol.modern.client.McpAsyncElicitationHandler; +import io.modelcontextprotocol.modern.client.McpClient; import java.io.IOException; import java.io.UncheckedIOException; import java.time.Duration; @@ -35,7 +38,8 @@ *

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()} makes the requests. + * 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. * *

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 @@ -77,13 +81,13 @@ public final class McpClientAdapter implements AutoCloseable { private int maxConcurrentCalls = McpProtocol.DEFAULT_MAX_CONCURRENT_CALLS; private Consumer requestCustomizer = request -> {}; private String protocolVersion = McpProtocol.VERSION; - private McpSchema.ClientCapabilities modernCapabilities = McpSchema.ClientCapabilities.NONE; - private McpInputHandler inputHandler; + private McpAsyncElicitationHandler formElicitation; + private McpAsyncElicitationHandler urlElicitation; private int maxInputRounds = DEFAULT_MAX_INPUT_ROUNDS; private McpJsonMapper jsonMapper = McpJsonDefaults.getMapper(); private boolean legacySessions; private String legacySessionId; - private McpModernClient modern; + private Modern modern; private McpLegacyEdge.Client legacy; private String negotiatedVersion; private boolean started; @@ -190,61 +194,66 @@ public synchronized String getProtocolVersion() { } /** - * Sets the client capabilities sent with each {@link McpProtocol#MODERN_VERSION} request, none - * by default. A server asks only for the input they declare, such as elicitation. + * Sets the JSON mapper of the {@link McpProtocol#MODERN_VERSION} client's messages, so that + * they share the application's settings. The SDK's default, Jackson 3 based, otherwise. * - * @param value The capabilities. + * @param value The mapper. */ - public synchronized void setModernCapabilities(McpSchema.ClientCapabilities value) { + public synchronized void setJsonMapper(McpJsonMapper value) { requireConfigurable(); - modernCapabilities = Objects.requireNonNull(value, "value"); + jsonMapper = Objects.requireNonNull(value, "jsonMapper"); } - public synchronized McpSchema.ClientCapabilities getModernCapabilities() { - return modernCapabilities; + public synchronized McpJsonMapper getJsonMapper() { + return jsonMapper; } /** - * Sets the JSON mapper of the {@link McpProtocol#MODERN_VERSION} client's messages, so that - * they share the application's settings. The SDK's default, Jackson 3 based, otherwise. + * Sets what answers the form elicitations of {@link McpProtocol#MODERN_VERSION} requests, + * through {@code input_required} results, after which the request is retried. With a handler, + * each request declares the form elicitation capability. Legacy servers ask for no input: the + * legacy edge declares no elicitation capability. * - * @param value The mapper. + * @param value The handler, or null for none. */ - public synchronized void setJsonMapper(McpJsonMapper value) { + public synchronized void setFormElicitation( + McpAsyncElicitationHandler value) { requireConfigurable(); - jsonMapper = Objects.requireNonNull(value, "jsonMapper"); + formElicitation = value; } - public synchronized McpJsonMapper getJsonMapper() { - return jsonMapper; + public synchronized McpAsyncElicitationHandler + getFormElicitation() { + return formElicitation; } /** - * Sets what answers the {@code input_required} results of {@link McpProtocol#MODERN_VERSION} - * requests, after which the request is retried; without one, the result is returned. Legacy - * servers ask for no input: the legacy edge declares no elicitation capability. + * Sets what answers the URL elicitations of {@link McpProtocol#MODERN_VERSION} requests, as + * {@link #setFormElicitation} does for forms. * * @param value The handler, or null for none. */ - public synchronized void setInputHandler(McpInputHandler value) { + public synchronized void setUrlElicitation( + McpAsyncElicitationHandler value) { requireConfigurable(); - inputHandler = value; + urlElicitation = value; } - public synchronized McpInputHandler getInputHandler() { - return inputHandler; + public synchronized McpAsyncElicitationHandler getUrlElicitation() { + return urlElicitation; } /** - * Sets how many {@code input_required} results the input handler answers for one request, - * {@value #DEFAULT_MAX_INPUT_ROUNDS} by default; the next one is returned. + * Sets how many {@code input_required} rounds the elicitation handlers answer for one request, + * {@value #DEFAULT_MAX_INPUT_ROUNDS} by default. Past it, the SDK's client fails the request, + * and {@link McpTasksClient} returns the result or task as it is. * - * @param value The number of rounds, zero or more. + * @param value The number of rounds, one or more. */ public synchronized void setMaxInputRounds(int value) { requireConfigurable(); - if (value < 0) { - throw new IllegalArgumentException("Input rounds must not be negative"); + if (value <= 0) { + throw new IllegalArgumentException("Input rounds must be positive"); } maxInputRounds = value; } @@ -360,7 +369,7 @@ private void startAuto() { McpEras.remove(target); } } - McpModernClient candidate = createModern(); + Modern candidate = createModern(); if (probe(candidate)) { modern = candidate; negotiatedVersion = McpProtocol.MODERN_VERSION; @@ -408,10 +417,11 @@ private NotModern() { * @return True for a modern server, which the candidate then serves; false for a legacy one, * for which the candidate is closed. */ - private boolean probe(McpModernClient candidate) { + private boolean probe(Modern candidate) { boolean kept = false; try { - McpSchema.DiscoverResult discovered = candidate.discover().block(requestTimeout); + McpSchema.DiscoverResult discovered = + candidate.client().discover().block(requestTimeout); List supported = discovered == null || discovered.supportedVersions() == null ? List.of() @@ -431,8 +441,9 @@ private boolean probe(McpModernClient candidate) { if (!kept) { try { candidate.close(); - } catch (IOException cleanup) { - // The probe exchange is over: nothing is left to release. + } catch (RuntimeException cleanup) { + // The probe exchange is over: its failure to close neither replaces the + // fallback nor the probe's own failure. } } } @@ -481,7 +492,23 @@ private static boolean offersLegacy(List supported) { return supported.stream().anyMatch(McpProtocol.LEGACY_VERSIONS::contains); } - private McpModernClient createModern() { + /** + * The {@code 2026-07-28} clients over one HTTP transport: the SDK's and the Tasks extension's. + */ + private record Modern( + McpAsyncClient client, McpTasksClient tasks, McpModernHttpTransport transport) { + + /** Ends the exchanges in flight and listen streams. */ + void close() { + try { + transport.close(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } + + private Modern createModern() { if (stream != null || target.startsWith("stdio:")) { throw new UnsupportedOperationException( "The MCP 2026-07-28 client supports HTTP only for now"); @@ -496,26 +523,38 @@ private McpModernClient createModern() { throw new IllegalStateException( "Borrowed MCP client must be started with followRedirects=false"); } - McpJsonMapper mapper = jsonMapper; - return new McpModernClient( + McpModernHttpTransport transport = new McpModernHttpTransport( client, target, - mapper, + jsonMapper, maxMessageBytes, maxConcurrentCalls, requestTimeout, - requestCustomizer), - mapper, - modernCapabilities, - inputHandler, - maxInputRounds); + requestCustomizer); + McpClient.AsyncBuilder builder = + McpClient.async(transport) + .jsonMapper(jsonMapper) + .roundTimeout(requestTimeout) + .maxInputRounds(maxInputRounds); + if (formElicitation != null) { + builder.formElicitation(formElicitation); + } + if (urlElicitation != null) { + builder.urlElicitation(urlElicitation); + } + return new Modern( + builder.build(), + new McpTasksClient( + transport, jsonMapper, formElicitation, urlElicitation, maxInputRounds), + transport); } /** Starts a {@code 2026-07-28} client, and discovers the server's support of it. */ - private void startModern(McpModernClient candidate) { + private void startModern(Modern candidate) { try { - McpSchema.DiscoverResult discovered = candidate.discover().block(requestTimeout); + McpSchema.DiscoverResult discovered = + candidate.client().discover().block(requestTimeout); if (discovered == null || discovered.supportedVersions() == null || !discovered.supportedVersions().contains(McpProtocol.MODERN_VERSION)) { @@ -524,7 +563,7 @@ private void startModern(McpModernClient candidate) { } catch (RuntimeException e) { try { candidate.close(); - } catch (IOException cleanup) { + } catch (RuntimeException cleanup) { e.addSuppressed(cleanup); } throw e; @@ -535,11 +574,28 @@ private void startModern(McpModernClient candidate) { } /** - * The {@link McpProtocol#MODERN_VERSION} client, when that is the revision set. + * 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()}. + * + * @return The client. + */ + public synchronized McpAsyncClient getModernClient() { + return modern().client(); + } + + /** + * The client of the Tasks extension, once {@link McpProtocol#MODERN_VERSION} is the revision + * spoken. * * @return The client. */ - public synchronized McpModernClient getModernClient() { + public synchronized McpTasksClient getTasksClient() { + return modern().tasks(); + } + + private Modern modern() { if (!started || modern == null) { throw new IllegalStateException("MCP 2026-07-28 client is not started"); } @@ -580,11 +636,11 @@ public synchronized boolean isStarted() { return started; } - private synchronized McpModernClient modernOrNull() { + private synchronized McpAsyncClient modernOrNull() { if (!started) { throw new IllegalStateException("MCP client is not started"); } - return modern; + return modern == null ? null : modern.client(); } /** @@ -594,15 +650,15 @@ private synchronized McpModernClient modernOrNull() { * @return The page of tools. */ public McpSchema.ListToolsResult listTools(String cursor) { - McpModernClient current = modernOrNull(); + McpAsyncClient current = modernOrNull(); if (current != null) { - return current.listTools(cursor).block(requestTimeout); + return current.tools().cursor(cursor).list().block(requestTimeout); } return legacy().listTools(cursor).block(requestTimeout); } /** - * Calls a tool, in either era. An {@code input_required} result the input handler doesn't + * Calls a tool, in either era. An {@code input_required} result the elicitation handlers don't * answer fails the call. * * @param name The tool. @@ -610,47 +666,34 @@ public McpSchema.ListToolsResult listTools(String cursor) { * @return The tool's result. */ public McpSchema.CallToolResult callTool(String name, Map arguments) { - McpModernClient current = modernOrNull(); + McpAsyncClient current = modernOrNull(); if (current == null) { return legacy().callTool( new McpSchema.CallToolRequest(name, arguments, null, null, null)) .block(requestTimeout); } - var outcome = - current.callTool(new McpSchema.CallToolRequest(name, arguments, null, null, null)) - .block(requestTimeout); - if (!(outcome instanceof McpSchema.CallToolResult result)) { - throw new IllegalStateException( - "MCP tool " + name + " requires input that was not provided"); - } - return result; + var tool = current.tool(name); + return (arguments == null ? tool : tool.arguments(arguments)).call().block(requestTimeout); } /** - * Reads a resource, in either era. An {@code input_required} result the input handler doesn't - * answer fails the read. + * Reads a resource, in either era. An {@code input_required} result the elicitation handlers + * don't answer fails the read. * * @param uri The resource URI. * @return The resource's contents. */ public McpSchema.ReadResourceResult readResource(String uri) { - McpModernClient current = modernOrNull(); + McpAsyncClient current = modernOrNull(); if (current == null) { return legacy().readResource(new McpSchema.ReadResourceRequest(uri, null, null, null)) .block(requestTimeout); } - var outcome = - current.readResource(new McpSchema.ReadResourceRequest(uri, null, null, null), null) - .block(requestTimeout); - if (!(outcome instanceof McpSchema.ReadResourceResult result)) { - throw new IllegalStateException( - "MCP resource " + uri + " requires input that was not provided"); - } - return result; + return current.resource(uri).read().block(requestTimeout); } /** - * Gets a prompt, in either era. An {@code input_required} result the input handler doesn't + * Gets a prompt, in either era. An {@code input_required} result the elicitation handlers don't * answer fails the request. * * @param name The prompt. @@ -658,17 +701,16 @@ public McpSchema.ReadResourceResult readResource(String uri) { * @return The prompt. */ public McpSchema.GetPromptResult getPrompt(String name, Map arguments) { - McpModernClient current = modernOrNull(); - var request = new McpSchema.GetPromptRequest(name, arguments, null, null, null); + McpAsyncClient current = modernOrNull(); if (current == null) { - return legacy().getPrompt(request).block(requestTimeout); - } - var outcome = current.getPrompt(request, null).block(requestTimeout); - if (!(outcome instanceof McpSchema.GetPromptResult result)) { - throw new IllegalStateException( - "MCP prompt " + name + " requires input that was not provided"); + return legacy().getPrompt( + new McpSchema.GetPromptRequest(name, arguments, null, null, null)) + .block(requestTimeout); } - return result; + var prompt = current.prompt(name); + return (arguments == null ? prompt : prompt.arguments(arguments)) + .get() + .block(requestTimeout); } private synchronized McpLegacyEdge.Client legacy() { @@ -683,8 +725,6 @@ public synchronized void stop() { started = false; try { modern.close(); - } catch (IOException e) { - throw new UncheckedIOException(e); } finally { modern = null; } diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpInputHandler.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpInputHandler.java deleted file mode 100644 index 09d36d067f..0000000000 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpInputHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 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 io.modelcontextprotocol.modern.McpSchema; -import java.util.Map; -import reactor.core.publisher.Mono; - -/** - * Answers the input an MCP {@link McpProtocol#MODERN_VERSION} server asks for, through an {@code - * input_required} result, such as an elicitation: {@link McpModernClient} then retries the request - * with the responses and the result's request state. Experimental: the SDK's modern API is a - * preview. - */ -@FunctionalInterface -public interface McpInputHandler { - - /** - * Answers the input requests of a result. - * - * @param required The result, with its input requests by key. - * @return The responses, by the keys of the input requests, such as {@code {"action": "accept", - * "content": {...}}} for an elicitation; or an empty {@code Mono} to return the result to - * the caller instead of retrying. - */ - Mono> respond(McpSchema.InputRequiredResult required); -} diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpModernClient.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpModernClient.java deleted file mode 100644 index d57cb78559..0000000000 --- a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpModernClient.java +++ /dev/null @@ -1,639 +0,0 @@ -/** - * 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 io.modelcontextprotocol.json.McpJsonMapper; -import io.modelcontextprotocol.json.TypeRef; -import io.modelcontextprotocol.modern.JsonRpc; -import io.modelcontextprotocol.modern.McpException; -import io.modelcontextprotocol.modern.McpSchema; -import io.modelcontextprotocol.modern.ToolParamHeaderAnnotations; -import java.io.IOException; -import java.math.BigDecimal; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.restlet.ext.mcp.internal.McpModernHttpTransport; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * A client of MCP revision {@link McpProtocol#MODERN_VERSION}, on the SDK's modern types, over - * HTTP: discovery, listings, tool calls, resource reads and prompts, with streamed progress, {@code - * input_required} retries and {@code subscriptions/listen}. Each request carries the protocol - * version and the client capabilities in its {@code _meta}, as the revision requires. Cancelling a - * returned {@code Mono} or {@code Flux} aborts its HTTP exchange, which the server sees as a - * cancellation. - * - *

Obtained from {@link McpClientAdapter#getModernClient()}, which owns its lifecycle. - * Experimental: the SDK's modern API is a preview. - */ -public final class McpModernClient { - private static final Logger LOGGER = Logger.getLogger(McpModernClient.class.getName()); - private static final TypeRef> MAP = new TypeRef<>() {}; - private static final String META = "_meta"; - private static final String REQUEST = "request"; - private static final String TASK_ID = "taskId"; - - /** The shortest wait between two polls of a task, in milliseconds. */ - public static final long MIN_POLL_MS = 100; - - /** The longest wait between two polls of a task, in milliseconds. */ - public static final long MAX_POLL_MS = 30_000; - - private static final long DEFAULT_POLL_MS = 1_000; - - private final McpModernHttpTransport transport; - private final McpJsonMapper mapper; - private final Map capabilities; - private final McpInputHandler inputHandler; - private final int maxInputRounds; - private final AtomicLong ids = new AtomicLong(); - - /** The tools last listed, by name, whose {@code x-mcp-header} arguments calls mirror. */ - private final Map tools = new ConcurrentHashMap<>(); - - McpModernClient( - McpModernHttpTransport transport, - McpJsonMapper mapper, - McpSchema.ClientCapabilities capabilities, - McpInputHandler inputHandler, - int maxInputRounds) { - this.transport = transport; - this.mapper = mapper; - this.capabilities = mapper.convertValue(capabilities, MAP); - this.inputHandler = inputHandler; - this.maxInputRounds = maxInputRounds; - } - - /** - * Discovers the server: its supported versions, capabilities and instructions. - * - * @return The discovery result. - */ - public Mono discover() { - return result(McpSchema.METHOD_SERVER_DISCOVER, new LinkedHashMap<>(), null, Map.of(), null) - .map(result -> mapper.convertValue(result, McpSchema.DiscoverResult.class)); - } - - /** - * Lists tools, and remembers their definitions: a later call mirrors the arguments their {@code - * x-mcp-header} annotations name into {@code Mcp-Param-*} headers, as the server requires. A - * call to an annotated tool this client has not listed is sent without them, and the server - * refuses it with a header mismatch. Listing the first page forgets the tools listed before. - * - * @param cursor The cursor of the page, or null for the first. - * @return The page of tools. - */ - public Mono listTools(String cursor) { - return page(McpSchema.METHOD_TOOLS_LIST, cursor, McpSchema.ListToolsResult.class) - .doOnNext( - page -> { - if (cursor == null) { - tools.clear(); - } - page.tools().forEach(tool -> tools.put(tool.name(), tool)); - }); - } - - /** - * Calls a tool; see {@link #callTool(McpSchema.CallToolRequest, Consumer)}. - * - * @param request The call. - * @return The tool's result, or an {@code input_required} result. - */ - public Mono callTool(McpSchema.CallToolRequest request) { - return callTool(request, null); - } - - /** - * Calls a tool. An {@code input_required} result is answered by the input handler, and the call - * retried, within the round limit; without a handler, or past the limit, it is returned. When - * the client capabilities declare the Tasks extension ({@link McpTask#EXTENSION_ID}), the - * server may run the call as a task: an {@link McpTaskResult} is returned then, for {@link - * #awaitTask} or the caller's own polling. - * - * @param request The call. - * @param progress Receives the progress notifications of the call, or null for none. - * @return The tool's result, an {@code input_required} result or a task. - */ - public Mono callTool( - McpSchema.CallToolRequest request, Consumer progress) { - Objects.requireNonNull(request, REQUEST); - // Worked out when subscribed, from the tools listed by then. - return Mono.defer( - () -> { - Map headers = paramHeaders(request); - return withInput( - request.inputResponses(), - request.requestState(), - (responses, state) -> - outcome( - McpSchema.METHOD_TOOLS_CALL, - new McpSchema.CallToolRequest( - request.name(), - request.arguments(), - responses, - state, - request.meta()), - request.name(), - headers, - progress, - McpSchema.CallToolResult.class, - McpSchema.CallToolOutcome.class), - 0); - }); - } - - /** - * Gets the state of a task, with {@code tasks/get}. - * - * @param taskId The task identifier. - * @return The state. - */ - public Mono getTask(String taskId) { - Objects.requireNonNull(taskId, TASK_ID); - return result("tasks/get", taskParams(taskId), taskId, Map.of(), null) - .map(McpTask::fromFields); - } - - /** - * Answers the questions a task waits on, with {@code tasks/update}. - * - * @param taskId The task identifier. - * @param inputResponses The answers, keyed as the task's {@code inputRequests}. - * @return Completes once the server took them. - */ - public Mono updateTask(String taskId, Map inputResponses) { - Objects.requireNonNull(taskId, TASK_ID); - Objects.requireNonNull(inputResponses, "inputResponses"); - Map params = taskParams(taskId); - params.put("inputResponses", inputResponses); - return result("tasks/update", params, taskId, Map.of(), null).then(); - } - - /** - * Asks a task to stop, with {@code tasks/cancel}. Cancellation is cooperative. - * - * @param taskId The task identifier. - * @return Completes once the server took the request. - */ - public Mono cancelTask(String taskId) { - Objects.requireNonNull(taskId, TASK_ID); - return result("tasks/cancel", taskParams(taskId), taskId, Map.of(), null).then(); - } - - /** - * Waits for a task to end, polling {@code tasks/get} at its {@code pollIntervalMs}, bounded to - * between {@value #MIN_POLL_MS} ms and {@value #MAX_POLL_MS} ms, one second by default. The - * questions of an {@code input_required} task go to the input handler, and its answers to - * {@code tasks/update}, within the round limit; without a handler, or past the limit, the task - * is returned as it is. Cancelling the returned {@code Mono} stops the polling, not the task: - * see {@link #cancelTask}. - * - * @param task The task, as {@code tools/call} answered it. - * @return The tool's result once completed, or the task still waiting on input. A failed task - * fails with an {@link McpException} carrying its error; a cancelled one with an internal - * error. - */ - public Mono awaitTask(McpTaskResult task) { - Objects.requireNonNull(task, "task"); - return awaitTask(task, MIN_POLL_MS); - } - - /** - * Waits for a task, polling no more often than {@code minPollMs}: one loop step per poll, so a - * long task grows neither the stack nor the chain. - */ - Mono awaitTask(McpTaskResult task, long minPollMs) { - return Mono.just(new Step(task.task(), 0, false)) - .expand(step -> next(step, minPollMs)) - .last() - .flatMap(this::outcome); - } - - /** A state of a task being waited for, and whether the wait stops at it. */ - private record Step(McpTask task, int round, boolean stop) {} - - /** The step after this one, or none once the task ended or the wait stops. */ - private Mono next(Step step, long minPollMs) { - McpTask task = step.task(); - if (step.stop() || task.status().isTerminal()) { - return Mono.empty(); - } - if (task.status() == McpTask.Status.WORKING) { - return poll(task, minPollMs).map(next -> new Step(next, step.round(), false)); - } - if (inputHandler == null || step.round() >= maxInputRounds) { - return Mono.empty(); - } - Map asked = new LinkedHashMap<>(); - asked.put("resultType", McpSchema.ResultType.INPUT_REQUIRED); - asked.put("inputRequests", task.inputRequests()); - return inputHandler - .respond(mapper.convertValue(asked, McpSchema.InputRequiredResult.class)) - .flatMap( - answers -> - updateTask(task.taskId(), answers) - .then(poll(task, minPollMs)) - .map(next -> new Step(next, step.round() + 1, false))) - // No answers: the task is handed back as it waits. - .defaultIfEmpty(new Step(task, step.round(), true)); - } - - /** What the wait ends with at its last step. */ - private Mono outcome(Step step) { - McpTask task = step.task(); - return switch (task.status()) { - case COMPLETED -> - Mono.just(mapper.convertValue(task.result(), McpSchema.CallToolResult.class)); - case FAILED -> - Mono.error( - new McpException( - mapper.convertValue( - task.error(), - JsonRpc.JSONRPCResponse.JSONRPCError.class))); - case CANCELLED -> - Mono.error( - new McpException( - McpSchema.ErrorCodes.INTERNAL_ERROR, - "MCP task cancelled: " + task.taskId())); - case WORKING, INPUT_REQUIRED -> Mono.just(new McpTaskResult(task)); - }; - } - - /** The task's next state, after its poll interval. */ - private Mono poll(McpTask task, long minPollMs) { - long interval = - task.pollIntervalMs() == null - ? DEFAULT_POLL_MS - : Math.clamp(task.pollIntervalMs(), minPollMs, MAX_POLL_MS); - return Mono.delay(Duration.ofMillis(interval)).then(getTask(task.taskId())); - } - - private static Map taskParams(String taskId) { - Map params = new LinkedHashMap<>(); - params.put(TASK_ID, taskId); - return params; - } - - /** - * Lists resources. - * - * @param cursor The cursor of the page, or null for the first. - * @return The page of resources. - */ - public Mono listResources(String cursor) { - return page(McpSchema.METHOD_RESOURCES_LIST, cursor, McpSchema.ListResourcesResult.class); - } - - /** - * Lists resource templates. - * - * @param cursor The cursor of the page, or null for the first. - * @return The page of resource templates. - */ - public Mono listResourceTemplates(String cursor) { - return page( - McpSchema.METHOD_RESOURCES_TEMPLATES_LIST, - cursor, - McpSchema.ListResourceTemplatesResult.class); - } - - /** - * Reads a resource, answering {@code input_required} results as {@link - * #callTool(McpSchema.CallToolRequest, Consumer)} does. - * - * @param request The read. - * @param progress Receives the progress notifications of the read, or null for none. - * @return The resource's contents, or an {@code input_required} result. - */ - public Mono readResource( - McpSchema.ReadResourceRequest request, Consumer progress) { - Objects.requireNonNull(request, REQUEST); - return withInput( - request.inputResponses(), - request.requestState(), - (responses, state) -> - outcome( - McpSchema.METHOD_RESOURCES_READ, - new McpSchema.ReadResourceRequest( - request.uri(), responses, state, request.meta()), - request.uri(), - Map.of(), - progress, - McpSchema.ReadResourceResult.class, - McpSchema.ReadResourceOutcome.class), - 0); - } - - /** - * Lists prompts. - * - * @param cursor The cursor of the page, or null for the first. - * @return The page of prompts. - */ - public Mono listPrompts(String cursor) { - return page(McpSchema.METHOD_PROMPTS_LIST, cursor, McpSchema.ListPromptsResult.class); - } - - /** - * Gets a prompt, answering {@code input_required} results as {@link - * #callTool(McpSchema.CallToolRequest, Consumer)} does. - * - * @param request The prompt and its arguments. - * @param progress Receives the progress notifications of the request, or null for none. - * @return The prompt, or an {@code input_required} result. - */ - public Mono getPrompt( - McpSchema.GetPromptRequest request, Consumer progress) { - Objects.requireNonNull(request, REQUEST); - return withInput( - request.inputResponses(), - request.requestState(), - (responses, state) -> - outcome( - McpSchema.METHOD_PROMPTS_GET, - new McpSchema.GetPromptRequest( - request.name(), - request.arguments(), - responses, - state, - request.meta()), - request.name(), - Map.of(), - progress, - McpSchema.GetPromptResult.class, - McpSchema.GetPromptOutcome.class), - 0); - } - - /** - * Listens to the changes a filter selects: tools, prompts and resources list changes, and the - * updates of the resources named. The stream emits each change notification as it comes, the - * acknowledgement excepted, and completes when the server ends it with its response, such as - * when it stops. Cancelling it ends the listen stream. It has no time limit. A slow subscriber - * holds back the stream: only a bounded number of notifications wait for it. - * - * @param filter The changes to listen to. - * @return The change notifications. - */ - public Flux listen(McpSchema.SubscriptionFilter filter) { - return Flux.defer(() -> listening(filter)); - } - - private Flux listening(McpSchema.SubscriptionFilter filter) { - Map params = params(new McpSchema.SubscriptionsListenRequest(filter, null)); - JsonRpc.JSONRPCRequest rpc = - new JsonRpc.JSONRPCRequest( - McpSchema.METHOD_SUBSCRIPTIONS_LISTEN, - ids.incrementAndGet(), - stamp(params)); - return transport - .send(rpc, null, Map.of(), true) - .handle( - (message, sink) -> { - if (message instanceof JsonRpc.JSONRPCNotification notification - && !McpSchema.METHOD_NOTIFICATION_SUBSCRIPTIONS_ACKNOWLEDGED - .equals(notification.method())) { - sink.next(notification); - } else if (message instanceof JsonRpc.JSONRPCResponse response - && response.error() != null) { - sink.error(new McpException(response.error())); - } - }); - } - - /** Retries a request with the input its handler gives, within the round limit. */ - private Mono withInput( - Map responses, - String state, - BiFunction, String, Mono> attempt, - int round) { - return attempt.apply(responses, state) - .flatMap( - outcome -> { - if (!(outcome instanceof McpSchema.InputRequiredResult required) - || inputHandler == null - || round >= maxInputRounds) { - return Mono.just(outcome); - } - return inputHandler - .respond(required) - .map(Optional::of) - .defaultIfEmpty(Optional.empty()) - .flatMap( - next -> - next.isPresent() - ? withInput( - next.get(), - required.requestState(), - attempt, - round + 1) - : Mono.just(outcome)); - }); - } - - /** A request whose result is complete, or input required. */ - private Mono outcome( - String method, - Object request, - String name, - Map headers, - Consumer progress, - Class complete, - Class type) { - return result(method, params(request), name, headers, progress) - .map( - result -> - type.cast( - McpSchema.ResultType.INPUT_REQUIRED.equals( - result.get("resultType")) - ? mapper.convertValue( - result, McpSchema.InputRequiredResult.class) - : McpTaskResult.RESULT_TYPE.equals( - result.get("resultType")) - && type.isAssignableFrom( - McpTaskResult.class) - ? new McpTaskResult( - McpTask.fromFields(result)) - : mapper.convertValue(result, complete))); - } - - private Mono page(String method, String cursor, Class type) { - return result( - method, - params(new McpSchema.PaginatedRequest(cursor, null)), - null, - Map.of(), - null) - .map(result -> mapper.convertValue(result, type)); - } - - /** - * Sends a request, passing its progress on, and returns its result; an error response fails - * with an {@link McpException}. - */ - private Mono> result( - String method, - Map params, - String name, - Map headers, - Consumer progress) { - return Mono.defer(() -> exchange(method, params, name, headers, progress)); - } - - private Mono> exchange( - String method, - Map given, - String name, - Map headers, - Consumer progress) { - // Each subscription sends its own request, with its own id. - Map params = new LinkedHashMap<>(given); - params.put(META, new LinkedHashMap<>(meta(given))); - long id = ids.incrementAndGet(); - Object token = progress == null ? null : "restlet-" + id; - if (token != null) { - meta(params).put(McpSchema.MetaKeys.PROGRESS_TOKEN, token); - } - stamp(params); - // The stream completes after the response: taking the last one doesn't cancel it. - return transport - .send(new JsonRpc.JSONRPCRequest(method, id, params), name, headers, false) - .doOnNext(message -> progress(message, token, progress)) - .ofType(JsonRpc.JSONRPCResponse.class) - .filter(response -> McpModernHttpTransport.sameId(response.id(), id)) - .last() - .onErrorMap( - java.util.NoSuchElementException.class, - e -> new IOException("MCP request got no response", e)) - .switchIfEmpty(Mono.error(() -> new IOException("MCP request got no response"))) - .map( - response -> { - if (response.error() != null) { - throw new McpException(response.error()); - } - return mapper.convertValue(response.result(), MAP); - }); - } - - private void progress( - JsonRpc.JSONRPCMessage message, - Object token, - Consumer progress) { - if (token != null - && message instanceof JsonRpc.JSONRPCNotification notification - && McpSchema.METHOD_NOTIFICATION_PROGRESS.equals(notification.method())) { - try { - McpSchema.ProgressParams params = - mapper.convertValue(notification.params(), McpSchema.ProgressParams.class); - if (token.equals(params.progressToken())) { - progress.accept(params); - } - } catch (RuntimeException e) { - // A malformed notification, or a failing consumer, doesn't fail the call. - LOGGER.log(Level.FINE, "MCP progress notification dropped", e); - } - } - } - - /** The params of a request, with a modifiable {@code _meta} merging what it had. */ - private Map params(Object request) { - Map params = new LinkedHashMap<>(mapper.convertValue(request, MAP)); - Map meta = new LinkedHashMap<>(); - if (params.get(META) instanceof Map given) { - given.forEach((key, value) -> meta.put(String.valueOf(key), value)); - } - params.put(META, meta); - return params; - } - - /** - * Adds what the revision requires in each request's {@code _meta}: the protocol version and the - * client capabilities, unless the request gives them. - */ - private Map stamp(Map params) { - meta(params).putIfAbsent(McpSchema.MetaKeys.PROTOCOL_VERSION, McpProtocol.MODERN_VERSION); - meta(params).putIfAbsent(McpSchema.MetaKeys.CLIENT_CAPABILITIES, capabilities); - return params; - } - - @SuppressWarnings("unchecked") - private static Map meta(Map params) { - return (Map) - params.computeIfAbsent(META, ignored -> new LinkedHashMap()); - } - - /** - * The {@code Mcp-Param-*} headers of a call: the arguments the tool's valid {@code - * x-mcp-header} annotations name, when the tool was listed. - */ - private Map paramHeaders(McpSchema.CallToolRequest request) { - McpSchema.Tool tool = tools.get(request.name()); - if (tool == null || request.arguments() == null) { - return Map.of(); - } - // The arguments as the server sees them, in JSON: a UUID or an enum is a string. - Map arguments = mapper.convertValue(request.arguments(), MAP); - Map headers = new LinkedHashMap<>(); - for (ToolParamHeaderAnnotations.Annotation annotation : - ToolParamHeaderAnnotations.parse(tool).valid()) { - String value = headerValue(argument(arguments, annotation.path())); - if (value != null) { - headers.put(annotation.name(), value); - } - } - return headers; - } - - /** - * An argument as a header value: a number in plain decimal notation, such as 10000000 rather - * than 1.0E7, as the server expects; a string or boolean as is; else null. - */ - private static String headerValue(Object value) { - return switch (value) { - case String text -> text; - case Boolean flag -> flag.toString(); - case Number number -> { - try { - yield new BigDecimal(number.toString()).toPlainString(); - } catch (NumberFormatException _) { - yield null; // NaN or infinite: not a JSON number. - } - } - case null, default -> null; - }; - } - - private static Object argument(Map arguments, List path) { - Object value = arguments; - for (String step : path) { - if (!(value instanceof Map map)) { - return null; - } - value = map.get(step); - } - return value; - } - - /** Ends the exchanges in flight and listen streams. */ - void close() throws IOException { - transport.close(); - } -} diff --git a/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpTasksClient.java b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpTasksClient.java new file mode 100644 index 0000000000..b9a84711ba --- /dev/null +++ b/org.restlet.ext.mcp/src/main/java/org/restlet/ext/mcp/McpTasksClient.java @@ -0,0 +1,481 @@ +/** + * 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 io.modelcontextprotocol.json.McpJsonMapper; +import io.modelcontextprotocol.json.TypeRef; +import io.modelcontextprotocol.modern.JsonRpc; +import io.modelcontextprotocol.modern.McpException; +import io.modelcontextprotocol.modern.McpSchema; +import io.modelcontextprotocol.modern.ToolParamHeaderAnnotations; +import io.modelcontextprotocol.modern.client.McpAsyncClient; +import io.modelcontextprotocol.modern.client.McpAsyncElicitationHandler; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; +import org.restlet.ext.mcp.internal.McpModernHttpTransport; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * The client side of the Tasks extension ({@link McpTask#EXTENSION_ID}) of MCP revision {@link + * McpProtocol#MODERN_VERSION}: tool calls the server may run as tasks, and {@code tasks/get}, + * {@code tasks/update} and {@code tasks/cancel}. The SDK's client, {@link + * McpClientAdapter#getModernClient()}, serves the rest of the revision; it can't declare the + * extension, which this client declares on each request, with the elicitation capabilities of the + * adapter's handlers. + * + *

The questions of an {@code input_required} result or task go to the adapter's form and URL + * elicitation handlers, and the call is retried, or the task updated, with their answers, within + * the round limit. A result asking for no input, only for a retry with its {@code requestState}, is + * retried after a short wait, 50 ms doubling up to 250 ms, as the SDK's client does. Unlike the + * SDK's client, which fails the call, a question no handler covers, a handler completing empty, or + * the round limit hands the result or task back to the caller as it is. + * + *

Obtained from {@link McpClientAdapter#getTasksClient()}, which owns its lifecycle. + * Experimental: the SDK's modern API and the Tasks extension are previews. + */ +public final class McpTasksClient { + private static final TypeRef> MAP = new TypeRef<>() {}; + private static final String META = "_meta"; + private static final String TASK_ID = "taskId"; + + /** The shortest wait between two polls of a task, in milliseconds. */ + public static final long MIN_POLL_MS = 100; + + /** The longest wait between two polls of a task, in milliseconds. */ + public static final long MAX_POLL_MS = 30_000; + + private static final long DEFAULT_POLL_MS = 1_000; + private static final long MIN_BACKOFF_MS = 50; + private static final long MAX_BACKOFF_MS = 250; + + private final McpModernHttpTransport transport; + private final McpJsonMapper mapper; + private final Map capabilities; + private final McpAsyncElicitationHandler formElicitation; + private final McpAsyncElicitationHandler urlElicitation; + private final int maxInputRounds; + private final AtomicLong ids = new AtomicLong(); + + McpTasksClient( + McpModernHttpTransport transport, + McpJsonMapper mapper, + McpAsyncElicitationHandler formElicitation, + McpAsyncElicitationHandler urlElicitation, + int maxInputRounds) { + this.transport = transport; + this.mapper = mapper; + this.formElicitation = formElicitation; + this.urlElicitation = urlElicitation; + this.maxInputRounds = maxInputRounds; + McpSchema.ClientCapabilities.Builder declared = + McpSchema.ClientCapabilities.builder() + .extensions(Map.of(McpTask.EXTENSION_ID, Map.of())); + if (formElicitation != null || urlElicitation != null) { + declared.elicitation( + new McpSchema.ClientCapabilities.Elicitation( + formElicitation == null + ? null + : new McpSchema.ClientCapabilities.Elicitation.Form(), + urlElicitation == null + ? null + : new McpSchema.ClientCapabilities.Elicitation.Url())); + } + this.capabilities = mapper.convertValue(declared.build(), MAP); + } + + /** + * Calls a tool, which the server may run as a task: an {@link McpTaskResult} is returned then, + * for {@link #awaitTask} or the caller's own polling. The arguments the tool's {@code + * x-mcp-header} annotations name are mirrored into {@code Mcp-Param-*} headers, as the server + * requires, from the definition given, such as one listed with {@link + * McpAsyncClient#listTools()}. + * + * @param request The call. + * @param tool The tool's definition, or null for a tool without {@code x-mcp-header} + * annotations. + * @return The tool's result, an {@code input_required} result left unanswered, or a task. The + * call fails with an {@link IllegalArgumentException} when the definition has an invalid + * annotation, such as one on a number, as the SDK's client refuses such a tool. + */ + public Mono callTool( + McpSchema.CallToolRequest request, McpSchema.Tool tool) { + Objects.requireNonNull(request, "request"); + return Mono.defer(() -> call(request, paramHeaders(request, tool), 0, 0)); + } + + /** + * One round of a call, then the next with the answers to its questions, if any, or after a wait + * when it asks for none. + */ + private Mono call( + McpSchema.CallToolRequest request, + Map headers, + int round, + int stateOnlyRounds) { + return result(McpSchema.METHOD_TOOLS_CALL, params(request), request.name(), headers) + .map(this::callOutcome) + .flatMap( + outcome -> { + if (!(outcome instanceof McpSchema.InputRequiredResult required) + || round >= maxInputRounds) { + return Mono.just(outcome); + } + if (required.inputRequests() == null + || required.inputRequests().isEmpty()) { + return Mono.delay(backoff(stateOnlyRounds + 1)) + .then( + call( + retry(request, null, required), + headers, + round + 1, + stateOnlyRounds + 1)); + } + return answers(required.inputRequests()) + .map(Optional::of) + .defaultIfEmpty(Optional.empty()) + .flatMap( + answers -> + answers.isEmpty() + ? Mono.just(outcome) + : call( + retry( + request, + answers.get(), + required), + headers, + round + 1, + 0)); + }); + } + + /** The retry of a call, with the answers given and the server's request state. */ + private static McpSchema.CallToolRequest retry( + McpSchema.CallToolRequest request, + Map answers, + McpSchema.InputRequiredResult required) { + return new McpSchema.CallToolRequest( + request.name(), + request.arguments(), + answers, + required.requestState(), + request.meta()); + } + + /** The wait before the nth retry in a row asking for no input: 50 ms, doubling up to 250 ms. */ + static Duration backoff(int n) { + return Duration.ofMillis(Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS << Math.min(n - 1, 10))); + } + + private McpSchema.CallToolOutcome callOutcome(Map result) { + Object type = result.get("resultType"); + if (McpSchema.ResultType.INPUT_REQUIRED.equals(type)) { + return mapper.convertValue(result, McpSchema.InputRequiredResult.class); + } + if (McpTaskResult.RESULT_TYPE.equals(type)) { + return new McpTaskResult(McpTask.fromFields(result)); + } + return mapper.convertValue(result, McpSchema.CallToolResult.class); + } + + /** + * Gets the state of a task, with {@code tasks/get}. + * + * @param taskId The task identifier. + * @return The state. + */ + public Mono getTask(String taskId) { + Objects.requireNonNull(taskId, TASK_ID); + return result("tasks/get", taskParams(taskId), taskId, Map.of()).map(McpTask::fromFields); + } + + /** + * Answers the questions a task waits on, with {@code tasks/update}. + * + * @param taskId The task identifier. + * @param inputResponses The answers, keyed as the task's {@code inputRequests}. + * @return Completes once the server took them. + */ + public Mono updateTask(String taskId, Map inputResponses) { + Objects.requireNonNull(taskId, TASK_ID); + Objects.requireNonNull(inputResponses, "inputResponses"); + Map params = taskParams(taskId); + params.put("inputResponses", inputResponses); + return result("tasks/update", params, taskId, Map.of()).then(); + } + + /** + * Asks a task to stop, with {@code tasks/cancel}. Cancellation is cooperative. + * + * @param taskId The task identifier. + * @return Completes once the server took the request. + */ + public Mono cancelTask(String taskId) { + Objects.requireNonNull(taskId, TASK_ID); + return result("tasks/cancel", taskParams(taskId), taskId, Map.of()).then(); + } + + /** + * Waits for a task to end, polling {@code tasks/get} at its {@code pollIntervalMs}, bounded to + * between {@value #MIN_POLL_MS} ms and {@value #MAX_POLL_MS} ms, one second by default. The + * questions of an {@code input_required} task go to the elicitation handlers, and their answers + * to {@code tasks/update}, within the round limit; otherwise the task is returned as it is. + * Cancelling the returned {@code Mono} stops the polling, not the task: see {@link + * #cancelTask}. + * + * @param task The task, as {@code tools/call} answered it. + * @return The tool's result once completed, or the task still waiting on input. A failed task + * fails with an {@link McpException} carrying its error; a cancelled one with an internal + * error. + */ + public Mono awaitTask(McpTaskResult task) { + Objects.requireNonNull(task, "task"); + return awaitTask(task, MIN_POLL_MS); + } + + /** + * Waits for a task, polling no more often than {@code minPollMs}: one loop step per poll, so a + * long task grows neither the stack nor the chain. + */ + Mono awaitTask(McpTaskResult task, long minPollMs) { + return Mono.just(new Step(task.task(), 0, false)) + .expand(step -> next(step, minPollMs)) + .last() + .flatMap(this::ending); + } + + /** A state of a task being waited for, and whether the wait stops at it. */ + private record Step(McpTask task, int round, boolean stop) {} + + /** The step after this one, or none once the task ended or the wait stops. */ + private Mono next(Step step, long minPollMs) { + McpTask task = step.task(); + if (step.stop() || task.status().isTerminal()) { + return Mono.empty(); + } + if (task.status() == McpTask.Status.WORKING) { + return poll(task, minPollMs).map(next -> new Step(next, step.round(), false)); + } + if (step.round() >= maxInputRounds) { + return Mono.empty(); + } + Map asked = new LinkedHashMap<>(); + asked.put("resultType", McpSchema.ResultType.INPUT_REQUIRED); + asked.put("inputRequests", task.inputRequests()); + return answers( + mapper.convertValue(asked, McpSchema.InputRequiredResult.class) + .inputRequests()) + .flatMap( + answers -> + updateTask(task.taskId(), answers) + .then(poll(task, minPollMs)) + .map(next -> new Step(next, step.round() + 1, false))) + // No answers: the task is handed back as it waits. + .defaultIfEmpty(new Step(task, step.round(), true)); + } + + /** What the wait ends with at its last step. */ + private Mono ending(Step step) { + McpTask task = step.task(); + return switch (task.status()) { + case COMPLETED -> + Mono.just(mapper.convertValue(task.result(), McpSchema.CallToolResult.class)); + case FAILED -> + Mono.error( + new McpException( + mapper.convertValue( + task.error(), + JsonRpc.JSONRPCResponse.JSONRPCError.class))); + case CANCELLED -> + Mono.error( + new McpException( + McpSchema.ErrorCodes.INTERNAL_ERROR, + "MCP task cancelled: " + task.taskId())); + case WORKING, INPUT_REQUIRED -> Mono.just(new McpTaskResult(task)); + }; + } + + /** The task's next state, after its poll interval. */ + private Mono poll(McpTask task, long minPollMs) { + long interval = + task.pollIntervalMs() == null + ? DEFAULT_POLL_MS + : Math.clamp(task.pollIntervalMs(), minPollMs, MAX_POLL_MS); + return Mono.delay(Duration.ofMillis(interval)).then(getTask(task.taskId())); + } + + private static Map taskParams(String taskId) { + Map params = new LinkedHashMap<>(); + params.put(TASK_ID, taskId); + return params; + } + + /** + * The handlers' answers to questions, by their keys; empty when a question has no handler or a + * handler gives no answer. + */ + private Mono> answers(Map questions) { + if (questions == null || questions.isEmpty()) { + return Mono.empty(); + } + List>> answering = new java.util.ArrayList<>(); + for (Map.Entry question : questions.entrySet()) { + Mono answer = answer(question.getValue()); + if (answer == null) { + return Mono.empty(); + } + answering.add(answer.map(result -> Map.entry(question.getKey(), result))); + } + return Flux.concat(answering) + .collectList() + .flatMap( + answered -> { + if (answered.size() < answering.size()) { + return Mono.empty(); + } + Map responses = new LinkedHashMap<>(); + answered.forEach( + entry -> + responses.put( + entry.getKey(), + mapper.convertValue(entry.getValue(), MAP))); + return Mono.just(responses); + }); + } + + /** The answer of the handler covering a question, or null if none does. */ + private Mono answer(McpSchema.InputRequest question) { + if (question instanceof McpSchema.ElicitInputRequest elicit) { + if (elicit.params() instanceof McpSchema.ElicitFormRequest form + && formElicitation != null) { + return Mono.defer(() -> formElicitation.elicit(form)); + } + if (elicit.params() instanceof McpSchema.ElicitUrlRequest url + && urlElicitation != null) { + return Mono.defer(() -> urlElicitation.elicit(url)); + } + } + return null; + } + + /** + * Sends a request and returns its result; an error response fails with an {@link McpException}. + * Each subscription sends its own request, with its own id. + */ + private Mono> result( + String method, Map given, String name, Map headers) { + return Mono.defer( + () -> { + Map params = new LinkedHashMap<>(given); + Map meta = new LinkedHashMap<>(); + if (given.get(META) instanceof Map map) { + map.forEach((key, value) -> meta.put(String.valueOf(key), value)); + } + meta.putIfAbsent( + McpSchema.MetaKeys.PROTOCOL_VERSION, McpProtocol.MODERN_VERSION); + meta.putIfAbsent(McpSchema.MetaKeys.CLIENT_CAPABILITIES, capabilities); + params.put(META, meta); + long id = ids.incrementAndGet(); + // The stream completes after the response: taking the last one doesn't + // cancel it. + return transport + .send( + new JsonRpc.JSONRPCRequest(method, id, params), + McpProtocol.MODERN_VERSION, + name, + headers, + false) + .ofType(JsonRpc.JSONRPCResponse.class) + .filter(response -> McpModernHttpTransport.sameId(response.id(), id)) + .next() + .switchIfEmpty( + Mono.error( + () -> new IOException("MCP request got no response"))) + .map( + response -> { + if (response.error() != null) { + throw new McpException(response.error()); + } + return mapper.convertValue(response.result(), MAP); + }); + }); + } + + /** The params of a request, as a modifiable map. */ + private Map params(Object request) { + return new LinkedHashMap<>(mapper.convertValue(request, MAP)); + } + + /** The {@code Mcp-Param-*} headers of a call: the arguments the tool's annotations name. */ + private Map paramHeaders( + McpSchema.CallToolRequest request, McpSchema.Tool tool) { + if (tool == null || request.arguments() == null || !tool.name().equals(request.name())) { + return Map.of(); + } + ToolParamHeaderAnnotations parsed = ToolParamHeaderAnnotations.parse(tool); + if (!parsed.isValid()) { + throw new IllegalArgumentException( + "Tool '" + + tool.name() + + "' can't be called: invalid " + + ToolParamHeaderAnnotations.KEYWORD + + " annotations: " + + parsed.invalid().stream() + .map(ToolParamHeaderAnnotations.InvalidAnnotation::describe) + .collect(java.util.stream.Collectors.joining("; "))); + } + // The arguments as the server sees them, in JSON: a UUID or an enum is a string. + Map arguments = mapper.convertValue(request.arguments(), MAP); + Map headers = new LinkedHashMap<>(); + for (ToolParamHeaderAnnotations.Annotation annotation : parsed.valid()) { + String value = headerValue(argument(arguments, annotation.path())); + if (value != null) { + headers.put(annotation.name(), value); + } + } + return headers; + } + + /** + * An argument as a header value: a number in plain decimal notation, such as 10000000 rather + * than 1.0E7, as the server expects; a string or boolean as is; else null. + */ + private static String headerValue(Object value) { + return switch (value) { + case String text -> text; + case Boolean flag -> flag.toString(); + case Number number -> { + try { + yield new BigDecimal(number.toString()).toPlainString(); + } catch (NumberFormatException _) { + yield null; // NaN or infinite: not a JSON number. + } + } + case null, default -> null; + }; + } + + private static Object argument(Map arguments, List path) { + Object value = arguments; + for (String step : path) { + if (!(value instanceof Map map)) { + return null; + } + value = map.get(step); + } + return value; + } +} 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 26c6296711..235673d8cc 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 @@ -10,6 +10,10 @@ import io.modelcontextprotocol.json.McpJsonMapper; import io.modelcontextprotocol.modern.JsonRpc; +import io.modelcontextprotocol.modern.McpSchema; +import io.modelcontextprotocol.modern.client.McpResponseLostException; +import io.modelcontextprotocol.modern.client.transport.McpClientTransport; +import io.modelcontextprotocol.modern.client.transport.McpTransportRequest; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -23,7 +27,10 @@ import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; import java.util.function.Consumer; import org.restlet.Client; import org.restlet.Request; @@ -32,6 +39,7 @@ import org.restlet.data.Method; import org.restlet.data.Preference; import org.restlet.data.ServerSentEvent; +import org.restlet.data.Status; import org.restlet.ext.mcp.McpProtocol; import org.restlet.representation.ByteArrayRepresentation; import org.restlet.representation.EventStreamReader; @@ -39,6 +47,7 @@ import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Operators; +import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; /** @@ -47,9 +56,10 @@ * response. Calls are admitted within the call limit and timeout; listen streams within their own * limit, without timeout. Messages are read as they are demanded, so a slow subscriber holds back * the server rather than filling memory. Cancelling a request aborts its HTTP exchange, which the - * server sees as a cancellation. It never retries or reconnects. + * server sees as a cancellation. It never retries or reconnects. It is the transport of the SDK's + * modern client, which it serves within the same limits. */ -public final class McpModernHttpTransport { +public final class McpModernHttpTransport implements McpClientTransport { private static final String BASE64_PREFIX = "=?base64?"; private static final String BASE64_SUFFIX = "?="; @@ -59,11 +69,17 @@ public final class McpModernHttpTransport { */ private static final int MAX_FRAMING_CHARS = 8192; + /** Delivers the messages received, each run on a new virtual thread. */ + private static final Scheduler DELIVERY = + Schedulers.fromExecutorService( + Executors.newVirtualThreadPerTaskExecutor(), "restlet-mcp-delivery"); + private final Client client; private final String target; private final McpJsonMapper mapper; private final int maxMessageBytes; private final Consumer customizer; + private final Duration timeout; private final McpWorkers calls; private final McpWorkers listeners; private final Set requests = ConcurrentHashMap.newKeySet(); @@ -91,26 +107,98 @@ public McpModernHttpTransport( this.mapper = Objects.requireNonNull(mapper, "mapper"); this.maxMessageBytes = maxMessageBytes; this.customizer = Objects.requireNonNull(customizer, "customizer"); + this.timeout = timeout; calls = new McpWorkers(maxConcurrentCalls, timeout); listeners = new McpWorkers(McpProtocol.DEFAULT_MAX_LISTEN_STREAMS, null, timeout); } + /** + * Sends a request of the SDK's client, within the call limit, or the listen limit for a {@code + * subscriptions/listen} stream. The round timeout the client gives is the request's only time + * limit: the client sends a round without one on purpose, such as after an accepted URL + * elicitation. Once the request reached the connector, an exchange that breaks before its + * response, such as a stream the server or a proxy closes, or a connection lost before the + * response's head (statuses 1001 and 1002), fails with {@link McpResponseLostException}, as the + * client expects. A request refused before it is sent, such as over a limit, fails as it is, + * and so does an HTTP failure, which keeps its status. + */ + @Override + public Flux exchange(McpTransportRequest request) { + boolean listen = McpSchema.METHOD_SUBSCRIPTIONS_LISTEN.equals(request.method()); + Flux sent = + send( + request.message(), + request.protocolVersion(), + request.name(), + request.paramHeaders(), + listen, + null, + (error, dispatched) -> + dispatched && isLost(error) + ? new McpResponseLostException(request.method(), error) + : error); + return listen ? sent : request.withRoundTimeout(sent); + } + + /** Whether a failure after dispatch broke the exchange, rather than answered it. */ + private static boolean isLost(Throwable error) { + if (error instanceof McpHttpStatusException status) { + return status.getStatus() == Status.CONNECTOR_ERROR_COMMUNICATION.getCode() + || status.getStatus() == Status.CONNECTOR_ERROR_INTERNAL.getCode(); + } + return error instanceof IOException; + } + + /** Sends the {@code Mcp-Param-*} headers of the tools' {@code x-mcp-header} arguments. */ + @Override + public boolean mirrorsToolParams() { + return true; + } + /** * Sends a request, and streams back the messages answering it: notifications, then its * response, after which the stream completes. Responses to other requests are dropped, and the * stream fails if it ends without its response. Cancelling the stream aborts the exchange. * * @param rpc The request. + * @param version The value of the {@code MCP-Protocol-Version} header. * @param name The value of the {@code Mcp-Name} header, or null. * @param params The values of the {@code Mcp-Param-*} headers, by name. * @param listen Whether this is a {@code subscriptions/listen} stream, without time limit. * @return The messages answering the request. */ public Flux send( - JsonRpc.JSONRPCRequest rpc, String name, Map params, boolean listen) { + JsonRpc.JSONRPCRequest rpc, + String version, + String name, + Map params, + boolean listen) { + return send( + rpc, + version, + name, + params, + listen, + listen ? null : timeout, + (error, sent) -> error); + } + + /** + * Sends a request within a time limit, or none, its failure mapped knowing whether the request + * reached the connector. + */ + private Flux send( + JsonRpc.JSONRPCRequest rpc, + String version, + String name, + Map params, + boolean listen, + Duration limit, + BiFunction failure) { return Flux.create( sink -> { AtomicReference active = new AtomicReference<>(); + AtomicBoolean dispatched = new AtomicBoolean(); Demand demand = new Demand(); sink.onRequest(demand::add); Emitter emitter = @@ -123,28 +211,46 @@ public Flux send( .submit( () -> exchange( - rpc, name, params, active, + rpc, + version, + name, + params, + active, + dispatched, emitter), - () -> abort(active.get())) - .subscribe(null, sink::error, sink::complete); + () -> abort(active.get()), + limit) + .subscribe( + null, + error -> + sink.error( + failure.apply( + error, + dispatched.get())), + sink::complete); sink.onCancel(running); }) // What follows runs off the worker, which then frees its slot without waiting. The - // worker reads only what this bounded queue has room for. - .publishOn(Schedulers.boundedElastic()); + // worker reads only what this bounded queue has room for. Each delivery runs on a + // thread of its own: a subscriber that cancels on the response, as the SDK's client + // does, and then blocks, such as an elicitation handler making a call, holds no + // pooled thread that the next exchange would wait behind. + .publishOn(DELIVERY); } private void exchange( JsonRpc.JSONRPCRequest rpc, + String version, String name, Map params, AtomicReference active, + AtomicBoolean dispatched, Emitter sink) throws IOException { if (closed) { throw new IOException("MCP client is closed"); } - Request request = request(rpc, name, params); + Request request = request(rpc, version, name, params); active.set(request); requests.add(request); Response response = null; @@ -153,6 +259,7 @@ private void exchange( request.abort(); throw new IOException("MCP exchange cancelled"); } + dispatched.set(true); response = client.handle(request); Representation entity = response.getEntity(); MediaType type = entity == null ? null : entity.getMediaType(); @@ -174,7 +281,8 @@ private void exchange( } } - private Request request(JsonRpc.JSONRPCRequest rpc, String name, Map params) + private Request request( + JsonRpc.JSONRPCRequest rpc, String version, String name, Map params) throws IOException { Request request = new Request( @@ -184,7 +292,7 @@ private Request request(JsonRpc.JSONRPCRequest rpc, String name, Map submit(Operation operation, Runnable cancel) { + return submit(operation, cancel, timeout); + } + + /** + * Submits a call with its own time limit instead of the workers' one. + * + * @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(Operation operation, Runnable cancel, Duration limit) { Mono call = Mono.create(sink -> admit(sink, operation, cancel)); - return timeout == null ? call : call.timeout(timeout); + return limit == null ? call : call.timeout(limit); } /** Admits a call, or refuses it at once; cancelling it interrupts its worker. */ diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpDualEraClientTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpDualEraClientTestCase.java index bc5bf1ffcf..660c440cd5 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpDualEraClientTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpDualEraClientTestCase.java @@ -228,7 +228,7 @@ void probesAgainWhenTheRememberedEraIsWrong() throws Exception { /** * The legacy edge declares no capability and refuses what a legacy server asks: an elicitation - * is never sent, and a ping from the server is refused, even with an input handler set. + * is never sent, and a ping from the server is refused, even with an elicitation handler set. */ @Test void refusesWhatALegacyServerAsks() throws Exception { @@ -238,18 +238,11 @@ void refusesWhatALegacyServerAsks() throws Exception { legacy.target, adapter -> { adapter.setLegacySessions(true); - adapter.setModernCapabilities( - io.modelcontextprotocol.modern.McpSchema.ClientCapabilities - .builder() - .elicitation( - new io.modelcontextprotocol.modern.McpSchema - .ClientCapabilities.Elicitation( - new io.modelcontextprotocol.modern - .McpSchema.ClientCapabilities - .Elicitation.Form(), - null)) - .build()); - adapter.setInputHandler(required -> Mono.just(Map.of())); + adapter.setFormElicitation( + request -> + Mono.just( + io.modelcontextprotocol.modern.McpSchema + .ElicitResult.decline())); }); assertEquals(List.of(Map.of()), legacy.host.capabilities); 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 c7436f842a..6fd85ad011 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 @@ -15,16 +15,19 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import io.modelcontextprotocol.modern.JsonRpc; import io.modelcontextprotocol.modern.McpException; import io.modelcontextprotocol.modern.McpSchema; import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome; -import io.modelcontextprotocol.modern.McpSchema.CallToolRequest; import io.modelcontextprotocol.modern.McpSchema.CallToolResult; import io.modelcontextprotocol.modern.McpSchema.ElicitFormRequest; +import io.modelcontextprotocol.modern.McpSchema.ElicitResult; import io.modelcontextprotocol.modern.McpSchema.InputRequiredResult; import io.modelcontextprotocol.modern.McpSchema.TextContent; import io.modelcontextprotocol.modern.McpSchema.Tool; +import io.modelcontextprotocol.modern.client.McpAsyncClient; +import io.modelcontextprotocol.modern.client.McpAsyncElicitationHandler; +import io.modelcontextprotocol.modern.client.McpTimeoutException; +import io.modelcontextprotocol.modern.client.SubscriptionEvent; import io.modelcontextprotocol.modern.server.McpAsyncResponse; import io.modelcontextprotocol.modern.server.feature.McpAsyncPrompt; import io.modelcontextprotocol.modern.server.feature.McpAsyncResource; @@ -51,8 +54,8 @@ /** * {@link McpClientAdapter} speaking MCP {@code 2026-07-28} to {@link McpServerAdapter} over real - * HTTP connectors: discovery, listings, calls, streamed progress, {@code input_required} retries, - * {@code subscriptions/listen} and cancellation. + * HTTP connectors, through the SDK's client: discovery, listings, calls, streamed progress, {@code + * input_required} retries, {@code subscriptions/listen} and cancellation. */ class McpModernClientTestCase { private static final Duration WAIT = Duration.ofSeconds(10); @@ -100,119 +103,130 @@ void discoversAndCallsOverHttp2() throws Exception { /** Discovery, then the tools, resources and prompts of both revisions' registrations. */ private void discoversAndCalls(String mode) throws Exception { - McpModernClient modern = start(mode, null); + McpAsyncClient modern = start(mode, null); McpSchema.DiscoverResult discovered = modern.discover().block(WAIT); assertEquals(List.of(McpProtocol.MODERN_VERSION), discovered.supportedVersions()); + // The SDK's client leaves out a tool it can't call, such as level, whose header argument + // is a number. assertEquals( - List.of("echo", "progress", "approve", "endless", "region", "level"), - modern.listTools(null).block(WAIT).tools().stream().map(Tool::name).toList()); + List.of("echo", "progress", "approve", "endless", "region", "slow"), + modern.tools().list().block(WAIT).tools().stream().map(Tool::name).toList()); assertEquals( "echo:café", - text( - modern.callTool( - new CallToolRequest( - "echo", Map.of("text", "café"), null, null, null)) - .block(WAIT))); + text(modern.tool("echo").arguments(Map.of("text", "café")).call().block(WAIT))); assertEquals( List.of("test://modern"), - modern.listResources(null).block(WAIT).resources().stream() + modern.resources().list().block(WAIT).resources().stream() .map(McpSchema.Resource::uri) .toList()); - McpSchema.ReadResourceResult read = - (McpSchema.ReadResourceResult) - modern.readResource( - new McpSchema.ReadResourceRequest( - "test://modern", null, null, null), - null) - .block(WAIT); + McpSchema.ReadResourceResult read = modern.resource("test://modern").read().block(WAIT); assertEquals( "modern", ((McpSchema.TextResourceContents) read.contents().getFirst()).text()); assertEquals( List.of("welcome"), - modern.listPrompts(null).block(WAIT).prompts().stream() + modern.prompts().list().block(WAIT).prompts().stream() .map(McpSchema.Prompt::name) .toList()); - McpSchema.GetPromptResult prompt = - (McpSchema.GetPromptResult) - modern.getPrompt( - new McpSchema.GetPromptRequest( - "welcome", null, null, null, null), - null) - .block(WAIT); - assertEquals("modern welcome", prompt.description()); + assertEquals("modern welcome", modern.prompt("welcome").get().block(WAIT).description()); } - /** A call's progress notifications reach its consumer before its result. */ + /** The adapter's convenience methods go through the SDK's client. */ + @Test + void theAdapterCallsThroughTheSdkClient() throws Exception { + start("HTTP2", null); + + assertEquals(6, client.listTools(null).tools().size()); + assertEquals("echo:hi", text(client.callTool("echo", Map.of("text", "hi")))); + assertEquals( + "modern", + ((McpSchema.TextResourceContents) + client.readResource("test://modern").contents().getFirst()) + .text()); + assertEquals("modern welcome", client.getPrompt("welcome", null).description()); + // Without an elicitation handler, the client declares no elicitation capability, and the + // server refuses to ask for one. + McpException refused = + assertThrows(McpException.class, () -> client.callTool("approve", null)); + assertEquals(McpSchema.ErrorCodes.INTERNAL_ERROR, refused.error().code().intValue()); + } + + /** A call's progress notifications reach its listener before its result. */ @Test void streamsProgress() throws Exception { - McpModernClient modern = start("HTTP2", null); + McpAsyncClient modern = start("HTTP2", null); List progress = new CopyOnWriteArrayList<>(); - CallToolOutcome outcome = - modern.callTool( - new CallToolRequest("progress", Map.of(), null, null, null), - update -> progress.add(update.message())) + CallToolResult result = + modern.tool("progress") + .progress( + update -> { + progress.add(update.message()); + return Mono.empty(); + }) + .call() .block(WAIT); - assertEquals("done", text(outcome)); + assertEquals("done", text(result)); assertEquals(List.of("half"), progress); } - /** Without a handler, an input_required result is returned; with one, the call is retried. */ + /** + * A single round returns an input_required result, for the caller to answer; a call answers it + * with the form elicitation handler, which also declares the capability the server requires. + */ @Test void answersInputRequired() throws Exception { - McpModernClient modern = start("HTTP2", null); - CallToolRequest approve = new CallToolRequest("approve", Map.of(), null, null, null); + List asked = new CopyOnWriteArrayList<>(); + McpAsyncClient modern = + start( + "HTTP2", + request -> { + asked.add(request.message()); + return Mono.just(ElicitResult.accept(Map.of())); + }); InputRequiredResult required = - assertInstanceOf(InputRequiredResult.class, modern.callTool(approve).block(WAIT)); + assertInstanceOf( + InputRequiredResult.class, modern.tool("approve").callOnce().block(WAIT)); assertNotNull(required.requestState()); // Sealed by the server. assertTrue(required.inputRequests().containsKey("confirm")); assertEquals( "approved:s1", text( - modern.callTool( - new CallToolRequest( - "approve", - Map.of(), - Map.of("confirm", accepted()), - required.requestState(), - null)) + modern.tool("approve") + .inputResponses(Map.of("confirm", accepted())) + .requestState(required.requestState()) + .call() .block(WAIT))); + assertEquals(List.of(), asked); - client.stop(); - McpModernClient handled = - start("HTTP2", result -> Mono.just(Map.of("confirm", accepted()))); - assertEquals("approved:s1", text(handled.callTool(approve).block(WAIT))); + assertEquals("approved:s1", text(modern.tool("approve").call().block(WAIT))); + assertEquals(List.of("Proceed?"), asked); } /** A listen stream carries the changes published, and completes when the server stops. */ @Test void listensToChanges() throws Exception { - McpModernClient modern = start("HTTP2", null); - BlockingQueue changes = new LinkedBlockingQueue<>(); + McpAsyncClient modern = start("HTTP2", null); + BlockingQueue changes = new LinkedBlockingQueue<>(); CountDownLatch completed = new CountDownLatch(1); List errors = new CopyOnWriteArrayList<>(); Disposable listening = - modern.listen( - McpSchema.SubscriptionFilter.of( - Map.of( - McpSchema.SubscriptionFilter.TOOLS_LIST_CHANGED, - true))) + modern.listen() + .toolsChanged() + .events() + .filter(SubscriptionEvent.ToolsListChanged.class::isInstance) .doOnComplete(completed::countDown) .subscribe(changes::add, errors::add); try { // The listen stream opens asynchronously: publish until the change arrives. - JsonRpc.JSONRPCNotification change = null; + SubscriptionEvent change = null; for (int i = 0; i < 200 && change == null; i++) { adapter.getChanges().broadcast(new ServerChange.ToolsListChanged()); change = changes.poll(50, TimeUnit.MILLISECONDS); } - assertEquals( - McpSchema.METHOD_NOTIFICATION_TOOLS_LIST_CHANGED, - change == null ? null : change.method(), - errors.toString()); + assertInstanceOf(SubscriptionEvent.ToolsListChanged.class, change, errors.toString()); adapter.stop(); assertTrue(completed.await(10, TimeUnit.SECONDS), "the listen stream did not end"); @@ -225,13 +239,17 @@ void listensToChanges() throws Exception { /** Cancelling a call aborts its exchange, which cancels the tool on the server. */ @Test void cancellingACallCancelsTheTool() throws Exception { - McpModernClient modern = start("HTTP2", null); + McpAsyncClient modern = start("HTTP2", null); CountDownLatch started = new CountDownLatch(1); Disposable call = - modern.callTool( - new CallToolRequest("endless", Map.of(), null, null, null), - update -> started.countDown()) + modern.tool("endless") + .progress( + update -> { + started.countDown(); + return Mono.empty(); + }) + .call() .subscribe(); assertTrue(started.await(10, TimeUnit.SECONDS), "the tool did not start"); call.dispose(); @@ -239,104 +257,97 @@ void cancellingACallCancelsTheTool() throws Exception { assertTrue(cancelled.await(10, TimeUnit.SECONDS), "the tool was not cancelled"); assertEquals( "echo:after", - text( - modern.callTool( - new CallToolRequest( - "echo", Map.of("text", "after"), null, null, null)) - .block(WAIT))); + text(modern.tool("echo").arguments(Map.of("text", "after")).call().block(WAIT))); } - /** A listed tool's x-mcp-header arguments are mirrored into Mcp-Param headers. */ + /** + * A tool's x-mcp-header arguments are mirrored into Mcp-Param headers, the client listing the + * tools it doesn't know first. + */ @Test void mirrorsAnnotatedArguments() throws Exception { - McpModernClient modern = start("HTTP2", null); - CallToolRequest region = - new CallToolRequest("region", Map.of("region", "eu"), null, null, null); + McpAsyncClient modern = start("HTTP2", null); - Mono unlistedCall = modern.callTool(region); - McpException unlisted = assertThrows(McpException.class, () -> unlistedCall.block(WAIT)); - assertEquals(McpSchema.ErrorCodes.HEADER_MISMATCH, unlisted.error().code().intValue()); - - modern.listTools(null).block(WAIT); - assertEquals("region:eu", text(modern.callTool(region).block(WAIT))); + assertEquals( + "region:eu", + text(modern.tool("region").arguments(Map.of("region", "eu")).call().block(WAIT))); + assertEquals( + "region:us", + text(modern.tool("region").arguments(Map.of("region", "us")).call().block(WAIT))); } /** - * With a single call slot, an input handler may make a blocking call: the first call no longer - * holds its slot, nor runs the handler on its interrupted worker. + * With a single call slot, an elicitation handler may make a blocking call: the first call no + * longer holds its slot. */ @Test - void anInputHandlerMayCallWithOneSlot() throws Exception { - AtomicReference holder = new AtomicReference<>(); + void anElicitationHandlerMayCallWithOneSlot() throws Exception { + AtomicReference holder = new AtomicReference<>(); List nested = new CopyOnWriteArrayList<>(); - McpModernClient modern = + McpAsyncClient modern = start( "HTTP2", - required -> + request -> Mono.fromCallable( () -> { nested.add( text( holder.get() - .callTool( - new CallToolRequest( - "echo", - Map.of( - "text", - "nested"), - null, - null, - null)) + .tool("echo") + .arguments( + Map.of( + "text", + "nested")) + .call() .block(WAIT))); - return Map.of("confirm", accepted()); + return ElicitResult.accept(Map.of()); }), configured -> configured.setMaxConcurrentCalls(1)); holder.set(modern); - assertEquals( - "approved:s1", - text( - modern.callTool(new CallToolRequest("approve", Map.of(), null, null, null)) - .block(WAIT))); + assertEquals("approved:s1", text(modern.tool("approve").call().block(WAIT))); assertEquals(List.of("echo:nested"), nested); } - /** A call's headers are worked out when it is sent, after a listing chained before it. */ + /** + * A tool whose x-mcp-header argument is a number isn't called: the SDK's client mirrors only + * strings, integers and booleans. + */ @Test - void headersFollowAChainedListing() throws Exception { - McpModernClient modern = start("HTTP2", null); - CallToolRequest region = - new CallToolRequest("region", Map.of("region", "eu"), null, null, null); + void aToolWithANumberHeaderIsNotCalled() throws Exception { + McpAsyncClient modern = start("HTTP2", null); - assertEquals( - "region:eu", - text(modern.listTools(null).then(modern.callTool(region)).block(WAIT))); + Mono level = modern.tool("level").arguments(Map.of("level", 1.0e7)).call(); + IllegalArgumentException refused = + assertThrows(IllegalArgumentException.class, () -> level.block(WAIT)); + assertTrue(refused.getMessage().contains("unsupported type number"), refused.getMessage()); } - /** A number argument is mirrored in plain decimal notation. */ + /** + * The SDK's round timeout is a request's only time limit: the adapter's request timeout is its + * default, and a longer one given for a call lets it run past it. + */ @Test - void mirrorsNumbersInPlainNotation() throws Exception { - McpModernClient modern = start("HTTP2", null); - modern.listTools(null).block(WAIT); - - assertEquals( - "level:1.0E7", - text( - modern.callTool( - new CallToolRequest( - "level", Map.of("level", 1.0e7), null, null, null)) - .block(WAIT))); + void theRoundTimeoutLimitsACall() throws Exception { + McpAsyncClient modern = + start( + "HTTP2", + null, + configured -> configured.setRequestTimeout(Duration.ofMillis(300))); + + Mono cut = modern.tool("slow").call(); + McpTimeoutException timeout = + assertThrows(McpTimeoutException.class, () -> cut.block(WAIT)); + assertEquals(McpTimeoutException.Kind.ROUND, timeout.kind()); + assertEquals("slow", text(modern.tool("slow").roundTimeout(WAIT).call().block(WAIT))); } /** An error response fails the request with its JSON-RPC error. */ @Test void anErrorResponseFails() throws Exception { - McpModernClient modern = start("HTTP2", null); + McpAsyncClient modern = start("HTTP2", null); - Mono missing = - modern.readResource( - new McpSchema.ReadResourceRequest("test://missing", null, null, null), - null); + Mono missing = modern.resource("test://missing").read(); McpException error = assertThrows(McpException.class, () -> missing.block(WAIT)); assertEquals(McpSchema.ErrorCodes.INVALID_PARAMS, error.error().code().intValue()); } @@ -347,6 +358,8 @@ void modernModeLimits() throws Exception { start("HTTP2", null); client.stop(); assertFalse(client.isStarted()); + assertThrows(IllegalStateException.class, client::getModernClient); + assertThrows(IllegalStateException.class, client::getTasksClient); McpClientAdapter stdio = new McpClientAdapter(connector, "stdio://localhost/mcp"); stdio.setProtocolVersion(McpProtocol.MODERN_VERSION); @@ -354,15 +367,20 @@ void modernModeLimits() throws Exception { McpClientAdapter unknown = new McpClientAdapter(connector, "http://localhost/mcp"); assertThrows( IllegalArgumentException.class, () -> unknown.setProtocolVersion("2024-11-05")); + assertThrows(IllegalArgumentException.class, () -> unknown.setMaxInputRounds(0)); } - /** Starts the server, if needed, and a modern client with an optional input handler. */ - private McpModernClient start(String mode, McpInputHandler inputHandler) throws Exception { - return start(mode, inputHandler, ignored -> {}); + /** Starts the server, if needed, and a modern client with an optional form handler. */ + private McpAsyncClient start( + String mode, McpAsyncElicitationHandler form) + throws Exception { + return start(mode, form, ignored -> {}); } - private McpModernClient start( - String mode, McpInputHandler inputHandler, Consumer configure) + private McpAsyncClient start( + String mode, + McpAsyncElicitationHandler form, + Consumer configure) throws Exception { if (adapter == null) { adapter = adapter(); @@ -380,13 +398,7 @@ private McpModernClient start( new McpClientAdapter( connector, "http://localhost:" + server.getActualPort() + "/mcp"); client.setProtocolVersion(McpProtocol.MODERN_VERSION); - client.setModernCapabilities( - McpSchema.ClientCapabilities.builder() - .elicitation( - new McpSchema.ClientCapabilities.Elicitation( - new McpSchema.ClientCapabilities.Elicitation.Form(), null)) - .build()); - client.setInputHandler(inputHandler); + client.setFormElicitation(form); configure.accept(client); client.start(); return client.getModernClient(); @@ -497,6 +509,15 @@ private McpServerAdapter adapter() throws Exception { "level:" + request.arguments() .get("level")))))); + served.getTools() + .add( + McpAsyncTool.of( + Tool.builder("slow", Map.of("type", "object")).build(), + (ctx, request) -> + Mono.delay(Duration.ofMillis(900)) + .thenReturn( + McpAsyncResponse.result( + result("slow"))))); served.getResources() .add( new McpResource( 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 9f5c63869b..cd2474fd81 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 @@ -16,8 +16,12 @@ import io.modelcontextprotocol.json.McpJsonDefaults; import io.modelcontextprotocol.modern.JsonRpc; +import io.modelcontextprotocol.modern.client.McpResponseLostException; +import io.modelcontextprotocol.modern.client.transport.McpTransportRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -36,6 +40,7 @@ import org.restlet.Server; import org.restlet.data.MediaType; import org.restlet.data.Protocol; +import org.restlet.ext.mcp.internal.McpHttpStatusException; import org.restlet.ext.mcp.internal.McpMessages; import org.restlet.ext.mcp.internal.McpModernHttpTransport; import org.restlet.representation.ByteArrayRepresentation; @@ -113,6 +118,98 @@ void aStreamWithoutItsResponseFails() throws Exception { assertTrue(failure.getMessage().contains("without a response"), failure.getMessage()); } + /** + * To the SDK's client, an exchange broken before its response is lost, as its transport + * contract says, while an HTTP failure keeps its status. + */ + @Test + void theSdkClientSeesABrokenExchangeAsLost() throws Exception { + start(1024, 1); + reply = events(NOTIFICATION); + JsonRpc.JSONRPCRequest rpc = new JsonRpc.JSONRPCRequest("tools/list", 1L, Map.of()); + McpTransportRequest request = + McpTransportRequest.builder(rpc, McpProtocol.MODERN_VERSION).build(); + + Flux broken = transport.exchange(request); + McpResponseLostException lost = + assertThrows(McpResponseLostException.class, () -> block(broken)); + assertInstanceOf(IOException.class, lost.getCause()); + + type = MediaType.TEXT_PLAIN; + Flux refused = transport.exchange(request); + assertThrows(McpHttpStatusException.class, () -> block(refused)); + assertTrue(transport.mirrorsToolParams()); + } + + /** + * A request refused before it is sent, over the size limit or by a closed transport, fails as + * it is: nothing was lost, and a client retrying lost exchanges would only be refused again. + */ + @Test + void aRequestRefusedBeforeItIsSentIsNotLost() throws Exception { + start(64, 1); + McpTransportRequest big = + McpTransportRequest.builder( + new JsonRpc.JSONRPCRequest( + "tools/list", 1L, Map.of("pad", "x".repeat(200))), + McpProtocol.MODERN_VERSION) + .build(); + Flux oversized = transport.exchange(big); + Exception refused = assertThrows(Exception.class, () -> block(oversized)); + assertFalse(refused instanceof McpResponseLostException, refused.toString()); + assertInstanceOf(IOException.class, refused); + + transport.close(); + McpTransportRequest small = + McpTransportRequest.builder( + new JsonRpc.JSONRPCRequest("tools/list", 2L, Map.of()), + McpProtocol.MODERN_VERSION) + .build(); + Flux closed = transport.exchange(small); + Exception closedFailure = assertThrows(Exception.class, () -> block(closed)); + assertFalse(closedFailure instanceof McpResponseLostException, closedFailure.toString()); + assertInstanceOf(IOException.class, closedFailure); + } + + /** A connection the server closes before the response's head is lost to the SDK's client. */ + @Test + void aConnectionLostBeforeTheResponseIsLost() throws Exception { + start(1024, 1); + try (ServerSocket closing = new ServerSocket(0)) { + Thread acceptor = + Thread.ofVirtual() + .start( + () -> { + try (Socket socket = closing.accept()) { + socket.getInputStream().read(new byte[1024]); + } catch (IOException ignored) { + // The connection is closed either way. + } + }); + McpModernHttpTransport dropped = + new McpModernHttpTransport( + connector, + "http://localhost:" + closing.getLocalPort() + "/mcp", + McpJsonDefaults.getMapper(), + 1024, + 1, + WAIT, + ignored -> {}); + try { + McpTransportRequest request = + McpTransportRequest.builder( + new JsonRpc.JSONRPCRequest("tools/list", 1L, Map.of()), + McpProtocol.MODERN_VERSION) + .build(); + Flux sent = dropped.exchange(request); + assertThrows(McpResponseLostException.class, () -> block(sent)); + } finally { + dropped.close(); + acceptor.join(WAIT); + } + } + } + @Test void aJsonReplyMustBeItsResponse() throws Exception { start(1024, 1); @@ -235,7 +332,11 @@ public void handle(Request request, Response response) { private Flux send(long id) { return transport.send( - new JsonRpc.JSONRPCRequest("tools/call", id, Map.of()), null, Map.of(), false); + new JsonRpc.JSONRPCRequest("tools/call", id, Map.of()), + McpProtocol.MODERN_VERSION, + null, + Map.of(), + false); } /** Blocks on a stream, rethrowing the checked exception it failed with. */ diff --git a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpTasksTestCase.java b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpTasksTestCase.java index d9ef9cf1dc..5ddf5ea641 100644 --- a/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpTasksTestCase.java +++ b/org.restlet.ext.mcp/src/test/java/org/restlet/ext/mcp/McpTasksTestCase.java @@ -22,8 +22,11 @@ import io.modelcontextprotocol.modern.McpSchema; import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome; import io.modelcontextprotocol.modern.McpSchema.CallToolRequest; +import io.modelcontextprotocol.modern.McpSchema.ElicitFormRequest; +import io.modelcontextprotocol.modern.McpSchema.ElicitResult; import io.modelcontextprotocol.modern.McpSchema.MetaKeys; import io.modelcontextprotocol.modern.McpSchema.Tool; +import io.modelcontextprotocol.modern.client.McpAsyncElicitationHandler; import io.modelcontextprotocol.modern.server.McpAsyncResponse; import io.modelcontextprotocol.modern.server.feature.McpAsyncTool; import java.io.ByteArrayOutputStream; @@ -264,16 +267,16 @@ void applicationSettingsForTheExtensionAreKept() throws Exception { @Test void theClientAwaitsATaskAnsweringItsQuestions() throws Exception { store.askFirst = true; - List> asked = new CopyOnWriteArrayList<>(); - McpModernClient modern = + List asked = new CopyOnWriteArrayList<>(); + McpTasksClient modern = start( - required -> { - asked.add(MAPPER.convertValue(required, new TypeRef<>() {})); - return Mono.just(Map.of("confirm", Map.of("action", "accept"))); + request -> { + asked.add(request); + return Mono.just(new ElicitResult(ElicitResult.Action.ACCEPT, null)); }); CallToolOutcome outcome = - modern.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + modern.callTool(new CallToolRequest("slow", Map.of(), null, null, null), null) .block(WAIT); McpTaskResult task = assertInstanceOf(McpTaskResult.class, outcome); assertEquals("t-1", task.task().taskId()); @@ -283,14 +286,134 @@ void theClientAwaitsATaskAnsweringItsQuestions() throws Exception { "done", firstText(MAPPER.convertValue(done, new TypeRef>() {}))); assertEquals(1, asked.size(), asked.toString()); - assertTrue(((Map) asked.get(0).get("inputRequests")).containsKey("confirm")); + assertEquals("Proceed?", asked.get(0).message()); assertEquals(Map.of("confirm", Map.of("action", "accept")), store.answers.get("t-1")); } + /** + * The tasks client answers a call's questions with the form handler, and mirrors the arguments + * the definition given annotates; without it, the server finds the header missing. + */ + @Test + void theTasksClientAnswersACallsQuestions() throws Exception { + List asked = new CopyOnWriteArrayList<>(); + McpTasksClient tasks = + start( + request -> { + asked.add(request.message()); + return Mono.just(ElicitResult.accept(Map.of())); + }); + Tool gated = gatedTool(); + CallToolRequest call = + new CallToolRequest("gated", Map.of("region", "eu"), null, null, null); + + assertEquals( + "gated:eu:accept", + firstText( + MAPPER.convertValue( + tasks.callTool(call, gated).block(WAIT), + new TypeRef>() {}))); + assertEquals(List.of("Proceed?"), asked); + Mono unmirrored = tasks.callTool(call, null); + McpException mismatch = assertThrows(McpException.class, () -> unmirrored.block(WAIT)); + assertEquals(McpSchema.ErrorCodes.HEADER_MISMATCH, mismatch.error().code().intValue()); + } + + /** + * A call's question goes back to the caller when the handler gives no answer, and past the + * round limit. + */ + @Test + void theTasksClientHandsBackUnansweredQuestions() throws Exception { + CallToolRequest call = + new CallToolRequest("gated", Map.of("region", "eu"), null, null, null); + McpTasksClient silent = start(request -> Mono.empty()); + assertInstanceOf( + McpSchema.InputRequiredResult.class, + silent.callTool(call, gatedTool()).block(WAIT)); + cleanup(); + + List rounds = new CopyOnWriteArrayList<>(); + McpTasksClient limited = + start( + request -> { + rounds.add("asked"); + return Mono.just(ElicitResult.accept(Map.of())); + }, + client -> client.setMaxInputRounds(1)); + assertEquals( + "gated:eu:accept", + firstText( + MAPPER.convertValue( + limited.callTool(call, gatedTool()).block(WAIT), + new TypeRef>() {}))); + assertEquals(1, rounds.size()); + CallToolRequest loop = + new CallToolRequest("gated", Map.of("region", "loop"), null, null, null); + McpSchema.InputRequiredResult again = + assertInstanceOf( + McpSchema.InputRequiredResult.class, + limited.callTool(loop, gatedTool()).block(WAIT)); + assertTrue(again.inputRequests().containsKey("confirm")); + assertEquals(2, rounds.size()); // One more round, then the limit. + } + + /** + * A result asking for no input, only for a retry with its request state, is retried; a tool + * whose header annotation is invalid isn't called. + */ + @Test + void theTasksClientRetriesStateOnlyRoundsAndRefusesInvalidTools() throws Exception { + McpTasksClient tasks = start(null); + CallToolRequest state = + new CallToolRequest("gated", Map.of("region", "state"), null, null, null); + + assertEquals( + "gated:state:none", + firstText( + MAPPER.convertValue( + tasks.callTool(state, gatedTool()).block(WAIT), + new TypeRef>() {}))); + assertEquals(Duration.ofMillis(50), McpTasksClient.backoff(1)); + assertEquals(Duration.ofMillis(100), McpTasksClient.backoff(2)); + assertEquals(Duration.ofMillis(250), McpTasksClient.backoff(9)); + + Tool numbered = + Tool.builder( + "gated", + Map.of( + "type", + "object", + "properties", + Map.of( + "region", + Map.of( + "type", + "number", + "x-mcp-header", + "Region")))) + .build(); + Mono invalid = + tasks.callTool( + new CallToolRequest("gated", Map.of("region", 1.5), null, null, null), + numbered); + IllegalArgumentException refused = + assertThrows(IllegalArgumentException.class, () -> invalid.block(WAIT)); + assertTrue(refused.getMessage().contains("unsupported type number"), refused.getMessage()); + } + + /** The definition of the gated tool, as the SDK's client lists it. */ + private Tool gatedTool() { + return client.getModernClient().tools().list().block(WAIT).tools().stream() + .filter(tool -> "gated".equals(tool.name())) + .findFirst() + .orElseThrow(); + } + /** Waiting for a task through thousands of polls grows neither the stack nor the chain. */ @Test void theClientAwaitsThroughManyPolls() throws Exception { - McpModernClient modern = start(null); + McpTasksClient modern = start(null); long few = depthAfter(modern, 5); long many = depthAfter(modern, 300); @@ -301,12 +424,14 @@ void theClientAwaitsThroughManyPolls() throws Exception { } /** The stack depth at which the result of a wait through {@code polls} polls arrives. */ - private long depthAfter(McpModernClient modern, int polls) { + private long depthAfter(McpTasksClient modern, int polls) { store.workingPolls.set(polls); McpTaskResult task = assertInstanceOf( McpTaskResult.class, - modern.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + modern.callTool( + new CallToolRequest("slow", Map.of(), null, null, null), + null) .block(WAIT)); return modern.awaitTask(task, 0) .map( @@ -328,22 +453,24 @@ private long depthAfter(McpModernClient modern, int polls) { @Test void theClientHandsBackATaskWaitingOnInput() throws Exception { store.askFirst = true; - McpModernClient bare = start(null); + McpTasksClient bare = start(null); McpTaskResult first = assertInstanceOf( McpTaskResult.class, - bare.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + bare.callTool(new CallToolRequest("slow", Map.of(), null, null, null), null) .block(WAIT)); McpTaskResult waiting = assertInstanceOf(McpTaskResult.class, bare.awaitTask(first).block(WAIT)); assertEquals(McpTask.Status.INPUT_REQUIRED, waiting.task().status()); cleanup(); - McpModernClient silent = start(required -> Mono.empty()); + McpTasksClient silent = start(request -> Mono.empty()); McpTaskResult second = assertInstanceOf( McpTaskResult.class, - silent.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + silent.callTool( + new CallToolRequest("slow", Map.of(), null, null, null), + null) .block(WAIT)); assertEquals( McpTask.Status.INPUT_REQUIRED, @@ -354,17 +481,19 @@ void theClientHandsBackATaskWaitingOnInput() throws Exception { store.askAlways = true; List rounds = new CopyOnWriteArrayList<>(); - McpModernClient limited = + McpTasksClient limited = start( - required -> { + request -> { rounds.add("asked"); - return Mono.just(Map.of("confirm", Map.of("action", "accept"))); + return Mono.just(new ElicitResult(ElicitResult.Action.ACCEPT, null)); }, client -> client.setMaxInputRounds(2)); McpTaskResult third = assertInstanceOf( McpTaskResult.class, - limited.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + limited.callTool( + new CallToolRequest("slow", Map.of(), null, null, null), + null) .block(WAIT)); assertEquals( McpTask.Status.INPUT_REQUIRED, @@ -414,9 +543,9 @@ void theGuardCoversStreamedTasks() throws Exception { /** The client's task methods, and a failed or cancelled task ending the wait with an error. */ @Test void theClientReportsFailedAndCancelledTasks() throws Exception { - McpModernClient modern = start(null); + McpTasksClient modern = start(null); CallToolOutcome outcome = - modern.callTool(new CallToolRequest("slow", Map.of(), null, null, null)) + modern.callTool(new CallToolRequest("slow", Map.of(), null, null, null), null) .block(WAIT); McpTaskResult task = assertInstanceOf(McpTaskResult.class, outcome); @@ -637,10 +766,76 @@ private McpServerAdapter adapter() { McpProtocol .CONTEXT_KEY))) : McpTestFeatures.text("done"))))); + adapter.getTools().add(gated()); adapter.setTaskStore(store); return adapter; } + /** + * A tool whose region argument is mirrored in a header, asking to confirm first, or again and + * again for the region "loop", then answering with the region and the confirmation. + */ + private static McpAsyncTool gated() { + return McpAsyncTool.of( + Tool.builder( + "gated", + Map.of( + "type", + "object", + "properties", + Map.of( + "region", + Map.of( + "type", + "string", + "x-mcp-header", + "Region")))) + .build(), + (ctx, request) -> { + Object region = request.arguments().get("region"); + if ("state".equals(region) && request.requestState() == null) { + // Asks for nothing, only for a retry with its state. + return Mono.just( + McpAsyncResponse.result( + McpSchema.InputRequiredResult.builder() + .requestState("s0") + .build())); + } + if ("state".equals(region)) { + return Mono.just( + McpAsyncResponse.result( + McpTestFeatures.text( + request.inputResponses() == null + ? "gated:state:none" + : "gated:state:answered"))); + } + CallToolOutcome outcome = + request.requestState() == null || "loop".equals(region) + ? McpSchema.InputRequiredResult.builder() + .elicit( + "confirm", + ElicitFormRequest.builder( + "Proceed?", + Map.of( + "type", + "object", + "properties", + Map.of())) + .build()) + .requestState("s1") + .build() + : McpTestFeatures.text( + "gated:" + + request.arguments().get("region") + + ":" + + ((Map) + request.inputResponses() + .get("confirm")) + .get("action")); + return Mono.just(McpAsyncResponse.result(outcome)); + }); + } + private static McpAsyncTool alwaysTask() { return McpAsyncTool.of( Tool.builder("always", Map.of("type", "object")).build(), @@ -651,12 +846,14 @@ private static McpAsyncTool alwaysTask() { McpTask.working("t-1", CREATED, null, null))))); } - private McpModernClient start(McpInputHandler inputHandler) throws Exception { - return start(inputHandler, ignored -> {}); + private McpTasksClient start(McpAsyncElicitationHandler form) + throws Exception { + return start(form, ignored -> {}); } - private McpModernClient start( - McpInputHandler inputHandler, java.util.function.Consumer configure) + private McpTasksClient start( + McpAsyncElicitationHandler form, + java.util.function.Consumer configure) throws Exception { McpServerAdapter adapter = adapter(); adapter.start(); @@ -670,17 +867,10 @@ private McpModernClient start( new McpClientAdapter( connector, "http://localhost:" + server.getActualPort() + "/mcp"); client.setProtocolVersion(MODERN); - client.setModernCapabilities( - McpSchema.ClientCapabilities.builder() - .elicitation( - new McpSchema.ClientCapabilities.Elicitation( - new McpSchema.ClientCapabilities.Elicitation.Form(), null)) - .extensions(Map.of(McpTask.EXTENSION_ID, Map.of())) - .build()); - client.setInputHandler(inputHandler); + client.setFormElicitation(form); configure.accept(client); client.start(); - return client.getModernClient(); + return client.getTasksClient(); } private Map call(