feat: Introduce McpJsonMapper interface to decouple from Jackson (#543)

This pull request creates two modules, `mcp-json` and `mcp-json-jackson`. It removes the `com.fasterxml.jackson.core:jackson-databind` and `com.networknt:json-schema-validator` dependencies from the `mcp` module. The `mcp` module now only depends on `com.fasterxml.jackson.core:jackson-annotations`.

To use Jackson, you have to add `mcp-jackson` to your dependencies in addition to `mcp`. I added the dependency `mcp-jackson` to both `mcp-spring-mvc` and `mcp-spring-webflux` to avoid a breaking change in those modules.

It provides two [SPI](https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html) `JsonSchemaValidatorSupplier` and `JacksonJsonSchemaValidatorSupplier` to allow easy replacement for consumers who don't want to use Jackson.

This pull request also ensures no `McpJsonMapper` is instantiated if one is provided via a builder method. Only if the builders don't receive a `McpJsonMapper` mapper, one is instantiated in the `build` method of the builder.
The logic behind this is to allow frameworks to provide a `McpJsonMapper` mapper singleton implementation and feed it to the builders without paying the price of instantiating `McpJsonMappers`, which will not be used. The goal is to be able to use the `ObjectMapper` singleton of an application also for the MCP code.

Signed-off-by: Christian Tzolov <christian.tzolov@broadcom.com>
This commit is contained in:
Graeme Rocher 2025-09-10 12:26:17 +02:00 • committed by Christian Tzolov
commit 80d0ad82a6
6 changed files with 2043 additions and 1421 deletions

View file

@ -0,0 +1,87 @@
/*
* Copyright 2025 - 2025 the original author or authors.
*/
package io.modelcontextprotocol.json.jackson;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.json.TypeRef;
import java.io.IOException;
/**
* Jackson-based implementation of JsonMapper. Wraps a Jackson ObjectMapper but keeps the
* SDK decoupled from Jackson at the API level.
*/
public final class JacksonMcpJsonMapper implements McpJsonMapper {
private final ObjectMapper objectMapper;
/**
* Constructs a new JacksonMcpJsonMapper instance with the given ObjectMapper.
* @param objectMapper the ObjectMapper to be used for JSON serialization and
* deserialization. Must not be null.
* @throws IllegalArgumentException if the provided ObjectMapper is null.
*/
public JacksonMcpJsonMapper(ObjectMapper objectMapper) {
if (objectMapper == null) {
throw new IllegalArgumentException("ObjectMapper must not be null");
}
this.objectMapper = objectMapper;
}
/**
* Returns the underlying Jackson {@link ObjectMapper} used for JSON serialization and
* deserialization.
* @return the ObjectMapper instance
*/
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public <T> T readValue(String content, Class<T> type) throws IOException {
return objectMapper.readValue(content, type);
}
@Override
public <T> T readValue(byte[] content, Class<T> type) throws IOException {
return objectMapper.readValue(content, type);
}
@Override
public <T> T readValue(String content, TypeRef<T> type) throws IOException {
JavaType javaType = objectMapper.getTypeFactory().constructType(type.getType());
return objectMapper.readValue(content, javaType);
}
@Override
public <T> T readValue(byte[] content, TypeRef<T> type) throws IOException {
JavaType javaType = objectMapper.getTypeFactory().constructType(type.getType());
return objectMapper.readValue(content, javaType);
}
@Override
public <T> T convertValue(Object fromValue, Class<T> type) {
return objectMapper.convertValue(fromValue, type);
}
@Override
public <T> T convertValue(Object fromValue, TypeRef<T> type) {
JavaType javaType = objectMapper.getTypeFactory().constructType(type.getType());
return objectMapper.convertValue(fromValue, javaType);
}
@Override
public String writeValueAsString(Object value) throws IOException {
return objectMapper.writeValueAsString(value);
}
@Override
public byte[] writeValueAsBytes(Object value) throws IOException {
return objectMapper.writeValueAsBytes(value);
}
}

View file

@ -0,0 +1,32 @@
/*
* Copyright 2025 - 2025 the original author or authors.
*/
package io.modelcontextprotocol.json.jackson;
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.json.McpJsonMapperSupplier;
/**
* A supplier of {@link McpJsonMapper} instances that uses the Jackson library for JSON
* serialization and deserialization.
* <p>
* This implementation provides a {@link McpJsonMapper} backed by a Jackson
* {@link com.fasterxml.jackson.databind.ObjectMapper}.
*/
public class JacksonMcpJsonMapperSupplier implements McpJsonMapperSupplier {
/**
* Returns a new instance of {@link McpJsonMapper} that uses the Jackson library for
* JSON serialization and deserialization.
* <p>
* The returned {@link McpJsonMapper} is backed by a new instance of
* {@link com.fasterxml.jackson.databind.ObjectMapper}.
* @return a new {@link McpJsonMapper} instance
*/
@Override
public McpJsonMapper get() {
return new JacksonMcpJsonMapper(new com.fasterxml.jackson.databind.ObjectMapper());
}
}

View file

@ -0,0 +1,172 @@
/*
* Copyright 2024-2024 the original author or authors.
*/
package io.modelcontextprotocol.json.schema.jackson;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
/**
* Default implementation of the {@link JsonSchemaValidator} interface. This class
* provides methods to validate structured content against a JSON schema. It uses the
* NetworkNT JSON Schema Validator library for validation.
*
* @author Christian Tzolov
*/
public class DefaultJsonSchemaValidator implements JsonSchemaValidator {
private static final Logger logger = LoggerFactory.getLogger(DefaultJsonSchemaValidator.class);
private final ObjectMapper objectMapper;
private final JsonSchemaFactory schemaFactory;
// TODO: Implement a strategy to purge the cache (TTL, size limit, etc.)
private final ConcurrentHashMap<String, JsonSchema> schemaCache;
public DefaultJsonSchemaValidator() {
this(new ObjectMapper());
}
public DefaultJsonSchemaValidator(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
this.schemaCache = new ConcurrentHashMap<>();
}
@Override
public ValidationResponse validate(Map<String, Object> schema, Object structuredContent) {
if (schema == null) {
throw new IllegalArgumentException("Schema must not be null");
}
if (structuredContent == null) {
throw new IllegalArgumentException("Structured content must not be null");
}
try {
JsonNode jsonStructuredOutput = this.objectMapper.valueToTree(structuredContent);
Set<ValidationMessage> validationResult = this.getOrCreateJsonSchema(schema).validate(jsonStructuredOutput);
// Check if validation passed
if (!validationResult.isEmpty()) {
return ValidationResponse
.asInvalid("Validation failed: structuredContent does not match tool outputSchema. "
+ "Validation errors: " + validationResult);
}
return ValidationResponse.asValid(jsonStructuredOutput.toString());
}
catch (JsonProcessingException e) {
logger.error("Failed to validate CallToolResult: Error parsing schema: {}", e);
return ValidationResponse.asInvalid("Error parsing tool JSON Schema: " + e.getMessage());
}
catch (Exception e) {
logger.error("Failed to validate CallToolResult: Unexpected error: {}", e);
return ValidationResponse.asInvalid("Unexpected validation error: " + e.getMessage());
}
}
/**
* Gets a cached JsonSchema or creates and caches a new one.
* @param schema the schema map to convert
* @return the compiled JsonSchema
* @throws JsonProcessingException if schema processing fails
*/
private JsonSchema getOrCreateJsonSchema(Map<String, Object> schema) throws JsonProcessingException {
// Generate cache key based on schema content
String cacheKey = this.generateCacheKey(schema);
// Try to get from cache first
JsonSchema cachedSchema = this.schemaCache.get(cacheKey);
if (cachedSchema != null) {
return cachedSchema;
}
// Create new schema if not in cache
JsonSchema newSchema = this.createJsonSchema(schema);
// Cache the schema
JsonSchema existingSchema = this.schemaCache.putIfAbsent(cacheKey, newSchema);
return existingSchema != null ? existingSchema : newSchema;
}
/**
* Creates a new JsonSchema from the given schema map.
* @param schema the schema map
* @return the compiled JsonSchema
* @throws JsonProcessingException if schema processing fails
*/
private JsonSchema createJsonSchema(Map<String, Object> schema) throws JsonProcessingException {
// Convert schema map directly to JsonNode (more efficient than string
// serialization)
JsonNode schemaNode = this.objectMapper.valueToTree(schema);
// Handle case where ObjectMapper might return null (e.g., in mocked scenarios)
if (schemaNode == null) {
throw new JsonProcessingException("Failed to convert schema to JsonNode") {
};
}
// Handle additionalProperties setting
if (schemaNode.isObject()) {
ObjectNode objectSchemaNode = (ObjectNode) schemaNode;
if (!objectSchemaNode.has("additionalProperties")) {
// Clone the node before modification to avoid mutating the original
objectSchemaNode = objectSchemaNode.deepCopy();
objectSchemaNode.put("additionalProperties", false);
schemaNode = objectSchemaNode;
}
}
return this.schemaFactory.getSchema(schemaNode);
}
/**
* Generates a cache key for the given schema map.
* @param schema the schema map
* @return a cache key string
*/
protected String generateCacheKey(Map<String, Object> schema) {
if (schema.containsKey("$id")) {
// Use the (optional) "$id" field as the cache key if present
return "" + schema.get("$id");
}
// Fall back to schema's hash code as a simple cache key
// For more sophisticated caching, could use content-based hashing
return String.valueOf(schema.hashCode());
}
/**
* Clears the schema cache. Useful for testing or memory management.
*/
public void clearCache() {
this.schemaCache.clear();
}
/**
* Returns the current size of the schema cache.
* @return the number of cached schemas
*/
public int getCacheSize() {
return this.schemaCache.size();
}
}

View file

@ -0,0 +1,29 @@
/*
* Copyright 2025 - 2025 the original author or authors.
*/
package io.modelcontextprotocol.json.schema.jackson;
import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier;
/**
* A concrete implementation of {@link JsonSchemaValidatorSupplier} that provides a
* {@link JsonSchemaValidator} instance based on the Jackson library.
*
* @see JsonSchemaValidatorSupplier
* @see JsonSchemaValidator
*/
public class JacksonJsonSchemaValidatorSupplier implements JsonSchemaValidatorSupplier {
/**
* Returns a new instance of {@link JsonSchemaValidator} that uses the Jackson library
* for JSON schema validation.
* @return A {@link JsonSchemaValidator} instance.
*/
@Override
public JsonSchemaValidator get() {
return new DefaultJsonSchemaValidator();
}
}

View file

@ -0,0 +1 @@
io.modelcontextprotocol.json.jackson.JacksonMcpJsonMapperSupplier

View file

@ -0,0 +1 @@
io.modelcontextprotocol.json.schema.jackson.JacksonJsonSchemaValidatorSupplier