Skip to content

Commit 3a47461

Browse files
bhuvnshclaude
andcommitted
Harden McpServerTool shortcuts and use them in the conformance server
Document threading, error handling and name validation on McpServerTool, and give it a toString. Add focused tests for the four handler factories (including which thread a sync handler runs on), error mapping, output-schema checks and ToolsFeature.ofTools, plus builder tests for duplicate names, the tools/* conflict check, the advertised capability with and without subscriptions, and the builder's schema validator. ModernConformanceServlet now registers its tools through McpServer.Builder#tools instead of a hand-written McpSyncToolRepository. The 2026-07-28 conformance suite passes as before. The one behaviour change is that a tools/list cursor, which the old repository ignored, is now rejected as invalid params. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dfc589d commit 3a47461

6 files changed

Lines changed: 531 additions & 185 deletions

File tree

‎conformance-tests/server-servlet-modern/src/main/java/io/modelcontextprotocol/conformance/server/modern/ModernConformanceServlet.java‎

Lines changed: 96 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.modelcontextprotocol.conformance.server.modern;
22

3+
import java.util.ArrayList;
34
import java.util.LinkedHashMap;
45
import java.util.List;
56
import java.util.Map;
@@ -14,8 +15,6 @@
1415
import io.modelcontextprotocol.modern.McpException;
1516
import io.modelcontextprotocol.modern.McpSchema.AudioContent;
1617
import io.modelcontextprotocol.modern.McpSchema.BlobResourceContents;
17-
import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome;
18-
import io.modelcontextprotocol.modern.McpSchema.CallToolRequest;
1918
import io.modelcontextprotocol.modern.McpSchema.CallToolResult;
2019
import io.modelcontextprotocol.modern.McpSchema.ClientCapabilities;
2120
import io.modelcontextprotocol.modern.McpSchema.CompleteResult;
@@ -45,22 +44,19 @@
4544
import io.modelcontextprotocol.modern.server.InputResponses;
4645
import io.modelcontextprotocol.modern.server.McpRequestContext;
4746
import io.modelcontextprotocol.modern.server.McpServer;
48-
import io.modelcontextprotocol.modern.server.McpSyncNotifier;
4947
import io.modelcontextprotocol.modern.server.McpSyncResponse;
5048
import io.modelcontextprotocol.modern.server.feature.CompletionsFeature;
5149
import io.modelcontextprotocol.modern.server.feature.McpChangeBroadcaster;
5250
import io.modelcontextprotocol.modern.server.feature.McpChangeFeed;
51+
import io.modelcontextprotocol.modern.server.feature.McpServerTool;
5352
import io.modelcontextprotocol.modern.server.feature.McpSyncPromptRepository;
5453
import io.modelcontextprotocol.modern.server.feature.McpSyncResourceRepository;
55-
import io.modelcontextprotocol.modern.server.feature.McpSyncToolRepository;
5654
import io.modelcontextprotocol.modern.server.feature.PromptsFeature;
5755
import io.modelcontextprotocol.modern.server.feature.PromptsPage;
5856
import io.modelcontextprotocol.modern.server.feature.ResourceTemplatesPage;
5957
import io.modelcontextprotocol.modern.server.feature.ResourcesFeature;
6058
import io.modelcontextprotocol.modern.server.feature.ResourcesPage;
6159
import io.modelcontextprotocol.modern.server.feature.ServerChange;
62-
import io.modelcontextprotocol.modern.server.feature.ToolsFeature;
63-
import io.modelcontextprotocol.modern.server.feature.ToolsPage;
6460
import io.modelcontextprotocol.modern.server.transport.HttpServletMcpTransport;
6561
import io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
6662
import org.apache.catalina.Context;
@@ -128,7 +124,7 @@ public static void main(String[] args) throws Exception {
128124

129125
McpServer mcpServer = McpServer.builder()
130126
.serverInfo(Implementation.builder("mcp-modern-conformance-server", "1.0.0").build())
131-
.feature(ToolsFeature.ofSync(new ConformanceTools(changes)))
127+
.tools(ConformanceTools.create(changes))
132128
.feature(ResourcesFeature.ofSync(new ConformanceResources()))
133129
.feature(PromptsFeature.ofSync(new ConformancePrompts()))
134130
.feature(CompletionsFeature
@@ -239,112 +235,107 @@ private interface Handler<R, O extends Result> {
239235

240236
}
241237

242-
@FunctionalInterface
243-
private interface StreamingTool {
244-
245-
CallToolResult run(McpRequestContext ctx, CallToolRequest request, McpSyncNotifier notifier);
246-
247-
}
248-
249238
private static <R, O extends Result> Handler<R, O> respond(BiFunction<McpRequestContext, R, O> fn) {
250239
return (ctx, request) -> McpSyncResponse.result(fn.apply(ctx, request));
251240
}
252241

253-
private static Handler<CallToolRequest, CallToolOutcome> stream(StreamingTool tool) {
254-
return (ctx, request) -> McpSyncResponse.streaming(notifier -> tool.run(ctx, request, notifier));
255-
}
256-
257-
private record ToolEntry(Tool tool, Handler<CallToolRequest, CallToolOutcome> handler) {
258-
}
259-
260-
private static final class ConformanceTools implements McpSyncToolRepository {
242+
private static final class ConformanceTools {
261243

262-
private final Map<String, ToolEntry> tools = new LinkedHashMap<>();
244+
private ConformanceTools() {
245+
}
263246

264-
ConformanceTools(McpChangeBroadcaster changes) {
265-
add("test_simple_text", "Returns simple text content for testing",
266-
respond((ctx, req) -> text("This is a simple text response for testing.")));
267-
add("test_image_content", "Returns image content for testing",
268-
respond((ctx, req) -> CallToolResult.builder()
247+
static List<McpServerTool> create(McpChangeBroadcaster changes) {
248+
List<McpServerTool> tools = new ArrayList<>();
249+
tools.add(McpServerTool.sync(tool("test_simple_text", "Returns simple text content for testing"),
250+
(ctx, req) -> text("This is a simple text response for testing.")));
251+
tools.add(McpServerTool.sync(tool("test_image_content", "Returns image content for testing"),
252+
(ctx, req) -> CallToolResult.builder()
269253
.addContent(ImageContent.builder(RED_PIXEL_PNG, "image/png").build())
270254
.build()));
271-
add("test_audio_content", "Returns audio content for testing",
272-
respond((ctx, req) -> CallToolResult.builder()
255+
tools.add(McpServerTool.sync(tool("test_audio_content", "Returns audio content for testing"),
256+
(ctx, req) -> CallToolResult.builder()
273257
.addContent(AudioContent.builder(MINIMAL_WAV, "audio/wav").build())
274258
.build()));
275-
add("test_embedded_resource", "Returns embedded resource content for testing",
276-
respond((ctx,
277-
req) -> CallToolResult.builder()
278-
.addContent(
279-
EmbeddedResource
280-
.builder(TextResourceContents
281-
.builder("test://embedded-resource",
282-
"This is an embedded resource content.")
283-
.mimeType("text/plain")
284-
.build())
259+
tools
260+
.add(McpServerTool.sync(tool("test_embedded_resource", "Returns embedded resource content for testing"),
261+
(ctx, req) -> CallToolResult.builder()
262+
.addContent(
263+
EmbeddedResource
264+
.builder(TextResourceContents
265+
.builder("test://embedded-resource",
266+
"This is an embedded resource content.")
267+
.mimeType("text/plain")
285268
.build())
286-
.build()));
287-
add("test_multiple_content_types", "Returns multiple content types for testing",
288-
respond((ctx,
289-
req) -> CallToolResult.builder()
290-
.addContent(TextContent.builder("Multiple content types test:").build())
291-
.addContent(ImageContent.builder(RED_PIXEL_PNG, "image/png").build())
292-
.addContent(
293-
EmbeddedResource
294-
.builder(TextResourceContents
295-
.builder("test://mixed-content-resource",
296-
"{\"test\":\"data\",\"value\":123}")
297-
.mimeType("application/json")
298-
.build())
269+
.build())
270+
.build()));
271+
tools.add(McpServerTool
272+
.sync(tool("test_multiple_content_types", "Returns multiple content types for testing"),
273+
(ctx, req) -> CallToolResult.builder()
274+
.addContent(TextContent.builder("Multiple content types test:").build())
275+
.addContent(ImageContent.builder(RED_PIXEL_PNG, "image/png").build())
276+
.addContent(
277+
EmbeddedResource
278+
.builder(TextResourceContents
279+
.builder("test://mixed-content-resource",
280+
"{\"test\":\"data\",\"value\":123}")
281+
.mimeType("application/json")
299282
.build())
300-
.build()));
301-
add("test_error_handling", "Tool that returns an error for testing error handling",
302-
respond((ctx, req) -> CallToolResult.builder()
283+
.build())
284+
.build()));
285+
tools.add(McpServerTool.sync(
286+
tool("test_error_handling", "Tool that returns an error for testing error handling"),
287+
(ctx, req) -> CallToolResult.builder()
303288
.addContent(TextContent.builder("This tool intentionally returns an error for testing").build())
304289
.isError(true)
305290
.build()));
306-
add("test_tool_with_progress", "Tool that reports progress notifications", stream((ctx, req, notifier) -> {
307-
notifier.progress(0, 100.0, null);
308-
sleep(50);
309-
notifier.progress(50, 100.0, null);
310-
sleep(50);
311-
notifier.progress(100, 100.0, null);
312-
return text("Tool execution completed with progress");
313-
}));
291+
tools.add(McpServerTool.syncStreaming(
292+
tool("test_tool_with_progress", "Tool that reports progress notifications"),
293+
(ctx, req, notifier) -> {
294+
notifier.progress(0, 100.0, null);
295+
sleep(50);
296+
notifier.progress(50, 100.0, null);
297+
sleep(50);
298+
notifier.progress(100, 100.0, null);
299+
return text("Tool execution completed with progress");
300+
}));
314301

315302
// SEP-1613 / SEP-2106 JSON Schema 2020-12 keyword preservation
316-
add(Tool.builder("json_schema_2020_12_tool", JSON, JSON_SCHEMA_2020_12_INPUT)
303+
tools.add(McpServerTool.sync(Tool.builder("json_schema_2020_12_tool", JSON, JSON_SCHEMA_2020_12_INPUT)
317304
.description("Tool with JSON Schema 2020-12 features (SEP-1613, SEP-2106)")
318-
.build(), respond((ctx, req) -> text("ok")));
305+
.build(), (ctx, req) -> text("ok")));
319306

320307
// SEP-2575 diagnostic tools
321-
add("test_missing_capability", "Test tool requiring sampling", (ctx, req) -> {
322-
if (!ctx.clientCapabilities().supportsSampling()) {
323-
throw McpException.missingClientCapability(ClientCapabilities.builder().sampling().build());
324-
}
325-
return McpSyncResponse.result(text("Success"));
326-
});
327-
add("test_streaming_elicitation", "Diagnostic tool validating response progress streams",
328-
stream((ctx, req, notifier) -> {
308+
tools
309+
.add(McpServerTool.sync(tool("test_missing_capability", "Test tool requiring sampling"), (ctx, req) -> {
310+
if (!ctx.clientCapabilities().supportsSampling()) {
311+
throw McpException.missingClientCapability(ClientCapabilities.builder().sampling().build());
312+
}
313+
return text("Success");
314+
}));
315+
tools.add(McpServerTool.syncStreaming(
316+
tool("test_streaming_elicitation", "Diagnostic tool validating response progress streams"),
317+
(ctx, req, notifier) -> {
329318
notifier.progress(50, 100.0, null);
330319
return text("Streaming complete");
331320
}));
332321
// Logging is deprecated and unsupported, so no log is ever sent; the suite
333322
// checks exactly that.
334-
add("test_logging_tool", "Diagnostic logging validator tool",
335-
stream((ctx, req, notifier) -> text("Logging evaluated")));
336-
add("test_trigger_tool_change", "Emits a tools list-changed notification", respond((ctx, req) -> {
337-
changes.broadcast(new ServerChange.ToolsListChanged());
338-
return text("Mutation triggered");
339-
}));
340-
add("test_trigger_prompt_change", "Emits a prompts list-changed notification", respond((ctx, req) -> {
341-
changes.broadcast(new ServerChange.PromptsListChanged());
342-
return text("Mutation triggered");
343-
}));
323+
tools.add(McpServerTool.syncStreaming(tool("test_logging_tool", "Diagnostic logging validator tool"),
324+
(ctx, req, notifier) -> text("Logging evaluated")));
325+
tools.add(McpServerTool.sync(tool("test_trigger_tool_change", "Emits a tools list-changed notification"),
326+
(ctx, req) -> {
327+
changes.broadcast(new ServerChange.ToolsListChanged());
328+
return text("Mutation triggered");
329+
}));
330+
tools.add(McpServerTool
331+
.sync(tool("test_trigger_prompt_change", "Emits a prompts list-changed notification"), (ctx, req) -> {
332+
changes.broadcast(new ServerChange.PromptsListChanged());
333+
return text("Mutation triggered");
334+
}));
344335

345336
// SEP-2322 MRTR tools
346-
add("test_input_required_result_elicitation", "MRTR: returns InputRequiredResult with elicitation request",
347-
respond((ctx, req) -> {
337+
tools.add(McpServerTool.sync(tool("test_input_required_result_elicitation",
338+
"MRTR: returns InputRequiredResult with elicitation request"), (ctx, req) -> {
348339
Map<String, Object> content = acceptedContent(req.inputResponses(), "user_name");
349340
if (content == null || !(content.get("name") instanceof String name)) {
350341
return InputRequiredResult.builder()
@@ -353,8 +344,8 @@ private static final class ConformanceTools implements McpSyncToolRepository {
353344
}
354345
return text("Hello, " + name + "!");
355346
}));
356-
add("test_input_required_result_sampling", "MRTR: returns InputRequiredResult with sampling request",
357-
respond((ctx, req) -> {
347+
tools.add(McpServerTool.sync(tool("test_input_required_result_sampling",
348+
"MRTR: returns InputRequiredResult with sampling request"), (ctx, req) -> {
358349
Map<String, Object> response = responseObject(req.inputResponses(), "capital_question");
359350
if (response == null) {
360351
return InputRequiredResult.builder()
@@ -365,16 +356,16 @@ private static final class ConformanceTools implements McpSyncToolRepository {
365356
Object answer = content instanceof Map<?, ?> m ? m.get("text") : null;
366357
return text("Sampling result: " + answer);
367358
}));
368-
add("test_input_required_result_list_roots", "MRTR: returns InputRequiredResult with roots/list request",
369-
respond((ctx, req) -> {
359+
tools.add(McpServerTool.sync(tool("test_input_required_result_list_roots",
360+
"MRTR: returns InputRequiredResult with roots/list request"), (ctx, req) -> {
370361
Map<String, Object> response = responseObject(req.inputResponses(), "client_roots");
371362
if (response == null || !(response.get("roots") instanceof List<?> roots)) {
372363
return InputRequiredResult.builder().listRoots("client_roots").build();
373364
}
374365
return text("Found " + roots.size() + " root(s): " + roots);
375366
}));
376-
add("test_input_required_result_request_state", "MRTR: returns InputRequiredResult with requestState",
377-
respond((ctx, req) -> {
367+
tools.add(McpServerTool.sync(tool("test_input_required_result_request_state",
368+
"MRTR: returns InputRequiredResult with requestState"), (ctx, req) -> {
378369
Map<String, Object> content = acceptedContent(req.inputResponses(), "confirm");
379370
if ("request-state".equals(req.requestState()) && content != null
380371
&& Boolean.TRUE.equals(content.get("ok"))) {
@@ -385,8 +376,8 @@ private static final class ConformanceTools implements McpSyncToolRepository {
385376
.requestState("request-state")
386377
.build();
387378
}));
388-
add("test_input_required_result_multiple_inputs",
389-
"MRTR: returns InputRequiredResult with multiple input requests", respond((ctx, req) -> {
379+
tools.add(McpServerTool.sync(tool("test_input_required_result_multiple_inputs",
380+
"MRTR: returns InputRequiredResult with multiple input requests"), (ctx, req) -> {
390381
Map<String, Object> user = acceptedContent(req.inputResponses(), "user_name");
391382
Map<String, Object> greeting = responseObject(req.inputResponses(), "greeting");
392383
Map<String, Object> roots = responseObject(req.inputResponses(), "client_roots");
@@ -402,8 +393,9 @@ private static final class ConformanceTools implements McpSyncToolRepository {
402393
.requestState("multiple-inputs")
403394
.build();
404395
}));
405-
add("test_input_required_result_multi_round", "MRTR: multi-round InputRequiredResult workflow",
406-
respond((ctx, req) -> {
396+
tools.add(McpServerTool.sync(
397+
tool("test_input_required_result_multi_round", "MRTR: multi-round InputRequiredResult workflow"),
398+
(ctx, req) -> {
407399
String state = req.requestState();
408400
if (state != null && state.startsWith("round-1")) {
409401
Map<String, Object> step1 = acceptedContent(req.inputResponses(), "step1");
@@ -428,8 +420,9 @@ private static final class ConformanceTools implements McpSyncToolRepository {
428420
}));
429421
// Integrity protection comes from the server's RequestStateCodec: a tampered
430422
// requestState is rejected before this handler runs.
431-
add("test_input_required_result_tampered_state", "MRTR: HMAC-signed requestState integrity test",
432-
respond((ctx, req) -> {
423+
tools.add(McpServerTool.sync(
424+
tool("test_input_required_result_tampered_state", "MRTR: HMAC-signed requestState integrity test"),
425+
(ctx, req) -> {
433426
if ("tamper-test".equals(req.requestState())
434427
&& responseObject(req.inputResponses(), "confirm") != null) {
435428
return text("integrity-ok: state verified");
@@ -439,8 +432,8 @@ && responseObject(req.inputResponses(), "confirm") != null) {
439432
.requestState("tamper-test")
440433
.build();
441434
}));
442-
add("test_input_required_result_capabilities", "MRTR: respects client capabilities in inputRequests",
443-
respond((ctx, req) -> {
435+
tools.add(McpServerTool.sync(tool("test_input_required_result_capabilities",
436+
"MRTR: respects client capabilities in inputRequests"), (ctx, req) -> {
444437
if (req.inputResponses() != null && !req.inputResponses().isEmpty()) {
445438
return text("capabilities-ok: received " + String.join(",", req.inputResponses().keySet()));
446439
}
@@ -458,34 +451,11 @@ && responseObject(req.inputResponses(), "confirm") != null) {
458451
}
459452
return builder.build();
460453
}));
454+
return tools;
461455
}
462456

463-
private void add(String name, String description, Handler<CallToolRequest, CallToolOutcome> handler) {
464-
add(Tool.builder(name, EMPTY_JSON_SCHEMA).description(description).build(), handler);
465-
}
466-
467-
private void add(Tool tool, Handler<CallToolRequest, CallToolOutcome> handler) {
468-
this.tools.put(tool.name(), new ToolEntry(tool, handler));
469-
}
470-
471-
@Override
472-
public ToolsPage list(McpRequestContext ctx, String cursor) {
473-
return ToolsPage.of(this.tools.values().stream().map(ToolEntry::tool).toList());
474-
}
475-
476-
@Override
477-
public Tool find(McpRequestContext ctx, String name) {
478-
ToolEntry entry = this.tools.get(name);
479-
return entry != null ? entry.tool() : null;
480-
}
481-
482-
@Override
483-
public McpSyncResponse<CallToolOutcome> call(McpRequestContext ctx, CallToolRequest request) {
484-
ToolEntry entry = this.tools.get(request.name());
485-
if (entry == null) {
486-
throw McpException.invalidParams("Unknown tool: " + request.name());
487-
}
488-
return entry.handler().handle(ctx, request);
457+
private static Tool tool(String name, String description) {
458+
return Tool.builder(name, EMPTY_JSON_SCHEMA).description(description).build();
489459
}
490460

491461
private static void sleep(long millis) {

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ private static String extractPrimitiveName(String method, Map<String, Object> pa
327327
}
328328

329329
/**
330-
* Builds an immutable {@link McpServer} from registered features.
330+
* Builds an immutable {@link McpServer} from registered features and tools.
331331
*/
332332
public static final class Builder {
333333

@@ -390,8 +390,12 @@ public Builder features(List<? extends McpFeature> features) {
390390
}
391391

392392
/**
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.
393+
* Registers a tool. The registered tools are served in registration order by a
394+
* {@link ToolsFeature} created at {@link #build()} with this builder's JSON
395+
* mapper and {@link #jsonSchemaValidator schema validator}, and no caching. No
396+
* other feature may then serve {@code tools/*}; for cache hints, register
397+
* {@link ToolsFeature#ofTools} as a feature instead.
398+
* @throws IllegalArgumentException if a tool with the same name is registered
395399
*/
396400
public Builder tool(McpServerTool tool) {
397401
Assert.notNull(tool, "tool must not be null");
@@ -401,6 +405,7 @@ public Builder tool(McpServerTool tool) {
401405
return this;
402406
}
403407

408+
/** Registers each of these tools, in order. See {@link #tool}. */
404409
public Builder tools(List<McpServerTool> tools) {
405410
Assert.notNull(tools, "tools must not be null");
406411
tools.forEach(this::tool);
@@ -453,6 +458,7 @@ public McpServer build() {
453458
McpJsonMapper mapper = this.jsonMapper != null ? this.jsonMapper : McpJsonDefaults.getMapper();
454459

455460
List<McpFeature> allFeatures = new ArrayList<>(this.features);
461+
// Added before capabilities are collected, which subscriptions depend on.
456462
if (!this.tools.isEmpty()) {
457463
JsonSchemaValidator validator = this.jsonSchemaValidator != null ? this.jsonSchemaValidator
458464
: McpJsonDefaults.getSchemaValidator();

0 commit comments

Comments
 (0)