Repository navigation
feat(mcp): add full_text_search tool (#4862) - #5263
Conversation
FullTextSearch.resolveFullTextIndex validated one snapshot of TypeIndex.getIndexesOnBuckets() while search() iterated a second, freshly allocated one. Extract a private resolveFullTextBuckets helper so validation and iteration share the same array, avoiding a redundant allocation on the query hot path. Also correct the class Javadoc to cover CLASSIC similarity alongside BM25, and add a test pinning the "is not a type index" branch reached when a bucket-level sub-index name is resolved directly.
Adds typeName (+ optional properties) as a second addressing form for the full_text_search MCP tool, with indexName winning when both are supplied, and consolidates every addressing failure into an actionable error listing the database's real full-text index names. Also removes a redundant schema-wide index scan from the success path: the index now validates via the exceptions FullTextSearch.resolveFullTextIndex already throws, paying the cost of enumerating every full-text index only when building an error message.
Eliminates a redundant TypeIndex resolution (and the array allocation inside TypeIndex.getIndexesOnBuckets()) on every successful full_text_search call by threading the resolved TypeIndex from resolveIndex/validateFullTextIndex through to execute() instead of re-resolving it by name. Also passes the caught SchemaException / CommandExecutionException as the cause of the wrapping IllegalArgumentException, reuses an already-materialized index list in the typeName-alone error path instead of walking the schema twice, and adds test coverage for the indexName-wins-over-typeName precedence rule and a stronger assertion on the non-full-text-index rejection message.
Resolve the full-text index exactly once per full_text_search call and pass the limit down to each bucket's cursor, which already bounds its own top-K with a min-heap instead of fully sorting every match. Reject limit < 1 with a clear error instead of a misleading count: 0.
Add a regression test that exercises the previously-untested cross-bucket merge path of the full-text limit push-down (all existing fixtures pin BUCKETS 1), asserting the bounded search returns the same top-k RID sequence as the unbounded search sorted and truncated the same way. Also: normalize limit < 1 to unbounded (-1) in the (TypeIndex, String, int) overload, since limit == 0 previously threw IllegalArgumentException on the BM25 path while silently returning everything on CLASSIC; remove the unused 2-arg search(TypeIndex, String) overload; and correct several comments/javadoc that overstated the min-heap mechanism (CLASSIC sorts and truncates instead), the bucket-array allocation savings, and the concurrently-deleted-record skip parity with unbounded index scans.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 47 |
🟢 Coverage 94.33% diff coverage · -7.72% coverage variation
Metric Results Coverage variation ✅ -7.72% coverage variation Diff coverage ✅ 94.33% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (741c1f7) 139116 104570 75.17% Head commit (0ad8626) 171578 (+32462) 115733 (+11163) 67.45% (-7.72%) Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch:
<coverage of head commit> - <coverage of common ancestor commit>Diff coverage details
Coverable lines Covered lines Diff coverage Pull request (#5263) 141 133 94.33% Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified:
<covered lines added or modified>/<coverable lines added or modified> * 100%
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
There was a problem hiding this comment.
Code Review
This pull request implements the full_text_search MCP tool for ArcadeDB. It extracts the core full-text search logic from SQLFunctionSearchIndex into a new stateless FullTextSearch engine helper, and introduces the server-side FullTextSearchTool registered across both HTTP and stdio transports. The tool supports index addressing by name or type/properties, respects read permissions, and returns ranked results with their similarity scores. Comprehensive unit and integration tests have been added to cover the new functionality. No review comments were provided, and I have no feedback to offer.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
Review: feat(mcp) add full_text_search tool (issue 4862) Reviewed the engine helper, the SQL delegate, the MCP tool, both transport registrations, and the tests. This is a high-quality, well-documented PR, and the candid self-review in the description mostly matches what the code does. Summary: looks good to merge, with a few small observations, none blocking. WHAT IS DONE WELL
MINOR OBSERVATIONS (non-blocking)
CROSS-BUCKET BM25 UNSOUNDNESS Agreed with the framing: this PR neither introduces nor worsens it (SQL ORDER BY score DESC has had identical exposure, and the push-down leaves scores unchanged). The important part is that issue 4861 hybrid_search will fuse these per-bucket scores with vector scores, baking the unsoundness into a harder-to-unwind surface. Filing the separate engine issue and linking it as a blocker on 4861 before that work starts is the right sequencing - please do open it so it does not stay implicit. NOTES
Nice work - the transparency about the deliberate deviations and the surfaced engine issue makes this easy to reason about. Generated with Claude Code |
|
Addressed in 0ad8626. Two of the three observations were real; I verified each against the code rather than assuming, and pushed back on the third. 1. Blank An empty string in the message, naming no cause. For an LLM caller that is close to useless. Now rejected up front with a message that says which argument is wrong and shows a valid form, mirroring the 3. Property-name normalization - confirmed, and more reachable than flagged. This is not only theoretical. A property name containing a space is creatable: CREATE PROPERTY Spaced.`my prop` STRING
CREATE INDEX ON Spaced (`my prop`) FULL_TEXTThe schema derives the index name as Verified the fix is load-bearing rather than trusting it: with the which is precisely the bug. 2. Cross-bucket BM25 issue: agreed on the sequencing, and I will open the engine issue and link it as a blocker on #4861 so it does not stay implicit. Tests after the fixes: engine 201/201, server 81/81 (was 79; +2). No pre-existing test edited. |
Review:
|
|
Engine issue filed as #5267 ("Full-text BM25 is scored per bucket, so cross-bucket relevance ranking is unsound"), and linked as a blocker on #4861 so the fusion strategy there is not settled before this is. It lays out three directions - type-wide corpus statistics, a global re-scoring pass over the merged candidate set, or an explicit best-effort contract - without picking one. Input welcome there rather than here, so this PR stays about #4862. |
Closes #4862. Part of epic #4859 (MCP GraphRAG & Agent-Memory Surface), Wave 1.
What this adds
An MCP
full_text_searchtool, the lexical leg of the epic's retrieval trio (vector_search#4860,hybrid_search#4861, this).Per the epic's governing principle, a new tool needs a justification beyond "
querycan already do it". This one is #1, ergonomic guardrail: the raw form isand a model reliably gets three things wrong there: the index name is a bracket literal auto-derived as
typeName + Arrays.toString(props); the BM25 relevance is only reachable as the context variable$score, which must be explicitly projected; and a miss throws a bareSchemaExceptionwith no recovery hint.Tool contract
database,queryText(required); address the index by eitherindexNameortypeName(+ optionalproperties);limit(default 10,< 1rejected).{indexName, similarity, count, results: [{rid, score, properties}]}, sorted by score descending.allowReads->SecurityException, exactly asQueryTool. Pure-read, so noOperationTypewrite-gating. No new config flag; safe-by-default (enabled=false) is unchanged.Structure. The search logic was extracted from the previously-private
SQLFunctionSearchIndex.performSearchinto a new engine helpercom.arcadedb.index.fulltext.FullTextSearch;performSearchis now a delegate.#4861 hybrid_searchgets the same entry point rather than a second copy of the traversal. The SQL path is unchanged, and no pre-existing test was edited anywhere on this branch - that is the evidence.Deliberately not synthesizing SQL:
queryTextlegitimately contains quotes (phrase queries, apostrophes), so it would have to be a bound parameter, butSEARCH_INDEXis anIndexableSQLFunctionthe planner may consume at plan time and no test in the repo binds its arguments as parameters. Staking the tool on an unproven path whose failure mode is SQL injection wasn't warranted when the programmatic path is exact.Two deliberate deviations from the issue text
1.
bm25Score->score, plus a top-levelsimilarityfield. An ArcadeDB full-text index is not necessarily BM25: indexes persisted before BM25 support load asCLASSIC, andMETADATA {"similarity": "CLASSIC"}pins it explicitly. On those, the value is a term-coordination count. Naming the fieldbm25Scorewould mislabel them, and would silently corrupt score fusion in #4861.similarityis reported fromLSMTreeFullTextIndex.isBM25().2. Index addressing also accepts
typeName+properties. RequiringindexNamealone would have reintroduced the exact footgun the tool exists to remove. Addressing errors now enumerate the database's real full-text index names, mirroring theMCPToolUtils.resolveDatabasehouse pattern, so the model self-corrects in one retry. The argument istypeName, nottype, to avoid colliding with JSON Schema's owntypekeyword.Review findings worth other eyes
A live bug, fixed here. The first cut aborted the entire search if any one hit had been deleted between the index scan and the record dereference, discarding every other valid result. The tool runs outside an explicit transaction, so those are separate read windows. It now skips the dangling hit, matching what index scans already do (
LocalDatabasedocuments this as the expected pattern). No regression test: deterministically producing a dangling posting needs fault injection, andSQLFunctionSearchIndex.searchFromTargetships the identical untested skip today.Top-k is now pushed down. The engine already had a bounded min-heap top-k in
LSMTreeFullTextIndex.buildScoredCursorthat only engages when a limit is supplied; we were passing-1and then re-sorting the full match set in the tool to return 10 rows. The limit is now pushed into each bucket cursor. Soundness: scores are limit-independent and the (score desc, RID asc) order is strict and applied identically per-bucket and on the merge, so the global top-k is contained in the union of the per-bucket top-ks. Guarded by aBUCKETS 4test that asserts (viaRID.getBucketId()) that the strong hits really do concentrate in one bucket, then that the bounded top-k RID sequence equals the unbounded one. SQL keeps passing-1(unbounded) - it uses the result as a boolean predicate over every candidate row, so narrowing it would be a silent regression.ArcadeDB scores BM25 per bucket. Document frequency is bucket-scoped while average document length is type-wide; the engine documents this itself:
So merging hits across buckets and ranking them globally is not strictly sound on the default multi-bucket layout. We hit it live during development: a less relevant document outranked a more relevant one, and the ranking test only became deterministic once the fixture forced
BUCKETS 1.To be clear about scope: this PR does not introduce it. SQL's existing
ORDER BY $score DESChas had the identical exposure all along, and the top-k push-down above neither creates nor worsens it (scores are unchanged). The reviewers were explicit that it is not a blocker for this PR.But it should not stay implicit, because:
hybrid_searchwill fuse these scores with vector scores, which would bake the unsoundness into a second surface where it is far harder to unwind.Suggested resolution, for discussion: file a separate engine issue (options include type-wide corpus statistics, or a global re-scoring pass over the merged candidate set) and link it as a blocker on #4861 before that work starts. Opinions welcome on which fix shape is right - that is why it is called out here rather than buried in a commit message.
Testing
engine: 201/201 green (FullTextSearchTest+ the fullSEARCH_INDEX/FullText*/LSMTreeFullTextIndex*/TypeFullTextIndexBuilderTestsuites, which are the regression net for the extraction).server: 79/79 green (MCP*Test), covering the happy path, ranking, limit rejection, both addressing forms,indexName-wins precedence, and the error paths (unknown index, non-full-text index, ambiguoustypeName, subtypetypeName, no addressing form).Merge-conflict note for the rest of Wave 1
MCPHttpHandler.javaandMCPStdioServer.javaare+4/-0and+3/-0, purely additive, no reordering. #4860 / #4863 / #4864 / #4865 touch the sameTOOLS_LISTblocks, dispatch switches, and thetools.length()assertion inMCPServerPluginTest(now 11), so expect adjacent-line conflicts there and nowhere else.Follow-ups
arcadedb-docsrepo: tool reference, query-syntax table, thesimilarityfield, and a cold-start note (a BM25 index with invalid counters runs a full type scan on its first query; remedy isREBUILD INDEX <name> WITH statsOnly = true). Docs should say "BM25 full-text index", never "Lucene index".🤖 Generated with Claude Code