Skip to content

feat(mcp): add full_text_search tool (#4862) - #5263

Merged
robfrank merged 11 commits into
mainfrom
feat/4862-mcp-full-text-search
Jul 14, 2026
Merged

robfrank merged 11 commits into
mainfrom
feat/4862-mcp-full-text-search

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #4862. Part of epic #4859 (MCP GraphRAG & Agent-Memory Surface), Wave 1.

What this adds

An MCP full_text_search tool, 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 "query can already do it". This one is #1, ergonomic guardrail: the raw form is

SELECT title, $score FROM Article WHERE SEARCH_INDEX('Article[content]', 'java') = true ORDER BY $score DESC

and 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 bare SchemaException with no recovery hint.

Tool contract

  • Input: database, queryText (required); address the index by either indexName or typeName (+ optional properties); limit (default 10, < 1 rejected).
  • Output: {indexName, similarity, count, results: [{rid, score, properties}]}, sorted by score descending.
  • Gated on allowReads -> SecurityException, exactly as QueryTool. Pure-read, so no OperationType write-gating. No new config flag; safe-by-default (enabled=false) is unchanged.
  • Registered in both transports. Tool count 10 -> 11.

Structure. The search logic was extracted from the previously-private SQLFunctionSearchIndex.performSearch into a new engine helper com.arcadedb.index.fulltext.FullTextSearch; performSearch is now a delegate. #4861 hybrid_search gets 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: queryText legitimately contains quotes (phrase queries, apostrophes), so it would have to be a bound parameter, but SEARCH_INDEX is an IndexableSQLFunction the 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-level similarity field. An ArcadeDB full-text index is not necessarily BM25: indexes persisted before BM25 support load as CLASSIC, and METADATA {"similarity": "CLASSIC"} pins it explicitly. On those, the value is a term-coordination count. Naming the field bm25Score would mislabel them, and would silently corrupt score fusion in #4861. similarity is reported from LSMTreeFullTextIndex.isBM25().

2. Index addressing also accepts typeName + properties. Requiring indexName alone would have reintroduced the exact footgun the tool exists to remove. Addressing errors now enumerate the database's real full-text index names, mirroring the MCPToolUtils.resolveDatabase house pattern, so the model self-corrects in one retry. The argument is typeName, not type, to avoid colliding with JSON Schema's own type keyword.

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 (LocalDatabase documents this as the expected pattern). No regression test: deterministically producing a dangling posting needs fault injection, and SQLFunctionSearchIndex.searchFromTarget ships the identical untested skip today.

Top-k is now pushed down. The engine already had a bounded min-heap top-k in LSMTreeFullTextIndex.buildScoredCursor that only engages when a limit is supplied; we were passing -1 and 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 a BUCKETS 4 test that asserts (via RID.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.

⚠️ Pre-existing engine issue this surfaced - needs a decision

ArcadeDB scores BM25 per bucket. Document frequency is bucket-scoped while average document length is type-wide; the engine documents this itself:

"note": "statistics are per bucket (BM25 is scored per bucket); totalDocs is this bucket's document count"
LSMTreeFullTextIndex.java:547

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 DESC has 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:

  • this tool's headline contract is "records ranked by relevance", and that is only strictly true on single-bucket types;
  • MCP: add hybrid_search tool #4861 hybrid_search will 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 full SEARCH_INDEX / FullText* / LSMTreeFullTextIndex* / TypeFullTextIndexBuilderTest suites, 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, ambiguous typeName, subtype typeName, no addressing form).
  • No pre-existing test file was edited.

Merge-conflict note for the rest of Wave 1

MCPHttpHandler.java and MCPStdioServer.java are +4/-0 and +3/-0, purely additive, no reordering. #4860 / #4863 / #4864 / #4865 touch the same TOOLS_LIST blocks, dispatch switches, and the tools.length() assertion in MCPServerPluginTest (now 11), so expect adjacent-line conflicts there and nowhere else.

Follow-ups

  • Docs live in the out-of-tree arcadedb-docs repo: tool reference, query-syntax table, the similarity field, and a cold-start note (a BM25 index with invalid counters runs a full type scan on its first query; remedy is REBUILD INDEX <name> WITH statsOnly = true). Docs should say "BM25 full-text index", never "Lucene index".
  • The cross-bucket BM25 engine issue above.

🤖 Generated with Claude Code

robfrank added 10 commits July 13, 2026 16:51
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.
@mergify

mergify Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 47 complexity

Metric Results
Complexity 47

View in Codacy

🟢 Coverage 94.33% diff coverage · -7.72% coverage variation

Metric Results
Coverage variation ✅ -7.72% coverage variation
Diff coverage ✅ 94.33% diff coverage

View coverage diff in Codacy

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@claude

claude Bot commented Jul 13, 2026

Copy link
Copy Markdown

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

  • Extraction is clean and behavior-preserving. SQLFunctionSearchIndex.performSearch collapses to a one-line delegate over FullTextSearch.search(database, indexName, queryText), keeping the -1/unbounded contract the SQL boolean-predicate path relies on. Existing full-text suites stay unedited as the regression net.
  • Top-k push-down is actually sound. Checked the tie-break claim end to end: the engine bounded min-heap in LSMTreeFullTextIndex.buildScoredCursor uses (Float.compare(score) desc, RID.compareTo asc) and the tool merge sort uses comparingByValue().reversed().thenComparing(getKey) - the same total order, so per-bucket truncation to limit cannot drop an entry belonging in the global top-k, even at tie boundaries.
  • Security parity with QueryTool. Gated on allowReads, and MCPToolUtils.resolveDatabase enforces user.canAccessToDatabase(...) (raises SecurityException), so no DB-level authorization gap. Both transports wrap execute in the same SecurityException / generic Exception to toolError handling, so a thrown IllegalArgumentException cannot crash the stdio loop.
  • Ergonomics. typeName+properties addressing, indexName-wins precedence, and the describeAvailable(...) hints that enumerate real index names are exactly the footgun-removal the tool exists for. Using typeName rather than type to dodge the JSON Schema keyword collision is a nice touch.
  • Test coverage is thorough. Engine FullTextSearchTest covers unbounded/bounded/BUCKETS-4 top-k equivalence, BM25/CLASSIC similarity, and exception paths; server MCPServerPluginTest covers both addressing forms, precedence, limit rejection, reads-disabled denial, ambiguous/subtype/unknown/non-full-text errors, and the tool-count 10 to 11 bump in both transports.

MINOR OBSERVATIONS (non-blocking)

  1. Empty queryText is not validated. args.getString(queryText) accepts an empty string, which flows straight into FullTextQueryExecutor.search. Worth confirming the parser returns empty results rather than throwing an opaque error; a one-line isBlank() guard mirroring the limit-less-than-1 rejection would give a friendlier message.
  2. getSimilarity re-walks the bucket array a third time (after resolveFullTextIndex and search). getIndexesOnBuckets() is cheap, so negligible - noting for completeness.
  3. Property-name normalization edge case. resolveIndex joins property strings verbatim while the engine derives via Arrays.toString(props).replace(space, empty). Matches for normal identifiers; a property name containing a space would diverge. Same latent engine limitation, not realistic for schema names - just flagging.

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

  • The two docs/superpowers plans+specs files (~1050 lines) are consistent with the established convention in that directory (66 files already tracked), so no objection.
  • I did not run the build/test suite; the PR reports engine 201/201 and server 79/79 green, and no pre-existing test file was edited (confirmed from the diff).

Nice work - the transparency about the deliberate deviations and the surfaced engine issue makes this easy to reason about.

Generated with Claude Code

@robfrank

Copy link
Copy Markdown
Collaborator Author

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 queryText - confirmed and fixed. I probed it rather than reason about it. An empty or whitespace-only query does not return empty results; it throws:

IndexException: Invalid search query:

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 limit < 1 guard. Test fullTextSearchRejectsBlankQueryText covers "" and " ", and asserts the opaque Invalid search query text is not what comes back.

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_TEXT

The schema derives the index name as typeName + Arrays.toString(props) with spaces stripped from the whole result (LocalDocumentType.java:1126), so that registers as Spaced[myprop]. The tool was joining property names verbatim and deriving Spaced[my prop], which can never match - the caller got "does not exist" for an index that plainly exists. Fixed by stripping spaces from the derived name, exactly as the schema does.

Verified the fix is load-bearing rather than trusting it: with the .replace(" ", "") reverted, the new test fullTextSearchDerivesIndexNameWithSpacesStripped fails with

Full-text index 'Spaced[my prop]' does not exist.
Available full-text indexes in 'graph': [..., Spaced[myprop]]

which is precisely the bug.

2. getSimilarity third bucket-array walk - not changing this, and I want the reasoning on the record. It is one array allocation per query, not per row (the redundant name lookup was already removed in c90c200). Eliminating it would mean reshaping a public engine signature so the search path returns the similarity alongside the result map. Restructuring public engine API to save one short-lived array per query is a bad trade, and it would widen this PR's engine surface for no measurable gain. Happy to be overruled if you disagree, but I would rather not churn the API for it.

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.

@claude

claude Bot commented Jul 13, 2026

Copy link
Copy Markdown

Review: full_text_search MCP tool (#5263)

Reviewed the engine helper, the MCP tool, both transport registrations, and the tests. This is a well-engineered, unusually well-documented change. The PR description already surfaces the main design trade-offs honestly, so I focused on verifying the claims and looking for anything unstated. Summary: looks good to merge; a few minor notes and one confirmation below.

What's good

  • Clean extraction. Pulling performSearch into a stateless FullTextSearch helper and leaving SQLFunctionSearchIndex.performSearch as a one-line delegate keeps the SQL path behavior-compatible, and the existing full-text suites act as the regression net exactly as claimed. No pre-existing test was edited.
  • Security gating mirrors QueryTool (allowReads -> SecurityException), pure-read so no write-gating, enabled=false default unchanged. Consistent with the house pattern.
  • Ergonomic error surface. The typeName/properties addressing plus describeAvailable() enumerating real index names is the right call - it removes the exact footgun (typeName + Arrays.toString(props)) the tool exists to hide, and the errors are self-correcting in one retry. The space-stripping in the derived name (FullTextSearchTool.java:186) matching the schema's own derivation is a nice catch.
  • Dangling-hit skip (FullTextSearchTool.java:136-141) is correct: outside an explicit transaction the scan and the lookupByRID are separate read windows, and skipping matches what index scans already do.
  • Top-k push-down soundness is genuine. I verified buildScoredCursor (LSMTreeFullTextIndex.java:459) only allocates the bounded min-heap when limit < size, so a large limit degrades to a full sort rather than over-allocating a PriorityQueue - no OOM footgun from an unbounded limit value.
  • Test coverage is excellent on both sides: engine covers the bounded/unbounded overloads, zero/negative-limit normalization, the cross-bucket merge (with a BUCKETS 4 fixture that asserts the actual bucket distribution rather than assuming it), similarity reporting, and all resolve error branches; server covers both addressing forms, indexName-wins precedence, blank query, limit rejection, reads-disabled, and every error path. Tool-count assertions updated to 11 in both MCPServerPluginTest and MCPStdioServerTest.

Confirming the flagged engine issue

The per-bucket BM25 scoping call-out is real and correctly scoped: this PR doesn't introduce it (SQL's ORDER BY $score DESC has the same exposure) and the push-down doesn't worsen it (scores are unchanged). I agree it should be tracked as an explicit blocker on #4861 hybrid_search before that work starts - fusing an already-unsound lexical score with vector scores bakes the unsoundness into a second, harder-to-unwind surface. Good that it's called out in the open rather than buried.

Minor notes (non-blocking)

  1. Redundant bucket-array materialization per query. getIndexesOnBuckets() is called three times per successful call: once in resolveFullTextIndex validation, once in search, once in getSimilarity. Each allocates a fresh array. Not a hot loop (once per query, not per row), so low priority, but since the commit history already chased these allocations, getSimilarity could be folded into the search traversal or read off the same snapshot if you want to close it out.
  2. Required-arg error message. args.getString("queryText") / getString("database") throw a raw JSONException if the key is absent (vs. the friendly IllegalArgumentException you raise for blank/limit). This matches QueryTool's existing style, so it's consistent - just noting the asymmetry between "absent" (cryptic) and "blank" (friendly) for a required field. Fine to leave as-is for parity.
  3. count reflects post-dangling-skip returned results, which is documented in-code - worth ensuring the out-of-tree docs say the same so callers don't treat count as a total-matches figure.

Style / conventions

Adheres to CLAUDE.md: final throughout, imported names (no FQNs), single-statement if without braces, JSONObject/JSONArray with default-valued getters, no System.out, source authored by the contributor (no Claude authorship in the code).

Nice work - the self-critical commit trail (single-snapshot fix, limit normalization, ranking-seed rationale) makes this easy to trust.

Automated review; I did not run the build locally - relying on the stated 201/201 engine + 79/79 server green runs.

@robfrank

Copy link
Copy Markdown
Collaborator Author

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.

@robfrank
robfrank merged commit 00b9d21 into main Jul 14, 2026
25 of 29 checks passed
@robfrank
robfrank deleted the feat/4862-mcp-full-text-search branch July 14, 2026 11:19
robfrank added a commit that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP: add full_text_search tool

1 participant