8000 mcp: token-budgeted responses — max_tokens on every search tool (#1058) by xerj-org · Pull Request #1067 · xerj-org/xerj · GitHub
[go: up one dir, main page]

Skip to content

mcp: token-budgeted responses — max_tokens on every search tool (#1058) - #1067

Merged
xerj-org merged 2 commits into
mainfrom
feat/mcp-max-tokens
Sep 30, 2026
Merged

xerj-org merged 2 commits into
mainfrom
feat/mcp-max-tokens

Conversation

@xerj-org
Copy link
Copy Markdown
Owner

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_tokens 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.

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: the full argument (max chars per passage, default 800) and the _passage projection 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.
  • The crate's own opt_typed policy — present-but-mistyped arguments error, never silently drop.

Design decisions

  1. One tokenizer, cited: XERJ's StandardTokenizer — UAX fix(api): complete OpenSearch Dashboards compatibility (product header + _cat/templates/{pattern}) #29 word boundaries via unicode_words() — the same word split the engine's analyzer uses for BM25. xerj-mcp depends on unicode-segmentation directly (the same crate and the same call StandardTokenizer::tokenize makes) 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_case is ONE token here); the budget is enforced in these tokens, not BPE pieces.
  2. 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.
  3. Both response surfaces budget identically: (1) hits whose file:line span 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.
  4. 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, a budget 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.
  5. Nothing binding → byte-identical passthrough (no budget, budget not reached, nothing to dedup): existing callers see zero change.
  6. Floor of 32: below it not even the envelope fits, so the tool refuses with an isError naming 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 mirrors provenance's field order, then falls back to the engine's _passage block (ordinal = zero-based start line, text line count bounds the span).
  • engine/crates/xerj-mcp/src/lib.rs: mod token_budget; shared max_tokens_arg_schema() on all five search tools plus a 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 — no new download).
  • 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.

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 --check and cargo clippy --all-targets clean.

  • Budget enforcement per tool (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 (_source file: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.
  • Dedup: overlapping file:line passages deduped before budgeting on both surfaces (explicit spans, _passage-ordinal spans, rendered-block span estimates), including when the budget does not bind.
  • Wiring: max_tokens never 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 with isError — 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_tokens 64 / 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

  • The issue's value metric — tokens per solved task, zero budget overruns — is an agent-workload measurement; the zero-overrun half is pinned by the tests here, the per-task token savings on a real corpus run unmeasured at PR time. The issue's ship-gate (benchmarks on the release binary) binds at release time, not PR time.
  • The UAX fix(api): complete OpenSearch Dashboards compatibility (product header + _cat/templates/{pattern}) #29 word count is a proxy for model context tokens (stated in the tool description); a BPE-exact count would need a tokenizer model in-tree, which does not exist.
  • xerj_code_search text budgeting estimates passage spans from the rendered block's line count (coarse by design — overlap detection, not citation).

Closes #1058.

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.
Same rule as every window: the CHANGELOG entry cites the PR it shipped
in, added after the PR number exists (#1067, issue #1058).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

agents: token-budgeted MCP responses — max_tokens on every search tool

1 participant

0