Skip to content

Commit 3fd1642

Browse files
committed
Add opt-in validation of required tool result content
1 parent c7fef64 commit 3fd1642

8 files changed

Lines changed: 657 additions & 13 deletions

File tree

‎docs/client.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,27 @@ var client = McpClient.sync(transport)
496496
.build();
497497
```
498498

499+
### Required Tool Result Content
500+
501+
By default, the SDK accepts a `tools/call` result with missing or null `content` and
502+
replaces it with an empty list. To reject these responses before that substitution,
503+
enable content validation on either the synchronous or asynchronous client builder:
504+
505+
```java
506+
var client = McpClient.async(transport)
507+
.validateCallToolResultContent(true)
508+
.build();
509+
```
510+
511+
With this option enabled, `callTool` fails with `IllegalArgumentException` when
512+
`content` is missing, null, or not an array, including when `isError` is true.
513+
An explicit `content: []` remains valid. This validates the required content field;
514+
it is separate from validating `structuredContent` against a tool's `outputSchema`.
515+
It does not enable strict validation for other MCP messages.
516+
517+
A rejected response does not imply that the server rolled back the tool's effects.
518+
The SDK does not retry the tool call because content validation failed.
519+
499520
### Pagination
500521

501522
`listTools`, `listResources`, `listResourceTemplates`, and `listPrompts` all accept an optional opaque `cursor` string, and their results carry a `nextCursor` that is non-null while more pages remain. Loop until `nextCursor` is `null` to collect every page:

‎mcp-core/src/main/java/io/modelcontextprotocol/client/McpAsyncClient.java‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,8 @@ public class McpAsyncClient {
185185

186186
private final boolean applyElicitationDefaults;
187187

188+
private final boolean validateCallToolResultContent;
189+
188190
/**
189191
* Create a new McpAsyncClient with the given transport and session request-response
190192
* timeout.
@@ -210,6 +212,7 @@ public class McpAsyncClient {
210212
this.toolsOutputSchemaCache = new ConcurrentHashMap<>();
211213
this.enableCallToolSchemaCaching = features.enableCallToolSchemaCaching();
212214
this.applyElicitationDefaults = features.applyElicitationDefaults();
215+
this.validateCallToolResultContent = features.validateCallToolResultContent();
213216

214217
// Request Handlers
215218
Map<String, RequestHandler<?>> requestHandlers = new HashMap<>();
@@ -672,6 +675,9 @@ static void applyElicitationDefaults(Map<String, Object> schema, Map<String, Obj
672675
private static final TypeRef<McpSchema.CallToolResult> CALL_TOOL_RESULT_TYPE_REF = new TypeRef<>() {
673676
};
674677

678+
private static final TypeRef<Object> RAW_TOOL_RESULT_TYPE_REF = new TypeRef<>() {
679+
};
680+
675681
private static final TypeRef<McpSchema.ListToolsResult> LIST_TOOLS_RESULT_TYPE_REF = new TypeRef<>() {
676682
};
677683

@@ -692,12 +698,26 @@ public Mono<McpSchema.CallToolResult> callTool(McpSchema.CallToolRequest callToo
692698
return Mono.error(new IllegalStateException("Server does not provide tools capability"));
693699
}
694700

695-
return init.mcpSession()
696-
.sendRequest(McpSchema.METHOD_TOOLS_CALL, callToolRequest, CALL_TOOL_RESULT_TYPE_REF)
697-
.flatMap(result -> Mono.just(validateToolResult(callToolRequest.name(), result)));
701+
Mono<McpSchema.CallToolResult> result = this.validateCallToolResultContent
702+
? init.mcpSession()
703+
.sendRequest(McpSchema.METHOD_TOOLS_CALL, callToolRequest, RAW_TOOL_RESULT_TYPE_REF)
704+
.map(this::decodeToolResultWithContentValidation)
705+
: init.mcpSession()
706+
.sendRequest(McpSchema.METHOD_TOOLS_CALL, callToolRequest, CALL_TOOL_RESULT_TYPE_REF);
707+
return result.map(value -> validateToolResult(callToolRequest.name(), value));
698708
});
699709
}
700710

711+
private McpSchema.CallToolResult decodeToolResultWithContentValidation(Object result) {
712+
// Check before CallToolResult.fromJson replaces missing or null content with [].
713+
Object content = result instanceof Map<?, ?> fields ? fields.get("content") : null;
714+
// Untyped JSON arrays may be represented as a List or a Java array by the mapper.
715+
if (!(content instanceof List<?>) && !(content instanceof Object[])) {
716+
throw new IllegalArgumentException("CallToolResult.content must be a non-null array");
717+
}
718+
return this.transport.unmarshalFrom(result, CALL_TOOL_RESULT_TYPE_REF);
719+
}
720+
701721
private McpSchema.CallToolResult validateToolResult(String toolName, McpSchema.CallToolResult result) {
702722

703723
if (!this.enableCallToolSchemaCaching || result == null || result.isError() == Boolean.TRUE) {

‎mcp-core/src/main/java/io/modelcontextprotocol/client/McpClient.java‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ class SyncSpec {
202202

203203
private boolean applyElicitationDefaults = false; // Default to false
204204

205+
private boolean validateCallToolResultContent;
206+
205207
private SyncSpec(McpClientTransport transport) {
206208
Assert.notNull(transport, "Transport must not be null");
207209
this.transport = transport;
@@ -545,6 +547,20 @@ public SyncSpec applyElicitationDefaults(boolean applyElicitationDefaults) {
545547
return this;
546548
}
547549

550+
/**
551+
* Validate that a tools/call result contains a non-null content array before
552+
* deserialization can substitute an empty list. Disabled by default for wire
553+
* compatibility. An explicit empty array remains valid. This check is independent
554+
* of tool output schema validation and also applies to results with isError=true.
555+
* @param validateCallToolResultContent true to reject missing, null or non-array
556+
* content with an IllegalArgumentException
557+
* @return This builder instance for method chaining
558+
*/
559+
public SyncSpec validateCallToolResultContent(boolean validateCallToolResultContent) {
560+
this.validateCallToolResultContent = validateCallToolResultContent;
561+
return this;
562+
}
563+
548564
/**
549565
* Create an instance of {@link McpSyncClient} with the provided configurations or
550566
* sensible defaults.
@@ -555,7 +571,8 @@ public McpSyncClient build() {
555571
this.roots, this.toolsChangeConsumers, this.resourcesChangeConsumers, this.resourcesUpdateConsumers,
556572
this.promptsChangeConsumers, this.loggingConsumers, this.progressConsumers,
557573
this.elicitationCompleteConsumers, this.samplingHandler, this.formElicitationHandler,
558-
this.urlElicitationHandler, this.enableCallToolSchemaCaching, this.applyElicitationDefaults);
574+
this.urlElicitationHandler, this.enableCallToolSchemaCaching, this.applyElicitationDefaults,
575+
this.validateCallToolResultContent);
559576

560577
McpClientFeatures.Async asyncFeatures = McpClientFeatures.Async.fromSync(syncFeatures);
561578

@@ -637,6 +654,8 @@ class AsyncSpec {
637654

638655
private boolean applyElicitationDefaults = false; // Default to false
639656

657+
private boolean validateCallToolResultContent;
658+
640659
private AsyncSpec(McpClientTransport transport) {
641660
Assert.notNull(transport, "Transport must not be null");
642661
this.transport = transport;
@@ -966,6 +985,20 @@ public AsyncSpec applyElicitationDefaults(boolean applyElicitationDefaults) {
966985
return this;
967986
}
968987

988+
/**
989+
* Validate that a tools/call result contains a non-null content array before
990+
* deserialization can substitute an empty list. Disabled by default for wire
991+
* compatibility. An explicit empty array remains valid. This check is independent
992+
* of tool output schema validation and also applies to results with isError=true.
993+
* @param validateCallToolResultContent true to reject missing, null or non-array
994+
* content with an IllegalArgumentException
995+
* @return This builder instance for method chaining
996+
*/
997+
public AsyncSpec validateCallToolResultContent(boolean validateCallToolResultContent) {
998+
this.validateCallToolResultContent = validateCallToolResultContent;
999+
return this;
1000+
}
1001+
9691002
/**
9701003
* Create an instance of {@link McpAsyncClient} with the provided configurations
9711004
* or sensible defaults.
@@ -980,8 +1013,8 @@ public McpAsyncClient build() {
9801013
this.toolsChangeConsumers, this.resourcesChangeConsumers, this.resourcesUpdateConsumers,
9811014
this.promptsChangeConsumers, this.loggingConsumers, this.progressConsumers,
9821015
this.elicitationCompleteConsumers, this.samplingHandler, this.formElicitationHandler,
983-
this.urlElicitationHandler, this.enableCallToolSchemaCaching,
984-
this.applyElicitationDefaults));
1016+
this.urlElicitationHandler, this.enableCallToolSchemaCaching, this.applyElicitationDefaults,
1017+
this.validateCallToolResultContent));
9851018
}
9861019

9871020
}

‎mcp-core/src/main/java/io/modelcontextprotocol/client/McpClientFeatures.java‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ class McpClientFeatures {
6666
* @param applyElicitationDefaults whether the client should fill in missing fields of
6767
* an accepted {@code ElicitResult.content} with the {@code default} values declared
6868
* in the {@code requestedSchema}.
69+
* @param validateCallToolResultContent whether to validate required tool result
70+
* content before deserialization.
6971
*/
7072
record Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,
7173
Map<String, McpSchema.Root> roots, List<Function<List<McpSchema.Tool>, Mono<Void>>> toolsChangeConsumers,
@@ -78,7 +80,8 @@ record Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities c
7880
Function<McpSchema.CreateMessageRequest, Mono<McpSchema.CreateMessageResult>> samplingHandler,
7981
Function<McpSchema.ElicitFormRequest, Mono<McpSchema.ElicitResult>> formElicitationHandler,
8082
Function<McpSchema.ElicitUrlRequest, Mono<McpSchema.ElicitResult>> urlElicitationHandler,
81-
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults) {
83+
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults,
84+
boolean validateCallToolResultContent) {
8285

8386
/**
8487
* Create an instance and validate the arguments.
@@ -95,6 +98,8 @@ record Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities c
9598
* @param applyElicitationDefaults whether the client should fill in missing
9699
* fields of an accepted {@code ElicitResult.content} with the {@code default}
97100
* values declared in the {@code requestedSchema}.
101+
* @param validateCallToolResultContent whether to validate required tool result
102+
* content before deserialization.
98103
*/
99104
public Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,
100105
Map<String, McpSchema.Root> roots,
@@ -108,7 +113,8 @@ public Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities c
108113
Function<McpSchema.CreateMessageRequest, Mono<McpSchema.CreateMessageResult>> samplingHandler,
109114
Function<McpSchema.ElicitFormRequest, Mono<McpSchema.ElicitResult>> formElicitationHandler,
110115
Function<McpSchema.ElicitUrlRequest, Mono<McpSchema.ElicitResult>> urlElicitationHandler,
111-
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults) {
116+
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults,
117+
boolean validateCallToolResultContent) {
112118

113119
Assert.notNull(clientInfo, "Client info must not be null");
114120
this.clientInfo = clientInfo;
@@ -132,6 +138,7 @@ public Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities c
132138
this.urlElicitationHandler = urlElicitationHandler;
133139
this.enableCallToolSchemaCaching = enableCallToolSchemaCaching;
134140
this.applyElicitationDefaults = applyElicitationDefaults;
141+
this.validateCallToolResultContent = validateCallToolResultContent;
135142
}
136143

137144
/**
@@ -148,7 +155,7 @@ public Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities c
148155
Function<McpSchema.ElicitFormRequest, Mono<McpSchema.ElicitResult>> elicitationHandler) {
149156
this(clientInfo, clientCapabilities, roots, toolsChangeConsumers, resourcesChangeConsumers,
150157
resourcesUpdateConsumers, promptsChangeConsumers, loggingConsumers, List.of(), List.of(),
151-
samplingHandler, elicitationHandler, null, false, false);
158+
samplingHandler, elicitationHandler, null, false, false, false);
152159
}
153160

154161
/**
@@ -223,7 +230,7 @@ public static Async fromSync(Sync syncSpec) {
223230
toolsChangeConsumers, resourcesChangeConsumers, resourcesUpdateConsumers, promptsChangeConsumers,
224231
loggingConsumers, progressConsumers, elicitationCompleteConsumers, samplingHandler,
225232
formElicitationHandler, urlElicitationHandler, syncSpec.enableCallToolSchemaCaching,
226-
syncSpec.applyElicitationDefaults);
233+
syncSpec.applyElicitationDefaults, syncSpec.validateCallToolResultContent);
227234
}
228235

229236
}
@@ -246,6 +253,8 @@ public static Async fromSync(Sync syncSpec) {
246253
* @param applyElicitationDefaults whether the client should fill in missing fields of
247254
* an accepted {@code ElicitResult.content} with the {@code default} values declared
248255
* in the {@code requestedSchema}.
256+
* @param validateCallToolResultContent whether to validate required tool result
257+
* content before deserialization.
249258
*/
250259
public record Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,
251260
Map<String, McpSchema.Root> roots, List<Consumer<List<McpSchema.Tool>>> toolsChangeConsumers,
@@ -258,7 +267,8 @@ public record Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabili
258267
Function<McpSchema.CreateMessageRequest, McpSchema.CreateMessageResult> samplingHandler,
259268
Function<McpSchema.ElicitFormRequest, McpSchema.ElicitResult> formElicitationHandler,
260269
Function<McpSchema.ElicitUrlRequest, McpSchema.ElicitResult> urlElicitationHandler,
261-
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults) {
270+
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults,
271+
boolean validateCallToolResultContent) {
262272

263273
/**
264274
* Create an instance and validate the arguments.
@@ -277,6 +287,8 @@ public record Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabili
277287
* @param applyElicitationDefaults whether the client should fill in missing
278288
* fields of an accepted {@code ElicitResult.content} with the {@code default}
279289
* values declared in the {@code requestedSchema}.
290+
* @param validateCallToolResultContent whether to validate required tool result
291+
* content before deserialization.
280292
*/
281293
public Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,
282294
Map<String, McpSchema.Root> roots, List<Consumer<List<McpSchema.Tool>>> toolsChangeConsumers,
@@ -289,7 +301,8 @@ public Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities cl
289301
Function<McpSchema.CreateMessageRequest, McpSchema.CreateMessageResult> samplingHandler,
290302
Function<McpSchema.ElicitFormRequest, McpSchema.ElicitResult> formElicitationHandler,
291303
Function<McpSchema.ElicitUrlRequest, McpSchema.ElicitResult> urlElicitationHandler,
292-
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults) {
304+
boolean enableCallToolSchemaCaching, boolean applyElicitationDefaults,
305+
boolean validateCallToolResultContent) {
293306

294307
Assert.notNull(clientInfo, "Client info must not be null");
295308
this.clientInfo = clientInfo;
@@ -313,6 +326,7 @@ public Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities cl
313326
this.urlElicitationHandler = urlElicitationHandler;
314327
this.enableCallToolSchemaCaching = enableCallToolSchemaCaching;
315328
this.applyElicitationDefaults = applyElicitationDefaults;
329+
this.validateCallToolResultContent = validateCallToolResultContent;
316330
}
317331

318332
/**
@@ -329,7 +343,7 @@ public Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities cl
329343
Function<McpSchema.ElicitUrlRequest, McpSchema.ElicitResult> urlElicitationHandler) {
330344
this(clientInfo, clientCapabilities, roots, toolsChangeConsumers, resourcesChangeConsumers,
331345
resourcesUpdateConsumers, promptsChangeConsumers, loggingConsumers, List.of(), List.of(),
332-
samplingHandler, formElicitationHandler, urlElicitationHandler, false, false);
346+
samplingHandler, formElicitationHandler, urlElicitationHandler, false, false, false);
333347
}
334348
}
335349

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Copyright 2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.client;
6+
7+
import io.modelcontextprotocol.spec.McpSchema;
8+
import org.junit.jupiter.api.Test;
9+
import org.junit.jupiter.params.ParameterizedTest;
10+
import org.junit.jupiter.params.provider.ValueSource;
11+
12+
import static org.assertj.core.api.Assertions.assertThat;
13+
14+
class McpClientFeaturesContentValidationTests {
15+
16+
private static final McpSchema.Implementation CLIENT_INFO = McpSchema.Implementation.builder("test", "1").build();
17+
18+
@ParameterizedTest
19+
@ValueSource(booleans = { true, false })
20+
void syncConversionPreservesContentValidation(boolean enabled) {
21+
var sync = new McpClientFeatures.Sync(CLIENT_INFO, null, null, null, null, null, null, null, null, null, null,
22+
null, null, true, true, enabled);
23+
var async = McpClientFeatures.Async.fromSync(sync);
24+
assertThat(async.validateCallToolResultContent()).isEqualTo(enabled);
25+
assertThat(async.enableCallToolSchemaCaching()).isTrue();
26+
assertThat(async.applyElicitationDefaults()).isTrue();
27+
assertThat(async.clientCapabilities()).isEqualTo(sync.clientCapabilities());
28+
}
29+
30+
@ParameterizedTest
31+
@ValueSource(booleans = { true, false })
32+
void asyncFeaturesPreserveContentValidation(boolean enabled) {
33+
var features = new McpClientFeatures.Async(CLIENT_INFO, null, null, null, null, null, null, null, null, null,
34+
null, null, null, true, true, enabled);
35+
assertThat(features.validateCallToolResultContent()).isEqualTo(enabled);
36+
assertThat(features.enableCallToolSchemaCaching()).isTrue();
37+
assertThat(features.applyElicitationDefaults()).isTrue();
38+
}
39+
40+
@Test
41+
void legacySyncConstructorKeepsContentValidationDisabled() {
42+
var sync = new McpClientFeatures.Sync(CLIENT_INFO, null, null, null, null, null, null, null, null, null, null);
43+
assertThat(sync.validateCallToolResultContent()).isFalse();
44+
assertThat(McpClientFeatures.Async.fromSync(sync).validateCallToolResultContent()).isFalse();
45+
}
46+
47+
@Test
48+
void legacyAsyncConstructorKeepsContentValidationDisabled() {
49+
var async = new McpClientFeatures.Async(CLIENT_INFO, null, null, null, null, null, null, null, null, null);
50+
assertThat(async.validateCallToolResultContent()).isFalse();
51+
}
52+
53+
}

0 commit comments

Comments
 (0)