Repository navigation
mcp: token-budgeted responses — max_tokens on every search tool (#1058) - #1067
Merged
Merged
Conversation
Motivation ========== The five MCP search tools are thin proxies: they returned whatever the engi 8000 ne sent, so an agent that asked for 50 hits got all 50 verbatim, context cost unknown and unbounded. Issue #1058 (plan item 5 of 10 from discussion #1054) asks for a max_tokens budget on every search tool with one named tokenizer, overlapping file:line passages deduped, over-budget hits as locators only, and the never-exceed rule enforced by test — not claimed. Precedent in-tree: xerj_code_search's char-level cap (the `full` argument, max chars per passage, default 800, at engine/crates/xerj-mcp/src/lib.rs:849 and :1460 in the pre-change tree) and the _passage projection default (:1124). This generalises that cap from per-passage chars to a whole-response token budget across all five search tools. Design ====== * ONE tokenizer, cited: XERJ's StandardTokenizer — UAX #29 word boundaries via unicode_words() (engine/crates/xerj-fts/src/analyzer.rs, StandardTokenizer::tokenize), the same word split the engine's analyzer uses for BM25. xerj-mcp depends on unicode-segmentation directly (same crate, same call) instead of pulling the whole FTS stack into a thin proxy; the count is identical by construction. The choice is stated in the shared argument description, including the honest scope: UAX #29 words under-count model-context subwords (snake_case is ONE token here); the budget is enforced in these tokens, not BPE pieces. * Enforcement is proxy-side on the RESPONSE; the engine never sees max_tokens (builders copy only their known keys — pinned by test), so request bodies are bit-identical with and without a budget. * Both response surfaces budget the same way: (1) hits resolving to a file:line span that OVERLAPS a higher-ranked shown passage are deduped entirely; (2) hits are admitted greedily in rank order while they fit; (3) the first over-budget hits become LOCATOR-ONLY (file:line, index/id — the citation, never the passage); (4) what cannot fit even as a locator is counted dropped. A _token_budget accounting block (JSON surface) / [token budget …] line (text surface) reports kept, locator-only, deduped, dropped, and tokens_used. * Never-exceed is by construction: a 32-token note reserve is subtracted before any content is admitted, every assembly path re-checks, and shapes the budgeter was not built for (non-JSON bodies, aggregation-only responses, budgets too small for the envelope) fall back to a word-boundary truncation with a visible marker. Errors are never budgeted — a refusal the agent cannot read end-to-end is worse than a long response. * Nothing binding (budget not reached, nothing to dedup) returns the engine text byte-identical: existing callers see zero change. * Present-but-mistyped or below the floor (32) is a builder error, never a silent drop — the crate's opt_typed policy; below the floor not even the envelope fits, so the tool refuses rather than lie. What changed ============ * engine/crates/xerj-mcp/src/token_budget.rs (NEW): count_tokens, truncate_to_budget, opt_max_tokens, budget_json_response (the four _search-proxying tools) and budget_code_text (xerj_code_search's rendered text), with span extraction mirroring xccode::passage::provenance's field order plus the engine's _passage block (ordinal = zero-based start line). * engine/crates/xerj-mcp/src/lib.rs: mod token_budget; shared max_tokens_arg_schema() on all five search tools (pointer sentence in each tool description); call_tool parses the budget for the four JSON search tools and refuses bad values before any request; engine_request takes Option<budget> and budgets successful responses; run_code_search parses it itself and budgets successful rendered text. * engine/crates/xerj-mcp/Cargo.toml + engine/Cargo.lock: unicode- segmentation = "1" (already in the lock via xerj-fts). * landing/docs/agents/schemas/mcp-tools.json: regenerated from the real binary via scripts/mcp-schema-check.sh --write (the documented generator); published_schema_drift stays green. Tests (all scoped cargo test --release -p xerj-mcp: 54 lib + 4 drift, 0 failed; cargo fmt --check and cargo clippy --all-targets clean) ================================================================= * The never-exceed invariant is pinned per tool across a RANGE of budgets (32..100_000), on both surfaces, in assert_never_exceeds — plus per-tool-shape tests (code-corpus hits with file:line and _passage, prose hits with no spans, hybrid's fused duplicates) and a lib-level test tying each of the five tools to the budgeter its dispatch path applies. * Dedup: overlapping file:line passages deduped before budgeting on both surfaces (explicit spans, _passage-ordinal spans, and rendered-block span estimates), even when the budget does not bind. * Wiring: max_tokens never reaches an engine request body (per builder); exactly the five search tools advertise it and the other six do not; the description names the tokenizer, the locator-only rule, and the floor; bad budgets are refused at dispatch with isError (no node needed). * End-to-end (not a test, a manual verification): the release binary driven over stdio against a fake engine returning 10 large hits — no budget: 963 words verbatim; max_tokens 64/150/400: 39/133/386 words with correct accounting; floor and mistyped budgets refused.
This was referenced Sep 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
The five MCP search tools are thin proxies: they returned whatever the engine sent, so an agent that asked for 50 hits got all 50 verbatim — context cost unknown and unbounded. #1058 (plan item 5 of 10, discussion #1054) asks for
max_tokenson every search tool with one named tokenizer, overlapping file:line passages deduped, over-budget hits as locators only, and the never-exceed rule enforced by test, not claimed.In-tree precedent followed (reference-code mandate note: the reference-coding corpora/server are unavailable in this sandbox post-reset 2026-09-29, so retrieval was not possible — the in-repo precedent is cited instead):
xerj_code_search's char-level cap: thefullargument (max chars per passage, default 800) and the_passageprojection default — generalised from per-passage chars to a whole-response token budget.xccode::passage::provenance(engine/crates/xerj-common/src/xccode/passage.rs:205) — the field-order contract for file:line locators (ax_path,ax_file,path,file;start_line/line).StandardTokenizer(engine/crates/xerj-fts/src/analyzer.rs:120) — the tokenizer, below.opt_typedpolicy — present-but-mistyped arguments error, never silently drop.Design decisions
StandardTokenizer— UAX fix(api): complete OpenSearch Dashboards compatibility (product header + _cat/templates/{pattern}) #29 word boundaries viaunicode_words()— the same word split the engine's analyzer uses for BM25.xerj-mcpdepends onunicode-segmentationdirectly (the same crate and the same callStandardTokenizer::tokenizemakes) rather than pulling the whole FTS stack (fst/roaring/zstd) into a thin proxy; the count is identical by construction. The choice is named in the shared argument description, with the honest scope stated: UAX fix(api): complete OpenSearch Dashboards compatibility (product header + _cat/templates/{pattern}) #29 words under-count model-context subwords (snake_caseis ONE token here); the budget is enforced in these tokens, not BPE pieces.max_tokens(builders copy only their known keys — pinned by test), so request bodies are bit-identical with and without a budget._token_budgetaccounting block (JSON surface) /[token budget …]line (text surface) reports kept, locator-only, deduped, dropped, andtokens_used.isErrornaming the floor — a budget it cannot honor is not silently ignored.What changed (file by file)
engine/crates/xerj-mcp/src/token_budget.rs(NEW):count_tokens,truncate_to_budget,opt_max_tokens,budget_json_response(the four_search-proxying tools),budget_code_text(xerj_code_search's rendered text). Span extraction mirrorsprovenance's field order, then falls back to the engine's_passageblock (ordinal= zero-based start line, text line count bounds the span).engine/crates/xerj-mcp/src/lib.rs:mod token_budget; sharedmax_tokens_arg_schema()on all five search tools plus a pointer sentence in each tool description;call_toolparses the budget for the four JSON search tools and refuses bad values before any request;engine_requesttakesOption<budget>and budgets successful responses;run_code_searchparses it itself and budgets successful rendered text.engine/crates/xerj-mcp/Cargo.toml+engine/Cargo.lock:unicode-segmentation = "1"(already in the lock via xerj-fts — no new download).landing/docs/agents/schemas/mcp-tools.json: regenerated from the real binary viascripts/mcp-schema-check.sh --write(the documented generator);published_schema_driftstays green.Crate scope respected: xerj-mcp + the published schema only; xerj-ai / xerj-api / xerj-autoindex untouched.
Tests (results)
Scoped
cargo test --release -p xerj-mcp: 54 lib + 4 drift passed, 0 failed.cargo fmt --checkandcargo clippy --all-targetsclean.assert_never_exceeds): the never-exceed invariant is pinned across a range of budgets (32…100_000) on both surfaces, plus per-tool-shape tests — code-corpus hits (_sourcefile:line +fields._passage), prose hits with no spans (semantic/vector shape), and hybrid's fused same-passage duplicates — and a lib-level test tying each of the five tools to the exact budgeter its dispatch path applies._passage-ordinal spans, rendered-block span estimates), including when the budget does not bind.max_tokensnever reaches an engine request body (pinned per builder); exactly the five search tools advertise it and the other six do not; the description names the tokenizer, the locator-only rule, and the floor; bad budgets (mistyped / below floor) are refused at dispatch withisError— verified with the real dispatch path, no node needed.Measured (not a test — a manual verification of the release binary over stdio against a fake engine returning 10 large hits): no budget → 963 words verbatim;
max_tokens64 / 150 / 400 → 39 / 133 / 386 words with correct accounting (hits_full,hits_locator_only,hits_dropped,tokens_used); floor and mistyped budgets refused.What remains to the issue's gate
xerj_code_searchtext budgeting estimates passage spans from the rendered block's line count (coarse by design — overlap detection, not citation).Closes #1058.