From 9e220119afab182a29121ffcad3d22e9add73786 Mon Sep 17 00:00:00 2001 From: Eric Hare Date: Thu, 19 Nov 2026 14:43:16 -0800 Subject: [PATCH] fix: describe map and string-or-object MCP tool arguments correctly Table columns were described by the private fields of LinkedHashMap. The column of a regular index, a table primary key, and a collection's lexical analyzer were described as objects only, though each also accepts a string. --- .../indexes/RegularIndexDefinitionDesc.java | 6 +- .../api/v1/mcp/McpSchemaCustomizer.java | 48 ++++- .../v1/mcp/McpSchemaShapeContractTest.java | 189 ++++++++++++++++++ 3 files changed, 238 insertions(+), 5 deletions(-) create mode 100644 src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaShapeContractTest.java diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/model/command/table/definition/indexes/RegularIndexDefinitionDesc.java b/src/main/java/io/stargate/sgv2/jsonapi/api/model/command/table/definition/indexes/RegularIndexDefinitionDesc.java index 904407d3ed..f1b582739d 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/model/command/table/definition/indexes/RegularIndexDefinitionDesc.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/model/command/table/definition/indexes/RegularIndexDefinitionDesc.java @@ -13,6 +13,7 @@ import io.stargate.sgv2.jsonapi.config.constants.TableDescDefaults; import jakarta.annotation.Nullable; import jakarta.validation.constraints.NotNull; +import java.util.Map; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; import org.eclipse.microprofile.openapi.annotations.media.Schema; @@ -32,7 +33,10 @@ public record RegularIndexDefinitionDesc( @Schema( description = "Required name of the column to index. To index the keys or values in a map column, use {\"my_map_colum\" : \"$keys\"} or {\"my_map_colum\" : \"$values\"}", - required = true) + required = true, + // RegularIndexColumnDeserializer reads either form. The record fields are the parsed + // result and are not request JSON. + anyOf = {String.class, Map.class}) @JsonDeserialize(using = RegularIndexColumnDeserializer.class) @JsonSerialize(using = RegularIndexColumnSerializer.class) @JsonProperty(TableDescConstants.IndexDefinitionDesc.COLUMN) diff --git a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaCustomizer.java b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaCustomizer.java index 5dbe9c9534..525206490d 100644 --- a/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaCustomizer.java +++ b/src/main/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaCustomizer.java @@ -6,9 +6,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.victools.jsonschema.generator.CustomDefinition; import com.github.victools.jsonschema.generator.CustomPropertyDefinition; +import com.github.victools.jsonschema.generator.SchemaGenerationContext; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import io.quarkiverse.mcp.server.runtime.SchemaGeneratorConfigCustomizer; import jakarta.inject.Singleton; +import java.util.Map; import org.eclipse.microprofile.openapi.annotations.media.Schema; /** @@ -49,11 +51,15 @@ public void customize(SchemaGeneratorConfigBuilder builder) { var schema = field.getAnnotationConsideringFieldAndGetter(Schema.class); return (ignore != null && ignore.value()) || (schema != null && schema.hidden()); }) - // A field with @Schema(ref) uses that OpenAPI component instead of its Java type. + // A field with @Schema(ref) uses that OpenAPI component instead of its Java type. A field + // with @Schema(anyOf) or @Schema(oneOf) accepts any of the listed types. .withCustomDefinitionProvider( (field, context) -> { - var schema = - schemaNode(field.getAnnotationConsideringFieldAndGetter(Schema.class), false); + var annotation = field.getAnnotationConsideringFieldAndGetter(Schema.class); + var schema = schemaNode(annotation, false); + if (schema == null) { + schema = alternativesNode(annotation, context); + } return schema == null ? null : new CustomPropertyDefinition(schema, CustomDefinition.AttributeInclusion.YES); @@ -76,10 +82,14 @@ public void customize(SchemaGeneratorConfigBuilder builder) { ? schema.description() : null; }) - // A type with a named @Schema uses that OpenAPI component instead of its Java fields. + // A type with a named @Schema uses that OpenAPI component instead of its Java fields. A + // map class such as ColumnsDescContainer is a JSON object keyed by caller-chosen names. .withCustomDefinitionProvider( (javaType, context) -> { var schema = schemaNode(javaType.getErasedType().getAnnotation(Schema.class), true); + if (schema == null && isMapClass(javaType.getErasedType())) { + schema = JsonNodeFactory.instance.objectNode().put("type", "object"); + } return schema == null ? null : new CustomDefinition( @@ -89,6 +99,36 @@ public void customize(SchemaGeneratorConfigBuilder builder) { }); } + /** + * Builds the schema for a field whose custom deserializer accepts more than one JSON shape, such + * as a column name or an object. Swagger reads the same {@code anyOf} and {@code oneOf} lists. + */ + private static ObjectNode alternativesNode(Schema annotation, SchemaGenerationContext context) { + if (annotation == null) { + return null; + } + var keyword = annotation.anyOf().length > 0 ? "anyOf" : "oneOf"; + var types = annotation.anyOf().length > 0 ? annotation.anyOf() : annotation.oneOf(); + if (types.length == 0) { + return null; + } + var schema = JsonNodeFactory.instance.objectNode(); + var alternatives = schema.putArray(keyword); + for (var type : types) { + alternatives.add(context.createDefinitionReference(context.getTypeContext().resolve(type))); + } + return schema; + } + + /** + * True for a class that extends a java.util map. The generator already describes fields declared + * as {@link Map} as objects, but it describes a subclass by the private fields of the map it + * extends, such as loadFactor. + */ + private static boolean isMapClass(Class type) { + return Map.class.isAssignableFrom(type) && !type.isInterface(); + } + private static ObjectNode schemaNode(Schema annotation, boolean typeAnnotation) { if (annotation == null) { return null; diff --git a/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaShapeContractTest.java b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaShapeContractTest.java new file mode 100644 index 0000000000..dfcdcf5fa7 --- /dev/null +++ b/src/test/java/io/stargate/sgv2/jsonapi/api/v1/mcp/McpSchemaShapeContractTest.java @@ -0,0 +1,189 @@ +package io.stargate.sgv2.jsonapi.api.v1.mcp; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.networknt.schema.JsonSchemaFactory; +import com.networknt.schema.SpecVersion; +import io.quarkiverse.mcp.server.GlobalInputSchemaGenerator; +import io.quarkiverse.mcp.server.ToolManager; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.stargate.sgv2.jsonapi.api.model.command.Command; +import io.stargate.sgv2.jsonapi.testresource.NoGlobalResourcesTestProfile; +import jakarta.inject.Inject; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Checks MCP tool input schemas for arguments whose JSON differs from their Java type. + * + *

Table columns are a map subclass. A table primary key, the column of a regular index, and a + * collection's lexical analyzer each accept a string or an object through a custom deserializer. A + * schema generated from the Java fields describes JSON the server does not accept. No commands run + * and no database is needed. + */ +@QuarkusTest +@TestProfile(NoGlobalResourcesTestProfile.Impl.class) +class McpSchemaShapeContractTest { + @Inject ObjectMapper objectMapper; + @Inject GlobalInputSchemaGenerator schemaGenerator; + @Inject ToolManager toolManager; + + /** A map subclass must be described by its entries, not by the fields of java.util maps. */ + @Test + void noToolShowsJavaMapFields() throws Exception { + for (var tool : toolManager) { + var document = inputSchema(tool.name()); + for (var name : new String[] {"accessOrder", "loadFactor", "threshold"}) { + assertNull(document.findParent(name), () -> tool.name() + " schema shows " + name); + } + } + } + + @ParameterizedTest + @ValueSource( + strings = { + """ + {"id": "text", "age": "int"} + """, + """ + {"id": "text", "embedding": {"type": "vector", "dimension": 3}} + """ + }) + void createTableAcceptsColumnsTheServerParses(String columns) throws Exception { + var definition = objectMapper.createObjectNode().put("primaryKey", "id"); + definition.set("columns", objectMapper.readTree(columns)); + var input = toolInput("readers").set("definition", definition); + + assertDoesNotThrow(() -> command("createTable", input)); + assertSchemaAccepts(inputSchema("createTable"), input); + } + + @Test + void createTableRejectsColumnsThatAreNotAnObject() throws Exception { + var definition = objectMapper.createObjectNode().put("primaryKey", "id").put("columns", "id"); + assertSchemaRejects( + inputSchema("createTable"), toolInput("readers").set("definition", definition)); + } + + @ParameterizedTest + @ValueSource( + strings = { + """ + "age" + """, + """ + {"tags": "$keys"} + """, + """ + {"tags": "$values"} + """ + }) + void createIndexAcceptsColumnsTheServerParses(String column) throws Exception { + var definition = objectMapper.createObjectNode().set("column", objectMapper.readTree(column)); + var input = toolInput("readers").put("indexName", "readers_idx"); + input.set("definition", definition); + + assertDoesNotThrow(() -> command("createIndex", input)); + assertSchemaAccepts(inputSchema("createIndex"), input); + } + + @ParameterizedTest + @ValueSource(strings = {"5", "[\"age\"]", "true"}) + void createIndexRejectsColumnsTheServerRejects(String column) throws Exception { + var definition = objectMapper.createObjectNode().set("column", objectMapper.readTree(column)); + var input = toolInput("readers").put("indexName", "readers_idx"); + input.set("definition", definition); + + assertThrows(Exception.class, () -> command("createIndex", input)); + assertSchemaRejects(inputSchema("createIndex"), input); + } + + @ParameterizedTest + @ValueSource( + strings = { + """ + "standard" + """, + """ + {"tokenizer": {"name": "whitespace"}} + """ + }) + void createCollectionAcceptsAnalyzersTheServerParses(String analyzer) throws Exception { + var lexical = objectMapper.createObjectNode().put("enabled", true); + lexical.set("analyzer", objectMapper.readTree(analyzer)); + var input = + objectMapper + .createObjectNode() + .put("keyspace", "default_keyspace") + .put("collection", "documents"); + input.set("options", objectMapper.createObjectNode().set("lexical", lexical)); + + var command = input.deepCopy(); + command.remove(List.of("keyspace", "collection")); + command.put("name", "documents"); + assertDoesNotThrow( + () -> + objectMapper.treeToValue( + objectMapper.createObjectNode().set("createCollection", command), Command.class)); + assertSchemaAccepts(inputSchema("createCollection"), input); + } + + @Test + void createCollectionRejectsAnAnalyzerThatIsNotAStringOrObject() throws Exception { + var lexical = objectMapper.createObjectNode().put("enabled", true).put("analyzer", 5); + var input = + objectMapper + .createObjectNode() + .put("keyspace", "default_keyspace") + .put("collection", "documents"); + input.set("options", objectMapper.createObjectNode().set("lexical", lexical)); + assertSchemaRejects(inputSchema("createCollection"), input); + } + + /** The input schema the MCP server publishes for a registered tool. */ + private JsonNode inputSchema(String name) throws Exception { + var tool = toolManager.getTool(name); + assertNotNull(tool); + return objectMapper.readTree(schemaGenerator.generate(tool).asJson()); + } + + /** Builds the command a tool call runs, without the MCP routing arguments. */ + private Command command(String tool, ObjectNode payload) throws Exception { + var arguments = payload.deepCopy(); + arguments.remove(List.of("keyspace", "table")); + // The createIndex tool names this argument indexName. The command JSON calls it name. + var indexName = arguments.remove("indexName"); + if (indexName != null) { + arguments.set("name", indexName); + } + return objectMapper.treeToValue( + objectMapper.createObjectNode().set(tool, arguments), Command.class); + } + + private ObjectNode toolInput(String table) { + // Routing arguments are required by MCP but are not part of the command. + return objectMapper.createObjectNode().put("keyspace", "default_keyspace").put("table", table); + } + + private void assertSchemaAccepts(JsonNode schema, JsonNode payload) { + var errors = + JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012) + .getSchema(schema) + .validate(payload); + assertTrue(errors.isEmpty(), () -> "Schema rejected " + payload + ": " + errors); + } + + private void assertSchemaRejects(JsonNode schema, JsonNode payload) { + var errors = + JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012) + .getSchema(schema) + .validate(payload); + assertFalse(errors.isEmpty(), () -> "Schema accepted invalid " + payload); + } +}