From a62ea5da5f7a30c1c6573490e0b766dd6ddd8537 Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Sat, 14 Nov 2026 21:30:44 -0500 Subject: [PATCH 1/6] feat(schema): add list-fields, Solr's Luke field listing passed through (#241) get-schema returns the full schema definition (about 35 KB on _default) and cannot say which dynamic fields hold data. list-fields sends one collection-level Luke request (numTerms=0, includeIndexFieldFlags=false) and returns Luke's fields and info sections as Solr sends them; info.key decodes the schema flag letters. The index section is left out: get-collection-stats covers it, and its directory entry names a path on the Solr host. The same JSON is served as the solr://{collection}/fields resource, with collection-name completion. The server adds no logic of its own. The tool description says how to read Solr's answer: point and docValues-only fields have no docs count (missing, or 0 on 9.11+/10.1+), and before Solr 9.11/10.1 Luke reads one shard of a multi-shard collection (SOLR-8127). The field tools now name each other so a model can tell them apart: get-schema is definitions and patterns, get-collection-stats is index size and performance, and search drops its suffix guide in favour of calling list-fields first. Its undefined-field and facet error hints point to list-fields. A registration test pins the cross-references. Closes #241 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- README.md | 6 +- THREAT_MODEL.md | 6 +- .../server/collection/CollectionService.java | 17 +- .../solr/mcp/server/schema/SchemaService.java | 105 +++++++++++- .../solr/mcp/server/search/SearchService.java | 51 ++---- src/main/resources/application.properties | 2 +- .../server/McpClientIntegrationTestBase.java | 60 ++++++- .../mcp/server/McpToolRegistrationTest.java | 29 +++- .../schema/ListFieldsIntegrationTest.java | 161 ++++++++++++++++++ .../mcp/server/schema/SchemaServiceTest.java | 66 +++++++ .../search/SearchServiceIntegrationTest.java | 10 +- .../mcp/server/search/SearchServiceTest.java | 10 +- 12 files changed, 467 insertions(+), 56 deletions(-) create mode 100644 src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java diff --git a/README.md b/README.md index 53e3e9a9..7f3c4224 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,8 @@ Using a different client, or want STDIO/HTTP/Docker options? See the per-client | `check-health` | Check the health status of a collection | | `add-fields` | Add fields to a collection schema (additive only; existing fields cannot be modified) | | `add-field-types` | Add field types — custom analyzers, `DenseVectorField` for semantic search, etc. | -| `get-schema` | Retrieve schema information for a collection | +| `get-schema` | Retrieve the full schema: field types, analyzers, dynamic-field patterns, copy fields | +| `list-fields` | List the fields that hold data in a collection, with types, flags and document counts | | `list-aliases` | List all Solr aliases and the collections they point to | | `create-alias` | Create or update a Solr alias pointing to one or more collections | | `delete-alias` | Delete a Solr alias (underlying collections are not affected) | @@ -131,6 +132,7 @@ Every tool advertises MCP behavior hints (`readOnlyHint`, `destructiveHint`, `id |--------------|-------------| | `solr://collections` | List of all Solr collections in the cluster | | `solr://{collection}/schema` | Schema definition for a collection (supports autocompletion) | +| `solr://{collection}/fields` | Fields that hold data in a collection, as `list-fields` returns them (supports autocompletion) | ### Prompts @@ -149,7 +151,7 @@ Slash-command-style workflow templates that walk the assistant through a canonic The server implements MCP argument autocompletion, so clients can suggest valid values as you type: -- **Resource argument** — the `{collection}` segment of `solr://{collection}/schema` completes to live collection names. +- **Resource arguments** — the `{collection}` segment of `solr://{collection}/schema` and `solr://{collection}/fields` completes to live collection names. - **Prompt arguments** — the `collection` argument of the `search-collection`, `index-data`, `view-schema`, and `design-schema` prompts completes to live collection names. Suggestions are matched case-insensitively by prefix and capped per request. diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 7495c26e..d4f47bda 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -62,8 +62,8 @@ it speaks MCP (JSON-RPC) to an AI client over one of two transports — **STDIO* **one** backend Solr instance whose location and credentials the operator fixes at startup via environment (`SOLR_URL`, optional `SOLR_USERNAME`/`SOLR_PASSWORD`). It exposes eleven tools (search, three indexing formats, collection create/list/ -stats/health, schema get/add-fields/add-field-types), two resources -(`solr://collections`, `solr://{collection}/schema`), and prompt/completion +stats/health, schema get/add-fields/add-field-types), three resources +(`solr://collections`, `solr://{collection}/schema`, `solr://{collection}/fields`), and prompt/completion helpers. It translates natural-language requests — as structured by the calling LLM into tool arguments — into Solr API calls, and returns Solr results back to the model. *(documented — README; AGENTS.md; `src/main/java/.../server/`.)* @@ -108,7 +108,7 @@ deferred to a later version (see §12). This is a deliberate scoping choice for | --- | --- | --- | --- | | STDIO transport | stdin/stdout JSON-RPC | child process of the client only | **Yes** | | HTTP transport | servlet on `:8080/mcp` + OAuth2 filter chain | **network listener** | **Yes (highest network exposure)** | -| Read tools | `search`, `list-collections`, `get-collection-stats`, `check-health`, `get-schema` | reads backend Solr | **Yes** | +| Read tools | `search`, `list-collections`, `get-collection-stats`, `check-health`, `get-schema`, `list-fields` | reads backend Solr | **Yes** | | Write/index tools | `index-json/csv/xml-documents` | writes backend Solr index | **Yes** | | Admin/schema tools | `create-collection`, `add-fields`, `add-field-types` | mutates backend Solr collections/schema | **Yes (privileged)** | | Backend SolrJ client | `SolrConfig` → `HttpJdkSolrClient` | outbound HTTP to `SOLR_URL` | **Yes (auth passthrough)** | diff --git a/src/main/java/org/apache/solr/mcp/server/collection/CollectionService.java b/src/main/java/org/apache/solr/mcp/server/collection/CollectionService.java index 030b792a..c75c8590 100644 --- a/src/main/java/org/apache/solr/mcp/server/collection/CollectionService.java +++ b/src/main/java/org/apache/solr/mcp/server/collection/CollectionService.java @@ -361,6 +361,19 @@ public List completeCollection(CompleteRequest.CompleteArgument argument } } + /** + * Completion for the {@code {collection}} segment of the {@code solr://{collection}/fields} + * resource template (defined in {@code SchemaService}). + * + * @param argument the partial value the client is completing + * @return matching collection names, capped at {@link #MAX_COMPLETION_RESULTS} + */ + @PreAuthorize("isAuthenticated()") + @McpComplete(uri = "solr://{collection}/fields") + public List completeFieldsResourceCollection(CompleteRequest.CompleteArgument argument) { + return completeCollection(argument); + } + /** * Completion for the {@code collection} argument of the {@code search-collection} prompt (defined * in {@code SearchService}). @@ -498,7 +511,9 @@ public List listCollections() throws SolrServerException, IOException { name = "get-collection-stats", annotations = @McpTool.McpAnnotations(readOnlyHint = true), description = - "Get stats/metrics on a Solr collection. cacheStats and handlerStats may be" + "Get index size and performance metrics for a Solr collection: document and segment " + + "counts, and query, cache and handler stats. It does not describe fields; use " + + "list-fields for the fields that hold data. cacheStats and handlerStats may be" + " null when Solr's /admin/metrics API does not provide them for the collection;" + " this is expected and not an error.") public SolrMetrics getCollectionStats( diff --git a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java index 3480205b..7b1382ec 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java @@ -26,10 +26,12 @@ import java.util.Map; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.request.LukeRequest; import org.apache.solr.client.solrj.request.schema.AnalyzerDefinition; import org.apache.solr.client.solrj.request.schema.FieldTypeDefinition; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.schema.SchemaRepresentation; +import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.util.PromptNames; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -122,6 +124,16 @@ public class SchemaService { "Failed to retrieve the schema. Hint: call list-collections to check" + " the collection name; if it persists, ask the operator to check the server logs."; + static final String FIELDS_RESOURCE_ERROR = + "Failed to list the fields. Hint: call list-collections to check" + + " the collection name; if it persists, ask the operator to check the server logs."; + + /** Luke response section holding one entry per field present in the index. */ + private static final String LUKE_FIELDS_KEY = "fields"; + + /** Luke response section whose {@code key} entry decodes the field flag letters. */ + private static final String LUKE_INFO_KEY = "info"; + /** SolrJ client for communicating with Solr server */ private final SolrClient solrClient; @@ -160,7 +172,7 @@ public SchemaService(SolrClient solrClient, JsonMapper objectMapper) { uri = "solr://{collection}/schema", name = "solr-collection-schema", description = - "Schema definition for a Solr collection including fields, field types, and copy fields", + "Full schema definition for a Solr collection: field types, declared fields, dynamic-field patterns and copy fields", mimeType = "application/json") public String getSchemaResource(String collection) { try { @@ -241,12 +253,99 @@ public String getSchemaResource(String collection) { @McpTool( name = "get-schema", annotations = @McpTool.McpAnnotations(readOnlyHint = true), - description = "Get schema for a Solr collection") + description = + "Get the full schema definition of a Solr collection: field types with their " + + "analyzers, declared fields, dynamic-field patterns (such as *_s) and copy fields. " + + "Use this before add-fields or add-field-types to see what is already defined. " + + "It does not say which fields hold data or which dynamic fields are in use; to " + + "choose fields for search, call list-fields instead.") public SchemaRepresentation getSchema(String collection) throws SolrServerException, IOException { SchemaRequest schemaRequest = new SchemaRequest(); return schemaRequest.process(solrClient, collection).getSchemaRepresentation(); } + /** + * MCP Resource endpoint that returns the fields holding data in a collection, the same JSON as + * {@link #listFields(String)}. + * + * @param collection the collection to list fields for + * @return JSON string containing the field listing + * @throws IllegalStateException with {@link #FIELDS_RESOURCE_ERROR} if the fields cannot be + * listed or serialized + */ + @PreAuthorize("isAuthenticated()") + @McpResource( + uri = "solr://{collection}/fields", + name = "solr-collection-fields", + description = + "The fields that hold data in a Solr collection, with their types, flags and document counts", + mimeType = "application/json") + public String getFieldsResource(String collection) { + try { + return objectMapper.writeValueAsString(listFields(collection)); + } catch (Exception e) { + // No cause, for the same reason as getSchemaResource: Solr failure text can + // carry internal host names and URLs. + logger.error("Failed to list fields for collection: {}", collection, e); + throw new IllegalStateException(FIELDS_RESOURCE_ERROR); + } + } + + /** + * Lists the fields that hold data in a collection: the {@code fields} and {@code info} sections + * of Solr's Luke response, passed through as Solr reports them. + * + *

Unlike {@link #getSchema(String)}, Luke reports the dynamic-field instances in the index + * ({@code genre_s}, not just {@code *_s}) and, per field, how many documents have terms in it. + * {@code info.key} decodes the letters of each field's {@code schema} flags. The {@code index} + * section is left out: {@code get-collection-stats} reports index statistics, and its {@code + * directory} entry names a path on the Solr host. + * + *

One collection-level request is made. Solr 9.11 and 10.1 distribute it across shards in + * SolrCloud (SOLR-8127); older versions answer from one core, which the tool description tells + * the model about. + * + * @param collection the collection to list fields for + * @return Luke's {@code fields} and {@code info} sections as nested maps + * @throws SolrServerException if Solr returns an error; an unknown collection surfaces as an + * unchecked {@code SolrException} (404) + * @throws IOException if communication with Solr fails + */ + @PreAuthorize("isAuthenticated()") + @McpTool( + name = "list-fields", + annotations = @McpTool.McpAnnotations(readOnlyHint = true), + description = + "List the fields that hold data in a collection, from Solr's Luke handler: per field its" + + " type, schema flags, dynamicBase for a dynamic-field instance (genre_s, not *_s), and" + + " docs, the number of documents with terms in the field (deleted documents count" + + " until their segments merge). info.key decodes the flag letters. Use this before" + + " search to decide which fields go in q, fq, facets and sorts. Unlike get-schema it" + + " shows no analyzers or field-type definitions; use get-schema before changing the" + + " schema. Numeric and date point fields and docValues-only fields have no terms, so" + + " their docs is missing, or 0 on Solr 9.11+ and 10.1+: that means not counted, not" + + " empty. Before Solr 9.11 and 10.1, a collection with more than one shard lists the" + + " fields and counts of one shard only.") + public Map listFields( + @McpToolParam(description = "Solr collection name") String collection) + throws SolrServerException, IOException { + requireCollection(collection); + + LukeRequest lukeRequest = new LukeRequest(); + lukeRequest.setNumTerms(0); + lukeRequest.setIncludeIndexFieldFlags(false); + NamedList response = lukeRequest.process(solrClient, collection).getResponse(); + + Map sections = new LinkedHashMap<>(); + for (String section : List.of(LUKE_FIELDS_KEY, LUKE_INFO_KEY)) { + // A JSON-parsed tree has no cycles, so asMap's depth guard never applies. + if (response.get(section) instanceof NamedList list) { + sections.put(section, list.asMap(Integer.MAX_VALUE)); + } + } + return sections; + } + /** * Adds one or more fields to a Solr collection schema as a single transactional batch. * @@ -482,6 +581,8 @@ public String viewSchemaPrompt( 3. Summarize dynamic fields and copy fields. - List dynamic-field patterns (e.g. `*_s`, `*_txt`) and their types — these accept fields whose names are not predeclared. + - The schema shows only the patterns. To see which dynamic fields are actually in + use (e.g. `genre_s`) and how many documents have each, call `list-fields`. - List copyField rules (source → destination) — these duplicate content into aggregator fields, often used for catch-all search fields. diff --git a/src/main/java/org/apache/solr/mcp/server/search/SearchService.java b/src/main/java/org/apache/solr/mcp/server/search/SearchService.java index 9fdf61ff..05591779 100644 --- a/src/main/java/org/apache/solr/mcp/server/search/SearchService.java +++ b/src/main/java/org/apache/solr/mcp/server/search/SearchService.java @@ -124,10 +124,10 @@ public class SearchService { */ static final String CANNOT_PARSE_TOKEN = "cannot parse"; - /** Remediation hint naming the {@code get-schema} tool; takes the collection. */ - static final String GET_SCHEMA_HINT_FORMAT = - ". Hint: call get-schema on collection '%s' to see the fields that" - + " exist; schemaless collections often store values under dynamic-suffix names such as name_s or price_d."; + /** Remediation hint naming the {@code list-fields} tool; takes the collection. */ + static final String LIST_FIELDS_HINT_FORMAT = + ". Hint: call list-fields on collection '%s' to see the field names that" + + " hold data, dynamic-field instances such as name_s or price_d included."; /** Remediation hint for an unparseable {@code q}. */ static final String LUCENE_SYNTAX_HINT = @@ -143,7 +143,7 @@ public class SearchService { + " if it persists, ask the operator to check Solr availability and connection settings."; private static final String RESPONSE_ERROR = "Search failed: unable to process the Solr response." - + " If facetFields were supplied, call get-schema to check those fields or retry without facetFields;" + + " If facetFields were supplied, call list-fields to check those fields have docValues or retry without facetFields;" + " if it persists, ask the operator to check server logs and Solr compatibility."; private final SolrClient solrClient; @@ -216,29 +216,9 @@ private static Map> getFacets(QueryResponse queryRespo to use eDisMax features (multi-field search, minimum-match, boosts), embed Solr local params in q, e.g. {!edismax qf='name author' mm=2}george martin. Put filters in fq (filterQueries) instead of q so Solr can cache and reuse them. - Note that solr has dynamic fields where name of field in schema may end with suffixes - _s: Represents a string field, used for exact string matching. - _i: Represents an integer field. - _l: Represents a long field. - _f: Represents a float field. - _d: Represents a double field. - _dt: Represents a date field. - _b: Represents a boolean field. - _t: Often used for text fields that undergo tokenization and analysis. - One example from the books collection: - { - "id":"0553579908", - "cat":["book"], - "name":["A Clash of Kings"], - "price":[7.99], - "inStock":[true], - "author":["George R.R. Martin"], - "series_t":"A Song of Ice and Fire", - "sequence_i":2, - "genre_s":"fantasy", - "_version_":1836275819373133824, - "_root_":"0553579908" - } + Call list-fields first to get the field names that hold data and their types, rather than + guessing names: dynamic fields such as genre_s exist only once documents use them. Facet + and sort only on fields that list-fields reports with docValues. """) // @formatter:on public SearchResponse search( @@ -374,7 +354,7 @@ private static RuntimeException withRemediationHint(SolrException e, String coll if (lower.contains(UNDEFINED_FIELD_TOKEN) || lower.contains(SORT_FIELD_NOT_FOUND_TOKEN)) { return new IllegalArgumentException( "Search failed: a referenced field is not defined" - + GET_SCHEMA_HINT_FORMAT.formatted(collection)); + + LIST_FIELDS_HINT_FORMAT.formatted(collection)); } if (lower.contains(SYNTAX_ERROR_TOKEN) || lower.contains(CANNOT_PARSE_TOKEN)) { return new IllegalArgumentException( @@ -383,7 +363,7 @@ private static RuntimeException withRemediationHint(SolrException e, String coll return new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Search failed: Solr rejected the request. Check query syntax, filter queries, facet fields," - + " sort clauses, and pagination; call get-schema to verify the fields."); + + " sort clauses, and pagination; call list-fields to verify the field names."); } if (e.code() == SolrException.ErrorCode.UNAUTHORIZED.code || e.code() == SolrException.ErrorCode.FORBIDDEN.code) { @@ -428,11 +408,14 @@ public String searchCollectionPrompt( Work incrementally — Solr query design is sensitive to the schema, so anchor on the schema before constructing queries. - 1. Learn the schema. - - Call `get-schema` on `%s`. Identify which fields are searchable text + 1. Learn the fields. + - Call `list-fields` on `%s`. It lists the fields that hold data, dynamic-field + instances included. From each field's `type` identify which are searchable text (`text_general` or similar tokenized types), which are filterable exact-match - (`string`/`strings`), which are numeric/date ranges, and which have `docValues` - (needed for faceting and sorting). + (`string`/`strings`), and which are numeric/date ranges. A `D` in a field's + `schema` flags (decoded by `info.key`) means docValues: those are the fields you + can facet and sort on. `dynamicBase` shows which pattern a field came from + (e.g. `*_s`). 2. Translate the question into Solr query parts. - Pick the most informative tokens from the question. Map them to fields: diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b1e5971d..6f423251 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -17,7 +17,7 @@ spring.application.name=solr-mcp spring.profiles.active=${PROFILES:stdio} spring.ai.mcp.server.instructions=This server provides tools to search, index, and manage Apache Solr collections. \ -Discover before acting: use list-collections and get-schema to see what exists before searching or indexing. \ +Discover before acting: use list-collections, then list-fields before searching and get-schema before changing a schema. \ Surface boundaries: there are no tools to delete documents or collections, drop or alter existing fields, \ or debug relevance scoring (debugQuery); vector/KNN search is not exposed; search facets are simple field \ facets only (no range, pivot, or JSON facets). Schema modification is additive only via add-fields and \ diff --git a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java index f4cbe19f..5a203802 100644 --- a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java +++ b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java @@ -30,8 +30,10 @@ import io.modelcontextprotocol.spec.McpSchema.PromptMessage; import io.modelcontextprotocol.spec.McpSchema.PromptReference; import io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest; +import io.modelcontextprotocol.spec.McpSchema.ReadResourceResult; import io.modelcontextprotocol.spec.McpSchema.ResourceReference; import io.modelcontextprotocol.spec.McpSchema.TextContent; +import io.modelcontextprotocol.spec.McpSchema.TextResourceContents; import io.modelcontextprotocol.spec.McpSchema.Tool; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -107,6 +109,7 @@ void listToolsReturnsExpectedTools() { assertTrue(toolNames.contains("check-health"), "Should have check-health tool"); assertTrue(toolNames.contains("get-collection-stats"), "Should have get-collection-stats tool"); assertTrue(toolNames.contains("get-schema"), "Should have get-schema tool"); + assertTrue(toolNames.contains("list-fields"), "Should have list-fields tool"); assertTrue(toolNames.contains("add-fields"), "Should have add-fields tool"); assertTrue(toolNames.contains("add-field-types"), "Should have add-field-types tool"); } @@ -124,6 +127,7 @@ void toolsExposeBehaviorHints() { assertReadOnly(tools, "get-collection-stats"); assertReadOnly(tools, "check-health"); assertReadOnly(tools, "get-schema"); + assertReadOnly(tools, "list-fields"); // create-collection: additive write (provisions a new collection, not // idempotent because a second call with the same name errors). @@ -1225,10 +1229,64 @@ void searchFailureIsAnActionableMcpToolError() { "facetFields", List.of("nonexistent_field_xyz")))); assertEquals(Boolean.TRUE, result.isError()); - assertTrue(extractText(result).contains("get-schema"), extractText(result)); + assertTrue(extractText(result).contains("list-fields"), extractText(result)); assertFalse(extractText(result).contains("Exception"), extractText(result)); } + // ===== list-fields (orders 41–43) ===== + + @Test + @Order(41) + void listShowsFieldsReturnsIndexedFields() { + CallToolResult result = + mcpClient.callTool( + new CallToolRequest("list-fields", Map.of("collection", SHOWS_COLLECTION))); + + assertNotError(result); + Map listing = + OBJECT_MAPPER.readValue(extractText(result), new TypeReference<>() {}); + java.util.Set names = fieldNames(listing); + assertTrue( + names.containsAll(List.of("id", "title", "platform", "genres", "release_year")), + "list-fields should list the indexed shows fields: " + names); + } + + @Test + @Order(42) + void fieldsResourceMatchesListFieldsTool() { + CallToolResult tool = + mcpClient.callTool( + new CallToolRequest("list-fields", Map.of("collection", SHOWS_COLLECTION))); + ReadResourceResult resource = + mcpClient.readResource(new ReadResourceRequest("solr://" + SHOWS_COLLECTION + "/fields")); + + assertInstanceOf(TextResourceContents.class, resource.contents().getFirst()); + String resourceText = ((TextResourceContents) resource.contents().getFirst()).text(); + assertEquals( + fieldNames(OBJECT_MAPPER.readValue(extractText(tool), new TypeReference<>() {})), + fieldNames(OBJECT_MAPPER.readValue(resourceText, new TypeReference<>() {}))); + } + + @Test + @Order(43) + void completeFieldsResourceCollection_ReturnsCreatedCollection() { + ResourceReference ref = new ResourceReference("solr://{collection}/fields"); + CompleteRequest request = + new CompleteRequest( + ref, new CompleteRequest.CompleteArgument("collection", COLLECTION.substring(0, 3))); + + List values = mcpClient.completeCompletion(request).completion().values(); + + assertTrue( + values.contains(COLLECTION), + "Fields-resource completion should include the created collection: " + values); + } + + @SuppressWarnings("unchecked") + private static java.util.Set fieldNames(Map listing) { + return ((Map) listing.get("fields")).keySet(); + } + @Test @Order(45) void schemaResourceFailureIsAnMcpErrorWithoutTheSolrUrl() { diff --git a/src/test/java/org/apache/solr/mcp/server/McpToolRegistrationTest.java b/src/test/java/org/apache/solr/mcp/server/McpToolRegistrationTest.java index 1de409fd..af0682ce 100644 --- a/src/test/java/org/apache/solr/mcp/server/McpToolRegistrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/McpToolRegistrationTest.java @@ -237,13 +237,13 @@ void testCollectionCompletionsCoverSchemaResourceAndCollectionTakingPrompts() { .map(m -> m.getAnnotation(McpComplete.class)) .toList(); - // Exactly one resource-template binding (the {collection}/schema URI). + // One resource-template binding per collection-scoped resource. List uriBindings = completions.stream().map(McpComplete::uri).filter(s -> !s.isEmpty()).sorted().toList(); assertEquals( - List.of("solr://{collection}/schema"), + List.of("solr://{collection}/fields", "solr://{collection}/schema"), uriBindings, - "Exactly one resource-template completion expected (the schema URI)"); + "One resource-template completion expected per collection-scoped resource"); // One prompt binding per prompt that takes a `collection` argument. // Referenced via PromptNames so a rename or deletion breaks compilation @@ -305,6 +305,29 @@ void everyMcpEndpointIsPreAuthorized() { } // Helper method to extract tool names from a service class + @Test + void fieldToolDescriptionsRouteToEachOther() { + // Several tools talk about fields. A model picks between them by description, + // so each one names the tool for the job it does not do. + String listFields = toolDescription(SchemaService.class, "list-fields"); + String getSchema = toolDescription(SchemaService.class, "get-schema"); + + assertTrue(listFields.contains("get-schema"), listFields); + assertTrue(getSchema.contains("list-fields"), getSchema); + assertTrue(toolDescription(SearchService.class, "search").contains("list-fields")); + assertTrue( + toolDescription(CollectionService.class, "get-collection-stats").contains("list-fields")); + } + + private static String toolDescription(Class serviceClass, String toolName) { + return Arrays.stream(serviceClass.getDeclaredMethods()) + .map(m -> m.getAnnotation(McpTool.class)) + .filter(tool -> tool != null && tool.name().equals(toolName)) + .map(McpTool::description) + .findFirst() + .orElseThrow(() -> new AssertionError("no @McpTool named " + toolName)); + } + private void addToolNames(Class serviceClass, List toolNames) { Method[] methods = serviceClass.getDeclaredMethods(); Arrays.stream(methods) diff --git a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java new file mode 100644 index 00000000..5b5957bb --- /dev/null +++ b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java @@ -0,0 +1,161 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.mcp.server.schema; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Map; +import org.apache.solr.client.solrj.SolrClient; +import org.apache.solr.client.solrj.SolrRequest; +import org.apache.solr.client.solrj.request.CollectionAdminRequest; +import org.apache.solr.client.solrj.request.GenericSolrRequest; +import org.apache.solr.client.solrj.request.UpdateRequest; +import org.apache.solr.common.SolrInputDocument; +import org.apache.solr.common.util.NamedList; +import org.apache.solr.mcp.server.TestcontainersConfiguration; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Integration tests for {@code list-fields} against a real Solr. + * + *

Only {@code *_s}, {@code *_i} and {@code id} fields are indexed, so documents match {@code + * _default}'s dynamic fields and nothing goes through schemaless field guessing. + */ +@SpringBootTest +@Import(TestcontainersConfiguration.class) +@Tag("integration") +@Testcontainers(disabledWithoutDocker = true) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class ListFieldsIntegrationTest { + + private static final String ONE_SHARD = "list_fields_one_shard"; + + private static final String TWO_SHARDS = "list_fields_two_shards"; + + @Autowired private SchemaService schemaService; + + @Autowired private SolrClient solrClient; + + @BeforeAll + void createCollections() throws Exception { + CollectionAdminRequest.createCollection(ONE_SHARD, "_default", 1, 1).process(solrClient); + UpdateRequest oneShard = new UpdateRequest(); + oneShard.add(doc("a", Map.of("genre_s", "drama", "year_i", 2020))); + oneShard.add(doc("b", Map.of("genre_s", "comedy", "year_i", 2021))); + oneShard.commit(solrClient, ONE_SHARD); + + // The implicit router lets the test decide which shard each document lands on. + CollectionAdminRequest.createCollectionWithImplicitRouter( + TWO_SHARDS, "_default", "shard_a,shard_b", 1) + .process(solrClient); + indexToShard("shard_a", doc("on-a", Map.of("only_a_s", "x"))); + indexToShard("shard_b", doc("on-b", Map.of("only_b_s", "y"))); + new UpdateRequest().commit(solrClient, TWO_SHARDS); + } + + @Test + void listsDynamicFieldInstancesWithTheirBase() throws Exception { + Map> fields = fields(ONE_SHARD); + + Map genre = fields.get("genre_s"); + assertNotNull(genre, "genre_s should be listed: " + fields.keySet()); + assertEquals("*_s", genre.get("dynamicBase")); + assertEquals("string", genre.get("type")); + assertEquals(2L, ((Number) genre.get("docs")).longValue()); + assertFalse(fields.get("id").containsKey("dynamicBase"), "id is an explicit field"); + } + + @Test + void pointFieldsHaveNoDocCount() throws Exception { + Map year = fields(ONE_SHARD).get("year_i"); + + assertNotNull(year, "year_i should be listed"); + assertEquals("pint", year.get("type")); + // Luke cannot count a field without terms: older Solr leaves docs out, + // distributed Luke (9.11+/10.1+) reports 0. + Object docs = year.get("docs"); + assertTrue(docs == null || ((Number) docs).longValue() == 0, "docs: " + docs); + } + + @Test + void passesThroughTheFlagLegendAndNotTheIndexSection() throws Exception { + Map listing = schemaService.listFields(ONE_SHARD); + + assertEquals(java.util.Set.of("fields", "info"), listing.keySet()); + Map key = (Map) ((Map) listing.get("info")).get("key"); + assertEquals("Indexed", key.get("I"), "info.key decodes the schema flag letters: " + key); + } + + @Test + void twoShardListingCoversBothShardsOnlyWhereSolrDistributesLuke() throws Exception { + Map> fields = fields(TWO_SHARDS); + + // Worked out from the server's version, not from the tool's answer. + if (solrDistributesLuke()) { + assertEquals(1L, ((Number) fields.get("only_a_s").get("docs")).longValue(), "" + fields); + assertEquals(1L, ((Number) fields.get("only_b_s").get("docs")).longValue(), "" + fields); + } else { + assertTrue( + fields.containsKey("only_a_s") != fields.containsKey("only_b_s"), + "a single core holds exactly one of the two shard-only fields: " + fields.keySet()); + } + } + + @Test + void unknownCollectionFails() { + assertThrows(Exception.class, () -> schemaService.listFields("no_such_collection_xyz")); + } + + private void indexToShard(String shard, SolrInputDocument document) throws Exception { + UpdateRequest update = new UpdateRequest(); + update.add(document); + update.setParam("_route_", shard); + update.process(solrClient, TWO_SHARDS); + } + + private static SolrInputDocument doc(String id, Map fields) { + SolrInputDocument document = new SolrInputDocument(); + document.addField("id", id); + fields.forEach(document::addField); + return document; + } + + @SuppressWarnings("unchecked") + private Map> fields(String collection) throws Exception { + return (Map>) schemaService.listFields(collection).get("fields"); + } + + /** SOLR-8127 shipped in 9.11 and 10.1; 10.0 does not have it. */ + private boolean solrDistributesLuke() throws Exception { + NamedList info = + new GenericSolrRequest(SolrRequest.METHOD.GET, "/admin/info/system") + .process(solrClient) + .getResponse(); + String version = (String) ((NamedList) info.get("lucene")).get("solr-spec-version"); + String[] parts = version.split("\\."); + int major = Integer.parseInt(parts[0]); + int minor = Integer.parseInt(parts[1]); + return major > 10 || (major == 10 && minor >= 1) || (major == 9 && minor >= 11); + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java index dba24d69..76fd2697 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java @@ -28,9 +28,12 @@ import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.request.LukeRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest.MultiUpdate; +import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; +import org.apache.solr.common.util.SimpleOrderedMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledInNativeImage; @@ -417,4 +420,67 @@ void viewSchemaPrompt_isReadOnlyAndReferencesGetSchema() { body.contains("design-schema"), "View prompt should cross-reference design-schema for follow-up modification"); } + + // ===== list-fields ===== + + private static final String COLLECTION = "shows"; + + @Test + void listFields_passesThroughLukeFieldsAndInfoSections() throws Exception { + NamedList genre = new SimpleOrderedMap<>(); + genre.add("type", "string"); + genre.add("schema", "I-SD-M---OF-----"); + genre.add("dynamicBase", "*_s"); + genre.add("docs", 5); + NamedList fields = new SimpleOrderedMap<>(); + fields.add("genre_s", genre); + NamedList key = new SimpleOrderedMap<>(); + key.add("I", "Indexed"); + NamedList info = new SimpleOrderedMap<>(); + info.add("key", key); + NamedList index = new SimpleOrderedMap<>(); + index.add("directory", "MMapDirectory@/var/solr/data/shows/index"); + NamedList response = new NamedList<>(); + response.add("index", index); + response.add("fields", fields); + response.add("info", info); + when(solrClient.request(any(LukeRequest.class), eq(COLLECTION))).thenReturn(response); + + Map listing = schemaService.listFields(COLLECTION); + + assertEquals( + Map.of( + "fields", + Map.of( + "genre_s", + Map.of( + "type", + "string", + "schema", + "I-SD-M---OF-----", + "dynamicBase", + "*_s", + "docs", + 5)), + "info", + Map.of("key", Map.of("I", "Indexed"))), + listing); + } + + @Test + void listFields_asksLukeForNoTopTermsAndNoIndexFlags() throws Exception { + ArgumentCaptor request = ArgumentCaptor.forClass(LukeRequest.class); + when(solrClient.request(request.capture(), eq(COLLECTION))).thenReturn(new NamedList<>()); + + schemaService.listFields(COLLECTION); + + SolrParams params = request.getValue().getParams(); + assertEquals("0", params.get("numTerms")); + assertEquals("false", params.get("includeIndexFieldFlags")); + } + + @Test + void listFields_rejectsBlankCollection() { + assertThrows(IllegalArgumentException.class, () -> schemaService.listFields(" ")); + } } diff --git a/src/test/java/org/apache/solr/mcp/server/search/SearchServiceIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/search/SearchServiceIntegrationTest.java index 862a2682..cf05b6ee 100644 --- a/src/test/java/org/apache/solr/mcp/server/search/SearchServiceIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/search/SearchServiceIntegrationTest.java @@ -254,7 +254,7 @@ void searchWithUndefinedFieldInQueryReturnsGetSchemaHint() { searchService.search( COLLECTION_NAME, "definitely_not_a_field:value", null, null, null, null, null)); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted(COLLECTION_NAME)), + e.getMessage().contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted(COLLECTION_NAME)), () -> "expected get-schema hint, got: " + e.getMessage()); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -269,7 +269,7 @@ void searchWithUndefinedFieldInFilterQueryReturnsGetSchemaHint() { searchService.search( COLLECTION_NAME, "*:*", filterQueries, null, null, null, null)); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted(COLLECTION_NAME)), + e.getMessage().contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted(COLLECTION_NAME)), () -> "expected get-schema hint, got: " + e.getMessage()); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -284,7 +284,7 @@ void searchWithUndefinedFacetFieldReturnsGetSchemaHint() { () -> searchService.search(COLLECTION_NAME, "*:*", null, facetFields, null, null, null)); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted(COLLECTION_NAME)), + e.getMessage().contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted(COLLECTION_NAME)), () -> "expected get-schema hint, got: " + e.getMessage()); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -301,7 +301,7 @@ void searchWithUndefinedSortFieldReturnsGetSchemaHint() { IllegalArgumentException.class, () -> searchService.search(COLLECTION_NAME, "*:*", null, null, sort, null, null)); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted(COLLECTION_NAME)), + e.getMessage().contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted(COLLECTION_NAME)), () -> "expected get-schema hint, got: " + e.getMessage()); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -351,7 +351,7 @@ void searchWithUnrecognizedSolrErrorPropagatesWithoutHint() { assertFalse(e.getMessage().contains("Hint:"), () -> "expected no hint, got: " + e.getMessage()); assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, e.code()); assertTrue(e.getMessage().contains("pagination")); - assertTrue(e.getMessage().contains("get-schema")); + assertTrue(e.getMessage().contains("list-fields")); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } diff --git a/src/test/java/org/apache/solr/mcp/server/search/SearchServiceTest.java b/src/test/java/org/apache/solr/mcp/server/search/SearchServiceTest.java index e5c697bd..5fb1e9d8 100644 --- a/src/test/java/org/apache/solr/mcp/server/search/SearchServiceTest.java +++ b/src/test/java/org/apache/solr/mcp/server/search/SearchServiceTest.java @@ -172,7 +172,7 @@ void search_BackendFailures_ShouldReturnSafeActionableErrors() throws Exception } assertTrue(e.getMessage().contains("Search failed"), e::getMessage); assertTrue( - e.getMessage().contains("operator") || e.getMessage().contains("get-schema"), + e.getMessage().contains("operator") || e.getMessage().contains("list-fields"), e::getMessage); assertNull(e.getCause(), "MCP must not unwrap a raw backend failure"); if (failure instanceof SolrException solrFailure) { @@ -229,7 +229,8 @@ void search_WithUndefinedField_ShouldHintGetSchema() throws Exception { assertFalse( e.getMessage().contains("undefined field bogus"), "raw Solr message must not be exposed"); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted("test_collection"))); + e.getMessage() + .contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted("test_collection"))); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -245,7 +246,8 @@ void search_WithUndefinedSortField_ShouldHintGetSchema() throws Exception { IllegalArgumentException.class, () -> localService.search("test_collection", "*:*", null, null, sort, null, null)); assertTrue( - e.getMessage().contains(SearchService.GET_SCHEMA_HINT_FORMAT.formatted("test_collection"))); + e.getMessage() + .contains(SearchService.LIST_FIELDS_HINT_FORMAT.formatted("test_collection"))); assertNull(e.getCause(), "MCP must not unwrap a raw Solr failure"); } @@ -675,7 +677,7 @@ void searchCollectionPrompt_includesKeyWorkflowSteps() { assertTrue( body.contains("What sci-fi shows are on Netflix?"), "Prompt should embed the user question"); - assertTrue(body.contains("get-schema"), "Prompt should reference get-schema tool"); + assertTrue(body.contains("list-fields"), "Prompt should reference list-fields tool"); assertTrue(body.contains("search"), "Prompt should reference search tool"); assertTrue(body.contains("filterQueries"), "Prompt should explain filterQueries"); assertTrue(body.contains("numFound"), "Prompt should mention numFound interpretation"); From 08fd05e0a5a3635f706e17625346032fe9a9bb5a Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Sat, 14 Nov 2026 21:43:53 -0500 Subject: [PATCH 2/6] fix(schema): address review of list-fields (#241) - Read Luke's raw NamedList with solrClient.request() instead of process(), which also builds SolrJ's typed LukeResponse: that parse casts each docs count to Integer and fails on a distributed sum past 2^31. - Move the docValues advice to the error path it applies to. Solr rejects a facet or sort on an unsuitable field with a 400, which gets the generic hint; RESPONSE_ERROR is a client-side parse failure. The search description and search-collection prompt also say sorting needs a single-valued field. - ListFieldsIntegrationTest: an unknown collection is a SolrException 404, and the comment on point-field docs names the right Solr code path. - Test against Solr 9.11, the first release with distributed Luke: added to both compatibility matrices and the tested-version lists. The full suite passes on solr:9.11-slim, which runs the two-shard test's distributed branch. - Update the tool and resource counts and lists in THREAT_MODEL.md, CHANGELOG.md and the client docs. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- .github/workflows/build-and-publish.yml | 3 ++- .github/workflows/ci.yml | 1 + AGENTS.md | 3 ++- CHANGELOG.md | 4 ++-- THREAT_MODEL.md | 7 ++++--- dev-docs/DEVELOPMENT.md | 2 +- docs/clients/chatgpt.md | 2 +- docs/clients/mcp-inspector.md | 2 +- docs/site/content/pages/mcp/quick-start.md | 4 ++-- .../apache/solr/mcp/server/schema/SchemaService.java | 10 +++++++--- .../apache/solr/mcp/server/search/SearchService.java | 11 ++++++----- .../mcp/server/schema/ListFieldsIntegrationTest.java | 11 +++++++---- 12 files changed, 36 insertions(+), 24 deletions(-) diff --git a/.github/workflows/build-and-publish.yml b/.github/workflows/build-and-publish.yml index b5edab81..17a1f243 100644 --- a/.github/workflows/build-and-publish.yml +++ b/.github/workflows/build-and-publish.yml @@ -177,7 +177,7 @@ jobs: # ============================================================================ # Tests the server against multiple Solr versions using Testcontainers. # Runs in parallel so each Solr version is an independent job. - # Tested versions: 9.4, 9.9, 9.10, 10 + # Tested versions: 9.4, 9.9, 9.10, 9.11, 10 # ============================================================================ solr-compatibility: name: Solr ${{ matrix.solr-version }} Compatibility @@ -190,6 +190,7 @@ jobs: - "9.4-slim" - "9.9-slim" - "9.10-slim" + - "9.11-slim" - "10-slim" steps: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f2848f1c..1b28c7ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,6 +165,7 @@ jobs: solr-version: - "9.4-slim" - "9.10-slim" + - "9.11-slim" - "10-slim" steps: diff --git a/AGENTS.md b/AGENTS.md index 72abf222..94c58ba1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -465,10 +465,11 @@ The Solr Docker image used in tests is pinned as `test-image-solr` in `gradle/li ./gradlew test -Dsolr.test.image=solr:9.4-slim # Solr 9.4 ./gradlew test -Dsolr.test.image=solr:9.9.0-slim # Solr 9.9 (the pinned default) ./gradlew test -Dsolr.test.image=solr:9.10-slim # Solr 9.10 +./gradlew test -Dsolr.test.image=solr:9.11-slim # Solr 9.11 ./gradlew test -Dsolr.test.image=solr:10-slim # Solr 10 ``` -**Tested compatible versions:** 9.4, 9.9, 9.10, 10 +**Tested compatible versions:** 9.4, 9.9, 9.10, 9.11, 10 ### Solr 10 Compatibility diff --git a/CHANGELOG.md b/CHANGELOG.md index d8c00aa3..2342cfe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ Apache Solr MCP 1.0.0 is the project's first release: a Model Context Protocol ( - **Search**: the `search` tool runs full-text queries with filter queries, faceting, sorting and pagination. - **Indexing in four formats**: `index-json-documents`, `index-csv-documents`, `index-xml-documents` (Solr update XML; only `` is accepted, so the tool cannot delete documents or issue commits) and `index-markdown-documents`, which extracts front matter, title, headings and body text from each document. - **Collection management**: `list-collections`, `create-collection`, `check-health` and `get-collection-stats`, plus alias management with `list-aliases`, `create-alias` and `delete-alias`. -- **Schema inspection and additive changes**: `get-schema`, `add-fields` and `add-field-types`. The schema tools only add; they never change or remove existing fields or field types. -- **Prompts, resources and completions**: guided prompts (`explore-collections`, `setup-collection`, `search-collection`, `index-data`, `view-schema`, `design-schema`), the `solr://collections` and `solr://{collection}/schema` resources, and collection-name completion for their arguments. +- **Schema inspection and additive changes**: `get-schema`, `list-fields` (the fields that hold data, from Solr's Luke handler), `add-fields` and `add-field-types`. The schema tools only add; they never change or remove existing fields or field types. +- **Prompts, resources and completions**: guided prompts (`explore-collections`, `setup-collection`, `search-collection`, `index-data`, `view-schema`, `design-schema`), the `solr://collections`, `solr://{collection}/schema` and `solr://{collection}/fields` resources, and collection-name completion for their arguments. - **STDIO and HTTP transports**: STDIO is the default; `PROFILES=http` serves stateless streamable HTTP. - **OAuth2 security for HTTP, on by default**: JWT bearer tokens from the issuer in `OAUTH2_ISSUER_URI`, with audience validation and configurable CORS origins (`MCP_CORS_ALLOWED_ORIGINS`). Setup guides cover Auth0 and Keycloak. - **Docker images**: `apache/solr-mcp`, a JVM image (amd64 and arm64) that serves both transports, and GraalVM native images for each transport (`-native-stdio`, `-native-http`) on GHCR. diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index d4f47bda..9a072043 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -61,9 +61,10 @@ it speaks MCP (JSON-RPC) to an AI client over one of two transports — **STDIO* (streamable-HTTP; a network listener). On the other side it speaks SolrJ HTTP to **one** backend Solr instance whose location and credentials the operator fixes at startup via environment (`SOLR_URL`, optional `SOLR_USERNAME`/`SOLR_PASSWORD`). -It exposes eleven tools (search, three indexing formats, collection create/list/ -stats/health, schema get/add-fields/add-field-types), three resources -(`solr://collections`, `solr://{collection}/schema`, `solr://{collection}/fields`), and prompt/completion +It exposes sixteen tools (search, four indexing formats, collection create/list/ +stats/health, alias list/create/delete, schema get/list-fields/add-fields/ +add-field-types), three resources (`solr://collections`, +`solr://{collection}/schema`, `solr://{collection}/fields`), and prompt/completion helpers. It translates natural-language requests — as structured by the calling LLM into tool arguments — into Solr API calls, and returns Solr results back to the model. *(documented — README; AGENTS.md; `src/main/java/.../server/`.)* diff --git a/dev-docs/DEVELOPMENT.md b/dev-docs/DEVELOPMENT.md index 193f9194..49ffe56e 100644 --- a/dev-docs/DEVELOPMENT.md +++ b/dev-docs/DEVELOPMENT.md @@ -226,7 +226,7 @@ Tests run against the Solr image pinned as `test-image-solr` in `gradle/libs.ver ./gradlew test -Dsolr.test.image=solr:10-slim # Solr 10 ``` -**Tested compatible versions:** 9.4, 9.9, 9.10, 10. +**Tested compatible versions:** 9.4, 9.9, 9.10, 9.11, 10. **Solr 10 notes.** Solr 10 is fully supported with the JSON wire format. The `/admin/mbeans` endpoint was removed in Solr 10, so `getCacheMetrics()`/`getHandlerMetrics()` catch diff --git a/docs/clients/chatgpt.md b/docs/clients/chatgpt.md index 9122d829..785450f8 100644 --- a/docs/clients/chatgpt.md +++ b/docs/clients/chatgpt.md @@ -46,7 +46,7 @@ Use the `https://…` address it prints, with `/mcp` appended. 1. **Settings → Security and login**: turn on **Developer mode**. 2. Open **ChatGPT Plugins**, select the **+** button and create a developer-mode app. 3. Enter a name and description, and under **Connection** give the public endpoint, ending in `/mcp`, for example `https:///mcp`. For a private server, choose **Tunnel** instead and select an available Secure MCP Tunnel. -4. Choose **No authentication**, create the connection and review the discovered tools. There should be twelve. +4. Choose **No authentication**, create the connection and review the discovered tools. There should be sixteen. 5. Start a chat, enable the app, and ask *"What Solr collections are available?"*. ChatGPT asks for confirmation before tool calls it treats as writes. Tools without a `readOnlyHint` annotation are treated as writes, so expect prompts for most Solr MCP tools. After restarting the server, use **Refresh** on the app so ChatGPT re-reads its tools. diff --git a/docs/clients/mcp-inspector.md b/docs/clients/mcp-inspector.md index ba12cbd7..49de2b6d 100644 --- a/docs/clients/mcp-inspector.md +++ b/docs/clients/mcp-inspector.md @@ -120,7 +120,7 @@ See the [HTTP security model](../security/http.md) for server-side OAuth2 setup ## Resources, prompts and completions ## -The **Resources** tab lists `solr://collections` and the `solr://{collection}/schema` template: +The **Resources** tab lists `solr://collections` and the `solr://{collection}/schema` and `solr://{collection}/fields` templates: ![MCP Inspector reading the solr://collections resource](../../images/mcp-inspector-list-resources.png) diff --git a/docs/site/content/pages/mcp/quick-start.md b/docs/site/content/pages/mcp/quick-start.md index 48b34b7c..71b14083 100644 --- a/docs/site/content/pages/mcp/quick-start.md +++ b/docs/site/content/pages/mcp/quick-start.md @@ -7,7 +7,7 @@ template: mcp/quick-start * Java 25+ ([Eclipse Temurin](https://adoptium.net/) recommended) * [Docker](https://docs.docker.com/get-docker/) and Docker Compose -* Apache Solr **9.4–10** (the bundled sample stack runs Solr 9; the server is tested against 9.4, 9.9, 9.10, and 10) +* Apache Solr **9.4–10** (the bundled sample stack runs Solr 9; the server is tested against 9.4, 9.9, 9.10, 9.11, and 10) * An MCP client — this guide uses [Claude Desktop](https://claude.ai/download), but any MCP-compatible client works. See [Adding to AI Clients](/mcp/clients/claude-desktop.html) for other options. ## Start Solr with Sample Data ## @@ -120,7 +120,7 @@ Open Claude Desktop and try these prompts: * *"Find all sci-fi movies released after 2000 and show the genre breakdown"* * *"Index this JSON into the books collection: [{"id": "1", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}]"* -**Tip:** clients that support MCP completions autocomplete collection names — for the `{collection}` in the `solr://{collection}/schema` resource and for the `collection` argument of the `search-collection`, `index-data`, `view-schema`, and `design-schema` prompts. +**Tip:** clients that support MCP completions autocomplete collection names — for the `{collection}` in the `solr://{collection}/schema` and `solr://{collection}/fields` resources and for the `collection` argument of the `search-collection`, `index-data`, `view-schema`, and `design-schema` prompts. *** diff --git a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java index 7b1382ec..e89e7e89 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java @@ -307,8 +307,9 @@ public String getFieldsResource(String collection) { * * @param collection the collection to list fields for * @return Luke's {@code fields} and {@code info} sections as nested maps - * @throws SolrServerException if Solr returns an error; an unknown collection surfaces as an - * unchecked {@code SolrException} (404) + * @throws SolrServerException if the request cannot be sent or its response read; an error Solr + * returns, an unknown collection's 404 included, surfaces as an unchecked {@code + * SolrException} * @throws IOException if communication with Solr fails */ @PreAuthorize("isAuthenticated()") @@ -334,7 +335,10 @@ public Map listFields( LukeRequest lukeRequest = new LukeRequest(); lukeRequest.setNumTerms(0); lukeRequest.setIncludeIndexFieldFlags(false); - NamedList response = lukeRequest.process(solrClient, collection).getResponse(); + // request(), not lukeRequest.process(): process() also builds SolrJ's typed LukeResponse, + // which casts each field's docs to Integer and fails on a distributed sum past 2^31 (a Long). + // The tool returns the raw sections, so that parse is never needed. + NamedList response = solrClient.request(lukeRequest, collection); Map sections = new LinkedHashMap<>(); for (String section : List.of(LUKE_FIELDS_KEY, LUKE_INFO_KEY)) { diff --git a/src/main/java/org/apache/solr/mcp/server/search/SearchService.java b/src/main/java/org/apache/solr/mcp/server/search/SearchService.java index 05591779..6051dbf8 100644 --- a/src/main/java/org/apache/solr/mcp/server/search/SearchService.java +++ b/src/main/java/org/apache/solr/mcp/server/search/SearchService.java @@ -143,7 +143,7 @@ public class SearchService { + " if it persists, ask the operator to check Solr availability and connection settings."; private static final String RESPONSE_ERROR = "Search failed: unable to process the Solr response." - + " If facetFields were supplied, call list-fields to check those fields have docValues or retry without facetFields;" + + " If facetFields were supplied, call list-fields to check those fields or retry without facetFields;" + " if it persists, ask the operator to check server logs and Solr compatibility."; private final SolrClient solrClient; @@ -218,7 +218,7 @@ to use eDisMax features (multi-field search, minimum-match, boosts), embed Solr Put filters in fq (filterQueries) instead of q so Solr can cache and reuse them. Call list-fields first to get the field names that hold data and their types, rather than guessing names: dynamic fields such as genre_s exist only once documents use them. Facet - and sort only on fields that list-fields reports with docValues. + only on fields that list-fields reports with docValues, and sort only on single-valued ones. """) // @formatter:on public SearchResponse search( @@ -363,7 +363,8 @@ private static RuntimeException withRemediationHint(SolrException e, String coll return new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Search failed: Solr rejected the request. Check query syntax, filter queries, facet fields," - + " sort clauses, and pagination; call list-fields to verify the field names."); + + " sort clauses, and pagination; call list-fields to verify the field names, and facet and" + + " sort only on single-valued fields with D (docValues) in their schema flags."); } if (e.code() == SolrException.ErrorCode.UNAUTHORIZED.code || e.code() == SolrException.ErrorCode.FORBIDDEN.code) { @@ -414,8 +415,8 @@ public String searchCollectionPrompt( (`text_general` or similar tokenized types), which are filterable exact-match (`string`/`strings`), and which are numeric/date ranges. A `D` in a field's `schema` flags (decoded by `info.key`) means docValues: those are the fields you - can facet and sort on. `dynamicBase` shows which pattern a field came from - (e.g. `*_s`). + can facet on, and sort on when they are single-valued (no `M`). `dynamicBase` + shows which pattern a field came from (e.g. `*_s`). 2. Translate the question into Solr query parts. - Pick the most informative tokens from the question. Map them to fields: diff --git a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java index 5b5957bb..dc74297e 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java @@ -24,6 +24,7 @@ import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.GenericSolrRequest; import org.apache.solr.client.solrj.request.UpdateRequest; +import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.TestcontainersConfiguration; @@ -92,8 +93,8 @@ void pointFieldsHaveNoDocCount() throws Exception { assertNotNull(year, "year_i should be listed"); assertEquals("pint", year.get("type")); - // Luke cannot count a field without terms: older Solr leaves docs out, - // distributed Luke (9.11+/10.1+) reports 0. + // Luke cannot count a field without terms: before 9.11/10.1 it leaves docs + // out, from 9.11/10.1 it reports 0. Object docs = year.get("docs"); assertTrue(docs == null || ((Number) docs).longValue() == 0, "docs: " + docs); } @@ -123,8 +124,10 @@ void twoShardListingCoversBothShardsOnlyWhereSolrDistributesLuke() throws Except } @Test - void unknownCollectionFails() { - assertThrows(Exception.class, () -> schemaService.listFields("no_such_collection_xyz")); + void unknownCollectionFailsWithNotFound() { + SolrException e = + assertThrows(SolrException.class, () -> schemaService.listFields("no_such_collection_xyz")); + assertEquals(SolrException.ErrorCode.NOT_FOUND.code, e.code()); } private void indexToShard(String shard, SolrInputDocument document) throws Exception { From d472311b8c121fb3441f73535c1c7b48e6efdeb3 Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Sat, 14 Nov 2026 21:50:29 -0500 Subject: [PATCH 3/6] fix(schema): resolve SonarCloud issues on list-fields (#241) - java:S1192: the Luke key constant LUKE_FIELDS_KEY ("fields") made Sonar ask the add-fields parameter check to reuse it, though that "fields" is an error-message name, not a Luke key. One list of the Luke sections to pass through replaces the two key constants. - java:S5785: assertNotEquals instead of assertTrue(a != b). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- .../apache/solr/mcp/server/schema/SchemaService.java | 12 ++++++------ .../mcp/server/schema/ListFieldsIntegrationTest.java | 5 +++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java index e89e7e89..0b32d135 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java @@ -128,11 +128,11 @@ public class SchemaService { "Failed to list the fields. Hint: call list-collections to check" + " the collection name; if it persists, ask the operator to check the server logs."; - /** Luke response section holding one entry per field present in the index. */ - private static final String LUKE_FIELDS_KEY = "fields"; - - /** Luke response section whose {@code key} entry decodes the field flag letters. */ - private static final String LUKE_INFO_KEY = "info"; + /** + * The Luke response sections {@code list-fields} passes through: {@code fields}, one entry per + * field present in the index, and {@code info}, whose {@code key} decodes the field flag letters. + */ + private static final List LUKE_SECTIONS = List.of("fields", "info"); /** SolrJ client for communicating with Solr server */ private final SolrClient solrClient; @@ -341,7 +341,7 @@ public Map listFields( NamedList response = solrClient.request(lukeRequest, collection); Map sections = new LinkedHashMap<>(); - for (String section : List.of(LUKE_FIELDS_KEY, LUKE_INFO_KEY)) { + for (String section : LUKE_SECTIONS) { // A JSON-parsed tree has no cycles, so asMap's depth guard never applies. if (response.get(section) instanceof NamedList list) { sections.put(section, list.asMap(Integer.MAX_VALUE)); diff --git a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java index dc74297e..0cdb040e 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java @@ -117,8 +117,9 @@ void twoShardListingCoversBothShardsOnlyWhereSolrDistributesLuke() throws Except assertEquals(1L, ((Number) fields.get("only_a_s").get("docs")).longValue(), "" + fields); assertEquals(1L, ((Number) fields.get("only_b_s").get("docs")).longValue(), "" + fields); } else { - assertTrue( - fields.containsKey("only_a_s") != fields.containsKey("only_b_s"), + assertNotEquals( + fields.containsKey("only_a_s"), + fields.containsKey("only_b_s"), "a single core holds exactly one of the two shard-only fields: " + fields.keySet()); } } From e16805e6732677214e1033bb2b6037c740d4e7b0 Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Mon, 16 Nov 2026 18:24:49 -0500 Subject: [PATCH 4/6] feat(schema): return get-schema as CollectionSchema records get-schema returned SolrJ's SchemaRepresentation, whose FieldTypeDefinition nests each type's properties under "attributes" and serializes every unset analyzer slot as null: 32 KB on _default against the Schema API's own 23 KB. It now returns a CollectionSchema record with typed components for the properties clients read (fields, field types, analyzers, copy fields). Every other property Solr sends is kept in a catch-all map, collected by @JsonAnySetter when the response is converted and written back at the same level by @JsonAnyGetter, so the JSON a client receives is the Schema API's, key for key, and a property a later Solr version adds is passed on rather than dropped. The response is read with solrClient.request() and converted by Jackson: the Schema API's JSON objects arrive as SimpleOrderedMap, a java.util.Map, so no mapping code is needed. Signed-off-by: Aditya Parikh Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- AGENTS.md | 2 +- .../mcp/server/config/SolrNativeHints.java | 17 +-- .../mcp/server/schema/CollectionSchema.java | 131 ++++++++++++++++++ .../solr/mcp/server/schema/SchemaService.java | 33 +++-- .../server/McpClientIntegrationTestBase.java | 19 +++ .../server/config/SolrNativeHintsTest.java | 23 +++ .../schema/SchemaServiceIntegrationTest.java | 125 ++++++++++------- .../mcp/server/schema/SchemaServiceTest.java | 32 +++++ 8 files changed, 303 insertions(+), 79 deletions(-) create mode 100644 src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java diff --git a/AGENTS.md b/AGENTS.md index 94c58ba1..7d605bba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -318,7 +318,7 @@ buildpacks (`bootBuildImage -Pnative`). Key configuration: generic `Object` dispatch): `AliasResult`, `CollectionCreationResult`, `SolrHealthStatus`, `SolrMetrics`, `IndexStats`, `QueryStats`, `CacheStats`, `CacheInfo`, `HandlerStats`, `HandlerInfo`, `SearchResponse`, `SortClause`, - `SchemaUpdateResult` + `SchemaUpdateResult`, `CollectionSchema` and its nested records - **Spring AI**: `org.springframework.ai.mcp.annotation.context.DefaultMetaProvider`, which `MetaUtils` instantiates reflectively - **Resources**: `logback-spring.xml` (see Logging Architecture above), and SolrJ's diff --git a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java index db17a355..b94b7bcd 100644 --- a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java +++ b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java @@ -66,7 +66,12 @@ class SolrNativeHints implements RuntimeHintsRegistrar { "org.apache.solr.mcp.server.collection.HandlerInfo", "org.apache.solr.mcp.server.search.SearchResponse", "org.apache.solr.mcp.server.search.SortClause", - "org.apache.solr.mcp.server.schema.SchemaUpdateResult"); + "org.apache.solr.mcp.server.schema.SchemaUpdateResult", + "org.apache.solr.mcp.server.schema.CollectionSchema", + "org.apache.solr.mcp.server.schema.CollectionSchema$Field", + "org.apache.solr.mcp.server.schema.CollectionSchema$FieldType", + "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", + "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField"); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { @@ -126,16 +131,6 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) .registerType( org.apache.solr.client.solrj.request.schema.FieldTypeDefinition.class, categories); - // SolrJ schema response type — returned by the get-schema MCP tool and - // serialized to JSON by Spring AI for MCP clients. Without reflection - // hints the JSON Spring AI produces in native image is missing the - // fields/fieldTypes/dynamicFields/copyFields arrays, which silently - // breaks any consumer that introspects the schema. - hints - .reflection() - .registerType( - org.apache.solr.client.solrj.response.schema.SchemaRepresentation.class, categories); - // MCP tool request/response records (some package-private, registered by // name); request records are deserialized reflectively by Jackson when // tool arguments are bound diff --git a/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java b/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java new file mode 100644 index 00000000..737d59c4 --- /dev/null +++ b/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java @@ -0,0 +1,131 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.mcp.server.schema; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * A collection's schema as the Schema API reports it, returned by the {@code get-schema} tool and + * the {@code solr://{collection}/schema} resource. + * + *

Each record types the properties clients read and keeps every other property Solr sends in + * {@code other}: {@link JsonAnySetter} collects them when Solr's response is converted, and {@link + * JsonAnyGetter} writes them back at the same level. The JSON a client receives is therefore the + * Schema API's own, key for key, and a property a later Solr version adds is passed on rather than + * dropped. + * + * @param name the schema name + * @param version the schema version + * @param uniqueKey the uniqueKey field + * @param fieldTypes the field types + * @param fields the declared fields + * @param dynamicFields the dynamic-field patterns + * @param copyFields the copy-field rules + * @param other every other top-level property, such as {@code similarity} + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record CollectionSchema( + @Nullable String name, + @Nullable Float version, + @Nullable String uniqueKey, + List fieldTypes, + List fields, + List dynamicFields, + List copyFields, + @JsonAnySetter @JsonAnyGetter Map other) { + + /** + * A declared field, or a dynamic-field pattern such as {@code *_s}. + * + * @param name the field name, or the pattern for a dynamic field + * @param type the field type name + * @param indexed whether the field is indexed, if set on the field + * @param stored whether the field is stored, if set on the field + * @param docValues whether the field has docValues, if set on the field + * @param multiValued whether the field is multi-valued, if set on the field + * @param required whether the field is required, if set on the field + * @param other every other property, such as {@code useDocValuesAsStored} + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Field( + String name, + String type, + @Nullable Boolean indexed, + @Nullable Boolean stored, + @Nullable Boolean docValues, + @Nullable Boolean multiValued, + @Nullable Boolean required, + @JsonAnySetter @JsonAnyGetter Map other) {} + + /** + * A field type, with its analyzers for a text type. + * + * @param name the type name + * @param className the implementing class, sent by Solr as {@code class} + * @param analyzer the analyzer used for both indexing and querying + * @param indexAnalyzer the index-time analyzer + * @param queryAnalyzer the query-time analyzer + * @param multiTermAnalyzer the analyzer for wildcard, prefix and range terms + * @param other every other property, such as {@code positionIncrementGap} or {@code + * vectorDimension} + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public record FieldType( + String name, + @JsonProperty("class") String className, + @Nullable Analyzer analyzer, + @Nullable Analyzer indexAnalyzer, + @Nullable Analyzer queryAnalyzer, + @Nullable Analyzer multiTermAnalyzer, + @JsonAnySetter @JsonAnyGetter Map other) {} + + /** + * An analyzer chain. Factory entries keep Solr's open-ended properties as maps. + * + * @param charFilters the char filters, in order + * @param tokenizer the tokenizer + * @param filters the token filters, in order + * @param other every other property, such as an analyzer {@code class} + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Analyzer( + @Nullable List> charFilters, + @Nullable Map tokenizer, + @Nullable List> filters, + @JsonAnySetter @JsonAnyGetter Map other) {} + + /** + * A copy-field rule. + * + * @param source the source field or pattern + * @param dest the destination field or pattern + * @param maxChars the number of characters copied, if limited + * @param other every other property + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public record CopyField( + String source, + String dest, + @Nullable Integer maxChars, + @JsonAnySetter @JsonAnyGetter Map other) {} +} diff --git a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java index 0b32d135..f8663163 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java @@ -30,7 +30,6 @@ import org.apache.solr.client.solrj.request.schema.AnalyzerDefinition; import org.apache.solr.client.solrj.request.schema.FieldTypeDefinition; import org.apache.solr.client.solrj.request.schema.SchemaRequest; -import org.apache.solr.client.solrj.response.schema.SchemaRepresentation; import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.util.PromptNames; import org.jspecify.annotations.Nullable; @@ -97,20 +96,20 @@ * *

{@code
  * // Get complete schema information
- * SchemaRepresentation schema = schemaService.getSchema("products");
+ * CollectionSchema schema = schemaService.getSchema("products");
  *
  * // Analyze field configurations
- * schema.getFields().forEach(field -> {
- * 	System.out.println("Field: " + field.getName() + " Type: " + field.getType());
+ * schema.fields().forEach(field -> {
+ * 	System.out.println("Field: " + field.name() + " Type: " + field.type());
  * });
  *
  * // Examine dynamic field patterns
- * schema.getDynamicFields().forEach(dynField -> {
- * 	System.out.println("Pattern: " + dynField.getName() + " Type: " + dynField.getType());
+ * schema.dynamicFields().forEach(dynField -> {
+ * 	System.out.println("Pattern: " + dynField.name() + " Type: " + dynField.type());
  * });
  * }
* - * @see SchemaRepresentation + * @see CollectionSchema * @see org.apache.solr.client.solrj.request.schema.SchemaRequest * @see org.springframework.ai.tool.annotation.Tool */ @@ -120,6 +119,9 @@ public class SchemaService { private static final Logger logger = LoggerFactory.getLogger(SchemaService.class); + /** The section of a Schema API response that holds the schema. */ + private static final String SCHEMA_SECTION = "schema"; + static final String SCHEMA_RESOURCE_ERROR = "Failed to retrieve the schema. Hint: call list-collections to check" + " the collection name; if it persists, ask the operator to check the server logs."; @@ -241,13 +243,12 @@ public String getSchemaResource(String collection) { * caching to reduce network overhead. * * @param collection the name of the Solr collection to retrieve schema information for - * @return complete schema representation containing all field and type definitions + * @return the schema as the Schema API reports it, every property Solr sends included * @throws SolrServerException if the Solr server returns an error; a missing collection surfaces * as an unchecked {@code SolrException} (404) - * @throws IOException if communication with the Solr server fails - * @see SchemaRepresentation + * @throws IOException if communication with Solr fails + * @see CollectionSchema * @see SchemaRequest - * @see org.apache.solr.client.solrj.response.schema.SchemaResponse */ @PreAuthorize("isAuthenticated()") @McpTool( @@ -259,9 +260,13 @@ public String getSchemaResource(String collection) { + "Use this before add-fields or add-field-types to see what is already defined. " + "It does not say which fields hold data or which dynamic fields are in use; to " + "choose fields for search, call list-fields instead.") - public SchemaRepresentation getSchema(String collection) throws SolrServerException, IOException { - SchemaRequest schemaRequest = new SchemaRequest(); - return schemaRequest.process(solrClient, collection).getSchemaRepresentation(); + public CollectionSchema getSchema(String collection) throws SolrServerException, IOException { + // request(), not schemaRequest.process(): process() parses into SolrJ's SchemaRepresentation, + // whose FieldTypeDefinition nests each type's properties under "attributes" and serializes + // every unset analyzer slot as null. The Schema API's own JSON objects arrive as + // SimpleOrderedMap, a java.util.Map, so Jackson converts them into the records directly. + NamedList response = solrClient.request(new SchemaRequest(), collection); + return objectMapper.convertValue(response.get(SCHEMA_SECTION), CollectionSchema.class); } /** diff --git a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java index 5a203802..715ab627 100644 --- a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java +++ b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java @@ -338,6 +338,25 @@ void getSchema() { assertNotError(result); String text = extractText(result); assertFalse(text.isEmpty(), "Schema response should not be empty"); + + // Spring AI serializes the CollectionSchema record. In Solr's own shape a field type's + // properties sit at the top level (no SolrJ "attributes" wrapper), the catch-all is merged + // in rather than emitted as "other", and the arrays are present (they go missing in a + // native image when the records lack reflection hints). + Map schema = OBJECT_MAPPER.readValue(text, new TypeReference<>() {}); + assertFalse(schema.containsKey("other"), text); + List fields = (List) schema.get("fields"); + assertTrue(fields.stream().anyMatch(f -> "id".equals(((Map) f).get("name"))), text); + Map textGeneral = + ((List) schema.get("fieldTypes")) + .stream() + .map(Map.class::cast) + .filter(t -> "text_general".equals(t.get("name"))) + .findFirst() + .orElseThrow(); + assertEquals("solr.TextField", textGeneral.get("class"), text); + assertEquals("100", textGeneral.get("positionIncrementGap"), text); + assertFalse(textGeneral.containsKey("attributes"), text); } @Test diff --git a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java index a8780a93..752b0928 100644 --- a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java +++ b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; import org.apache.solr.client.solrj.response.QueryResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -84,6 +85,28 @@ void registersMcpResponseRecordHints() { .test(hints)); } + @Test + void registersCollectionSchemaRecordHints() { + // Jackson builds these from Solr's response (constructors) and writes the catch-all + // back out through its @JsonAnyGetter accessor (methods), so both are needed. + for (String record : + List.of( + "org.apache.solr.mcp.server.schema.CollectionSchema", + "org.apache.solr.mcp.server.schema.CollectionSchema$Field", + "org.apache.solr.mcp.server.schema.CollectionSchema$FieldType", + "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", + "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField")) { + assertTrue( + RuntimeHintsPredicates.reflection() + .onType(TypeReference.of(record)) + .withMemberCategories( + MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, + MemberCategory.INVOKE_DECLARED_METHODS) + .test(hints), + record); + } + } + @Test void registersLogbackSpringXmlResourceHint() { // The configuration Spring Boot loads by convention; it carries the diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java index 387a647c..ab50ba23 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java @@ -24,9 +24,10 @@ import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.SolrQuery; +import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.QueryResponse; -import org.apache.solr.client.solrj.response.schema.SchemaRepresentation; import org.apache.solr.common.SolrInputDocument; +import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.TestcontainersConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; @@ -35,6 +36,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; /** * Integration test suite for SchemaService using real Solr containers. Tests actual schema @@ -50,6 +53,8 @@ class SchemaServiceIntegrationTest { @Autowired private SolrClient solrClient; + @Autowired private JsonMapper jsonMapper; + private static final String TEST_COLLECTION = "schema_test_collection"; private static boolean initialized = false; @@ -67,26 +72,24 @@ void setupCollection() throws Exception { @Test void testGetSchema_ValidCollection() throws Exception { // When - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); // Then assertNotNull(schema, "Schema should not be null"); - assertNotNull(schema.getFields(), "Schema fields should not be null"); - assertNotNull(schema.getFieldTypes(), "Schema field types should not be null"); + assertNotNull(schema.fields(), "Schema fields should not be null"); + assertNotNull(schema.fieldTypes(), "Schema field types should not be null"); // Verify basic schema properties - assertFalse(schema.getFields().isEmpty(), "Schema should have at least some fields"); - assertFalse(schema.getFieldTypes().isEmpty(), "Schema should have at least some field types"); + assertFalse(schema.fields().isEmpty(), "Schema should have at least some fields"); + assertFalse(schema.fieldTypes().isEmpty(), "Schema should have at least some field types"); // Check for common default fields in Solr - boolean hasIdField = - schema.getFields().stream().anyMatch(field -> "id".equals(field.get("name"))); + boolean hasIdField = schema.fields().stream().anyMatch(field -> "id".equals(field.name())); assertTrue(hasIdField, "Schema should have an 'id' field"); // Check for common field types boolean hasStringType = - schema.getFieldTypes().stream() - .anyMatch(fieldType -> "string".equals(fieldType.getAttributes().get("name"))); + schema.fieldTypes().stream().anyMatch(fieldType -> "string".equals(fieldType.name())); assertTrue(hasStringType, "Schema should have a 'string' field type"); } @@ -115,50 +118,49 @@ void testGetSchema_EmptyCollection() { @Test void testGetSchema_ValidatesSchemaContent() throws Exception { // When - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); // Then - verify schema has expected structure - assertNotNull(schema.getName(), "Schema should have a name"); + assertNotNull(schema.name(), "Schema should have a name"); // Check that we can access field details schema - .getFields() + .fields() .forEach( field -> { - assertNotNull(field.get("name"), "Field should have a name"); - assertNotNull(field.get("type"), "Field should have a type"); + assertNotNull(field.name(), "Field should have a name"); + assertNotNull(field.type(), "Field should have a type"); // indexed and stored can be null (defaults to true in many cases) }); // Check that we can access field type details schema - .getFieldTypes() + .fieldTypes() .forEach( fieldType -> { - assertNotNull(fieldType.getAttributes().get("name"), "Field type should have a name"); - assertNotNull( - fieldType.getAttributes().get("class"), "Field type should have a class"); + assertNotNull(fieldType.name(), "Field type should have a name"); + assertNotNull(fieldType.className(), "Field type should have a class"); }); } @Test void testGetSchema_ChecksDynamicFields() throws Exception { // When - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); // Then - verify dynamic fields are accessible - assertNotNull(schema.getDynamicFields(), "Dynamic fields should not be null"); + assertNotNull(schema.dynamicFields(), "Dynamic fields should not be null"); // The _default configset defines dynamic fields such as *_s and *_i - assertFalse(schema.getDynamicFields().isEmpty(), "Dynamic fields should not be empty"); + assertFalse(schema.dynamicFields().isEmpty(), "Dynamic fields should not be empty"); // Check for common dynamic field patterns boolean hasStringDynamicField = - schema.getDynamicFields().stream() + schema.dynamicFields().stream() .anyMatch( dynField -> { - String name = (String) dynField.get("name"); - return name != null && (name.contains("*_s") || name.contains("*_str")); + String name = dynField.name(); + return name.contains("*_s") || name.contains("*_str"); }); assertTrue(hasStringDynamicField, "Schema should have string dynamic fields"); @@ -167,22 +169,39 @@ void testGetSchema_ChecksDynamicFields() throws Exception { @Test void testGetSchema_ChecksCopyFields() throws Exception { // When - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); // Then - verify copy fields are accessible - assertNotNull(schema.getCopyFields(), "Copy fields should not be null"); + assertNotNull(schema.copyFields(), "Copy fields should not be null"); + } + + @Test + void getSchema_serializesToTheSchemaApiResponse() throws Exception { + // The records must not add, drop or reshape anything: serialized, they are Solr's own + // Schema API JSON. Both sides are written to JSON text and parsed back, so key order and the + // parser's Float-versus-Double choice for decimals such as version do not matter. + NamedList raw = solrClient.request(new SchemaRequest(), TEST_COLLECTION); + TypeReference> asMap = new TypeReference<>() {}; + Map fromSolr = + jsonMapper.readValue(jsonMapper.writeValueAsString(raw.get("schema")), asMap); + + Map fromTool = + jsonMapper.readValue( + jsonMapper.writeValueAsString(schemaService.getSchema(TEST_COLLECTION)), asMap); + + assertEquals(fromSolr, fromTool); } @Test void testGetSchema_ReturnsUniqueKey() throws Exception { // When - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); // Then - verify unique key is accessible // Unique key can be null in some schemas, but the method should work // Most default schemas have 'id' as unique key - if (schema.getUniqueKey() != null) { - assertNotNull(schema.getUniqueKey(), "Unique key should be accessible"); + if (schema.uniqueKey() != null) { + assertNotNull(schema.uniqueKey(), "Unique key should be accessible"); } } @@ -218,27 +237,27 @@ void addFields_endToEnd_persistsToSchema() throws Exception { assertEquals(List.of("addf_title", "addf_platform", "addf_year"), result.addedNames()); - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); - Map title = - schema.getFields().stream() - .filter(f -> "addf_title".equals(f.get("name"))) + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema.Field title = + schema.fields().stream() + .filter(f -> "addf_title".equals(f.name())) .findFirst() .orElseThrow(); - Map platform = - schema.getFields().stream() - .filter(f -> "addf_platform".equals(f.get("name"))) + CollectionSchema.Field platform = + schema.fields().stream() + .filter(f -> "addf_platform".equals(f.name())) .findFirst() .orElseThrow(); - Map year = - schema.getFields().stream() - .filter(f -> "addf_year".equals(f.get("name"))) + CollectionSchema.Field year = + schema.fields().stream() + .filter(f -> "addf_year".equals(f.name())) .findFirst() .orElseThrow(); - assertEquals("text_general", title.get("type")); - assertEquals("string", platform.get("type")); - assertEquals(Boolean.TRUE, platform.get("docValues")); - assertEquals("pint", year.get("type")); + assertEquals("text_general", title.type()); + assertEquals("string", platform.type()); + assertEquals(Boolean.TRUE, platform.docValues()); + assertEquals("pint", year.type()); } @Test @@ -304,22 +323,22 @@ void addFieldTypes_denseVectorField_schemaRoundTrip() throws Exception { "similarityFunction", "cosine"))); - SchemaRepresentation schema = schemaService.getSchema(TEST_COLLECTION); - Map vt = - schema.getFieldTypes().stream() - .filter(t -> "aft_test_vector".equals(t.getAttributes().get("name"))) + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); + CollectionSchema.FieldType vt = + schema.fieldTypes().stream() + .filter(t -> "aft_test_vector".equals(t.name())) .findFirst() - .orElseThrow() - .getAttributes(); + .orElseThrow(); - assertEquals("solr.DenseVectorField", vt.get("class")); - Object vectorDimension = vt.get("vectorDimension"); + assertEquals("solr.DenseVectorField", vt.className()); + // vectorDimension has no record component, so it is kept in the catch-all + Object vectorDimension = vt.other().get("vectorDimension"); int vectorDimensionInt = vectorDimension instanceof Number n ? n.intValue() : Integer.parseInt(vectorDimension.toString()); assertEquals(4, vectorDimensionInt); - assertEquals("cosine", vt.get("similarityFunction")); + assertEquals("cosine", vt.other().get("similarityFunction")); } @Test diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java index 76fd2697..c8f77c5f 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java @@ -71,6 +71,38 @@ void testSchemaService_InstantiatesCorrectly() { assertNotNull(service, "SchemaService should be instantiated correctly"); } + @Test + void getSchema_keepsPropertiesTheRecordsDoNotDeclare() throws Exception { + // A property a later Solr version adds has no record component. It must reach the client + // at the same level Solr sent it, not be dropped and not be wrapped in an "other" object. + SimpleOrderedMap field = new SimpleOrderedMap<>(); + field.add("name", "genre"); + field.add("type", "string"); + field.add("futureFlag", true); + SimpleOrderedMap schema = new SimpleOrderedMap<>(); + schema.add("name", "test"); + schema.add("uniqueKey", "id"); + schema.add("fieldTypes", List.of()); + schema.add("fields", List.of(field)); + schema.add("dynamicFields", List.of()); + schema.add("copyFields", List.of()); + schema.add("futureSection", Map.of("k", "v")); + NamedList response = new NamedList<>(); + response.add("schema", schema); + when(solrClient.request(any(SchemaRequest.class), eq("c"))).thenReturn(response); + JsonMapper realMapper = JsonMapper.builder().build(); + + CollectionSchema result = new SchemaService(solrClient, realMapper).getSchema("c"); + + assertEquals("genre", result.fields().getFirst().name()); + assertEquals(true, result.fields().getFirst().other().get("futureFlag")); + assertEquals(Map.of("k", "v"), result.other().get("futureSection")); + String json = realMapper.writeValueAsString(result); + assertTrue(json.contains("\"futureFlag\":true"), json); + assertTrue(json.contains("\"futureSection\":{\"k\":\"v\"}"), json); + assertFalse(json.contains("\"other\""), json); + } + @Test void testGetSchema_CollectionNotFound() throws Exception { // Given From 741bb75c23d62c59ec9cac56581408cf0e8bb95d Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Mon, 16 Nov 2026 20:35:58 -0500 Subject: [PATCH 5/6] feat(schema): report field and field-type flags as SolrJ FieldFlag The Schema API's boolean properties (indexed, stored, docValues, multiValued, omitNorms, sortMissingLast, ...) are now reported on every field, dynamic field and field type as "flags", a set of SolrJ's FieldFlag, the enum Luke's flag letters decode to. list-fields uses the same enum, so both tools describe a field's flags the same way. Only properties set to true appear: a flag property set to false, or inherited from the field type, is not reported. required, which FieldFlag has no counterpart for, stays a typed property; other properties without one (useDocValuesAsStored, large, default) stay in the catch-all unchanged. Flags are written as their constant names (DOC_VALUES). Jackson 3 writes enums with toString() by default, which for FieldFlag is Luke's legend text ("D - DocValues"). Signed-off-by: Aditya Parikh Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- .../mcp/server/config/SolrNativeHints.java | 8 +- .../mcp/server/schema/CollectionSchema.java | 58 ++++++++++--- .../solr/mcp/server/schema/FieldFlags.java | 86 +++++++++++++++++++ .../server/McpClientIntegrationTestBase.java | 10 ++- .../server/config/SolrNativeHintsTest.java | 4 +- .../schema/SchemaServiceIntegrationTest.java | 56 ++++++++++-- .../mcp/server/schema/SchemaServiceTest.java | 9 ++ 7 files changed, 208 insertions(+), 23 deletions(-) create mode 100644 src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java diff --git a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java index b94b7bcd..b10175d4 100644 --- a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java +++ b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java @@ -24,6 +24,7 @@ import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; +import org.apache.solr.common.luke.FieldFlag; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.jspecify.annotations.Nullable; @@ -71,7 +72,9 @@ class SolrNativeHints implements RuntimeHintsRegistrar { "org.apache.solr.mcp.server.schema.CollectionSchema$Field", "org.apache.solr.mcp.server.schema.CollectionSchema$FieldType", "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", - "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField"); + "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField", + // Jackson instantiates this @JsonSerialize(contentUsing = ...) serializer reflectively + "org.apache.solr.mcp.server.schema.FieldFlags$NameSerializer"); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { @@ -97,6 +100,9 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) hints.reflection().registerType(FacetField.class, categories); hints.reflection().registerType(FacetField.Count.class, categories); + // SolrJ's Luke flag enum, serialized in get-schema and list-fields responses + hints.reflection().registerType(FieldFlag.class, categories); + // SolrJ / Solr API model types used by CoreAdminResponse.getCoreStatus() // which deserializes via Jackson reflection. for (String solrApiType : diff --git a/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java b/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java index 737d59c4..7ceb515b 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/CollectionSchema.java @@ -20,9 +20,13 @@ import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import org.apache.solr.common.luke.FieldFlag; import org.jspecify.annotations.Nullable; +import tools.jackson.databind.annotation.JsonSerialize; /** * A collection's schema as the Schema API reports it, returned by the {@code get-schema} tool and @@ -30,9 +34,9 @@ * *

Each record types the properties clients read and keeps every other property Solr sends in * {@code other}: {@link JsonAnySetter} collects them when Solr's response is converted, and {@link - * JsonAnyGetter} writes them back at the same level. The JSON a client receives is therefore the - * Schema API's own, key for key, and a property a later Solr version adds is passed on rather than - * dropped. + * JsonAnyGetter} writes them back at the same level, so a property a later Solr version adds is + * passed on rather than dropped. The one change to the Schema API's JSON is that the boolean flag + * properties of fields and field types are reported as {@code flags}, see {@link FieldFlags}. * * @param name the schema name * @param version the schema version @@ -57,12 +61,14 @@ public record CollectionSchema( /** * A declared field, or a dynamic-field pattern such as {@code *_s}. * + *

The Schema API's boolean properties ({@code indexed}, {@code stored}, {@code docValues}, …) + * are reported as {@code flags}, SolrJ's {@link FieldFlag}, the same enum {@code list-fields} + * uses. Only properties set to {@code true} on the field appear; a property set to {@code false} + * or inherited from the field type does not. + * * @param name the field name, or the pattern for a dynamic field * @param type the field type name - * @param indexed whether the field is indexed, if set on the field - * @param stored whether the field is stored, if set on the field - * @param docValues whether the field has docValues, if set on the field - * @param multiValued whether the field is multi-valued, if set on the field + * @param flags the flags set to {@code true} on the field * @param required whether the field is required, if set on the field * @param other every other property, such as {@code useDocValuesAsStored} */ @@ -70,18 +76,31 @@ public record CollectionSchema( public record Field( String name, String type, - @Nullable Boolean indexed, - @Nullable Boolean stored, - @Nullable Boolean docValues, - @Nullable Boolean multiValued, + @JsonSerialize(contentUsing = FieldFlags.NameSerializer.class) Set flags, @Nullable Boolean required, - @JsonAnySetter @JsonAnyGetter Map other) {} + @JsonAnySetter @JsonAnyGetter Map other) { + + /** + * Moves the boolean flag properties Jackson collected into {@code other} into {@code flags}. + */ + public Field { + if (flags == null || flags.isEmpty()) { + Map rest = new LinkedHashMap<>(other); + flags = FieldFlags.fromSchemaProperties(rest); + other = rest; + } + } + } /** * A field type, with its analyzers for a text type. * + *

Its boolean properties are defaults for the fields of this type, and are reported as {@code + * flags} as on {@link Field}. + * * @param name the type name * @param className the implementing class, sent by Solr as {@code class} + * @param flags the flags set to {@code true} on the type * @param analyzer the analyzer used for both indexing and querying * @param indexAnalyzer the index-time analyzer * @param queryAnalyzer the query-time analyzer @@ -93,11 +112,24 @@ public record Field( public record FieldType( String name, @JsonProperty("class") String className, + @JsonSerialize(contentUsing = FieldFlags.NameSerializer.class) Set flags, @Nullable Analyzer analyzer, @Nullable Analyzer indexAnalyzer, @Nullable Analyzer queryAnalyzer, @Nullable Analyzer multiTermAnalyzer, - @JsonAnySetter @JsonAnyGetter Map other) {} + @JsonAnySetter @JsonAnyGetter Map other) { + + /** + * Moves the boolean flag properties Jackson collected into {@code other} into {@code flags}. + */ + public FieldType { + if (flags == null || flags.isEmpty()) { + Map rest = new LinkedHashMap<>(other); + flags = FieldFlags.fromSchemaProperties(rest); + other = rest; + } + } + } /** * An analyzer chain. Factory entries keep Solr's open-ended properties as maps. diff --git a/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java b/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java new file mode 100644 index 00000000..93868250 --- /dev/null +++ b/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.mcp.server.schema; + +import java.util.EnumSet; +import java.util.Map; +import org.apache.solr.common.luke.FieldFlag; +import tools.jackson.core.JsonGenerator; +import tools.jackson.databind.SerializationContext; +import tools.jackson.databind.ValueSerializer; + +/** + * Field and field-type flags expressed as SolrJ's {@link FieldFlag}, the enum Luke's flag letters + * decode to, so that {@code get-schema} and {@code list-fields} describe a field's flags the same + * way. + */ +public final class FieldFlags { + + /** + * Schema API boolean properties and the {@link FieldFlag} each one sets. The Schema API names + * them as {@code SchemaField} properties; {@code FieldFlag} has no counterpart for {@code + * required}, {@code useDocValuesAsStored} or {@code large}, which stay ordinary properties. + */ + static final Map SCHEMA_PROPERTIES = + Map.ofEntries( + Map.entry("indexed", FieldFlag.INDEXED), + Map.entry("stored", FieldFlag.STORED), + Map.entry("docValues", FieldFlag.DOC_VALUES), + Map.entry("uninvertible", FieldFlag.UNINVERTIBLE), + Map.entry("multiValued", FieldFlag.MULTI_VALUED), + Map.entry("termVectors", FieldFlag.TERM_VECTOR_STORED), + Map.entry("termOffsets", FieldFlag.TERM_VECTOR_OFFSET), + Map.entry("termPositions", FieldFlag.TERM_VECTOR_POSITION), + Map.entry("termPayloads", FieldFlag.TERM_VECTOR_PAYLOADS), + Map.entry("omitNorms", FieldFlag.OMIT_NORMS), + Map.entry("omitTermFreqAndPositions", FieldFlag.OMIT_TF), + Map.entry("omitPositions", FieldFlag.OMIT_POSITIONS), + Map.entry("storeOffsetsWithPositions", FieldFlag.STORE_OFFSETS_WITH_POSITIONS), + Map.entry("sortMissingFirst", FieldFlag.SORT_MISSING_FIRST), + Map.entry("sortMissingLast", FieldFlag.SORT_MISSING_LAST)); + + private FieldFlags() {} + + /** + * Removes the flag properties from a field's or field type's properties and returns the flags + * that were set to {@code true}. A property set to {@code false} is removed and not reported, so + * the result does not tell an explicit {@code false} from a property inherited from the type. + * + * @param properties the remaining Schema API properties; flag properties are removed from it + * @return the flags set to {@code true} + */ + static EnumSet fromSchemaProperties(Map properties) { + EnumSet flags = EnumSet.noneOf(FieldFlag.class); + for (Map.Entry property : SCHEMA_PROPERTIES.entrySet()) { + if (Boolean.TRUE.equals(properties.remove(property.getKey()))) { + flags.add(property.getValue()); + } + } + return flags; + } + + /** + * Writes a flag as its enum constant name ({@code DOC_VALUES}). Without it Jackson 3 writes + * {@link FieldFlag#toString()}, Luke's legend text ({@code "D - DocValues"}). + */ + public static final class NameSerializer extends ValueSerializer { + @Override + public void serialize(FieldFlag flag, JsonGenerator generator, SerializationContext context) { + generator.writeString(flag.name()); + } + } +} diff --git a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java index 715ab627..21a535b3 100644 --- a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java +++ b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java @@ -346,7 +346,15 @@ void getSchema() { Map schema = OBJECT_MAPPER.readValue(text, new TypeReference<>() {}); assertFalse(schema.containsKey("other"), text); List fields = (List) schema.get("fields"); - assertTrue(fields.stream().anyMatch(f -> "id".equals(((Map) f).get("name"))), text); + Map id = + fields.stream() + .map(Map.class::cast) + .filter(f -> "id".equals(f.get("name"))) + .findFirst() + .orElseThrow(); + // flags are SolrJ FieldFlag constant names, not Luke legend text ("I - Indexed") + assertTrue(((List) id.get("flags")).containsAll(List.of("INDEXED", "STORED")), text); + assertFalse(id.containsKey("indexed"), text); Map textGeneral = ((List) schema.get("fieldTypes")) .stream() diff --git a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java index 752b0928..d77af252 100644 --- a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java +++ b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java @@ -95,7 +95,9 @@ void registersCollectionSchemaRecordHints() { "org.apache.solr.mcp.server.schema.CollectionSchema$Field", "org.apache.solr.mcp.server.schema.CollectionSchema$FieldType", "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", - "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField")) { + "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField", + "org.apache.solr.mcp.server.schema.FieldFlags$NameSerializer", + "org.apache.solr.common.luke.FieldFlag")) { assertTrue( RuntimeHintsPredicates.reflection() .onType(TypeReference.of(record)) diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java index ab50ba23..7d6e5c2a 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.CollectionAdminRequest; @@ -27,6 +28,7 @@ import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; +import org.apache.solr.common.luke.FieldFlag; import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.TestcontainersConfiguration; import org.junit.jupiter.api.BeforeEach; @@ -176,20 +178,60 @@ void testGetSchema_ChecksCopyFields() throws Exception { } @Test - void getSchema_serializesToTheSchemaApiResponse() throws Exception { - // The records must not add, drop or reshape anything: serialized, they are Solr's own - // Schema API JSON. Both sides are written to JSON text and parsed back, so key order and the - // parser's Float-versus-Double choice for decimals such as version do not matter. + void getSchema_isTheSchemaApiResponseWithFlagPropertiesAsFlags() throws Exception { + // The records may change one thing about the Schema API's JSON: on every field, dynamic + // field and field type, the boolean flag properties become a "flags" list of the ones set to + // true. Everything else must come through unchanged. Both sides are written to JSON text and + // parsed back, so key order and Float-versus-Double for decimals such as version do not matter. NamedList raw = solrClient.request(new SchemaRequest(), TEST_COLLECTION); TypeReference> asMap = new TypeReference<>() {}; - Map fromSolr = + Map expected = jsonMapper.readValue(jsonMapper.writeValueAsString(raw.get("schema")), asMap); + for (String section : List.of("fields", "dynamicFields", "fieldTypes")) { + for (Object entry : (List) expected.get(section)) { + @SuppressWarnings("unchecked") + Map properties = (Map) entry; + List flags = + FieldFlags.SCHEMA_PROPERTIES.entrySet().stream() + .filter(property -> Boolean.TRUE.equals(properties.remove(property.getKey()))) + .map(Map.Entry::getValue) + .sorted() + .map(Enum::name) + .toList(); + properties.put("flags", flags); + } + } Map fromTool = jsonMapper.readValue( jsonMapper.writeValueAsString(schemaService.getSchema(TEST_COLLECTION)), asMap); - assertEquals(fromSolr, fromTool); + assertEquals(expected, fromTool); + } + + @Test + void getSchema_reportsFieldFlags() throws Exception { + CollectionSchema schema = schemaService.getSchema(TEST_COLLECTION); + + CollectionSchema.Field id = + schema.fields().stream().filter(f -> "id".equals(f.name())).findFirst().orElseThrow(); + CollectionSchema.Field root = + schema.fields().stream().filter(f -> "_root_".equals(f.name())).findFirst().orElseThrow(); + CollectionSchema.FieldType strings = + schema.fieldTypes().stream() + .filter(t -> "strings".equals(t.name())) + .findFirst() + .orElseThrow(); + + // _default declares id indexed and stored, _root_ indexed but stored=false + assertTrue(id.flags().containsAll(Set.of(FieldFlag.INDEXED, FieldFlag.STORED)), id::toString); + assertTrue(root.flags().contains(FieldFlag.INDEXED), root::toString); + assertFalse(root.flags().contains(FieldFlag.STORED), root::toString); + assertFalse(root.other().containsKey("stored"), root::toString); + // a type's flags are defaults for its fields + assertTrue( + strings.flags().containsAll(Set.of(FieldFlag.MULTI_VALUED, FieldFlag.SORT_MISSING_LAST)), + strings::toString); } @Test @@ -256,7 +298,7 @@ void addFields_endToEnd_persistsToSchema() throws Exception { assertEquals("text_general", title.type()); assertEquals("string", platform.type()); - assertEquals(Boolean.TRUE, platform.docValues()); + assertTrue(platform.flags().contains(FieldFlag.DOC_VALUES), platform::toString); assertEquals("pint", year.type()); } diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java index c8f77c5f..bea88cdc 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java @@ -25,12 +25,14 @@ import java.io.IOException; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.LukeRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.request.schema.SchemaRequest.MultiUpdate; +import org.apache.solr.common.luke.FieldFlag; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; @@ -78,6 +80,8 @@ void getSchema_keepsPropertiesTheRecordsDoNotDeclare() throws Exception { SimpleOrderedMap field = new SimpleOrderedMap<>(); field.add("name", "genre"); field.add("type", "string"); + field.add("indexed", true); + field.add("stored", false); field.add("futureFlag", true); SimpleOrderedMap schema = new SimpleOrderedMap<>(); schema.add("name", "test"); @@ -96,11 +100,16 @@ void getSchema_keepsPropertiesTheRecordsDoNotDeclare() throws Exception { assertEquals("genre", result.fields().getFirst().name()); assertEquals(true, result.fields().getFirst().other().get("futureFlag")); + // flag properties become FieldFlags (true only) and leave the catch-all + assertEquals(Set.of(FieldFlag.INDEXED), result.fields().getFirst().flags()); + assertFalse(result.fields().getFirst().other().containsKey("indexed")); + assertFalse(result.fields().getFirst().other().containsKey("stored")); assertEquals(Map.of("k", "v"), result.other().get("futureSection")); String json = realMapper.writeValueAsString(result); assertTrue(json.contains("\"futureFlag\":true"), json); assertTrue(json.contains("\"futureSection\":{\"k\":\"v\"}"), json); assertFalse(json.contains("\"other\""), json); + assertTrue(json.contains("\"flags\":[\"INDEXED\"]"), json); } @Test From 8b5692c274e1ac4d365ff38f168e953b03b55ea2 Mon Sep 17 00:00:00 2001 From: Aditya Parikh Date: Mon, 16 Nov 2026 20:58:47 -0500 Subject: [PATCH 6/6] feat(schema): return list-fields as FieldListing records with FieldFlag flags list-fields passed Luke's fields and info sections through as maps. An agent had to decode each field's schema letters ("I-SD------OF-----l") with the info.key legend to learn, for example, whether it can facet on the field. It now returns a FieldListing record. Each field's letters are decoded into SolrJ's FieldFlag, the enum get-schema uses, so the info legend is no longer needed and is left out. docs is a Long, so a distributed sum past 2^31 no longer depends on how the value was parsed. Every other property Luke sends is kept in a catch-all and written back at the same level. The letters are decoded with FieldFlag.getFlag rather than LukeResponse.FieldInfo.parseFlags, which adds getFlag's result without a null check and so would throw on a letter a later Solr version adds. On an unknown letter the letters are kept as they are. Signed-off-by: Aditya Parikh Co-Authored-By: Claude Opus 5.5 Signed-off-by: Aditya Parikh --- AGENTS.md | 2 +- .../mcp/server/config/SolrNativeHints.java | 4 +- .../solr/mcp/server/schema/FieldFlags.java | 27 ++++++ .../solr/mcp/server/schema/FieldListing.java | 84 +++++++++++++++++++ .../solr/mcp/server/schema/SchemaService.java | 52 ++++++------ .../server/McpClientIntegrationTestBase.java | 7 ++ .../server/config/SolrNativeHintsTest.java | 2 + .../schema/ListFieldsIntegrationTest.java | 52 +++++++----- .../mcp/server/schema/SchemaServiceTest.java | 84 ++++++++++++++----- 9 files changed, 245 insertions(+), 69 deletions(-) create mode 100644 src/main/java/org/apache/solr/mcp/server/schema/FieldListing.java diff --git a/AGENTS.md b/AGENTS.md index 7d605bba..4ed807c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -318,7 +318,7 @@ buildpacks (`bootBuildImage -Pnative`). Key configuration: generic `Object` dispatch): `AliasResult`, `CollectionCreationResult`, `SolrHealthStatus`, `SolrMetrics`, `IndexStats`, `QueryStats`, `CacheStats`, `CacheInfo`, `HandlerStats`, `HandlerInfo`, `SearchResponse`, `SortClause`, - `SchemaUpdateResult`, `CollectionSchema` and its nested records + `SchemaUpdateResult`, `CollectionSchema` and `FieldListing` and their nested records - **Spring AI**: `org.springframework.ai.mcp.annotation.context.DefaultMetaProvider`, which `MetaUtils` instantiates reflectively - **Resources**: `logback-spring.xml` (see Logging Architecture above), and SolrJ's diff --git a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java index b10175d4..05bda072 100644 --- a/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java +++ b/src/main/java/org/apache/solr/mcp/server/config/SolrNativeHints.java @@ -74,7 +74,9 @@ class SolrNativeHints implements RuntimeHintsRegistrar { "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField", // Jackson instantiates this @JsonSerialize(contentUsing = ...) serializer reflectively - "org.apache.solr.mcp.server.schema.FieldFlags$NameSerializer"); + "org.apache.solr.mcp.server.schema.FieldFlags$NameSerializer", + "org.apache.solr.mcp.server.schema.FieldListing", + "org.apache.solr.mcp.server.schema.FieldListing$IndexedField"); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { diff --git a/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java b/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java index 93868250..12706314 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/FieldFlags.java @@ -19,6 +19,7 @@ import java.util.EnumSet; import java.util.Map; import org.apache.solr.common.luke.FieldFlag; +import org.jspecify.annotations.Nullable; import tools.jackson.core.JsonGenerator; import tools.jackson.databind.SerializationContext; import tools.jackson.databind.ValueSerializer; @@ -73,6 +74,32 @@ static EnumSet fromSchemaProperties(Map properties) { return flags; } + /** + * Decodes Luke's flag string ({@code "I-SD------OF-----l"}) with SolrJ's {@link + * FieldFlag#getFlag(char)}. + * + *

Not {@code LukeResponse.FieldInfo.parseFlags}: it adds {@code getFlag}'s result without a + * null check, so a letter a later Solr version adds would throw. + * + * @param letters Luke's flag string + * @return the decoded flags, or {@code null} if a letter is not a known flag, so the caller can + * keep the string rather than report a partial set + */ + static @Nullable EnumSet fromLukeLetters(String letters) { + EnumSet flags = EnumSet.noneOf(FieldFlag.class); + for (char letter : letters.toCharArray()) { + if (letter == '-') { + continue; + } + FieldFlag flag = FieldFlag.getFlag(letter); + if (flag == null) { + return null; + } + flags.add(flag); + } + return flags; + } + /** * Writes a flag as its enum constant name ({@code DOC_VALUES}). Without it Jackson 3 writes * {@link FieldFlag#toString()}, Luke's legend text ({@code "D - DocValues"}). diff --git a/src/main/java/org/apache/solr/mcp/server/schema/FieldListing.java b/src/main/java/org/apache/solr/mcp/server/schema/FieldListing.java new file mode 100644 index 00000000..b5a1d877 --- /dev/null +++ b/src/main/java/org/apache/solr/mcp/server/schema/FieldListing.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.solr.mcp.server.schema; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import org.apache.solr.common.luke.FieldFlag; +import org.jspecify.annotations.Nullable; +import tools.jackson.databind.annotation.JsonSerialize; + +/** + * The fields that hold data in a collection, as Solr's Luke handler reports them, returned by the + * {@code list-fields} tool and the {@code solr://{collection}/fields} resource. + * + * @param fields each field in the index by name, in Luke's order + */ +public record FieldListing(Map fields) { + + /** + * One field in the index. + * + *

Luke's {@code schema} flag letters ({@code "I-SD------OF-----l"}) are reported as {@code + * flags}, SolrJ's {@link FieldFlag}, the same enum {@code get-schema} uses. Every other property + * Luke sends is kept in {@code other} and written back at the same level, so a property a later + * Solr version adds is passed on rather than dropped. + * + * @param type the field type name + * @param flags the field's flags, decoded from Luke's {@code schema} letters + * @param dynamicBase the dynamic-field pattern this field is an instance of, such as {@code *_s} + * @param docs the number of documents with terms in the field, deleted documents included; Luke + * cannot count a field without terms (point and docValues-only fields), so it is absent, or 0 + * on Solr 9.11+ and 10.1+, for those + * @param other every other property Luke sends, and the {@code schema} letters themselves if one + * is not a flag SolrJ knows + */ + @JsonInclude(JsonInclude.Include.NON_NULL) + public record IndexedField( + @Nullable String type, + @JsonSerialize(contentUsing = FieldFlags.NameSerializer.class) Set flags, + @Nullable String dynamicBase, + @Nullable Long docs, + @JsonAnySetter @JsonAnyGetter Map other) { + + /** + * Decodes the {@code schema} letters Jackson collected into {@code other} into {@code flags}. + */ + public IndexedField { + if (flags == null || flags.isEmpty()) { + Map rest = new LinkedHashMap<>(other); + EnumSet decoded = + rest.get(LUKE_FLAGS) instanceof String letters + ? FieldFlags.fromLukeLetters(letters) + : null; + if (decoded != null) { + rest.remove(LUKE_FLAGS); + } + flags = decoded != null ? decoded : EnumSet.noneOf(FieldFlag.class); + other = rest; + } + } + } + + /** The Luke property holding a field's schema flags as letters. */ + private static final String LUKE_FLAGS = "schema"; +} diff --git a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java index f8663163..26071ec7 100644 --- a/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java +++ b/src/main/java/org/apache/solr/mcp/server/schema/SchemaService.java @@ -42,6 +42,7 @@ import org.springframework.ai.mcp.annotation.McpToolParam; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import tools.jackson.core.type.TypeReference; import tools.jackson.databind.json.JsonMapper; /** @@ -130,11 +131,12 @@ public class SchemaService { "Failed to list the fields. Hint: call list-collections to check" + " the collection name; if it persists, ask the operator to check the server logs."; - /** - * The Luke response sections {@code list-fields} passes through: {@code fields}, one entry per - * field present in the index, and {@code info}, whose {@code key} decodes the field flag letters. - */ - private static final List LUKE_SECTIONS = List.of("fields", "info"); + /** The section of a Luke response that lists the fields, one entry per field in the index. */ + private static final String LUKE_FIELDS_SECTION = "fields"; + + /** Keeps Luke's field order, which is alphabetical. */ + private static final TypeReference> + INDEXED_FIELDS = new TypeReference<>() {}; /** SolrJ client for communicating with Solr server */ private final SolrClient solrClient; @@ -297,21 +299,22 @@ public String getFieldsResource(String collection) { } /** - * Lists the fields that hold data in a collection: the {@code fields} and {@code info} sections - * of Solr's Luke response, passed through as Solr reports them. + * Lists the fields that hold data in a collection, from the {@code fields} section of Solr's Luke + * response. * *

Unlike {@link #getSchema(String)}, Luke reports the dynamic-field instances in the index * ({@code genre_s}, not just {@code *_s}) and, per field, how many documents have terms in it. - * {@code info.key} decodes the letters of each field's {@code schema} flags. The {@code index} - * section is left out: {@code get-collection-stats} reports index statistics, and its {@code - * directory} entry names a path on the Solr host. + * Each field's {@code schema} flag letters are decoded into {@link + * org.apache.solr.common.luke.FieldFlag}s, so Luke's {@code info} legend is not needed and is + * left out. The {@code index} section is left out too: {@code get-collection-stats} reports index + * statistics, and its {@code directory} entry names a path on the Solr host. * *

One collection-level request is made. Solr 9.11 and 10.1 distribute it across shards in * SolrCloud (SOLR-8127); older versions answer from one core, which the tool description tells * the model about. * * @param collection the collection to list fields for - * @return Luke's {@code fields} and {@code info} sections as nested maps + * @return the fields Luke reports, with their flags decoded * @throws SolrServerException if the request cannot be sent or its response read; an error Solr * returns, an unknown collection's 404 included, surfaces as an unchecked {@code * SolrException} @@ -323,16 +326,18 @@ public String getFieldsResource(String collection) { annotations = @McpTool.McpAnnotations(readOnlyHint = true), description = "List the fields that hold data in a collection, from Solr's Luke handler: per field its" - + " type, schema flags, dynamicBase for a dynamic-field instance (genre_s, not *_s), and" - + " docs, the number of documents with terms in the field (deleted documents count" - + " until their segments merge). info.key decodes the flag letters. Use this before" + + " type, flags (INDEXED, STORED, DOC_VALUES, MULTI_VALUED, ...), dynamicBase for a" + + " dynamic-field instance (genre_s, not *_s), and docs, the number of documents with" + + " terms in the field (deleted documents count until their segments merge). Facet" + + " only on fields with DOC_VALUES, and sort only on ones without MULTI_VALUED. Use" + + " this before" + " search to decide which fields go in q, fq, facets and sorts. Unlike get-schema it" + " shows no analyzers or field-type definitions; use get-schema before changing the" + " schema. Numeric and date point fields and docValues-only fields have no terms, so" + " their docs is missing, or 0 on Solr 9.11+ and 10.1+: that means not counted, not" + " empty. Before Solr 9.11 and 10.1, a collection with more than one shard lists the" + " fields and counts of one shard only.") - public Map listFields( + public FieldListing listFields( @McpToolParam(description = "Solr collection name") String collection) throws SolrServerException, IOException { requireCollection(collection); @@ -341,18 +346,13 @@ public Map listFields( lukeRequest.setNumTerms(0); lukeRequest.setIncludeIndexFieldFlags(false); // request(), not lukeRequest.process(): process() also builds SolrJ's typed LukeResponse, - // which casts each field's docs to Integer and fails on a distributed sum past 2^31 (a Long). - // The tool returns the raw sections, so that parse is never needed. + // which casts each field's docs to Integer and fails on a distributed sum past 2^31 (a Long), + // and drops dynamicBase. Luke's JSON objects arrive as SimpleOrderedMap, a java.util.Map, so + // Jackson converts the fields section into the records directly. NamedList response = solrClient.request(lukeRequest, collection); - - Map sections = new LinkedHashMap<>(); - for (String section : LUKE_SECTIONS) { - // A JSON-parsed tree has no cycles, so asMap's depth guard never applies. - if (response.get(section) instanceof NamedList list) { - sections.put(section, list.asMap(Integer.MAX_VALUE)); - } - } - return sections; + Object fields = response.get(LUKE_FIELDS_SECTION); + return new FieldListing( + fields == null ? Map.of() : objectMapper.convertValue(fields, INDEXED_FIELDS)); } /** diff --git a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java index 21a535b3..e9592cc3 100644 --- a/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java +++ b/src/test/java/org/apache/solr/mcp/server/McpClientIntegrationTestBase.java @@ -1276,6 +1276,13 @@ void listShowsFieldsReturnsIndexedFields() { assertTrue( names.containsAll(List.of("id", "title", "platform", "genres", "release_year")), "list-fields should list the indexed shows fields: " + names); + + // Through Spring AI's serialization: Luke's flag letters arrive decoded as FieldFlag + // constant names, with neither the letters nor Luke's info legend left over. + assertFalse(listing.containsKey("info"), "" + listing.keySet()); + Map id = (Map) ((Map) listing.get("fields")).get("id"); + assertTrue(((List) id.get("flags")).containsAll(List.of("INDEXED", "STORED")), "" + id); + assertFalse(id.containsKey("schema"), "" + id); } @Test diff --git a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java index d77af252..0cb37d39 100644 --- a/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java +++ b/src/test/java/org/apache/solr/mcp/server/config/SolrNativeHintsTest.java @@ -97,6 +97,8 @@ void registersCollectionSchemaRecordHints() { "org.apache.solr.mcp.server.schema.CollectionSchema$Analyzer", "org.apache.solr.mcp.server.schema.CollectionSchema$CopyField", "org.apache.solr.mcp.server.schema.FieldFlags$NameSerializer", + "org.apache.solr.mcp.server.schema.FieldListing", + "org.apache.solr.mcp.server.schema.FieldListing$IndexedField", "org.apache.solr.common.luke.FieldFlag")) { assertTrue( RuntimeHintsPredicates.reflection() diff --git a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java index 0cdb040e..32434615 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/ListFieldsIntegrationTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.*; import java.util.Map; +import java.util.Set; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.request.CollectionAdminRequest; @@ -26,6 +27,7 @@ import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; +import org.apache.solr.common.luke.FieldFlag; import org.apache.solr.common.util.NamedList; import org.apache.solr.mcp.server.TestcontainersConfiguration; import org.junit.jupiter.api.BeforeAll; @@ -77,45 +79,52 @@ void createCollections() throws Exception { @Test void listsDynamicFieldInstancesWithTheirBase() throws Exception { - Map> fields = fields(ONE_SHARD); + Map fields = fields(ONE_SHARD); - Map genre = fields.get("genre_s"); + FieldListing.IndexedField genre = fields.get("genre_s"); assertNotNull(genre, "genre_s should be listed: " + fields.keySet()); - assertEquals("*_s", genre.get("dynamicBase")); - assertEquals("string", genre.get("type")); - assertEquals(2L, ((Number) genre.get("docs")).longValue()); - assertFalse(fields.get("id").containsKey("dynamicBase"), "id is an explicit field"); + assertEquals("*_s", genre.dynamicBase()); + assertEquals("string", genre.type()); + assertEquals(2L, genre.docs()); + assertNull(fields.get("id").dynamicBase(), "id is an explicit field"); } @Test void pointFieldsHaveNoDocCount() throws Exception { - Map year = fields(ONE_SHARD).get("year_i"); + FieldListing.IndexedField year = fields(ONE_SHARD).get("year_i"); assertNotNull(year, "year_i should be listed"); - assertEquals("pint", year.get("type")); + assertEquals("pint", year.type()); // Luke cannot count a field without terms: before 9.11/10.1 it leaves docs // out, from 9.11/10.1 it reports 0. - Object docs = year.get("docs"); - assertTrue(docs == null || ((Number) docs).longValue() == 0, "docs: " + docs); + Long docs = year.docs(); + assertTrue(docs == null || docs == 0, "docs: " + docs); } @Test - void passesThroughTheFlagLegendAndNotTheIndexSection() throws Exception { - Map listing = schemaService.listFields(ONE_SHARD); - - assertEquals(java.util.Set.of("fields", "info"), listing.keySet()); - Map key = (Map) ((Map) listing.get("info")).get("key"); - assertEquals("Indexed", key.get("I"), "info.key decodes the schema flag letters: " + key); + void decodesLukeFlagLettersIntoFieldFlags() throws Exception { + Map fields = fields(ONE_SHARD); + + // _default: *_s is string (indexed, stored, docValues), *_i is pint (no multiValued) + FieldListing.IndexedField genre = fields.get("genre_s"); + assertTrue( + genre + .flags() + .containsAll(Set.of(FieldFlag.INDEXED, FieldFlag.STORED, FieldFlag.DOC_VALUES)), + genre::toString); + assertFalse(genre.other().containsKey("schema"), "letters are decoded, not kept: " + genre); + assertFalse(fields.get("year_i").flags().contains(FieldFlag.MULTI_VALUED), "" + fields); + assertTrue(fields.get("year_i").flags().contains(FieldFlag.DOC_VALUES), "" + fields); } @Test void twoShardListingCoversBothShardsOnlyWhereSolrDistributesLuke() throws Exception { - Map> fields = fields(TWO_SHARDS); + Map fields = fields(TWO_SHARDS); // Worked out from the server's version, not from the tool's answer. if (solrDistributesLuke()) { - assertEquals(1L, ((Number) fields.get("only_a_s").get("docs")).longValue(), "" + fields); - assertEquals(1L, ((Number) fields.get("only_b_s").get("docs")).longValue(), "" + fields); + assertEquals(1L, fields.get("only_a_s").docs(), "" + fields); + assertEquals(1L, fields.get("only_b_s").docs(), "" + fields); } else { assertNotEquals( fields.containsKey("only_a_s"), @@ -145,9 +154,8 @@ private static SolrInputDocument doc(String id, Map fields) { return document; } - @SuppressWarnings("unchecked") - private Map> fields(String collection) throws Exception { - return (Map>) schemaService.listFields(collection).get("fields"); + private Map fields(String collection) throws Exception { + return schemaService.listFields(collection).fields(); } /** SOLR-8127 shipped in 9.11 and 10.1; 10.0 does not have it. */ diff --git a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java index bea88cdc..28c738a8 100644 --- a/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java +++ b/src/test/java/org/apache/solr/mcp/server/schema/SchemaServiceTest.java @@ -467,10 +467,10 @@ void viewSchemaPrompt_isReadOnlyAndReferencesGetSchema() { private static final String COLLECTION = "shows"; @Test - void listFields_passesThroughLukeFieldsAndInfoSections() throws Exception { + void listFields_decodesFlagsAndLeavesOutTheInfoAndIndexSections() throws Exception { NamedList genre = new SimpleOrderedMap<>(); genre.add("type", "string"); - genre.add("schema", "I-SD-M---OF-----"); + genre.add("schema", "I-SD-M----OF-----l"); genre.add("dynamicBase", "*_s"); genre.add("docs", 5); NamedList fields = new SimpleOrderedMap<>(); @@ -486,26 +486,72 @@ void listFields_passesThroughLukeFieldsAndInfoSections() throws Exception { response.add("fields", fields); response.add("info", info); when(solrClient.request(any(LukeRequest.class), eq(COLLECTION))).thenReturn(response); + JsonMapper realMapper = JsonMapper.builder().build(); - Map listing = schemaService.listFields(COLLECTION); + FieldListing listing = new SchemaService(solrClient, realMapper).listFields(COLLECTION); + FieldListing.IndexedField field = listing.fields().get("genre_s"); + assertEquals("string", field.type()); assertEquals( - Map.of( - "fields", - Map.of( - "genre_s", - Map.of( - "type", - "string", - "schema", - "I-SD-M---OF-----", - "dynamicBase", - "*_s", - "docs", - 5)), - "info", - Map.of("key", Map.of("I", "Indexed"))), - listing); + Set.of( + FieldFlag.INDEXED, + FieldFlag.STORED, + FieldFlag.DOC_VALUES, + FieldFlag.MULTI_VALUED, + FieldFlag.OMIT_NORMS, + FieldFlag.OMIT_TF, + FieldFlag.SORT_MISSING_LAST), + field.flags()); + assertEquals("*_s", field.dynamicBase()); + assertEquals(5L, field.docs()); + assertEquals(Map.of(), field.other(), "the schema letters are decoded, not kept"); + String json = realMapper.writeValueAsString(listing); + assertEquals( + "{\"fields\":{\"genre_s\":{\"type\":\"string\",\"flags\":[\"INDEXED\",\"STORED\"," + + "\"DOC_VALUES\",\"MULTI_VALUED\",\"OMIT_NORMS\",\"OMIT_TF\",\"SORT_MISSING_LAST\"]," + + "\"dynamicBase\":\"*_s\",\"docs\":5}}}", + json); + } + + @Test + void listFields_keepsADistributedDocCountPastIntegerMax() throws Exception { + // SolrJ's LukeResponse casts docs to Integer; a sum across shards can exceed it. + NamedList title = new SimpleOrderedMap<>(); + title.add("type", "text_general"); + title.add("schema", "ITS---------------"); + title.add("docs", 3_000_000_000L); + NamedList fields = new SimpleOrderedMap<>(); + fields.add("title", title); + NamedList response = new NamedList<>(); + response.add("fields", fields); + when(solrClient.request(any(LukeRequest.class), eq(COLLECTION))).thenReturn(response); + + FieldListing listing = + new SchemaService(solrClient, JsonMapper.builder().build()).listFields(COLLECTION); + + assertEquals(3_000_000_000L, listing.fields().get("title").docs()); + } + + @Test + void listFields_keepsTheLettersWhenOneIsNotAKnownFlag() throws Exception { + // A letter a later Solr version adds must not throw or yield a partial flag set. + NamedList future = new SimpleOrderedMap<>(); + future.add("type", "string"); + future.add("schema", "I-S-----------Z"); + NamedList fields = new SimpleOrderedMap<>(); + fields.add("future_s", future); + NamedList response = new NamedList<>(); + response.add("fields", fields); + when(solrClient.request(any(LukeRequest.class), eq(COLLECTION))).thenReturn(response); + + FieldListing.IndexedField field = + new SchemaService(solrClient, JsonMapper.builder().build()) + .listFields(COLLECTION) + .fields() + .get("future_s"); + + assertEquals(Set.of(), field.flags()); + assertEquals("I-S-----------Z", field.other().get("schema")); } @Test