Skip to content

Commit dfc589d

Browse files
bhuvnshclaude
andcommitted
Add McpServerTool shortcuts for registering tools on the modern server
Registering one tool on the modern server meant implementing a whole McpSyncToolRepository, wrapping it in a ToolsFeature and registering the feature. McpServer.Builder#tool now takes an McpServerTool (a Tool and its handler) and serves all of them through one ToolsFeature built at build(), so argument and output validation still apply. Duplicate and invalid tool names fail at registration, and combining tool(...) with another feature serving tools/* fails build() with a message naming the shortcut. ToolsFeature.ofTools(...) serves a fixed set of tools for users who need custom cache hints or a validator. Tools only; prompts, resources, templates and completions would follow the same shape. See #1200. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 54e8b61 commit dfc589d

9 files changed

Lines changed: 595 additions & 0 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/modern/server/McpServer.java‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import io.modelcontextprotocol.json.McpJsonDefaults;
1818
import io.modelcontextprotocol.json.McpJsonMapper;
1919
import io.modelcontextprotocol.json.TypeRef;
20+
import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
2021
import io.modelcontextprotocol.modern.JsonRpc.JSONRPCMessage;
2122
import io.modelcontextprotocol.modern.JsonRpc.JSONRPCNotification;
2223
import io.modelcontextprotocol.modern.JsonRpc.JSONRPCRequest;
@@ -35,6 +36,8 @@
3536
import io.modelcontextprotocol.modern.McpSchema.ServerCapabilities;
3637
import io.modelcontextprotocol.modern.McpSchema.UnsupportedProtocolVersionData;
3738
import io.modelcontextprotocol.modern.server.feature.McpChangePublisher;
39+
import io.modelcontextprotocol.modern.server.feature.McpServerTool;
40+
import io.modelcontextprotocol.modern.server.feature.ToolsFeature;
3841
import io.modelcontextprotocol.util.Assert;
3942
import org.slf4j.Logger;
4043
import org.slf4j.LoggerFactory;
@@ -338,6 +341,10 @@ public static final class Builder {
338341

339342
private final List<McpFeature> features = new ArrayList<>();
340343

344+
private final Map<String, McpServerTool> tools = new LinkedHashMap<>();
345+
346+
private JsonSchemaValidator jsonSchemaValidator;
347+
341348
private long discoverTtlMs = 0L;
342349

343350
private CacheScope discoverCacheScope = CacheScope.PRIVATE;
@@ -382,6 +389,34 @@ public Builder features(List<? extends McpFeature> features) {
382389
return this;
383390
}
384391

392+
/**
393+
* Registers a tool, served in registration order by a {@link ToolsFeature} built
394+
* at {@link #build()}. No other feature may serve {@code tools/*} then.
395+
*/
396+
public Builder tool(McpServerTool tool) {
397+
Assert.notNull(tool, "tool must not be null");
398+
if (this.tools.putIfAbsent(tool.tool().name(), tool) != null) {
399+
throw new IllegalArgumentException("Tool '" + tool.tool().name() + "' is already registered");
400+
}
401+
return this;
402+
}
403+
404+
public Builder tools(List<McpServerTool> tools) {
405+
Assert.notNull(tools, "tools must not be null");
406+
tools.forEach(this::tool);
407+
return this;
408+
}
409+
410+
/**
411+
* The validator for the arguments and structured output of tools registered with
412+
* {@link #tool}. Defaults to {@link McpJsonDefaults#getSchemaValidator()}.
413+
*/
414+
public Builder jsonSchemaValidator(JsonSchemaValidator jsonSchemaValidator) {
415+
Assert.notNull(jsonSchemaValidator, "jsonSchemaValidator must not be null");
416+
this.jsonSchemaValidator = jsonSchemaValidator;
417+
return this;
418+
}
419+
385420
/**
386421
* Registers {@code subscriptions/listen}, backed by {@code publisher}, for the
387422
* tools, prompts and resources features that are registered.
@@ -418,6 +453,12 @@ public McpServer build() {
418453
McpJsonMapper mapper = this.jsonMapper != null ? this.jsonMapper : McpJsonDefaults.getMapper();
419454

420455
List<McpFeature> allFeatures = new ArrayList<>(this.features);
456+
if (!this.tools.isEmpty()) {
457+
JsonSchemaValidator validator = this.jsonSchemaValidator != null ? this.jsonSchemaValidator
458+
: McpJsonDefaults.getSchemaValidator();
459+
allFeatures.add(registeredWith("tool(...)", ToolsFeature.ofTools(List.copyOf(this.tools.values()),
460+
mapper, validator, 0L, CacheScope.PRIVATE)));
461+
}
421462

422463
ServerCapabilities.Builder capabilitiesBuilder = ServerCapabilities.builder();
423464
for (McpFeature feature : allFeatures) {
@@ -462,6 +503,22 @@ public McpServer build() {
462503
Set.copyOf(inputRequiredMethods), codec, subscriptionsFeature);
463504
}
464505

506+
// Checked here rather than by the method collision check in build(), whose
507+
// "served by both ToolsFeature and ToolsFeature" would not say which
508+
// registration to move.
509+
private McpFeature registeredWith(String shortcut, McpFeature feature) {
510+
for (McpFeature explicit : this.features) {
511+
for (String method : feature.methods()) {
512+
if (explicit.methods().contains(method)) {
513+
throw new IllegalStateException("Primitives registered with " + shortcut
514+
+ " cannot be combined with " + explicit.getClass().getName() + ", which also serves '"
515+
+ method + "'; register them on that feature's repository instead");
516+
}
517+
}
518+
}
519+
return feature;
520+
}
521+
465522
}
466523

467524
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import java.util.Collections;
8+
import java.util.LinkedHashMap;
9+
import java.util.List;
10+
import java.util.Map;
11+
12+
import io.modelcontextprotocol.modern.McpException;
13+
import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome;
14+
import io.modelcontextprotocol.modern.McpSchema.CallToolRequest;
15+
import io.modelcontextprotocol.modern.McpSchema.Tool;
16+
import io.modelcontextprotocol.modern.server.McpAsyncResponse;
17+
import io.modelcontextprotocol.modern.server.McpRequestContext;
18+
import io.modelcontextprotocol.util.Assert;
19+
import reactor.core.publisher.Mono;
20+
21+
/**
22+
* A fixed set of {@link McpServerTool}s, listed in registration order on a single page.
23+
*/
24+
final class InMemoryToolRepository implements McpAsyncToolRepository {
25+
26+
private final Map<String, McpServerTool> tools;
27+
28+
private final ToolsPage page;
29+
30+
InMemoryToolRepository(List<McpServerTool> tools) {
31+
Assert.notNull(tools, "tools must not be null");
32+
Map<String, McpServerTool> byName = new LinkedHashMap<>();
33+
for (McpServerTool tool : tools) {
34+
Assert.notNull(tool, "tool must not be null");
35+
if (byName.putIfAbsent(tool.tool().name(), tool) != null) {
36+
throw new IllegalArgumentException("Duplicate tool name: " + tool.tool().name());
37+
}
38+
}
39+
this.tools = Collections.unmodifiableMap(byName);
40+
this.page = ToolsPage.of(byName.values().stream().map(McpServerTool::tool).toList());
41+
}
42+
43+
@Override
44+
public Mono<ToolsPage> list(McpRequestContext ctx, String cursor) {
45+
// Everything fits on one page, so no cursor is ever issued.
46+
if (cursor != null) {
47+
return Mono.error(McpException.invalidParams("Invalid cursor"));
48+
}
49+
return Mono.just(this.page);
50+
}
51+
52+
@Override
53+
public Mono<Tool> find(McpRequestContext ctx, String name) {
54+
McpServerTool tool = this.tools.get(name);
55+
return tool != null ? Mono.just(tool.tool()) : Mono.empty();
56+
}
57+
58+
@Override
59+
public Mono<McpAsyncResponse<CallToolOutcome>> call(McpRequestContext ctx, CallToolRequest request) {
60+
McpServerTool tool = this.tools.get(request.name());
61+
if (tool == null) {
62+
return Mono.error(McpException.invalidParams("Unknown tool: " + request.name()));
63+
}
64+
return tool.call(ctx, request);
65+
}
66+
67+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import io.modelcontextprotocol.modern.McpException;
8+
import io.modelcontextprotocol.modern.server.McpRequestContext;
9+
import reactor.core.publisher.Mono;
10+
11+
/**
12+
* Answers a request for one primitive with a single result, e.g. the handler of
13+
* {@link McpServerTool#async}. It must not block. An {@link McpException} fails the
14+
* request with its error.
15+
*
16+
* @param <R> the request type, e.g. {@code CallToolRequest}
17+
* @param <O> the outcome type, e.g. {@code CallToolOutcome}
18+
*/
19+
@FunctionalInterface
20+
public interface McpAsyncHandler<R, O> {
21+
22+
Mono<O> handle(McpRequestContext ctx, R request);
23+
24+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import io.modelcontextprotocol.modern.server.McpAsyncNotifier;
8+
import io.modelcontextprotocol.modern.server.McpRequestContext;
9+
import reactor.core.publisher.Mono;
10+
11+
/**
12+
* Answers a request for one primitive with a stream of notifications ending in the
13+
* result, e.g. the handler of {@link McpServerTool#asyncStreaming}. It runs once the
14+
* transport has started the stream, and must not block.
15+
*
16+
* @param <R> the request type, e.g. {@code CallToolRequest}
17+
* @param <O> the outcome type, e.g. {@code CallToolOutcome}
18+
*/
19+
@FunctionalInterface
20+
public interface McpAsyncStreamingHandler<R, O> {
21+
22+
Mono<O> handle(McpRequestContext ctx, R request, McpAsyncNotifier notifier);
23+
24+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import java.util.function.BiFunction;
8+
9+
import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome;
10+
import io.modelcontextprotocol.modern.McpSchema.CallToolRequest;
11+
import io.modelcontextprotocol.modern.McpSchema.Tool;
12+
import io.modelcontextprotocol.modern.server.McpAsyncResponse;
13+
import io.modelcontextprotocol.modern.server.McpRequestContext;
14+
import io.modelcontextprotocol.modern.server.McpSyncResponse;
15+
import io.modelcontextprotocol.util.Assert;
16+
import io.modelcontextprotocol.util.ToolNameValidator;
17+
import reactor.core.publisher.Mono;
18+
19+
/**
20+
* A tool and the handler answering its {@code tools/call}: what
21+
* {@code McpServer.Builder#tool} registers. The tool is served by a {@link ToolsFeature},
22+
* so its arguments and structured output are validated as for any repository.
23+
*/
24+
public final class McpServerTool {
25+
26+
private final Tool tool;
27+
28+
private final BiFunction<McpRequestContext, CallToolRequest, Mono<McpAsyncResponse<CallToolOutcome>>> call;
29+
30+
private McpServerTool(Tool tool,
31+
BiFunction<McpRequestContext, CallToolRequest, Mono<McpAsyncResponse<CallToolOutcome>>> call) {
32+
Assert.notNull(tool, "tool must not be null");
33+
ToolNameValidator.validate(tool.name(), ToolNameValidator.isStrictByDefault());
34+
this.tool = tool;
35+
this.call = call;
36+
}
37+
38+
/** Answers each call with the handler's result. */
39+
public static McpServerTool sync(Tool tool, McpSyncHandler<CallToolRequest, CallToolOutcome> handler) {
40+
Assert.notNull(handler, "handler must not be null");
41+
return new McpServerTool(tool, (ctx, request) -> SyncAdapters.respond(ctx,
42+
() -> McpSyncResponse.result(handler.handle(ctx, request))));
43+
}
44+
45+
/** Answers each call with a stream of the handler's notifications and its result. */
46+
public static McpServerTool syncStreaming(Tool tool,
47+
McpSyncStreamingHandler<CallToolRequest, CallToolOutcome> handler) {
48+
Assert.notNull(handler, "handler must not be null");
49+
return new McpServerTool(tool, (ctx, request) -> SyncAdapters.respond(ctx,
50+
() -> McpSyncResponse.streaming(notifier -> handler.handle(ctx, request, notifier))));
51+
}
52+
53+
/** Answers each call with the handler's result. */
54+
public static McpServerTool async(Tool tool, McpAsyncHandler<CallToolRequest, CallToolOutcome> handler) {
55+
Assert.notNull(handler, "handler must not be null");
56+
return new McpServerTool(tool,
57+
(ctx, request) -> Mono.defer(() -> handler.handle(ctx, request)).map(McpAsyncResponse::result));
58+
}
59+
60+
/** Answers each call with a stream of the handler's notifications and its result. */
61+
public static McpServerTool asyncStreaming(Tool tool,
62+
McpAsyncStreamingHandler<CallToolRequest, CallToolOutcome> handler) {
63+
Assert.notNull(handler, "handler must not be null");
64+
return new McpServerTool(tool, (ctx, request) -> Mono
65+
.just(McpAsyncResponse.streaming(notifier -> handler.handle(ctx, request, notifier))));
66+
}
67+
68+
public Tool tool() {
69+
return this.tool;
70+
}
71+
72+
Mono<McpAsyncResponse<CallToolOutcome>> call(McpRequestContext ctx, CallToolRequest request) {
73+
return this.call.apply(ctx, request);
74+
}
75+
76+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import io.modelcontextprotocol.modern.McpException;
8+
import io.modelcontextprotocol.modern.server.McpRequestContext;
9+
10+
/**
11+
* Answers a request for one primitive with a single result, e.g. the handler of
12+
* {@link McpServerTool#sync}. It runs on the calling thread for a blocking transport and
13+
* off the event loop otherwise. An {@link McpException} fails the request with its error.
14+
*
15+
* @param <R> the request type, e.g. {@code CallToolRequest}
16+
* @param <O> the outcome type, e.g. {@code CallToolOutcome}
17+
*/
18+
@FunctionalInterface
19+
public interface McpSyncHandler<R, O> {
20+
21+
O handle(McpRequestContext ctx, R request);
22+
23+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.modern.server.feature;
6+
7+
import io.modelcontextprotocol.modern.server.McpRequestContext;
8+
import io.modelcontextprotocol.modern.server.McpSyncNotifier;
9+
10+
/**
11+
* Answers a request for one primitive with a stream of notifications ending in the
12+
* result, e.g. the handler of {@link McpServerTool#syncStreaming}. It runs once the
13+
* transport has started the stream; see {@link McpSyncHandler} for where.
14+
*
15+
* @param <R> the request type, e.g. {@code CallToolRequest}
16+
* @param <O> the outcome type, e.g. {@code CallToolOutcome}
17+
*/
18+
@FunctionalInterface
19+
public interface McpSyncStreamingHandler<R, O> {
20+
21+
O handle(McpRequestContext ctx, R request, McpSyncNotifier notifier);
22+
23+
}

‎mcp-core/src/main/java/io/modelcontextprotocol/modern/server/feature/ToolsFeature.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ public static ToolsFeature ofSync(McpSyncToolRepository repository, McpJsonMappe
8585
return ofAsync(adapt(repository), jsonMapper, jsonSchemaValidator, defaultTtlMs, defaultCacheScope);
8686
}
8787

88+
/**
89+
* Serves a fixed set of tools, listed in this order on a single page. Duplicate names
90+
* are rejected.
91+
*/
92+
public static ToolsFeature ofTools(List<McpServerTool> tools, McpJsonMapper jsonMapper,
93+
JsonSchemaValidator jsonSchemaValidator, long defaultTtlMs, CacheScope defaultCacheScope) {
94+
return ofAsync(new InMemoryToolRepository(tools), jsonMapper, jsonSchemaValidator, defaultTtlMs,
95+
defaultCacheScope);
96+
}
97+
8898
@Override
8999
public Set<String> methods() {
90100
return Set.of(McpSchema.METHOD_TOOLS_LIST, McpSchema.METHOD_TOOLS_CALL);

0 commit comments

Comments
 (0)