Repository navigation
feat(mcp): add strategy parameter to the search tool - #462
Conversation
Semantic search picks multi-hop whenever the provider can rerank, and the VoyageAI provider always can (rerank-2.5 is the default model). Multi-hop reranks the initial pool, then expands and reranks again until its time limit (5 s by default). MCP callers that rerank results themselves had no way to ask for the plain vector search the CLI exposes as --single-hop. strategy: 'auto' (default, unchanged), 'single_hop', or 'multi_hop', passed through as force_strategy.
|
@fstrasz Hi |
ofriw
left a comment
There was a problem hiding this comment.
PR #462 review: strategy parameter for the MCP search tool
PR: #462
Head: c841175
Scope: chunkhound/mcp_server/tools.py, tests/test_semantic_provider_detection.py
Verdict: Request changes
The new strategy argument reaches SearchService for plain semantic search. Four points need work: the auto value adds no behavior, commit-scoped diff search drops the value without a message, an unknown value silently uses the default, and the test does not cover the full contract.
Triage
| ID | Finding | Severity | Owner |
|---|---|---|---|
| 1 | auto duplicates the service default |
High | PR author |
| 2 | strategy is silently ignored on the diff path |
High | PR author |
| 3 | Unknown strategy values are not rejected |
Medium | PR author |
| 4 | Test and docstring do not state the full contract | Low | PR author |
1. auto duplicates the service default
Where
chunkhound/mcp_server/tools.py:683adds"auto"to theLiteral.chunkhound/mcp_server/tools.py:750maps"auto"toforce_strategy=None.chunkhound/services/search_service.py:110already treatsNoneas "select by provider capability".
Observed
force_strategy=None selects multi-hop when the provider can rerank, else single-hop. "auto" is a second name for that same state. A caller that omits the argument already gets this behavior. The PR thus adds three named values for two behaviors, and one of the names means "use the default".
Hanan Kavitz raised this on the PR and asked to default to multi_hop (comment). His premise holds for reranking providers, such as VoyageAI. Other providers get single-hop today.
Risk
The dead value spreads. Each check, doc line, schema, and test must carry auto, and callers must learn a value that changes nothing. It also blocks the diff guard in finding 2, which needs to tell "caller asked for multi-hop" from "caller used the default".
Change
Remove "auto" from the Literal and the docstring. Keep the argument optional, so omission selects by provider capability:
strategy: Literal["single_hop", "multi_hop"] | None = Nonesearch_impl then passes force_strategy=strategy and needs no auto branch. For reranking providers the effective default is multi-hop, which matches today and satisfies Hanan's intent.
If the team wants the literal default multi_hop instead, the fallback at chunkhound/services/search_service.py:124 must drop to debug. Otherwise every search on a non-reranking provider logs "falling back to single-hop".
Done when
- The schema exposes two values.
- An omitted argument forwards
None. - No
autoreference remains in the code, docstring, or tests. - A non-reranking provider runs a search with no warning.
2. strategy does nothing when the search uses a git diff
Where
chunkhound/mcp_server/tools.py:750forwardsforce_strategy.chunkhound/services/diff_aware_search_service.py:227acceptsforce_strategy.chunkhound/services/diff_aware_search_service.py:249calls_search_diff, which has no such parameter (line 140).chunkhound/services/diff_aware_search_service.py:265uses the same call for the diff half ofboth.
Observed
vector_source |
Effect of strategy |
|---|---|
diff (default) |
None. _search_diff ignores it. No warning. |
both |
Half. The DB path obeys it, the diff path does not. |
db |
Full. No diff service is created. |
The CLI already rejects this pair at chunkhound/api/cli/commands/search.py:82. The MCP tool has no equivalent check, so a client can request strategy="multi_hop" with commit_range and get single-hop results with no signal.
Risk
Callers cannot trust the parameter. A caller that depends on multi_hop reranking for a commit review gets results that do not match the request. The response looks correct, so the caller cannot detect the loss.
Change
Raise an error in search_impl when strategy is not None, a commit argument is present, and vector_source is not db. Match the CLI wording. Put the check after _resolve_commit_range, next to the existing parameter checks.
This check depends on the None default from finding 1. If the default becomes the literal multi_hop, every commit-scoped search would raise, and the only remaining option is to document the mismatch. Do not take that path for a new parameter.
Done when
search_impl(..., commit_range="HEAD~5..HEAD", strategy="multi_hop")raisesValueError.- The message names
strategyand the commit arguments. - An omitted
strategywith commit arguments still runs. vector_source="db"with a commit argument still runs.- A test covers the rejected pair and the accepted
dbcase.
3. Unknown strategy values are silently accepted
Where: chunkhound/mcp_server/tools.py:683
Literal is a type hint only. Python does not check it at runtime. The MCP dispatcher (chunkhound/mcp_server/tools.py:1106) passes request keys to the tool without schema validation, so the JSON Schema enum is advisory. A direct call with strategy="foo" reaches line 750 as force_strategy="foo". SearchService (chunkhound/services/search_service.py:110) compares against the two known values and falls through to the capability-based default. The caller gets a valid answer for a strategy that does not exist.
Risk
Typos and stale client values change search cost and ranking with no error. This hides integration defects and makes support reports hard to read.
Change
Validate at parse time in search_impl, next to the type check, before any service work:
if strategy not in (None, "single_hop", "multi_hop"):
raise ValueError(
f"Invalid search strategy: '{strategy}'. "
"Must be 'single_hop' or 'multi_hop'."
)Keep the Literal annotation for the schema.
Done when
search_impl(..., strategy="foo")raisesValueError.- The error lists the valid values.
- A test covers the rejection.
4. Test and docstring do not state the full contract
Where
tests/test_semantic_provider_detection.py:69chunkhound/mcp_server/tools.py:699
Observed
The test proves the schema enum, single_hop forwarding, and auto → None. It does not prove multi_hop forwarding or that type="regex" ignores strategy. Both are part of the documented contract, and neither path raises on regression.
The docstring says multi_hop "requires a reranking provider". The service does not raise. It logs a warning and falls back to single-hop (chunkhound/services/search_service.py:124). A caller reads "requires" as a hard failure.
Risk
A refactor can drop multi_hop forwarding or start applying strategy to regex search, and the suite stays green. The docstring sets a false expectation about failure behavior.
Change
- Update the schema assertion to the two values from finding 1.
- Assert forwarding for
single_hopandmulti_hop. - Assert that an omitted
strategyforwardsNone. - Assert that
type="regex"reaches the regex path with noforce_strategy. - Reword the docstring: "If the provider cannot rerank, the service logs a warning and uses single-hop."
Done when
- The test asserts both forwarded values and the omitted case.
- The test asserts that regex search ignores
strategy. - The docstring states the fallback, not a requirement.
Review follow-up for chunkhound#462. - Drop "auto". strategy is Literal["single_hop", "multi_hop"] | None and defaults to None, which is forwarded as force_strategy=None, so omitting it keeps choosing by provider capability (multi-hop when the provider can rerank) and a non-reranking provider searches with no warning. - A semantic search that sets strategy together with commit_range, commit_hash or last_n_commits raises ValueError unless vector_source="db". The diff path has no strategies, so the value used to be dropped silently. Same rule as the CLI's --single-hop/--multi-hop. - An unknown strategy raises ValueError naming the valid values, before any service work. The Literal stays for the schema. - Tests cover the two-value schema, forwarding of both values and of an omitted one, regex ignoring strategy, the unknown value, each commit argument with vector_source diff and both, the db exception, and the no-warning default. The docstring states the single-hop fallback instead of "requires". Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, both. All four findings are fixed in 3fafc4b, on top of the reviewed head. @HananKavitzAmat: agreed on the intent. I went with the review's version of it:
I checked each test by undoing its fix: no validation, no diff guard, a literal Checks, on Windows: every test that references |
Search queries go through provider.embed_query once chunkhound#469 lands. The test's Mock provider only had embed as an AsyncMock, so on a tree with both PRs the query embedding raised and the test failed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up for chunkhound#462. - Drop "auto". strategy is Literal["single_hop", "multi_hop"] | None and defaults to None, which is forwarded as force_strategy=None, so omitting it keeps choosing by provider capability (multi-hop when the provider can rerank) and a non-reranking provider searches with no warning. - A semantic search that sets strategy together with commit_range, commit_hash or last_n_commits raises ValueError unless vector_source="db". The diff path has no strategies, so the value used to be dropped silently. Same rule as the CLI's --single-hop/--multi-hop. - An unknown strategy raises ValueError naming the valid values, before any service work. The Literal stays for the schema. - Tests cover the two-value schema, forwarding of both values and of an omitted one, regex ignoring strategy, the unknown value, each commit argument with vector_source diff and both, the db exception, and the no-warning default. The docstring states the single-hop fallback instead of "requires". Co-Authored-By: Claude Opus 5.5 <[email protected]>
HananKavitzAmat
left a comment
There was a problem hiding this comment.
Summary: The PR fixes all four of ofriw's findings and the new tests cover them. The only leftovers are small, non-blocking points.
Strengths
- All four findings are fixed as specified:
- auto is gone. The signature is Literal["single_hop", "multi_hop"] | None = None and the value is forwarded as force_strategy=strategy.
- Unknown values raise a ValueError that lists the valid ones.
- Combining strategy with a commit argument and a non-db vector_source now raises. The message matches the CLI rule at chunkhound/api/cli/commands/search.py:89.
- The docstring now says the service "logs a warning and uses single-hop" instead of "requires".
- The schema generator at tools.py:152-175 unwraps the optional Literal into an enum and does not mark it required. The two-value schema test is consistent with that code.
- The tests assert contracts, as the repo's TESTING_PHILOSOPHY asks.
- They check forwarding, the omitted default, regex ignoring strategy, rejection, and the db exception.
- Fakes are used only at the provider and database boundary.
- The no-warning test uses a real SearchService and a loguru sink.
Issues
- Critical: none.
- Major: none.
- Minor:
a. tests/test_semantic_provider_detection.py (the no-warning test) says embed_query is used "once #469 lands". embed_query does not exist in chunkhound/ on main, so the comment points at unmerged work and the mock does nothing today. Drop the embed_query mock and comment, or confirm #469 is merged first.
b. tools.py:473-485 (SEARCH_DESCRIPTION) lists the git-history parameters but does not mention strategy. The Args docstring feeds the JSON schema, but this prose is what the LLM reads. One bullet, plus a note that strategy is rejected with commit input unless vector_source='db', would help callers avoid the new ValueError. The same text is duplicated at tools.py:525 and in the no-research variant.
c. tests/test_semantic_provider_detection.py:~66: a stray extra blank line, and the first _strategy_fixture is missing a blank line before the def. This is PEP 8 and ruff-format nitpicking; run ruff format on the test file.
d. The strategy guard sits before the semantic branch and re-checks type == "semantic". This works, but folding it into the existing diff-injection condition at tools.py:727 would put the commit logic in one place. Optional.
Reusability
- The guard duplicates the CLI's --single-hop/--multi-hop versus commit-args rule from search.py:82-89. It is only two call sites, so a shared helper is not warranted now. A third entry point, such as the research tool, would justify extracting one.
- strategy is not wired into the second tool at tools.py:798. That tool has commit arguments but no semantic search strategy, so leaving it out is correct.
Decision: APPROVE. Minor item 1 (the stale #469 reference) is worth fixing before merge. The rest can be follow-ups. The PR is still marked "changes requested" from ofriw's review, so the merge needs ofriw to re-review and clear that.
|
@ofriw, when you have a moment, could you re-review? All four findings from your 11-02 review were addressed the same day, in 3fafc4b. My comment above lists each fix. 1750650, the current head, adds only an awaitable |
ofriw
left a comment
There was a problem hiding this comment.
Note: This review was generated by an AI agent. If you'd like to talk with other humans, drop by our Discord!
PR #462 — MCP search strategy Review Report
PR: chunkhound/chunkhound#462 — feat(mcp): add strategy parameter to the search tool
Snapshot: head 1750650e against 11357f88. Line numbers refer to this snapshot.
Scope: 2 files, +222 / −0.
Decision: Approve with changes. The forwarding logic and the guard are correct, and the new tests pass. The findings below are documentation and hygiene gaps. F1–F3 are required before merge. F4–F5 are cleanup.
Priority key: P1 = required before merge. P2 = cleanup.
Findings at a glance
| ID | Priority | Finding | Suggested owner |
|---|---|---|---|
| F1 | P1 | Tool prose never names strategy |
MCP search tool |
| F2 | P1 | Docstring gives a wrong regex rule and omits two raises | MCP search tool |
| F3 | P1 | Guard comment describes the CLI rule, not the MCP rule | MCP search tool |
| F4 | P2 | Test mocks a method that this revision never calls | Tests |
| F5 | P2 | Four blank lines at the new fixture seam | Tests |
P1 — Required before merge
F1 — Tool prose never names strategy
Locations: chunkhound/mcp_server/tools.py:468 (SEARCH_DESCRIPTION), chunkhound/mcp_server/tools.py:490 (SEARCH_DESCRIPTION_NO_RESEARCH)
Current: strategy appears only in the generated parameter schema. It comes from the Args docstring line at tools.py:699. TOOL_REGISTRY["search"].description contains no strategy. A client model that reads only the description cannot find the parameter, the enum values, or the rule that blocks commit inputs.
Required: Add one bullet to SEARCH_DESCRIPTION, in the git-history block:
- strategy: Optional semantic strategy. Omit it to let the provider choose.
single_hopruns one vector search with no expansion or reranking — fast, for callers that rerank results themselves.multi_hopforces expansion with reranking. A valid value does nothing for type='regex'. Invalid values raise. Cannot be combined with commit_range, commit_hash, or last_n_commits unless vector_source='db'.vector_source='both'is also rejected.
Add a shorter bullet to SEARCH_DESCRIPTION_NO_RESEARCH. That variant drops the git-history block, so keep only the strategy meaning and the regex rule. The MCP server serves this variant when no LLM manager is configured (chunkhound/mcp_server/base.py:1353-1358), and the parameter still applies.
Impact: The PR exists to let callers skip multi-hop. Today a caller finds that option only by reading the schema, so the main feature stays unused. A caller that adds strategy to a commit-scoped search learns the conflict from a ValueError, not from the tool text.
F2 — Docstring gives a wrong regex rule and omits two raises
Locations: chunkhound/mcp_server/tools.py:699, chunkhound/mcp_server/tools.py:703-706
Current: The docstring says Ignored for type='regex'. The check at tools.py:712-717 runs before the type branch, so an invalid value raises for regex too. Only a valid value is ignored. The Raises section lists the invalid-type and missing-provider errors only. It omits the invalid-strategy error and the strategy-with-commit-input error.
Required: State the real regex rule: a valid value has no effect, and an invalid value raises. Add both ValueError cases to Raises. Keep the text short, because the generator copies it into the schema.
Impact: The docstring is the source of the schema description. A wrong rule and an incomplete raise list hide real failure modes from every client.
F3 — Guard comment describes the CLI rule, not the MCP rule
Locations: chunkhound/mcp_server/tools.py:724-733, chunkhound/api/cli/commands/search.py:82-89
Current: The comment claims the guard is the same rule as the CLI's --single-hop/--multi-hop. It is not. The CLI rejects a forced strategy with any commit input, without exception. The MCP guard also rejects vector_source='both', and it allows vector_source='db'.
Required: Replace the comment with the actual rule:
- The diff path has no strategy. It cannot honor one.
vector_source='db'skips the diff path, so the strategy applies and the guard steps aside.vector_source='both'runs both halves. The DB half honors the strategy and the diff half cannot. The guard refuses that partial application instead of applying the strategy to one half only. The same reason applies tovector_source='diff'.
Impact: A maintainer who trusts the comment may align the MCP guard with the CLI. That change breaks the supported vector_source='db' combination and the test at tests/test_semantic_provider_detection.py:209-212.
P2 — Cleanup
F4 — Test mocks a method that this revision never calls
Locations: tests/test_semantic_provider_detection.py:244-247
Current: The no-warning test sets provider.embed_query and adds a comment about PR #469. embed_query has no call site in chunkhound/ at head 1750650e. PR #469 is open. The mock therefore tests nothing, and the comment names work that is not in this branch.
Required: Delete the three lines (comment, attribute, and the blank line that separates them). Verified: all 16 tests in the file pass after the removal.
Impact: Dead setup and a reference to unmerged work slow the next reader. If #469 lands, its author must re-check this test against the merged code, not against a comment.
F5 — Four blank lines at the new fixture seam
Locations: tests/test_semantic_provider_detection.py:64-67
Current: The patch appends three blank lines after an existing one, which leaves four blank lines before _strategy_fixture. ruff format keeps two.
Required: Collapse the seam to two blank lines.
Impact: Local noise only. CI does not run ruff format (ci.yml has no ruff step, and make lint runs ruff check only). Note that ruff format --check fails on this file before and after the PR, because of pre-existing backslash continuations at lines 36 and 61-63. A full-file format pass would fix those lines too. Decide that separately, since it adds unrelated diff.
Name `strategy` in both search tool descriptions, state the real regex rule (a valid value has no effect, an invalid one raises), list every ValueError in the docstring, and replace the guard comment with the MCP rule, which differs from the CLI's. Drop the embed_query mock that nothing on this branch calls, and collapse the blank-line seam. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@ofriw thanks. All five findings are addressed in 6494576.
Checks: the 16 tests in |
Brings in the 36 commits merged to main since this branch was last updated, including chunkhound#534's rust-checks fix. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two tests mocked interfaces that main has since changed. _inject_diff_service now returns the services alone (chunkhound#407), so the commit-diff test's mock returns services instead of a (services, None) tuple. Semantic search now embeds the query with embed_query (chunkhound#469), so the no-warning test's provider mocks embed_query instead of embed. Both assertions are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged main into this branch. Two tests in
🤖 Generated with Claude Code, reviewed by FStrasz |
|
looks good |
All the issues raised by you were handled
strasz/pinned now carries upstream main (23547a3), including chunkhound#462's MCP strategy contract. One conflict, in chunkhound/mcp_server/tools.py: the search_impl docstring and the commit-input guard comment. Resolved to keep chunkhound#462's rules (a valid strategy has no effect for type='regex', an invalid one raises; vector_source='both' is refused like 'diff') with this branch's single_hop_rerank default and value. chunkhound#462's two tool descriptions now name single_hop_rerank and the provider-chosen default. Built without a checkout (merge-tree plus a temporary index) because a live ChunkHound daemon watches this worktree. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Problem
SearchService.search_semanticpicks multi-hop whenever the embedding provider supports reranking. The VoyageAI provider always does:rerank_modeldefaults torerank-2.5, and config cannot set it to null. As a result, every MCPsearchwithtype="semantic"on a Voyage index runs multi-hop:multi_hop_time_limit, whose default is 5 s and minimum is 1 s.The CLI can opt out with
--single-hop, but the MCP tool has no equivalent. MCP clients that rerank results themselves therefore pay for ChunkHound's expansion and reranking anyway.Measured on a ~12k-chunk TypeScript repo (voyage-code-4, warm MCP server):
search, auto (multi-hop)search,strategy="single_hop", page_size 90, then client-side rerankWith the client-side rerank, the results stayed relevant on the probe queries we ran.
Change
Add an optional
strategyparameter to the MCPsearchtool:"auto"(the default, so existing callers are unchanged),"single_hop"or"multi_hop". It is passed through tosearch_semanticas the existingforce_strategy, which the CLI already uses.type="regex"ignores it.Tests
tests/test_semantic_provider_detection.py::test_semantic_search_strategy_reaches_service_and_schemachecks that:"single_hop"reaches the service asforce_strategy="single_hop";"auto"reaches it asNone.I confirmed the test fails when the forwarding is removed.
Related: #408 (multi-hop pagination totals vary between identical queries).
strategy="single_hop"gives MCP callers a deterministic path: one vector search, no expansion. It does not fix the multi-hop race itself.