Skip to content

Commit 8c39d24

Browse files
committed
Preserve explicit null in structured content (modelcontextprotocol#1000)
1 parent 932e656 commit 8c39d24

11 files changed

Lines changed: 460 additions & 21 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package io.modelcontextprotocol.json;
6+
7+
import com.fasterxml.jackson.annotation.JsonValue;
8+
9+
/**
10+
* Represents an explicit JSON {@code null}, distinct from an absent optional field
11+
* represented by Java {@code null}. For example, pass {@link #INSTANCE} as structured
12+
* content to include {@code "structuredContent": null} in a tool result.
13+
*
14+
* <p>
15+
* Custom {@link McpJsonMapper} implementations must serialize this value as JSON
16+
* {@code null}. Custom {@link io.modelcontextprotocol.json.schema.JsonSchemaValidator}
17+
* implementations must validate it as JSON {@code null}.
18+
*/
19+
public enum JsonNull {
20+
21+
/**
22+
* The JSON {@code null} value.
23+
*/
24+
INSTANCE;
25+
26+
/**
27+
* Returns the JSON representation of this value.
28+
* @return {@code null}
29+
*/
30+
@JsonValue
31+
public Object value() {
32+
return null;
33+
}
34+
35+
@Override
36+
public String toString() {
37+
return "null";
38+
}
39+
40+
}

‎mcp-core/src/main/java/io/modelcontextprotocol/json/schema/JsonSchemaValidator.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ public static ValidationResponse asInvalid(String message) {
6262
* JSON document and parsed before validation; quote embedded strings accordingly (for
6363
* example {@code "\"red\""} for the JSON string value {@code red}). Any other type is
6464
* converted to its JSON representation directly.
65+
* {@link io.modelcontextprotocol.json.JsonNull#INSTANCE} represents the explicit JSON
66+
* {@code null} value and must be validated as such.
6567
* @param schema The JSON schema to validate against.
6668
* @param structuredContent The structured content to validate.
6769
* @return A ValidationResponse indicating whether the validation was successful or

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

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
1616
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
1717
import com.fasterxml.jackson.annotation.JsonInclude;
1818
import com.fasterxml.jackson.annotation.JsonProperty;
19+
import com.fasterxml.jackson.annotation.JsonSetter;
1920
import com.fasterxml.jackson.annotation.JsonSubTypes;
2021
import com.fasterxml.jackson.annotation.JsonTypeInfo;
22+
import com.fasterxml.jackson.annotation.Nulls;
23+
import io.modelcontextprotocol.json.JsonNull;
2124
import io.modelcontextprotocol.json.McpJsonMapper;
2225
import io.modelcontextprotocol.json.TypeRef;
2326
import io.modelcontextprotocol.util.Assert;
@@ -1182,6 +1185,16 @@ public ReadResourceResult build() {
11821185
}
11831186
}
11841187

1188+
/**
1189+
* Result of a tool call.
1190+
*
1191+
* @param content returned content blocks
1192+
* @param structuredContent structured JSON output; Java {@code null} means absent.
1193+
* Use {@link JsonNull#INSTANCE} for explicit JSON {@code null}.
1194+
* @param isError whether tool execution failed
1195+
* @param resultType result kind
1196+
* @param meta protocol metadata
1197+
*/
11851198
@JsonInclude(JsonInclude.Include.NON_ABSENT)
11861199
@JsonIgnoreProperties(ignoreUnknown = true)
11871200
public record CallToolResult( // @formatter:off
@@ -1196,12 +1209,36 @@ public record CallToolResult( // @formatter:off
11961209
resultType = resultType == null ? ResultType.COMPLETE : resultType;
11971210
}
11981211

1199-
@JsonCreator
1200-
static CallToolResult fromJson(@JsonProperty("content") List<Content> content,
1201-
@JsonProperty("structuredContent") Object structuredContent, @JsonProperty("isError") Boolean isError,
1202-
@JsonProperty("resultType") String resultType, @JsonProperty("_meta") Map<String, Object> meta) {
1203-
content = content == null ? List.of() : content;
1204-
return new CallToolResult(content, structuredContent, isError, resultType, meta);
1212+
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
1213+
static CallToolResult fromJson(CallToolResultJson result) {
1214+
List<Content> content = result.content == null ? List.of() : result.content;
1215+
return new CallToolResult(content, result.structuredContentValue, result.isError, result.resultType,
1216+
result.meta);
1217+
}
1218+
1219+
@JsonIgnoreProperties(ignoreUnknown = true)
1220+
private static final class CallToolResultJson {
1221+
1222+
@JsonProperty("content")
1223+
private List<Content> content;
1224+
1225+
@JsonProperty("isError")
1226+
private Boolean isError;
1227+
1228+
@JsonProperty("resultType")
1229+
private String resultType;
1230+
1231+
@JsonProperty("_meta")
1232+
private Map<String, Object> meta;
1233+
1234+
@JsonIgnore
1235+
private Object structuredContentValue;
1236+
1237+
@JsonSetter(value = "structuredContent", nulls = Nulls.SET)
1238+
private void setStructuredContent(Object value) {
1239+
this.structuredContentValue = value == null ? JsonNull.INSTANCE : value;
1240+
}
1241+
12051242
}
12061243

12071244
public static Builder builder() {
@@ -1230,6 +1267,12 @@ public Builder addContent(Content contentItem) {
12301267
return this;
12311268
}
12321269

1270+
/**
1271+
* Sets the structured content value. Use {@link JsonNull#INSTANCE} for
1272+
* explicit JSON {@code null}, or Java {@code null} to leave the field absent.
1273+
* @param structuredContent the structured JSON value, or Java {@code null}
1274+
* @return this builder
1275+
*/
12331276
public Builder structuredContent(Object structuredContent) {
12341277
this.structuredContent = structuredContent;
12351278
return this;

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

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@
1616
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
1717
import com.fasterxml.jackson.annotation.JsonInclude;
1818
import com.fasterxml.jackson.annotation.JsonProperty;
19+
import com.fasterxml.jackson.annotation.JsonSetter;
1920
import com.fasterxml.jackson.annotation.JsonSubTypes;
2021
import com.fasterxml.jackson.annotation.JsonTypeInfo;
22+
import com.fasterxml.jackson.annotation.Nulls;
23+
import io.modelcontextprotocol.json.JsonNull;
2124
import io.modelcontextprotocol.json.McpJsonMapper;
2225
import io.modelcontextprotocol.json.TypeRef;
2326
import io.modelcontextprotocol.util.Assert;
@@ -3227,7 +3230,8 @@ public CallToolRequest build() {
32273230
* @param isError If true, indicates that the tool execution failed and the content
32283231
* contains error information. If false or absent, indicates successful execution.
32293232
* @param structuredContent An optional structured JSON value. Java {@code null}
3230-
* indicates that the field is absent.
3233+
* indicates that the field is absent; {@link JsonNull#INSTANCE} represents explicit
3234+
* JSON {@code null}.
32313235
* @param meta See specification for notes on _meta usage
32323236
* <p>
32333237
* Note: {@code content} is required by the MCP specification. Deserialization accepts
@@ -3246,15 +3250,36 @@ public record CallToolResult( // @formatter:off
32463250
Assert.notNull(content, "content must not be null");
32473251
}
32483252

3249-
@JsonCreator
3250-
static CallToolResult fromJson(@JsonProperty("content") List<Content> content,
3251-
@JsonProperty("isError") Boolean isError, @JsonProperty("structuredContent") Object structuredContent,
3252-
@JsonProperty("_meta") Map<String, Object> meta) {
3253+
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
3254+
static CallToolResult fromJson(CallToolResultJson result) {
3255+
List<Content> content = result.content;
32533256
if (content == null) {
32543257
logger.warn("CallToolResult: missing required fields during deserialization: content -> []");
32553258
content = List.of();
32563259
}
3257-
return new CallToolResult(content, isError, structuredContent, meta);
3260+
return new CallToolResult(content, result.isError, result.structuredContentValue, result.meta);
3261+
}
3262+
3263+
@JsonIgnoreProperties(ignoreUnknown = true)
3264+
private static final class CallToolResultJson {
3265+
3266+
@JsonProperty("content")
3267+
private List<Content> content;
3268+
3269+
@JsonProperty("isError")
3270+
private Boolean isError;
3271+
3272+
@JsonProperty("_meta")
3273+
private Map<String, Object> meta;
3274+
3275+
@JsonIgnore
3276+
private Object structuredContentValue;
3277+
3278+
@JsonSetter(value = "structuredContent", nulls = Nulls.SET)
3279+
private void setStructuredContent(Object value) {
3280+
this.structuredContentValue = value == null ? JsonNull.INSTANCE : value;
3281+
}
3282+
32583283
}
32593284

32603285
/**
@@ -3310,22 +3335,31 @@ public Builder content(List<Content> content) {
33103335
return this;
33113336
}
33123337

3338+
/**
3339+
* Sets the structured content value. Use {@link JsonNull#INSTANCE} for
3340+
* explicit JSON {@code null}; omit this call to leave the field absent.
3341+
* @param structuredContent the non-null structured JSON value
3342+
* @return this builder
3343+
* @throws IllegalArgumentException if structuredContent is Java {@code null}
3344+
*/
33133345
public Builder structuredContent(Object structuredContent) {
33143346
Assert.notNull(structuredContent, "structuredContent must not be null");
33153347
this.structuredContent = structuredContent;
33163348
return this;
33173349
}
33183350

33193351
/**
3320-
* Sets the structured content by parsing a non-null JSON value.
3352+
* Sets the structured content by parsing a JSON value, including JSON
3353+
* {@code null}, which is represented by {@link JsonNull#INSTANCE}.
33213354
* @param jsonMapper the mapper used to parse the value
3322-
* @param structuredContent the JSON-encoded non-null structured content
3355+
* @param structuredContent the JSON-encoded structured content
33233356
* @return this builder
33243357
*/
33253358
public Builder structuredContent(McpJsonMapper jsonMapper, String structuredContent) {
33263359
Assert.hasText(structuredContent, "structuredContent must not be empty");
33273360
try {
3328-
this.structuredContent(jsonMapper.readValue(structuredContent, Object.class));
3361+
Object value = jsonMapper.readValue(structuredContent, Object.class);
3362+
this.structuredContent(value == null ? JsonNull.INSTANCE : value);
33293363
}
33303364
catch (IOException e) {
33313365
throw new IllegalArgumentException("Invalid structured content: " + structuredContent, e);

‎mcp-json-jackson2/src/test/java/io/modelcontextprotocol/json/McpJsonMapperTest.java‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,17 @@
66

77
import static org.assertj.core.api.Assertions.assertThat;
88

9+
import java.util.stream.Stream;
10+
11+
import com.fasterxml.jackson.annotation.JsonAutoDetect;
12+
import com.fasterxml.jackson.annotation.JsonSetter;
13+
import com.fasterxml.jackson.annotation.Nulls;
14+
import com.fasterxml.jackson.annotation.PropertyAccessor;
15+
import com.fasterxml.jackson.databind.ObjectMapper;
16+
import org.junit.jupiter.api.Named;
917
import org.junit.jupiter.api.Test;
18+
import org.junit.jupiter.params.ParameterizedTest;
19+
import org.junit.jupiter.params.provider.MethodSource;
1020

1121
import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper;
1222

@@ -17,4 +27,34 @@ void shouldUseJackson2Mapper() {
1727
assertThat(McpJsonDefaults.getMapper()).isInstanceOf(JacksonMcpJsonMapper.class);
1828
}
1929

30+
@ParameterizedTest
31+
@MethodSource("customMappers")
32+
void callToolResultsPreserveJsonNullWithCustomMapper(McpJsonMapper mapper) throws Exception {
33+
String json = "{\"content\":[],\"structuredContent\":null,\"structuredContentValue\":\"ignored\",\"future\":true}";
34+
var legacy = mapper.readValue(json, io.modelcontextprotocol.spec.McpSchema.CallToolResult.class);
35+
var modern = mapper.readValue(json, io.modelcontextprotocol.modern.McpSchema.CallToolResult.class);
36+
37+
assertThat(legacy.structuredContent()).isSameAs(JsonNull.INSTANCE);
38+
assertThat(modern.structuredContent()).isSameAs(JsonNull.INSTANCE);
39+
assertThat(mapper.writeValueAsString(legacy)).contains("\"structuredContent\":null");
40+
assertThat(mapper.writeValueAsString(modern)).contains("\"structuredContent\":null");
41+
42+
String absentJson = "{\"content\":[],\"structuredContentValue\":\"ignored\"}";
43+
var absentLegacy = mapper.readValue(absentJson, io.modelcontextprotocol.spec.McpSchema.CallToolResult.class);
44+
var absentModern = mapper.readValue(absentJson, io.modelcontextprotocol.modern.McpSchema.CallToolResult.class);
45+
46+
assertThat(absentLegacy.structuredContent()).isNull();
47+
assertThat(absentModern.structuredContent()).isNull();
48+
assertThat(mapper.writeValueAsString(absentLegacy)).doesNotContain("\"structuredContent\"");
49+
assertThat(mapper.writeValueAsString(absentModern)).doesNotContain("\"structuredContent\"");
50+
}
51+
52+
static Stream<Named<McpJsonMapper>> customMappers() {
53+
ObjectMapper fieldVisibility = new ObjectMapper().setVisibility(PropertyAccessor.FIELD,
54+
JsonAutoDetect.Visibility.ANY);
55+
ObjectMapper skipNulls = new ObjectMapper().setDefaultSetterInfo(JsonSetter.Value.forValueNulls(Nulls.SKIP));
56+
return Stream.of(Named.of("field visibility ANY", new JacksonMcpJsonMapper(fieldVisibility)),
57+
Named.of("skip null setters", new JacksonMcpJsonMapper(skipNulls)));
58+
}
59+
2060
}

‎mcp-json-jackson2/src/test/java/io/modelcontextprotocol/json/jackson2/DefaultJsonSchemaValidatorTests.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import java.util.Map;
1919
import java.util.stream.Stream;
2020

21+
import io.modelcontextprotocol.json.JsonNull;
2122
import io.modelcontextprotocol.spec.McpSchema;
2223

2324
import org.junit.jupiter.api.BeforeEach;
@@ -78,6 +79,12 @@ private List<Map<String, Object>> toListMap(String json) {
7879
}
7980
}
8081

82+
@Test
83+
void testValidateExplicitJsonNull() {
84+
assertTrue(validator.validate(Map.of("type", "null"), JsonNull.INSTANCE).valid());
85+
assertFalse(validator.validate(Map.of("type", "object"), JsonNull.INSTANCE).valid());
86+
}
87+
8188
@Test
8289
void testDefaultConstructor() {
8390
DefaultJsonSchemaValidator defaultValidator = new DefaultJsonSchemaValidator();

‎mcp-json-jackson3/src/test/java/io/modelcontextprotocol/json/DefaultJsonSchemaValidatorTests.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ private List<Map<String, Object>> toListMap(String json) {
7878
}
7979
}
8080

81+
@Test
82+
void testValidateExplicitJsonNull() {
83+
assertTrue(validator.validate(Map.of("type", "null"), JsonNull.INSTANCE).valid());
84+
assertFalse(validator.validate(Map.of("type", "object"), JsonNull.INSTANCE).valid());
85+
}
86+
8187
@Test
8288
void testDefaultConstructor() {
8389
DefaultJsonSchemaValidator defaultValidator = new DefaultJsonSchemaValidator();

‎mcp-json-jackson3/src/test/java/io/modelcontextprotocol/json/McpJsonMapperTest.java‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,58 @@
66

77
import static org.assertj.core.api.Assertions.assertThat;
88

9+
import java.util.stream.Stream;
10+
11+
import com.fasterxml.jackson.annotation.JsonAutoDetect;
12+
import com.fasterxml.jackson.annotation.JsonSetter;
13+
import com.fasterxml.jackson.annotation.Nulls;
14+
import org.junit.jupiter.api.Named;
915
import org.junit.jupiter.api.Test;
16+
import org.junit.jupiter.params.ParameterizedTest;
17+
import org.junit.jupiter.params.provider.MethodSource;
18+
19+
import tools.jackson.databind.json.JsonMapper;
1020

1121
import io.modelcontextprotocol.json.jackson3.JacksonMcpJsonMapper;
1222

1323
class McpJsonMapperTest {
1424

1525
@Test
16-
void shouldUseJackson2Mapper() {
26+
void shouldUseJackson3Mapper() {
1727
assertThat(McpJsonDefaults.getMapper()).isInstanceOf(JacksonMcpJsonMapper.class);
1828
}
1929

30+
@ParameterizedTest
31+
@MethodSource("customMappers")
32+
void callToolResultsPreserveJsonNullWithCustomMapper(McpJsonMapper mapper) throws Exception {
33+
String json = "{\"content\":[],\"structuredContent\":null,\"structuredContentValue\":\"ignored\",\"future\":true}";
34+
var legacy = mapper.readValue(json, io.modelcontextprotocol.spec.McpSchema.CallToolResult.class);
35+
var modern = mapper.readValue(json, io.modelcontextprotocol.modern.McpSchema.CallToolResult.class);
36+
37+
assertThat(legacy.structuredContent()).isSameAs(JsonNull.INSTANCE);
38+
assertThat(modern.structuredContent()).isSameAs(JsonNull.INSTANCE);
39+
assertThat(mapper.writeValueAsString(legacy)).contains("\"structuredContent\":null");
40+
assertThat(mapper.writeValueAsString(modern)).contains("\"structuredContent\":null");
41+
42+
String absentJson = "{\"content\":[],\"structuredContentValue\":\"ignored\"}";
43+
var absentLegacy = mapper.readValue(absentJson, io.modelcontextprotocol.spec.McpSchema.CallToolResult.class);
44+
var absentModern = mapper.readValue(absentJson, io.modelcontextprotocol.modern.McpSchema.CallToolResult.class);
45+
46+
assertThat(absentLegacy.structuredContent()).isNull();
47+
assertThat(absentModern.structuredContent()).isNull();
48+
assertThat(mapper.writeValueAsString(absentLegacy)).doesNotContain("\"structuredContent\"");
49+
assertThat(mapper.writeValueAsString(absentModern)).doesNotContain("\"structuredContent\"");
50+
}
51+
52+
static Stream<Named<McpJsonMapper>> customMappers() {
53+
JsonMapper fieldVisibility = JsonMapper.builder()
54+
.changeDefaultVisibility(visibility -> visibility.withFieldVisibility(JsonAutoDetect.Visibility.ANY))
55+
.build();
56+
JsonMapper skipNulls = JsonMapper.builder()
57+
.changeDefaultNullHandling(nulls -> JsonSetter.Value.forValueNulls(Nulls.SKIP))
58+
.build();
59+
return Stream.of(Named.of("field visibility ANY", new JacksonMcpJsonMapper(fieldVisibility)),
60+
Named.of("skip null setters", new JacksonMcpJsonMapper(skipNulls)));
61+
}
62+
2063
}

0 commit comments

Comments
 (0)