Support distinguishing null vs absent fields in MCP tool parameters for partial update operations
Problem
When building MCP tools that perform partial updates, there is currently no way to
distinguish between a field that was explicitly set to null (meaning "clear this value")
and a field that was simply omitted from the call (meaning "leave this value unchanged").
This is a common requirement for update operations. For example, a tool that updates
an entity with optional description and parent_id fields:
@Tool
public void updateItem(String id, String description, Long parentId) {
// Was parentId omitted (skip) or explicitly null (clear)?
// Impossible to tell after deserialization.
}
When the LLM calls this tool with {"id": "123", "description": "new value"},
both the omitted parentId and an explicitly passed null arrive as null in Java —
the intent is lost.
Expected Behavior
It should be possible to detect whether a parameter was explicitly set to null or was absent from the tool call payload.
One well-established solution is jackson-databind-nullable (https://github.com/OpenAPITools/jackson-databind-nullable),
which provides a JsonNullable<T> wrapper type for exactly this distinction:
@Tool
public void updateItem(String id, JsonNullable<String> description, JsonNullable<Long> parentId) {
if (JsonNullable.undefined().equals(parentId)) {
// field was omitted — skip
} else if (parentId.get() == null) {
// field was explicitly null — clear it
} else {
// field has a value — update it
}
}
Workaround (partial)
It is possible to fix the deserialization side today by manually patching Spring AI's (v.1.1.4) internal ObjectMapper at application startup:
@PostConstruct
public void registerJsonNullableModule() {
JsonParser.getObjectMapper().registerModule(new JsonNullableModule());
}
@Bean(name = "mcpServerObjectMapper")
public ObjectMapper mcpServerObjectMapper() {
return JsonMapper.builder()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.addModules(JacksonUtils.instantiateAvailableModules())
.addModule(new JsonNullableModule()) // module registration
.build();
}
However, this only partially solves the problem:
- ✅ JsonNullable
fields are correctly deserialized from tool call payloads - ❌ JsonSchemaGenerator does not support JsonNullableModule, so the generated
MCP input schema for JsonNullable
patameters is incorrect — the LLM receives a wrong or misleading schema for those fields
Hi, I can take a look at this.
I went through JsonSchemaGenerator and the underlying victools setup. The gap is that JsonNullable<T> is unknown to the schema generator, so the generated schema may describe the wrapper rather than the wrapped value, and a JsonNullable<T> parameter still ends up in required[], which does not match the optional/nullable semantics users expect from it.
I think a small, focused PR could cover this:
- treat
jackson-databind-nullableas a classpath-detected optional integration, not a runtime dependency, - when present, unwrap
JsonNullable<T>toTfor both top-level tool parameters and POJO/record fields, - mark unannotated
JsonNullable<T>parameters/properties as not required, while still respecting explicit annotations such as@ToolParam(required = true), - allow explicit
nullin the generated schema so the model can send a "clear this value" signal.
Automatic ObjectMapper / JsonNullableModule registration would stay out of scope.
Please let me know if this is an acceptable direction, or if you'd prefer something different.
@jewoodev, Hi! Thanks for your response.
I investigated the code myself and can confirm that the minimum change needed is an option to register custom modules in org.springframework.ai.util.json.schema.JsonSchemaGenerator.
Locally, I implemented a FlattenedWrapperModule<JsonNullable> and registered it in JsonSchemaGenerator.
package org.springframework.ai.util.json.schema;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.impl.module.FlattenedWrapperModule;
import org.openapitools.jackson.nullable.JsonNullable;
public class JsonNullableSchemaModule extends FlattenedWrapperModule<JsonNullable> {
public JsonNullableSchemaModule() {
super(JsonNullable.class);
}
@Override
public void applyToConfigBuilder(SchemaGeneratorConfigBuilder builder) {
super.applyToConfigBuilder(builder);
builder.forFields()
.withNullableCheck(field -> this.hasMemberWrapperType(field) ? Boolean.TRUE : null);
builder.forMethods()
.withNullableCheck(method -> this.hasMemberWrapperType(method) ? Boolean.TRUE : null);
}
}
This solved the issue - types are now properly resolved and produce the following JSON:
{
"email": {
"type": [
"string",
"null"
]
}
}
As for the required section, @ToolParam(required = false) is sufficient for my use case.
Thanks for the pointer to FlattenedWrapperModule, @Dryunkaaa — it was helpful for the member-level record/POJO cases, and I extended the implementation to cover top-level tool parameters as well. I've now opened the implementation as #6071.
The member-level record/POJO cases work well with the wrapper-module approach. The extra gap I found is top-level @Tool method parameters: those don't go through the forFields() / forMethods() hooks, so the PR adds a type-level custom definition provider inside the schema module.
That provider detects JsonNullable<T>, delegates schema generation to the wrapped T, and marks the result as nullable. The targeted JsonSchemaGeneratorTests suite now covers top-level parameters, record/POJO fields, generic wrappers, object wrappers, and explicit @ToolParam(required = true) override cases.
For required, the PR treats unannotated JsonNullable<T> parameters/fields as not required by default, while explicit @ToolParam, JsonProperty, or Schema settings still win. If you prefer to preserve Spring AI's required-by-default policy and rely on @ToolParam(required = false) instead, I can adjust the PR in that direction.
@jewoodev, thanks for the detailed write-up and the PR! The approach with the type-level custom definition provider for top-level parameters makes sense.
Regarding required: I prefer the default required = false for JsonNullable<T> parameters - it feels semantically correct, since the whole point of wrapping a field in JsonNullable is to make it optional.
The schema-side implementation for this is open as #6071. It detects JsonNullable on the classpath (the artifact is optional) and registers a schema module the same way the existing KotlinModule is, unwrapping JsonNullable<T> to T and adding "null" to the allowed types — for both top-level @Tool parameters and record/POJO fields.
One design point I'd like the team's call on: the PR special-cases JsonNullable directly, which adds jackson-databind-nullable as an optional dependency to spring-ai-model. The alternative @Dryunkaaa raised earlier is a general hook in JsonSchemaGenerator for registering custom schema modules — no new dependency and nothing library-specific, at the cost of more setup on the user side. I went with the focused version but am happy to switch to the general hook if you'd rather keep that dependency out.
(The required default — not-required for unannotated JsonNullable<T>, explicit annotations winning — is already settled with @Dryunkaaa.)
@jewoodev , Hi!
JsonNullable<EnumType> needs null added to enum, not just type
Building on PR #6071's approach (FlattenedWrapperModule<JsonNullable> unwrapping JsonNullable<T> and adding "null" to the generated schema's "type"), there's a gap when T is an enum that isn't covered by the PR's current tests.
Repro
public enum UserStatus { ACTIVE, BLOCKED }
record Request(JsonNullable<UserStatus> status) {}
Generated schema for status:
{
"type": ["string", "null"],
"enum": ["ACTIVE", "BLOCKED"]
}
Problem
In JSON Schema, "type" and "enum" are independent constraints that both must be satisfied — "type" allowing null doesn't imply "enum" does. Since null isn't listed in "enum", a conforming validator rejects an explicit "status": null, e.g. does not have a value in the enumeration [ACTIVE, BLOCKED].
In an MCP server (validateToolInputs defaults to true), this rejection happens at the protocol layer, before the tool method is ever invoked — no application code, no @Valid/Bean Validation, nothing downstream gets a chance to run. The practical effect: an enum-typed field can never be cleared to null at all — every such call is rejected purely because the generated schema is internally inconsistent (type permits null, enum forbids it), not because of any real validation rule. Non-enum JsonNullable fields (String, Integer, nested objects, etc.) aren't affected, since they don't carry an enum constraint to contradict — which is why this is easy to miss until specifically testing an enum field.
Possible fix
private static void addNullToEnum(ObjectNode schema) {
JsonNode enumNode = schema.get("enum");
if (enumNode == null || !enumNode.isArray()) {
return;
}
ArrayNode enumValues = (ArrayNode) enumNode;
for (JsonNode value : enumValues) {
if (value.isNull()) {
return;
}
}
enumValues.addNull();
}
@jewoodev , one more finding while trying out #6071 against a real MCP server.
McpJsonSchemaGenerator (spring-ai-mcp-annotations) isn't covered by this fix — @McpTool parameter schemas stay unfixed
PR #6071 registers JsonNullableSchemaModule in org.springframework.ai.util.json.schema.JsonSchemaGenerator (module spring-ai-model). But the schema for an @McpTool method's parameters — what actually matters for MCP tools — isn't built by that class. It's built by a separate one, org.springframework.ai.mcp.annotation.method.tool.utils.McpJsonSchemaGenerator, in a different module (spring-ai-mcp-annotations).
That class builds its own hardcoded SchemaGeneratorConfigBuilder:
Module jacksonModule = new JacksonSchemaModule(JacksonOption.RESPECT_JSONPROPERTY_REQUIRED);
Module openApiModule = new Swagger2Module();
Module springAiSchemaModule = ...; // McpSpringAiSchemaModule
...
if (kotlinPresent) {
subtypeConfigBuilder.with(new KotlinModule());
}
SUBTYPE_SCHEMA_GENERATOR = new SchemaGenerator(subtypeConfig);
There's no classpath-detection for JsonNullable here, and no registration of JsonNullableSchemaModule — PR #6071 doesn't touch this file at all.
Confirmed live, not just from reading the code: I built spring-ai-model from pr-6071 (plus the addNullToEnum fix from my earlier comment) and wired the jar into a real MCP server with @McpTool methods taking JsonNullable<T> parameters. The generated tool input schemas still came out as opaque, unfixed placeholders ({"type": "object"}, no unwrapping) — exactly the pre-fix behavior, confirming this isn't just a theoretical gap.
So as currently scoped, #6071 wouldn't actually fix JsonNullable<T> support for MCP tool parameters — the code path that matters for MCP servers never reaches JsonNullableSchemaModule. Would it make sense for McpJsonSchemaGenerator to also register it conditionally, the same way JsonSchemaGenerator does?