|
| 1 | +/* |
| 2 | + * Copyright 2026-2026 the original author or authors. |
| 3 | + */ |
| 4 | +package io.modelcontextprotocol.json.schema.jackson2; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.concurrent.ConcurrentHashMap; |
| 9 | + |
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | + |
| 13 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 14 | +import com.fasterxml.jackson.databind.JsonNode; |
| 15 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 16 | +import com.networknt.schema.Error; |
| 17 | +import com.networknt.schema.Schema; |
| 18 | +import com.networknt.schema.SchemaRegistry; |
| 19 | +import com.networknt.schema.dialect.Dialects; |
| 20 | + |
| 21 | +import io.modelcontextprotocol.json.schema.JsonSchemaValidator; |
| 22 | + |
| 23 | +/** |
| 24 | + * Default implementation of the {@link JsonSchemaValidator} interface. This class |
| 25 | + * provides methods to validate structured content against a JSON schema. It uses the |
| 26 | + * NetworkNT JSON Schema Validator library for validation. |
| 27 | + * |
| 28 | + * @author Christian Tzolov |
| 29 | + */ |
| 30 | +public class DefaultJsonSchemaValidator implements JsonSchemaValidator { |
| 31 | + |
| 32 | + private static final Logger logger = LoggerFactory.getLogger(DefaultJsonSchemaValidator.class); |
| 33 | + |
| 34 | + private final ObjectMapper objectMapper; |
| 35 | + |
| 36 | + private final SchemaRegistry schemaFactory; |
| 37 | + |
| 38 | + // TODO: Implement a strategy to purge the cache (TTL, size limit, etc.) |
| 39 | + private final ConcurrentHashMap<String, Schema> schemaCache; |
| 40 | + |
| 41 | + public DefaultJsonSchemaValidator() { |
| 42 | + this(new ObjectMapper()); |
| 43 | + } |
| 44 | + |
| 45 | + public DefaultJsonSchemaValidator(ObjectMapper objectMapper) { |
| 46 | + this.objectMapper = objectMapper; |
| 47 | + this.schemaFactory = SchemaRegistry.withDialect(Dialects.getDraft202012()); |
| 48 | + this.schemaCache = new ConcurrentHashMap<>(); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public ValidationResponse validate(Map<String, Object> schema, Object structuredContent) { |
| 53 | + |
| 54 | + if (schema == null) { |
| 55 | + throw new IllegalArgumentException("Schema must not be null"); |
| 56 | + } |
| 57 | + if (structuredContent == null) { |
| 58 | + throw new IllegalArgumentException("Structured content must not be null"); |
| 59 | + } |
| 60 | + |
| 61 | + try { |
| 62 | + |
| 63 | + JsonNode jsonStructuredOutput = (structuredContent instanceof String) |
| 64 | + ? this.objectMapper.readTree((String) structuredContent) |
| 65 | + : this.objectMapper.valueToTree(structuredContent); |
| 66 | + |
| 67 | + List<Error> validationResult = this.getOrCreateJsonSchema(schema).validate(jsonStructuredOutput); |
| 68 | + |
| 69 | + // Check if validation passed |
| 70 | + if (!validationResult.isEmpty()) { |
| 71 | + return ValidationResponse |
| 72 | + .asInvalid("Validation failed: structuredContent does not match tool outputSchema. " |
| 73 | + + "Validation errors: " + validationResult); |
| 74 | + } |
| 75 | + |
| 76 | + return ValidationResponse.asValid(jsonStructuredOutput.toString()); |
| 77 | + |
| 78 | + } |
| 79 | + catch (JsonProcessingException e) { |
| 80 | + logger.error("Failed to validate CallToolResult: Error parsing schema: {}", e); |
| 81 | + return ValidationResponse.asInvalid("Error parsing tool JSON Schema: " + e.getMessage()); |
| 82 | + } |
| 83 | + catch (Exception e) { |
| 84 | + logger.error("Failed to validate CallToolResult: Unexpected error: {}", e); |
| 85 | + return ValidationResponse.asInvalid("Unexpected validation error: " + e.getMessage()); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Gets a cached Schema or creates and caches a new one. |
| 91 | + * @param schema the schema map to convert |
| 92 | + * @return the compiled Schema |
| 93 | + * @throws JsonProcessingException if schema processing fails |
| 94 | + */ |
| 95 | + private Schema getOrCreateJsonSchema(Map<String, Object> schema) throws JsonProcessingException { |
| 96 | + // Generate cache key based on schema content |
| 97 | + String cacheKey = this.generateCacheKey(schema); |
| 98 | + |
| 99 | + // Try to get from cache first |
| 100 | + Schema cachedSchema = this.schemaCache.get(cacheKey); |
| 101 | + if (cachedSchema != null) { |
| 102 | + return cachedSchema; |
| 103 | + } |
| 104 | + |
| 105 | + // Create new schema if not in cache |
| 106 | + Schema newSchema = this.createJsonSchema(schema); |
| 107 | + |
| 108 | + // Cache the schema |
| 109 | + Schema existingSchema = this.schemaCache.putIfAbsent(cacheKey, newSchema); |
| 110 | + return existingSchema != null ? existingSchema : newSchema; |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Creates a new Schema from the given schema map. |
| 115 | + * @param schema the schema map |
| 116 | + * @return the compiled Schema |
| 117 | + * @throws JsonProcessingException if schema processing fails |
| 118 | + */ |
| 119 | + private Schema createJsonSchema(Map<String, Object> schema) throws JsonProcessingException { |
| 120 | + // Convert schema map directly to JsonNode (more efficient than string |
| 121 | + // serialization) |
| 122 | + JsonNode schemaNode = this.objectMapper.valueToTree(schema); |
| 123 | + |
| 124 | + // Handle case where ObjectMapper might return null (e.g., in mocked scenarios) |
| 125 | + if (schemaNode == null) { |
| 126 | + throw new JsonProcessingException("Failed to convert schema to JsonNode") { |
| 127 | + }; |
| 128 | + } |
| 129 | + |
| 130 | + return this.schemaFactory.getSchema(schemaNode); |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Generates a cache key for the given schema map. |
| 135 | + * @param schema the schema map |
| 136 | + * @return a cache key string |
| 137 | + */ |
| 138 | + protected String generateCacheKey(Map<String, Object> schema) { |
| 139 | + if (schema.containsKey("$id")) { |
| 140 | + // Use the (optional) "$id" field as the cache key if present |
| 141 | + return "" + schema.get("$id"); |
| 142 | + } |
| 143 | + // Fall back to schema's hash code as a simple cache key |
| 144 | + // For more sophisticated caching, could use content-based hashing |
| 145 | + return String.valueOf(schema.hashCode()); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Clears the schema cache. Useful for testing or memory management. |
| 150 | + */ |
| 151 | + public void clearCache() { |
| 152 | + this.schemaCache.clear(); |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Returns the current size of the schema cache. |
| 157 | + * @return the number of cached schemas |
| 158 | + */ |
| 159 | + public int getCacheSize() { |
| 160 | + return this.schemaCache.size(); |
| 161 | + } |
| 162 | + |
| 163 | +} |
0 commit comments