package p.studio.app.mcp; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashSet; /** Validator for the deliberately small JSON Schema vocabulary in our packaged schemas. * Not a general-purpose JSON Schema engine; never accepts client-supplied schemas. */ final class ContractSchema { private ContractSchema() { } static void validate(JsonNode schema, JsonNode value) { if (value == null) fail(); if (schema.has("oneOf")) { int matches = 0; for (var branch : schema.get("oneOf")) if (matches(branch, value)) matches++; if (matches != 1) fail(); } if (schema.has("not") && matches(schema.get("not"), value)) fail(); if (schema.has("const") && !schema.get("const").equals(value)) fail(); if (schema.has("type")) { boolean valid = switch (schema.get("type").asText()) { case "object" -> value.isObject(); case "array" -> value.isArray(); case "string" -> value.isTextual(); case "integer" -> value.isIntegralNumber() && value.canConvertToLong(); case "boolean" -> value.isBoolean(); default -> throw new IllegalStateException("Unsupported packaged schema type"); }; if (!valid) fail(); } if (schema.has("minLength") && value.textValue().codePointCount(0, value.textValue().length()) < schema.get("minLength").intValue()) fail(); if (schema.has("minimum") && value.longValue() < schema.get("minimum").longValue()) fail(); if (schema.has("maximum") && value.longValue() > schema.get("maximum").longValue()) fail(); if (schema.has("required")) for (var key : schema.get("required")) if (!value.has(key.asText())) fail(); if (schema.has("properties")) { var allowed = new HashSet(); schema.get("properties").fields().forEachRemaining(field -> { allowed.add(field.getKey()); if (value.has(field.getKey())) validate(field.getValue(), value.get(field.getKey())); }); if (!schema.path("additionalProperties").asBoolean(true)) value.fieldNames().forEachRemaining(key -> { if (!allowed.contains(key)) fail(); }); } if (schema.has("items")) for (var item : value) validate(schema.get("items"), item); } private static boolean matches(JsonNode schema, JsonNode value) { try { validate(schema, value); return true; } catch (IllegalArgumentException failure) { return false; } } private static void fail() { throw new IllegalArgumentException("Arguments do not match the tool contract"); } }