Skip to content

Commit 50e788d

Browse files
authored
Enforce required client capabilities in the modern server (#1283)
Handlers had to check ctx.clientCapabilities() themselves before asking for elicitation, sampling or roots. Nothing stopped one from sending an input request the client never declared. Tools, prompts and resources can now declare the capabilities they cannot work without, via of(..., requiredCapabilities, handler) on McpAsync/SyncTool, McpAsync/SyncPrompt and McpAsync/SyncResource. The feature checks them before the handler runs and answers a client that lacks them with -32021, listing only what is missing. Optional input is still requested only when the client declares it. McpServer now rejects any input request for an undeclared capability as an internal error, checking URL-mode elicitation separately. This covers extension methods too. The javadoc on the handler types, InputRequired, McpRequestContext and McpException describes which strategy to use. Signed-off-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
1 parent 5133786 commit 50e788d

21 files changed

Lines changed: 579 additions & 54 deletions

File tree

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

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
1212
import io.modelcontextprotocol.json.McpJsonDefaults;
1313
import io.modelcontextprotocol.json.McpJsonMapper;
14-
import io.modelcontextprotocol.modern.McpException;
1514
import io.modelcontextprotocol.modern.McpSchema.AudioContent;
1615
import io.modelcontextprotocol.modern.McpSchema.BlobResourceContents;
1716
import io.modelcontextprotocol.modern.McpSchema.CallToolOutcome;
@@ -255,6 +254,15 @@ private static Handler<CallToolRequest, CallToolOutcome> stream(StreamingTool to
255254
return (ctx, request) -> McpSyncResponse.streaming(notifier -> tool.run(ctx, request, notifier));
256255
}
257256

257+
private static final ClientCapabilities.Elicitation FORM = new ClientCapabilities.Elicitation(
258+
new ClientCapabilities.Elicitation.Form(), null);
259+
260+
private static final ClientCapabilities ELICITATION = ClientCapabilities.builder().elicitation(FORM).build();
261+
262+
private static final ClientCapabilities SAMPLING = ClientCapabilities.builder().sampling().build();
263+
264+
private static final ClientCapabilities ROOTS = ClientCapabilities.builder().roots().build();
265+
258266
private static final class ConformanceTools implements McpSyncToolRepository {
259267

260268
private final Map<String, McpSyncTool> tools = new LinkedHashMap<>();
@@ -316,12 +324,8 @@ private static final class ConformanceTools implements McpSyncToolRepository {
316324
.build(), respond((ctx, req) -> text("ok")));
317325

318326
// SEP-2575 diagnostic tools
319-
add("test_missing_capability", "Test tool requiring sampling", (ctx, req) -> {
320-
if (!ctx.clientCapabilities().supportsSampling()) {
321-
throw McpException.missingClientCapability(ClientCapabilities.builder().sampling().build());
322-
}
323-
return McpSyncResponse.result(text("Success"));
324-
});
327+
add("test_missing_capability", "Test tool requiring sampling", SAMPLING,
328+
respond((ctx, req) -> text("Success")));
325329
add("test_streaming_elicitation", "Diagnostic tool validating response progress streams",
326330
stream((ctx, req, notifier) -> {
327331
notifier.progress(50, 100.0, null);
@@ -342,7 +346,7 @@ private static final class ConformanceTools implements McpSyncToolRepository {
342346

343347
// SEP-2322 MRTR tools
344348
add("test_input_required_result_elicitation", "MRTR: returns InputRequiredResult with elicitation request",
345-
respond((ctx, req) -> {
349+
ELICITATION, respond((ctx, req) -> {
346350
Map<String, Object> content = acceptedContent(req.inputResponses(), "user_name");
347351
if (content == null || !(content.get("name") instanceof String name)) {
348352
return InputRequiredResult.builder()
@@ -352,7 +356,7 @@ private static final class ConformanceTools implements McpSyncToolRepository {
352356
return text("Hello, " + name + "!");
353357
}));
354358
add("test_input_required_result_sampling", "MRTR: returns InputRequiredResult with sampling request",
355-
respond((ctx, req) -> {
359+
SAMPLING, respond((ctx, req) -> {
356360
Map<String, Object> response = responseObject(req.inputResponses(), "capital_question");
357361
if (response == null) {
358362
return InputRequiredResult.builder()
@@ -364,15 +368,15 @@ private static final class ConformanceTools implements McpSyncToolRepository {
364368
return text("Sampling result: " + answer);
365369
}));
366370
add("test_input_required_result_list_roots", "MRTR: returns InputRequiredResult with roots/list request",
367-
respond((ctx, req) -> {
371+
ROOTS, respond((ctx, req) -> {
368372
Map<String, Object> response = responseObject(req.inputResponses(), "client_roots");
369373
if (response == null || !(response.get("roots") instanceof List<?> roots)) {
370374
return InputRequiredResult.builder().listRoots("client_roots").build();
371375
}
372376
return text("Found " + roots.size() + " root(s): " + roots);
373377
}));
374378
add("test_input_required_result_request_state", "MRTR: returns InputRequiredResult with requestState",
375-
respond((ctx, req) -> {
379+
ELICITATION, respond((ctx, req) -> {
376380
Map<String, Object> content = acceptedContent(req.inputResponses(), "confirm");
377381
if ("request-state".equals(req.requestState()) && content != null
378382
&& Boolean.TRUE.equals(content.get("ok"))) {
@@ -384,7 +388,8 @@ private static final class ConformanceTools implements McpSyncToolRepository {
384388
.build();
385389
}));
386390
add("test_input_required_result_multiple_inputs",
387-
"MRTR: returns InputRequiredResult with multiple input requests", respond((ctx, req) -> {
391+
"MRTR: returns InputRequiredResult with multiple input requests",
392+
ClientCapabilities.builder().elicitation(FORM).sampling().roots().build(), respond((ctx, req) -> {
388393
Map<String, Object> user = acceptedContent(req.inputResponses(), "user_name");
389394
Map<String, Object> greeting = responseObject(req.inputResponses(), "greeting");
390395
Map<String, Object> roots = responseObject(req.inputResponses(), "client_roots");
@@ -400,7 +405,7 @@ private static final class ConformanceTools implements McpSyncToolRepository {
400405
.requestState("multiple-inputs")
401406
.build();
402407
}));
403-
add("test_input_required_result_multi_round", "MRTR: multi-round InputRequiredResult workflow",
408+
add("test_input_required_result_multi_round", "MRTR: multi-round InputRequiredResult workflow", ELICITATION,
404409
respond((ctx, req) -> {
405410
String state = req.requestState();
406411
if (state != null && state.startsWith("round-1")) {
@@ -427,7 +432,7 @@ private static final class ConformanceTools implements McpSyncToolRepository {
427432
// Integrity protection comes from the server's RequestStateCodec: a tampered
428433
// requestState is rejected before this handler runs.
429434
add("test_input_required_result_tampered_state", "MRTR: HMAC-signed requestState integrity test",
430-
respond((ctx, req) -> {
435+
ELICITATION, respond((ctx, req) -> {
431436
if ("tamper-test".equals(req.requestState())
432437
&& responseObject(req.inputResponses(), "confirm") != null) {
433438
return text("integrity-ok: state verified");
@@ -459,11 +464,21 @@ && responseObject(req.inputResponses(), "confirm") != null) {
459464
}
460465

461466
private void add(String name, String description, Handler<CallToolRequest, CallToolOutcome> handler) {
462-
add(Tool.builder(name, EMPTY_JSON_SCHEMA).description(description).build(), handler);
467+
add(name, description, ClientCapabilities.NONE, handler);
468+
}
469+
470+
private void add(String name, String description, ClientCapabilities requiredCapabilities,
471+
Handler<CallToolRequest, CallToolOutcome> handler) {
472+
add(Tool.builder(name, EMPTY_JSON_SCHEMA).description(description).build(), requiredCapabilities, handler);
463473
}
464474

465475
private void add(Tool tool, Handler<CallToolRequest, CallToolOutcome> handler) {
466-
this.tools.put(tool.name(), McpSyncTool.of(tool, handler::handle));
476+
add(tool, ClientCapabilities.NONE, handler);
477+
}
478+
479+
private void add(Tool tool, ClientCapabilities requiredCapabilities,
480+
Handler<CallToolRequest, CallToolOutcome> handler) {
481+
this.tools.put(tool.name(), McpSyncTool.of(tool, requiredCapabilities, handler::handle));
467482
}
468483

469484
@Override
@@ -608,7 +623,7 @@ private static final class ConformancePrompts implements McpSyncPromptRepository
608623
.build())));
609624
add(Prompt.builder("test_input_required_result_prompt")
610625
.description("MRTR: prompt that requires elicitation input")
611-
.build(), respond((ctx, req) -> {
626+
.build(), ELICITATION, respond((ctx, req) -> {
612627
Map<String, Object> content = acceptedContent(req.inputResponses(), "user_context");
613628
if (content == null || !(content.get("context") instanceof String context)) {
614629
return InputRequiredResult.builder()
@@ -622,7 +637,12 @@ private static final class ConformancePrompts implements McpSyncPromptRepository
622637
}
623638

624639
private void add(Prompt prompt, Handler<GetPromptRequest, GetPromptOutcome> handler) {
625-
this.prompts.put(prompt.name(), McpSyncPrompt.of(prompt, handler::handle));
640+
add(prompt, ClientCapabilities.NONE, handler);
641+
}
642+
643+
private void add(Prompt prompt, ClientCapabilities requiredCapabilities,
644+
Handler<GetPromptRequest, GetPromptOutcome> handler) {
645+
this.prompts.put(prompt.name(), McpSyncPrompt.of(prompt, requiredCapabilities, handler::handle));
626646
}
627647

628648
private static GetPromptResult messages(PromptMessage... messages) {

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@ public static McpException invalidParams(String message, Object data) {
4242
return new McpException(ErrorCodes.INVALID_PARAMS, message, data);
4343
}
4444

45+
/**
46+
* The request cannot be served without {@code required}, which the client did not
47+
* declare. Answered with {@code -32021}. Tools, prompts and resources declare such
48+
* capabilities up front instead (see
49+
* {@link io.modelcontextprotocol.modern.server.feature.McpAsyncTool}); this is for
50+
* extension methods.
51+
*/
4552
public static McpException missingClientCapability(ClientCapabilities required) {
4653
return new McpException(ErrorCodes.MISSING_REQUIRED_CLIENT_CAPABILITY, "Missing required client capability",
4754
new MissingRequiredClientCapabilityData(required));

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,11 @@ public interface CacheableResult extends Result {
192192
* A result asking the client for more input before the request can complete. An
193193
* extension method supporting multi round-trip requests returns its own record
194194
* implementing this interface and the method's outcome type.
195+
* <p>
196+
* Each input request needs a client capability: {@code elicitation} in the request's
197+
* mode, {@code sampling} or {@code roots}. Only input whose capability the client
198+
* declared for this request may be requested; a result asking for anything else is
199+
* answered with an internal error.
195200
*/
196201
public interface InputRequired extends Result {
197202

@@ -1410,7 +1415,8 @@ public String mode() {
14101415
/**
14111416
* A result signalling that the server needs more input before it can complete the
14121417
* original request. Only {@code tools/call}, {@code resources/read} and
1413-
* {@code prompts/get} may return it.
1418+
* {@code prompts/get} may return it, and only with the input requests
1419+
* {@link InputRequired} allows.
14141420
*/
14151421
@JsonInclude(JsonInclude.Include.NON_ABSENT)
14161422
@JsonIgnoreProperties(ignoreUnknown = true)

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import java.util.Set;
88

99
import io.modelcontextprotocol.modern.McpException;
10+
import io.modelcontextprotocol.modern.McpSchema.InputRequired;
1011
import io.modelcontextprotocol.modern.McpSchema.Result;
1112
import io.modelcontextprotocol.modern.McpSchema.ServerCapabilities;
1213
import reactor.core.publisher.Mono;
@@ -38,8 +39,8 @@ default void capabilities(ServerCapabilities.Builder builder) {
3839

3940
/**
4041
* The methods that support multi round-trip requests: they may answer with an
41-
* {@code InputRequired} result and accept its {@code requestState} on retry. Default:
42-
* none.
42+
* {@link InputRequired} result, within the input requests it allows, and accept its
43+
* {@code requestState} on retry. Default: none.
4344
*/
4445
default Set<String> inputRequiredMethods() {
4546
return Set.of();

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import io.modelcontextprotocol.common.McpTransportContext;
1010
import io.modelcontextprotocol.modern.McpSchema.ClientCapabilities;
1111
import io.modelcontextprotocol.modern.McpSchema.Implementation;
12+
import io.modelcontextprotocol.modern.McpSchema.InputRequired;
1213
import io.modelcontextprotocol.util.Assert;
1314

1415
/**
@@ -76,7 +77,10 @@ public String protocolVersion() {
7677
return this.protocolVersion;
7778
}
7879

79-
/** The client capabilities declared in {@code _meta} for this request. */
80+
/**
81+
* The client capabilities declared in {@code _meta} for this request. Input requests
82+
* may only use these; see {@link InputRequired}.
83+
*/
8084
public ClientCapabilities clientCapabilities() {
8185
return this.clientCapabilities;
8286
}

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import io.modelcontextprotocol.modern.McpSchema.CacheScope;
2828
import io.modelcontextprotocol.modern.McpSchema.CacheableResult;
2929
import io.modelcontextprotocol.modern.McpSchema.ClientCapabilities;
30+
import io.modelcontextprotocol.modern.McpSchema.ElicitUrlRequest;
3031
import io.modelcontextprotocol.modern.McpSchema.ErrorCodes;
3132
import io.modelcontextprotocol.modern.McpSchema.Implementation;
3233
import io.modelcontextprotocol.modern.McpSchema.InputRequired;
@@ -238,6 +239,17 @@ private JSONRPCResponse resultResponse(McpRequestContext ctx, Result result) {
238239
return bug(ctx, "Method does not support input-required results");
239240
}
240241
Map<String, Object> resultMap = new LinkedHashMap<>(this.jsonMapper.convertValue(result, MAP_TYPE_REF));
242+
if (result instanceof InputRequired) {
243+
// Checked on the serialized form, so a request's elicitation mode is read the
244+
// same way the client will read it.
245+
String undeclared = undeclaredInputRequest(ctx.clientCapabilities(), resultMap.get("inputRequests"));
246+
if (undeclared != null) {
247+
return bug(ctx,
248+
"Input request '" + undeclared
249+
+ "' needs a client capability the request did not declare; require the capability"
250+
+ " up front or only request input the client declared");
251+
}
252+
}
241253
Map<String, Object> resultMeta = new LinkedHashMap<>();
242254
if (resultMap.get("_meta") instanceof Map<?, ?> existingMeta) {
243255
existingMeta.forEach((k, v) -> resultMeta.put(String.valueOf(k), v));
@@ -267,6 +279,31 @@ private static JSONRPCResponse errorResponse(Object id, Throwable throwable) {
267279
return JSONRPCResponse.error(id, new JSONRPCError(ErrorCodes.INTERNAL_ERROR, "Internal error"));
268280
}
269281

282+
// The key of the first input request the client cannot answer, or null if it can
283+
// answer all of them. Methods outside the spec's three are not checked.
284+
private static String undeclaredInputRequest(ClientCapabilities declared, Object inputRequests) {
285+
if (!(inputRequests instanceof Map<?, ?> requests)) {
286+
return null;
287+
}
288+
for (Map.Entry<?, ?> entry : requests.entrySet()) {
289+
if (!(entry.getValue() instanceof Map<?, ?> request)) {
290+
continue;
291+
}
292+
boolean supported = switch (String.valueOf(request.get("method"))) {
293+
case McpSchema.METHOD_ELICITATION_CREATE -> request.get("params") instanceof Map<?, ?> params
294+
&& ElicitUrlRequest.MODE.equals(params.get("mode")) ? declared.supportsElicitationUrl()
295+
: declared.supportsElicitationForm();
296+
case McpSchema.METHOD_SAMPLING_CREATE_MESSAGE -> declared.supportsSampling();
297+
case McpSchema.METHOD_ROOTS_LIST -> declared.supportsRoots();
298+
default -> true;
299+
};
300+
if (!supported) {
301+
return String.valueOf(entry.getKey());
302+
}
303+
}
304+
return null;
305+
}
306+
270307
private static JSONRPCResponse bug(McpRequestContext ctx, String problem) {
271308
logger.warn("Request {} ({}): {}", ctx.requestId(), ctx.method(), problem);
272309
return JSONRPCResponse.error(ctx.requestId(), new JSONRPCError(ErrorCodes.INTERNAL_ERROR, "Internal error"));

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
package io.modelcontextprotocol.modern.server.feature;
66

7+
import io.modelcontextprotocol.modern.McpSchema.ClientCapabilities;
78
import io.modelcontextprotocol.modern.McpSchema.GetPromptOutcome;
89
import io.modelcontextprotocol.modern.McpSchema.GetPromptRequest;
910
import io.modelcontextprotocol.modern.McpSchema.Prompt;
@@ -14,30 +15,55 @@
1415

1516
/**
1617
* A prompt's definition together with the handler that renders it.
18+
* <p>
19+
* Client capabilities the prompt cannot be rendered without belong in
20+
* {@link #requiredCapabilities()}: a client that did not declare them gets {@code -32021}
21+
* and the handler does not run. Input the prompt can do without, or can get another way,
22+
* is requested only when {@link McpRequestContext#clientCapabilities()} declares its
23+
* capability. Requesting input the client did not declare is answered with an internal
24+
* error.
1725
*
1826
* @author Dariusz Jędrzejczyk
1927
*/
2028
public final class McpAsyncPrompt {
2129

2230
private final Prompt definition;
2331

32+
private final ClientCapabilities requiredCapabilities;
33+
2434
private final Handler handler;
2535

26-
private McpAsyncPrompt(Prompt definition, Handler handler) {
36+
private McpAsyncPrompt(Prompt definition, ClientCapabilities requiredCapabilities, Handler handler) {
2737
Assert.notNull(definition, "definition must not be null");
38+
Assert.notNull(requiredCapabilities, "requiredCapabilities must not be null");
2839
Assert.notNull(handler, "handler must not be null");
2940
this.definition = definition;
41+
this.requiredCapabilities = requiredCapabilities;
3042
this.handler = handler;
3143
}
3244

45+
/** A prompt that requires no client capabilities. */
3346
public static McpAsyncPrompt of(Prompt definition, Handler handler) {
34-
return new McpAsyncPrompt(definition, handler);
47+
return new McpAsyncPrompt(definition, ClientCapabilities.NONE, handler);
48+
}
49+
50+
/**
51+
* A prompt that only works with clients declaring {@code requiredCapabilities}. A
52+
* request from any other client is rejected with {@code -32021} without running the
53+
* handler.
54+
*/
55+
public static McpAsyncPrompt of(Prompt definition, ClientCapabilities requiredCapabilities, Handler handler) {
56+
return new McpAsyncPrompt(definition, requiredCapabilities, handler);
3557
}
3658

3759
public Prompt definition() {
3860
return this.definition;
3961
}
4062

63+
public ClientCapabilities requiredCapabilities() {
64+
return this.requiredCapabilities;
65+
}
66+
4167
public Handler handler() {
4268
return this.handler;
4369
}

0 commit comments

Comments
 (0)