Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

feat(mcp): add ordered batch retrieval to CLI and MCP (#2333)

Jarvis6af0b42000b1
diff --git a/AGENTS.md b/AGENTS.md
index d5e006336..31634add9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -171,12 +171,12 @@ do not inherit a shell `PATH`. Add `"XERJ_AUTH": "ApiKey <key>"` when the node
is not running `--insecure` — the key is `<data-dir>/admin.key`. `--url` and
`--auth` flags override the two environment variables.
-Twenty-one tools: `xerj_search`, `xerj_semantic_search`, `xerj_vector_search`,
+Twenty-two tools: `xerj_search`, `xerj_semantic_search`, `xerj_vector_search`,
`xerj_hybrid_search`, `xerj_memory_store`, `xerj_memory_recall`,
`xerj_brain_overview`, `xerj_brain_ego`, `xerj_brain_link`, `xerj_brain_unlink`,
`xerj_plan`, `xerj_map`, `xerj_code_search`, `xerj_index_budget`,
`xerj_autoindex_remove`, `xerj_field_report`, `xerj_corpus_feedback`,
-`xerj_hub_find`, `xerj_hub_def`, `xerj_hub_ask`, `xerj_def`. The first eleven are
+`xerj_hub_find`, `xerj_hub_def`, `xerj_hub_ask`, `xerj_def`, `xerj_batch_search`. The first eleven are
each a *thin proxy*: they build exactly the request the ES-compatible surface already accepts
(`xerj_plan` is `POST /_ask`, the deterministic rule-based planner) and hand back
whatever the engine returned, errors and refusals verbatim — no capability of
@@ -191,6 +191,14 @@ the `xerj code` reference-coding pipeline ([`tools/xerj-code/`](tools/xerj-code/
— staleness refusal, licence warnings, no-match-as-guidance — and returns its
rendered text rather than a raw response.
+`xerj_batch_search` and `xerj batch-search --input <file|->` share an ordered
+batch-retrieval adapter over `/_msearch`: up to 50 queries, independent errors
+and explicit empty-result abstentions, citations on every returned hit. Exact
+IDs require a caller-selected indexed keyword field. It does not generate
+answers or calibrate confidence. Whole-response token budgets preserve item
+outcomes and at least one citation per matched item, or refuse explicitly.
+See [docs/recipes/batch-search.md](./docs/recipes/batch-search.md).
+
`xerj_def` finds definitions in local autoindexed data, sharing the query,
lexical ranking and location deduplication of `xerj def --json`. For example,
`{"symbol":"Cache","prefix":"project","kind":"struct","lang":"rust","k":5}`
@@ -211,7 +219,7 @@ true. `xerj_field_report` files an agent field report (a GitHub PR first, the
`/api/field-report` endpoint when GitHub is unavailable). `xerj_corpus_feedback`
rates a hub corpus. `xerj_hub_find`, `xerj_hub_def` and `xerj_hub_ask` answer
from Corpus Hub packs already on the machine, the `xerj ask` flow. A binary with
-no hub key omits the three hub tools and serves eighteen.
+no hub key omits the three hub tools and serves nineteen.
Two honesty notes that bind how you describe results: `xerj_semantic_search`
embeds server-side with the **lexical feature-hashing** embedder unless the node
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ce591c85..ea7c472d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the documents themselves is the replica backfill entry above (part of
[#1170](https://github.com/xerj-org/xerj/issues/1170)).
+- `xerj batch-search --input <file|->` and MCP `xerj_batch_search` retrieve
+ up to 50 IDs or questions in input order through one `_msearch` call.
+ Each item returns cited evidence, an explicit empty-result abstention, or
+ an independent error. Exact IDs require an indexed keyword field. Optional
+ whole-response token budgets preserve outcomes and at least one citation
+ per matched item, or refuse explicitly. This is retrieval, not generated
+ answers or calibrated confidence (#1801, partial implementation).
+
- With `[cluster] enabled = true`, a single-document index or delete is
acknowledged when a quorum of the shard's copies has confirmed, not only
when every placed replica has. Copies are the primary plus the replicas
diff --git a/README.md b/README.md
index 3f2bab6b9..b24559280 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,9 @@ xerj def "euler_to_rotationmatrix" # go-to-definition: file:line +
xerj gain # what it did for you — counted, not estimated
```
+For several IDs or questions at once, use `xerj batch-search --input queries.json`
+or MCP `xerj_batch_search`: [ordered results, citations and per-item errors](docs/recipes/batch-search.md).
+
Keep that data directory outside any folder you will autoindex. `data/` is not in the
built-in ignore list, so `--data-dir ./data` inside a tree you then index makes the node
index its own storage.
diff --git a/docs/RERANK.md b/docs/RERANK.md
index ef10d065f..9443877e7 100644
--- a/docs/RERANK.md
+++ b/docs/RERANK.md
@@ -374,12 +374,15 @@ the picture:
[air-gapped recipe](./recipes/air-gapped-deployment.md) names the three pages
that link the fonts, and a blocked request falls back to system fonts.
- **The command-line clients in the same binary** (`xerj autoindex`,
- `xerj mcp`, `xerj search`, `xerj code`, `xerj corpus list`, `xerj hub` and
- the others) send what they read to the node URL you give them,
+ `xerj mcp`, `xerj batch-search`, `xerj search`, `xerj code`, `xerj corpus list`,
+ `xerj hub` and the others) send what they read to the node URL you give them,
`http://localhost:9200` unless you say otherwise. On an empty corpus ledger,
`xerj code` and `xerj corpus list` also POST one catalog search to that same
node URL (autoindex run prefixes, and the API key when one is configured);
no document text and no user query.
+ `xerj batch-search` sends the batch's queries or identifiers to `/_msearch`
+ and optionally reads index mappings at that node, with the configured API
+ key when present (`--url` / `--auth` override `XERJ_URL` / `XERJ_AUTH`).
`xerj feedback --open-pr` runs your `gh` to open a GitHub pull request with
the report it drafted; without that flag it does nothing over the network.
diff --git a/docs/recipes/batch-search.md b/docs/recipes/batch-search.md
new file mode 100644
index 000000000..eb382858d
--- /dev/null
+++ b/docs/recipes/batch-search.md
@@ -0,0 +1,79 @@
+# Retrieve several IDs or questions in one call
+
+`xerj batch-search` and the MCP tool `xerj_batch_search` share one adapter.
+They retrieve evidence from a node that is already running; neither starts a
+node, downloads a corpus, writes data, or generates an answer.
+
+Save this as `queries.json`, replacing the index and field with those in your
+data map. `id` must be an indexed **keyword** field for the identifier lookup.
+There is no guessed ID field and no tokenized-text fallback for exact IDs.
+
+```json
+{
+ "index": "advisories",
+ "size": 3,
+ "queries": [
+ {"key": "known", "identifier": "CVE-2026-12345", "field": "id"},
+ {"key": "question", "query": "when should we rotate keys"},
+ {"key": "structured", "query": {"match": {"body": "rotation"}}}
+ ]
+}
+```
+
+```sh
+xerj batch-search --input queries.json --url http://127.0.0.1:9200
+# Or pipe the same JSON:
+cat queries.json | xerj batch-search --input -
+```
+
+For MCP, call `xerj_batch_search` with that JSON object as `arguments`.
+`XERJ_URL`, `XERJ_AUTH`, explicit `--url`/`--auth` and loopback admin-key discovery
+work as for `xerj mcp`. The node must already be running. `prefix` can replace
+`index`; combining both is an error. With neither, the target is `ax-*`.
+
+The response has one `results` entry for each input, in the same order. Its
+zero-based `position` is authoritative; optional `key` values may repeat.
+
+| Status | Meaning |
+|---|---|
+| `hits`, `abstain: false` | Retrieved hits, each with `citation` and raw `hit` evidence. A hit is not a generated answer or a calibrated relevance guarantee. |
+| `abstain`, `abstain: true`, `reason: no_hits` | The item completed with an empty hit list. This is retrieval abstention, not a confidence judgment. |
+| `error` | Invalid item, unsupported exact-field mapping, failed/partial search, malformed response, or transport failure. Never relabeled as a miss. |
+
+Citations always retain `_index` and `_id`. Available `ax_path`/`path`,
+`ax_locator`, `ax_file`, stored line/page/cell and calculated `match_line` fields
+are included too. No file line is inferred from a JSONL record ordinal.
+There is no deduplication across questions, even for identical inputs.
+
+Limits: 1–50 items, `size` 1–50 per item (default 3), a 1 MiB serialized input,
+256 UTF-8 bytes per optional key, a 32 MiB HTTP response, and the MCP client's
+30-second HTTP timeout. Locally invalid items do not reach the node. The other
+items use one `_msearch` request and, when needed, one shared mapping read.
+An unreadable mapping fails exact-ID items; plain text retains the established
+search-query fallback. Exact ID fields must be flat and keyword-mapped wherever
+present, with indexing enabled. Nested fields are outside this first version.
+
+`max_tokens` optionally caps the entire successful response JSON, using the
+same UAX #29 word counter as the other MCP search tools. This is **not BPE**.
+If binding, the adapter removes raw `hit` bodies starting at later items,
+then extra hits; it retains every item outcome and at least one citation per
+matched item. `hits_omitted` counts omitted hits, and `_token_budget` names the
+counter and limit. A nonbinding budget leaves the response byte-identical.
+If the remaining statuses, errors and citations cannot fit, the whole call
+returns an explicit error naming the minimum required budget. Split the batch
+or increase the budget. Errors are outside the budget and are never truncated.
+
+CLI exit codes: `0` all items completed (including abstentions); `3` one or more
+per-item errors (the JSON still contains all outcomes); `2` invalid CLI/input
+envelope; `1` a batch-wide execution or budget error. Treat exit `3` as a partial
+result to inspect, not a reason to discard the successful items.
+
+The batch path uses `_msearch` rather than repeated `_search` calls. Plain-text
+items reuse the mapping-aware search query and code-path demotion; the engine's
+`_msearch` renderer returns stored evidence, not `_search`'s extracted `_passage`
+field. Rerank/judge and per-item scopes/options are not exposed here. No latency,
+model-token savings, rust-vulns accuracy or confidence claim is made.
+
+This is the batch retrieval part of [#1801](https://github.com/xerj-org/xerj/issues/1801).
+Full answer/abstain calibration, alias-aware ID discovery and the requested
+rust-vulns evaluation remain separate work; this does not close that issue.
diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rs
index 54050733b..0367c06db 100644
--- a/engine/crates/xerj-hub/src/cli.rs
+++ b/engine/crates/xerj-hub/src/cli.rs
@@ -1475,6 +1475,7 @@ catalogue could not be loaded (hub unreachable, no signed catalogue served, or
pub const KNOWN_SUBCOMMANDS: &[&str] = &[
"index",
"search",
+ "batch-search",
"def",
"init",
"gain",
diff --git a/engine/crates/xerj-mcp/src/batch.rs b/engine/crates/xerj-mcp/src/batch.rs
new file mode 100644
index 000000000..21041f570
--- /dev/null
+++ b/engine/crates/xerj-mcp/src/batch.rs
@@ -0,0 +1,502 @@
+//! Ordered, read-only batch retrieval over the existing `_msearch` endpoint.
+//! No answer generation or confidence threshold is inferred from a BM25 score.
+use serde_json::{json, Value};
+
+use crate::{build_search_with_mapping, fetch_mapping, search_index, token_budget, tool_text, Ctx};
+
+pub const MAX_INPUT_BYTES: usize = 1024 * 1024;
+const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;
+
+pub(crate) fn spec() -> Value {
+ json!({
+ "name":"xerj_batch_search",
+ "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Optional max_tokens caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.",
+ "inputSchema":{
+ "type":"object", "additionalProperties":false,
+ "properties":{
+ "queries":{"type":"array","minItems":1,"maxItems":50,
+ "description":"Ordered queries. Duplicate keys are allowed; position is authoritative. Entire input is limited to 1 MiB.",
+ "items":{"type":"object","additionalProperties":false,"properties":{
+ "key":{"type":"string","description":"Optional correlation key, at most 256 UTF-8 bytes."},
+ "query":{"oneOf":[{"type":"string","minLength":1},{"type":"object"}],
+ "description":"Plain text or ES query clause. Cannot be combined with identifier/field."},
+ "identifier":{"type":"string","minLength":1,"description":"Exact value, used verbatim in a term query; requires field."},
+ "field":{"type":"string","minLength":1,"description":"Flat keyword field for identifier. Must be mapped as keyword wherever present; unreadable, absent or conflicting mappings fail this item."}
+ }, "oneOf":[{"required":["query"]},{"required":["identifier","field"]}]}},
+ "index":{"type":"string","description":"Index or pattern; alternative to prefix. Defaults to ax-*."},
+ "prefix":{"type":"string","description":"Autoindex prefix, e.g. project searches project-*. Cannot combine with index."},
+ "size":{"type":"integer","minimum":1,"maximum":50,"default":3,"description":"Maximum hits per item."},
+ "max_tokens":{"type":"integer","minimum":32,"description":format!("Whole-response budget counted with {} (not BPE); minimum 32. A successful response NEVER exceeds it. Preserves ordered item outcomes and at least one citation per matched item, removing raw bodies first. Refuses if that minimum cannot fit; split the batch or increase the budget. Errors are outside this budget.", token_budget::TOKENIZER_NAME)}
+ },"required":["queries"]
+ }
+ })
+}
+
+fn known_keys(value: &Value, allowed: &[&str]) -> Result<(), String> {
+ let obj = value.as_object().ok_or("arguments must be a JSON object")?;
+ if let Some(key) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
+ return Err(format!("unsupported argument `{key}`"));
+ }
+ Ok(())
+}
+
+fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, String> {
+ value
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| format!("`{key}` must be a non-blank string"))
+}
+
+pub(super) struct Batch<'a> {
+ index: String,
+ size: usize,
+ limit: Option<usize>,
+ items: &'a [Value],
+}
+
+pub(super) fn envelope(args: &Value) -> Result<Batch<'_>, String> {
+ known_keys(args, &["queries", "index", "prefix", "size", "max_tokens"])?;
+ if args.to_string().len() > MAX_INPUT_BYTES {
+ return Err("batch input exceeds 1 MiB; split it into smaller batches".into());
+ }
+ if args
+ .get("index")
+ .is_some_and(|v| !v.is_string() && !v.is_null())
+ {
+ return Err("`index` must be a string".into());
+ }
+ let index = search_index(args)?;
+ let queries = args
+ .get("queries")
+ .and_then(Value::as_array)
+ .filter(|a| (1..=50).contains(&a.len()))
+ .ok_or("`queries` must be an array of 1..50 items")?;
+ let size = match args.get("size") {
+ None => 3,
+ Some(v) => v
+ .as_u64()
+ .filter(|n| (1..=50).contains(n))
+ .ok_or("`size` must be an integer from 1 to 50")? as usize,
+ };
+ let budget = token_budget::opt_max_tokens(args)?;
+ Ok(Batch {
+ index,
+ size,
+ limit: budget,
+ items: queries,
+ })
+}
+
+fn validate_item(item: &Value) -> Result<(), String> {
+ known_keys(item, &["key", "query", "identifier", "field"])?;
+ if item
+ .get("key")
+ .is_some_and(|v| v.as_str().is_none_or(|s| s.len() > 256))
+ {
+ return Err("`key` must be a string of at most 256 UTF-8 bytes".into());
+ }
+ if let Some(query) = item.get("query") {
+ if item.get("identifier").is_some() || item.get("field").is_some() {
+ return Err("use either query or identifier plus field, not both".into());
+ }
+ if !(query.as_str().is_some_and(|s| !s.trim().is_empty())
+ || query.as_object().is_some_and(|o| !o.is_empty()))
+ {
+ return Err("`query` must be non-blank text or a nonempty ES query object".into());
+ }
+ } else {
+ text(item, "identifier")?;
+ let field = text(item, "field")?;
+ if field.contains('.') {
+ return Err(
+ "`field` must name a flat keyword field; nested fields are not supported".into(),
+ );
+ }
+ }
+ Ok(())
+}
+
+fn item_body(
+ item: &Value,
+ index: &str,
+ size: usize,
+ mapping: Option<&Value>,
+) -> Result<Value, String> {
+ if item.get("identifier").is_some() {
+ let field = text(item, "field")?;
+ let mappings = mapping
+ .and_then(Value::as_object)
+ .ok_or("cannot verify exact identifier field: mapping unavailable")?;
+ let mut present = false;
+ for m in mappings.values() {
+ if let Some(spec) = m.pointer("/mappings/properties").and_then(|p| p.get(field)) {
+ present = true;
+ if spec["type"] != "keyword" || spec["index"] == false {
+ return Err(format!("exact identifier field `{field}` must be indexed keyword in every mapping where present"));
+ }
+ }
+ }
+ if !present {
+ return Err(format!("exact identifier field `{field}` is not mapped"));
+ }
+ return Ok(json!({"query":{"term":{(field):item["identifier"]}},"size":size}));
+ }
+ let args = json!({"index":index,"query":item["query"],"size":size,"_source":true});
+ let (_, _, body) = build_search_with_mapping(&args, mapping)?;
+ let mut body = body.expect("search builder always supplies a body");
+ if crate::plain_search_demotes_test_paths(&args, mapping) {
+ body["size"] = json!(xerj_autoindex::search::search_fetch_size(size));
+ }
+ Ok(body)
+}
+
+fn item_base(position: usize, item: &Value) -> Value {
+ let mut out = json!({"position":position});
+ if let Some(key) = item
+ .get("key")
+ .and_then(Value::as_str)
+ .filter(|s| s.len() <= 256)
+ {
+ out["key"] = json!(key);
+ }
+ out
+}
+
+fn failed(mut base: Value, error: Value) -> Value {
+ base["status"] = json!("error");
+ base["error"] = error;
+ base
+}
+
+fn citation(hit: &Value) -> Result<Value, String> {
+ let mut out = serde_json::Map::new();
+ for key in ["_index", "_id"] {
+ out.insert(key.into(), json!(text(hit, key)?));
+ }
+ if let Some(source) = hit.get("_source") {
+ for key in [
+ "ax_path",
+ "path",
+ "ax_file",
+ "ax_locator",
+ "line",
+ "start_line",
+ "page",
+ "cell",
+ ] {
+ if let Some(v) = source.get(key).filter(|v| v.is_string() || v.is_number()) {
+ out.insert(key.into(), v.clone());
+ }
+ }
+ }
+ for key in ["match_line", "match_lines"] {
+ if let Some(v) = hit.get(key) {
+ out.insert(key.into(), v.clone());
+ }
+ }
+ Ok(Value::Object(out))
+}
+
+fn item_result(
+ mut base: Value,
+ mut response: Value,
+ item: &Value,
+ size: usize,
+ mapping: Option<&Value>,
+) -> Value {
+ if response.get("error").is_some_and(|v| !v.is_null())
+ || response["status"].as_u64().is_some_and(|s| s >= 400)
+ {
+ return failed(base, response);
+ }
+ if response["timed_out"] == true
+ || response
+ .pointer("/_shards/failed")
+ .and_then(Value::as_u64)
+ .unwrap_or(0)
+ > 0
+ {
+ return failed(
+ base,
+ json!({"reason":"search_incomplete","response":response}),
+ );
+ }
+ let query = item.get("query").map(|v| {
+ v.as_str()
+ .map(str::to_string)
+ .unwrap_or_else(|| v.to_string())
+ });
+ if let Some(query) = query {
+ xerj_common::xccode::passage::annotate_search_match_lines(&mut response, &query);
+ }
+ if crate::plain_search_demotes_test_paths(&json!({"query":item["query"]}), mapping) {
+ if let Some(hits) = response
+ .pointer_mut("/hits/hits")
+ .and_then(Value::as_array_mut)
+ {
+ xerj_autoindex::def::penalize_demoted_paths(hits);
+ hits.truncate(size);
+ }
+ }
+ let Some(hits) = response.pointer("/hits/hits").and_then(Value::as_array) else {
+ return failed(
+ base,
+ json!({"reason":"invalid_search_response","message":"missing hits.hits"}),
+ );
+ };
+ if hits.is_empty() {
+ let total = response
+ .pointer("/hits/total/value")
+ .and_then(Value::as_u64)
+ .or_else(|| response.pointer("/hits/total").and_then(Value::as_u64));
+ if total.is_some_and(|n| n > 0) {
+ return failed(
+ base,
+ json!({"reason":"invalid_search_response","message":"empty page despite a positive total"}),
+ );
+ }
+ base["status"] = json!("abstain");
+ base["abstain"] = json!(true);
+ base["reason"] = json!("no_hits");
+ return base;
+ }
+ let mut cited = Vec::new();
+ for hit in hits.iter().take(size) {
+ let citation = match citation(hit) {
+ Ok(c) => c,
+ Err(e) => {
+ return failed(
+ base,
+ json!({"reason":"invalid_search_response","message":e}),
+ )
+ }
+ };
+ cited.push(json!({"citation":citation,"hit":hit}));
+ }
+ base["status"] = json!("hits");
+ base["abstain"] = json!(false);
+ base["hits"] = json!(cited);
+ base["hits_omitted"] = json!(hits.len().saturating_sub(cited.len()));
+ base
+}
+
+async fn msearch(ctx: &Ctx, ndjson: String) -> Result<Vec<Value>, String> {
+ let mut req = ctx
+ .client
+ .post(format!("{}/_msearch", ctx.base_url))
+ .header("Content-Type", "application/x-ndjson")
+ .body(ndjson);
+ if let Some(auth) = &ctx.auth {
+ req = req.header("Authorization", auth);
+ }
+ let mut resp = req.send().await.map_err(|e| crate::error_detail(&e))?;
+ let status = resp.status();
+ let mut bytes = Vec::new();
+ while let Some(chunk) = resp.chunk().await.map_err(|e| crate::error_detail(&e))? {
+ if bytes.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
+ return Err("batch response exceeds 32 MiB; reduce size or split the batch".into());
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ if !status.is_success() {
+ return Err(format!(
+ "batch endpoint returned HTTP {status}: {}",
+ String::from_utf8_lossy(&bytes)
+ ));
+ }
+ let response: Value =
+ serde_json::from_slice(&bytes).map_err(|_| "batch endpoint returned invalid JSON")?;
+ response
+ .get("responses")
+ .and_then(Value::as_array)
+ .cloned()
+ .ok_or_else(|| "batch endpoint returned no responses array".into())
+}
+
+/// Never discard an item's outcome to meet a budget. At least one citation
+/// survives each matched item; errors and abstentions retain their meanings.
+fn budget(mut response: Value, limit: Option<usize>) -> Result<String, String> {
+ let Some(limit) = limit else {
+ return Ok(response.to_string());
+ };
+ let count = |v: &Value| token_budget::count_tokens(&v.to_string());
+ if count(&response) <= limit {
+ return Ok(response.to_string());
+ }
+ response["_token_budget"] = json!({"tokenizer":token_budget::TOKENIZER_ID,"max_tokens":limit});
+ let mut used = count(&response);
+ // Lower ranked items lose raw bodies first, but never their citations.
+ let n = response["results"].as_array().unwrap().len();
+ for i in (0..n).rev() {
+ let len = response["results"][i]["hits"]
+ .as_array()
+ .map_or(0, Vec::len);
+ for j in (0..len).rev() {
+ if let Some(hit) = response["results"][i]["hits"][j]
+ .as_object_mut()
+ .unwrap()
+ .remove("hit")
+ {
+ // JSON punctuation separates fields into word boundaries. Count
+ // just the removed subtree rather than serializing a 32 MiB
+ // response once for every hit. Final serialization is checked.
+ used = used.saturating_sub(count(&json!({"hit":hit})));
+ }
+ if used <= limit {
+ return checked_budget(&response, limit);
+ }
+ }
+ }
+ for i in (0..n).rev() {
+ while response["results"][i]["hits"]
+ .as_array()
+ .is_some_and(|a| a.len() > 1)
+ {
+ let hit = response["results"][i]["hits"]
+ .as_array_mut()
+ .unwrap()
+ .pop()
+ .unwrap();
+ used = used.saturating_sub(count(&hit));
+ let omitted = response["results"][i]["hits_omitted"].as_u64().unwrap_or(0);
+ response["results"][i]["hits_omitted"] = json!(omitted + 1);
+ if used <= limit {
+ return checked_budget(&response, limit);
+ }
+ }
+ }
+ let minimum = token_budget::count_tokens(&response.to_string());
+ Err(format!("max_tokens {limit} cannot preserve every item outcome and one citation per matched item; this response needs at least {minimum} UAX #29 words. Increase max_tokens or split the batch. Nothing was written."))
+}
+
+fn checked_budget(response: &Value, limit: usize) -> Result<String, String> {
+ let text = response.to_string();
+ if token_budget::count_tokens(&text) <= limit {
+ Ok(text)
+ } else {
+ Err("batch budget accounting could not preserve valid JSON; increase max_tokens or split the batch".into())
+ }
+}
+
+pub(crate) async fn execute(ctx: &Ctx, args: &Value) -> Result<String, String> {
+ let Batch {
+ index,
+ size,
+ limit,
+ items,
+ } = envelope(args)?;
+ // Validate locally before any I/O; invalid items do not sink siblings.
+ let validation: Vec<_> = items.iter().map(validate_item).collect();
+ let needs_mapping = items.iter().zip(&validation).any(|(item, valid)| {
+ valid.is_ok() && (item.get("identifier").is_some() || item["query"].is_string())
+ });
+ let mapping = if needs_mapping {
+ fetch_mapping(ctx, &index).await
+ } else {
+ None
+ };
+ let mut results: Vec<Value> = items
+ .iter()
+ .enumerate()
+ .map(|(i, item)| item_base(i, item))
+ .collect();
+ let mut pending = Vec::new();
+ let mut batch_error = None;
+ let mut ndjson = String::new();
+ for (i, item) in items.iter().enumerate() {
+ let built = validation[i]
+ .clone()
+ .and_then(|()| item_body(item, &index, size, mapping.as_ref()));
+ match built {
+ Ok(body) => {
+ ndjson.push_str(&json!({"index":index}).to_string());
+ ndjson.push('\n');
+ ndjson.push_str(&body.to_string());
+ ndjson.push('\n');
+ pending.push(i);
+ }
+ Err(message) => {
+ results[i] = failed(
+ results[i].clone(),
+ json!({"reason":"invalid_item","message":message}),
+ )
+ }
+ }
+ }
+ if !pending.is_empty() {
+ match msearch(ctx, ndjson).await {
+ Ok(responses) if responses.len() == pending.len() => {
+ for (i, response) in pending.into_iter().zip(responses) {
+ results[i] = item_result(
+ results[i].clone(),
+ response,
+ &items[i],
+ size,
+ mapping.as_ref(),
+ );
+ }
+ }
+ other => {
+ let message = match other {
+ Ok(_) => "batch endpoint returned the wrong number of responses; item correspondence cannot be trusted".to_string(),
+ Err(e) => e,
+ };
+ for i in pending {
+ results[i] = failed(
+ results[i].clone(),
+ json!({"reason":"batch_request_failed","details":"see batch_error"}),
+ );
+ }
+ // Preserve the complete transport error once, rather than
+ // multiplying a large HTTP error body by up to 50 items.
+ batch_error = Some(message);
+ }
+ }
+ }
+ let mut response = json!({"results":results});
+ if let Some(error) = batch_error {
+ response["batch_error"] = json!(error);
+ }
+ budget(response, limit)
+}
+
+pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {
+ match execute(ctx, args).await {
+ Ok(text) => tool_text(text, false),
+ Err(error) => tool_text(error, true),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn batch_budget_keeps_outcomes_and_citations_or_refuses() {
+ let response = json!({"results":[
+ {"position":0,"status":"hits","abstain":false,"hits_omitted":0,
+ "hits":[{"citation":{"_index":"docs","_id":"one"},"hit":{"body":"word ".repeat(1000)}},
+ {"citation":{"_index":"docs","_id":"two"},"hit":{"body":"other ".repeat(1000)}}]},
+ {"position":1,"status":"abstain","abstain":true,"reason":"no_hits"},
+ {"position":2,"status":"error","error":{"reason":"backend_failed"}}
+ ]});
+ assert_eq!(
+ budget(response.clone(), Some(10000)).unwrap(),
+ response.to_string()
+ );
+ for limit in [32, 64, 80, 120, 300, 3000] {
+ match budget(response.clone(), Some(limit)) {
+ Ok(text) => {
+ assert!(token_budget::count_tokens(&text) <= limit);
+ let v: Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(v["results"].as_array().unwrap().len(), 3);
+ assert_eq!(v["results"][0]["hits"][0]["citation"]["_id"], "one");
+ assert_eq!(v["results"][1]["status"], "abstain");
+ assert_eq!(v["results"][2]["status"], "error");
+ }
+ Err(e) => assert!(e.contains("needs at least"), "{e}"),
+ }
+ }
+ }
+}
diff --git a/engine/crates/xerj-mcp/src/batch_cli.rs b/engine/crates/xerj-mcp/src/batch_cli.rs
new file mode 100644
index 000000000..1c34f3308
--- /dev/null
+++ b/engine/crates/xerj-mcp/src/batch_cli.rs
@@ -0,0 +1,187 @@
+//! JSON-in/JSON-out CLI for the same batch adapter MCP calls.
+use std::io::Read;
+use std::time::Duration;
+
+use crate::{batch, resolve_auth, Ctx, DEFAULT_XERJ_URL};
+
+const HELP: &str = "xerj batch-search — ordered batch retrieval (#1801)
+
+USAGE: xerj batch-search --input <file|-> [--url URL] [--auth VALUE]
+
+Read one JSON object (at most 1 MiB) using the xerj_batch_search schema:
+ {\"prefix\":\"project\",\"size\":3,\"queries\":[
+ {\"key\":\"question\",\"query\":\"rotate the WAL\"},
+ {\"key\":\"advisory\",\"identifier\":\"CVE-2026-12345\",\"field\":\"id\"}
+ ]}
+
+queries: 1..50 objects, each query (text or ES query clause) OR identifier+field.
+Exact identifiers require a flat indexed keyword field. index/prefix, size
+(1..50, default 3) and optional max_tokens are shared by all items.
+Output is one JSON object with ordered results; position is zero-based and
+authoritative even for duplicate keys. status is hits, abstain (complete empty
+search only), or error. Hits contain citations and raw evidence, not generated
+answers or calibrated confidence. A miss does not discard its siblings.
+max_tokens counts the entire JSON as UAX #29 words, not model/BPE tokens.
+It removes raw bodies and then extra hits, retaining every item outcome and
+one citation per matched item; an insufficient budget is an error, not truncation.
+
+--url / --auth override XERJ_URL / XERJ_AUTH. Default URL: http://localhost:9200.
+Local loopback admin-key discovery is the same as xerj mcp. A node must already
+be running. This command writes no data and does not download any corpus.
+Exit: 0 all items completed (including abstentions), 3 per-item errors,
+ 2 invalid CLI/input, 1 a batch-wide execution/budget error.
+";
+
+struct Options {
+ input: String,
+ url: Option<String>,
+ auth: Option<String>,
+}
+
+fn options(args: &[String]) -> Result<Options, String> {
+ let mut out = Options {
+ input: String::new(),
+ url: None,
+ auth: None,
+ };
+ let mut it = args.iter();
+ while let Some(arg) = it.next() {
+ match arg.as_str() {
+ "--input" | "--url" | "--auth" => {
+ let value = it.next().ok_or_else(|| format!("{arg} requires a value"))?;
+ match arg.as_str() {
+ "--input" => out.input = value.clone(),
+ "--url" => out.url = Some(value.clone()),
+ _ => out.auth = Some(value.clone()),
+ }
+ }
+ xerj_common::feedback::DISABLE_FLAG => {}
+ _ => {
+ return Err(format!(
+ "unknown argument `{arg}`; see xerj batch-search --help"
+ ))
+ }
+ }
+ }
+ if out.input.is_empty() {
+ return Err("--input <file|-> is required; see xerj batch-search --help".into());
+ }
+ Ok(out)
+}
+
+fn read_input(path: &str) -> Result<serde_json::Value, String> {
+ let reader: Box<dyn Read> = if path == "-" {
+ Box::new(std::io::stdin())
+ } else {
+ Box::new(std::fs::File::open(path).map_err(|e| format!("cannot open input: {e}"))?)
+ };
+ let mut bytes = Vec::new();
+ reader
+ .take(batch::MAX_INPUT_BYTES as u64 + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|e| format!("cannot read input: {e}"))?;
+ if bytes.len() > batch::MAX_INPUT_BYTES {
+ return Err("batch input exceeds 1 MiB; split it".into());
+ }
+ serde_json::from_slice(&bytes).map_err(|e| format!("invalid batch JSON: {e}"))
+}
+
+/// Called before node startup by the main binary; never starts a node.
+pub async fn run_batch_cli(args: &[String]) -> i32 {
+ if args.iter().any(|s| s == "--help" || s == "-h") {
+ print!("{HELP}");
+ return 0;
+ }
+ let opts = match options(args) {
+ Ok(o) => o,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return 2;
+ }
+ };
+ let input = match read_input(&opts.input) {
+ Ok(v) => v,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return 2;
+ }
+ };
+ if let Err(e) = batch::envelope(&input) {
+ eprintln!("error: {e}");
+ return 2;
+ }
+ let base_url = opts
+ .url
+ .or_else(|| std::env::var("XERJ_URL").ok())
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| DEFAULT_XERJ_URL.into())
+ .trim_end_matches('/')
+ .to_string();
+ let (auth, path) = resolve_auth(opts.auth, std::env::var("XERJ_AUTH").ok(), &base_url);
+ if let Some(path) = path {
+ eprintln!(
+ "xerj batch-search: using local admin key at {}",
+ path.display()
+ );
+ }
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(30))
+ .build()
+ {
+ Ok(c) => c,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return 1;
+ }
+ };
+ match batch::execute(
+ &Ctx {
+ client,
+ base_url,
+ auth,
+ },
+ &input,
+ )
+ .await
+ {
+ Ok(text) => {
+ let result: serde_json::Value =
+ serde_json::from_str(&text).expect("batch returns JSON");
+ let errors = result["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|r| r["status"] == "error");
+ println!("{text}");
+ if errors {
+ 3
+ } else {
+ 0
+ }
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ 1
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn cli_requires_explicit_input_and_rejects_typos() {
+ assert!(options(&[]).is_err());
+ assert!(options(&["--input".into()]).is_err());
+ assert!(options(&["--input".into(), "-".into(), "--urll".into()]).is_err());
+ let parsed = options(&[
+ "--input".into(),
+ "-".into(),
+ "--url".into(),
+ "http://localhost:9201".into(),
+ ])
+ .unwrap();
+ assert_eq!(parsed.input, "-");
+ assert_eq!(parsed.url.as_deref(), Some("http://localhost:9201"));
+ }
+}
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index be2c94b50..35362cb73 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -9,10 +9,10 @@
//!
//! It speaks the MCP **stdio transport**: newline-delimited
//! JSON-RPC 2.0 messages on stdin/stdout. It exposes XERJ to any MCP-capable
-//! agent host (Claude Desktop, IDE agents, custom orchestrators) as twenty-one
-//! tools: eighteen without a hub key, and three Corpus Hub tools
+//! agent host (Claude Desktop, IDE agents, custom orchestrators) as twenty-two
+//! tools: nineteen without a hub key, and three Corpus Hub tools
//! (`xerj_hub_*`) that run the `xerj ask` flow itself. Thirteen of those
-//! eighteen construct exactly the request the running engine already accepts
+//! nineteen construct exactly the request the running engine already accepts
//! and forward it to a configurable base URL. `xerj_index_budget` counts a
//! folder and returns the budget plans; it does not index. `xerj_autoindex_remove`
//! deletes one autoindexed folder after listing what that folder owns, and only
@@ -29,6 +29,7 @@
//! |------------------------|---------------------------------------|-----------------|
//! | `xerj_def` | `GET /{index}/_mapping` + `POST /{index}/_search` | local definition lookup with CLI ranking and deduplication |
//! | `xerj_search` | `POST /{index}/_search` | ES query-DSL search (full-text / keyword / structured) |
+//! | `xerj_batch_search` | `GET /{index}/_mapping` + `POST /_msearch` | ordered per-item evidence, abstention or error; shared with `xerj batch-search` |
//! | `xerj_semantic_search` | `POST /{index}/_search` (`semantic`) | server-side lexical embedding, no external key |
//! | `xerj_vector_search` | `POST /{index}/_search` (`knn`) | kNN over a `dense_vector` field (HNSW-served unfiltered, exact filtered) |
//! | `xerj_hybrid_search` | `POST /{index}/_search` (`hybrid`) | RRF or linear fusion of sub-queries |
@@ -100,11 +101,15 @@
//! words), with duplicate passages removed before budgeting and
//! over-budget hits reduced to locators.
+mod batch;
+mod batch_cli;
mod def;
mod hub;
mod map;
mod token_budget;
+pub use batch_cli::run_batch_cli;
+
use std::time::Duration;
use serde_json::{json, Value};
@@ -757,6 +762,7 @@ pub fn tool_specs() -> Value {
pub fn tool_specs_with(include_hub: bool) -> Value {
let mut specs = json!([
def::spec(),
+ batch::spec(),
{
"name": "xerj_search",
"description":
@@ -1862,6 +1868,9 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {
let mut demote_page: Option<usize> = None;
let result = match name {
"xerj_def" => return def::run(ctx, &args).await,
+ // Keep the batch state machine off the shared dispatcher future's
+ // stack: single-item tools must not inherit its larger frame.
+ "xerj_batch_search" => return Box::pin(batch::run(ctx, &args)).await,
"xerj_search" => {
// Resolve before even the mapping GET: conflicting or malformed
// scope arguments must never silently query a different corpus.
@@ -4335,7 +4344,7 @@ mod tests {
}
#[test]
- fn exactly_the_six_search_tools_advertise_max_tokens() {
+ fn search_tools_advertise_their_budget_contracts() {
let specs = tool_specs();
let search_tools = [
"xerj_def",
@@ -4375,6 +4384,15 @@ mod tests {
.unwrap_or(false),
"{name}: `max_tokens` is optional"
);
+ } else if name == "xerj_batch_search" {
+ // Unlike the single-search adapter, a batch must preserve
+ // every item's outcome and refuse an undersized envelope.
+ let d = prop["description"].as_str().expect("described");
+ assert!(d.contains(token_budget::TOKENIZER_NAME), "{d}");
+ assert!(d.contains("NEVER exceeds"), "{d}");
+ assert!(d.contains("ordered item outcomes"), "{d}");
+ assert!(d.contains("Refuses"), "{d}");
+ assert_eq!(prop["minimum"], token_budget::MIN_MAX_TOKENS);
} else if name == "xerj_hub_ask" {
// The hub's own budget (docs/hub-v2-grpc-mcp-notes.md): the
// `xerj ask --max-tokens` cap, a SOFT ~4-chars-a-token trim of
@@ -5367,7 +5385,7 @@ mod tests {
.iter()
.map(|t| t["name"].as_str().unwrap())
.collect();
- assert_eq!(names.len(), 21);
+ assert_eq!(names.len(), 22);
for n in [
"xerj_def",
"xerj_search",
@@ -5483,23 +5501,23 @@ mod tests {
.collect()
};
let without = names(false);
- assert_eq!(without.len(), 18, "{without:?}");
+ assert_eq!(without.len(), 19, "{without:?}");
assert!(
without.iter().all(|n| !n.starts_with("xerj_hub_")),
"{without:?}"
);
let with = names(true);
- assert_eq!(with.len(), 21, "{with:?}");
+ assert_eq!(with.len(), 22, "{with:?}");
for n in ["xerj_hub_find", "xerj_hub_def", "xerj_hub_ask"] {
assert!(with.iter().any(|name| name == n), "missing {n}");
}
let help = tools_paragraph(false);
- assert!(help.contains("proxies 18 tools"), "{help}");
+ assert!(help.contains("proxies 19 tools"), "{help}");
assert!(!help.contains("xerj_hub_"), "{help}");
assert!(help.contains("~/xerj-data"), "{help}");
let help = tools_paragraph(true);
- assert!(help.contains("proxies 21 tools"), "{help}");
+ assert!(help.contains("proxies 22 tools"), "{help}");
assert!(help.contains("xerj_hub_ask"), "{help}");
assert!(help.contains("serves 3 Corpus Hub tools"), "{help}");
}
diff --git a/engine/crates/xerj-mcp/tests/batch_search.rs b/engine/crates/xerj-mcp/tests/batch_search.rs
new file mode 100644
index 000000000..3d93d601e
--- /dev/null
+++ b/engine/crates/xerj-mcp/tests/batch_search.rs
@@ -0,0 +1,341 @@
+//! The batch adapter preserves item boundaries across errors, misses and budgets.
+use std::sync::{Arc, Mutex};
+
+use axum::{routing::get, Json, Router};
+use serde_json::{json, Value};
+
+async fn call(url: &str, args: Value) -> Value {
+ let response = xerj_mcp::handle_message_for_test(
+ url,
+ Some("ApiKey batch-test".into()),
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
+ "params":{"name":"xerj_batch_search","arguments":args}}),
+ )
+ .await
+ .unwrap();
+ response["result"].clone()
+}
+
+fn body(result: &Value) -> Value {
+ assert_eq!(result["isError"], false, "{result}");
+ serde_json::from_str(result["content"][0]["text"].as_str().unwrap()).unwrap()
+}
+
+#[tokio::test]
+async fn batch_preserves_positions_errors_duplicates_and_exact_ids() {
+ let requests = Arc::new(Mutex::new(Vec::<String>::new()));
+ let seen = requests.clone();
+ let app = Router::new()
+ .route(
+ "/:index/_mapping",
+ get(|| async {
+ Json(json!({"docs":{"mappings":{"properties":{
+ "body":{"type":"text"},"advisory":{"type":"keyword"}
+ }}}}))
+ }),
+ )
+ .route(
+ "/_msearch",
+ axum::routing::post(move |headers: axum::http::HeaderMap, text: String| {
+ assert_eq!(headers["authorization"], "ApiKey batch-test");
+ assert_eq!(headers["content-type"], "application/x-ndjson");
+ seen.lock().unwrap().push(text.clone());
+ async move {
+ assert!(text.ends_with('\n'));
+ let lines: Vec<Value> = text
+ .lines()
+ .map(|s| serde_json::from_str(s).unwrap())
+ .collect();
+ let responses: Vec<Value> = lines.chunks_exact(2).map(|pair| {
+ assert_eq!(pair[0]["index"], "docs");
+ let q = pair[1]["query"].to_string();
+ if q.contains("missing") {
+ json!({"hits":{"total":{"value":0,"relation":"eq"},"hits":[]}})
+ } else if q.contains("broken") {
+ json!({"error":{"type":"test_error","reason":"invalid query"},"status":400})
+ } else {
+ json!({"hits":{"total":{"value":1,"relation":"eq"},"hits":[{
+ "_index":"docs","_id":"record-1","_source":{
+ "ax_path":"advisories.jsonl","ax_locator":"b100",
+ "body":"CVE-2026-12345 is the evidence"}}]}})
+ }
+ }).collect();
+ Json(json!({"responses":responses}))
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let result = body(
+ &call(
+ &url,
+ json!({"index":"docs","queries":[
+ {"key":"same","identifier":"CVE-2026-12345","field":"advisory"},
+ {"query":{"match":{"body":"missing"}}},
+ {"query":{"match":{"body":"broken"}}},
+ {"query":17},
+ {"key":"same","identifier":"CVE-2026-12345","field":"advisory"}
+ ]}),
+ )
+ .await,
+ );
+ let items = result["results"].as_array().unwrap();
+ assert_eq!(items.len(), 5);
+ for (i, item) in items.iter().enumerate() {
+ assert_eq!(item["position"], i);
+ }
+ assert_eq!(items[0]["status"], "hits");
+ assert_eq!(items[0]["abstain"], false);
+ assert_eq!(items[0]["hits"][0]["citation"]["ax_locator"], "b100");
+ assert_eq!(items[1]["status"], "abstain");
+ assert_eq!(items[1]["reason"], "no_hits");
+ assert_eq!(items[2]["status"], "error");
+ assert_eq!(items[3]["status"], "error");
+ assert_eq!(items[4]["hits"], items[0]["hits"]);
+ {
+ let requests = requests.lock().unwrap();
+ assert_eq!(
+ requests.len(),
+ 1,
+ "one HTTP search round trip for the batch"
+ );
+ let lines: Vec<Value> = requests[0]
+ .lines()
+ .map(|s| serde_json::from_str(s).unwrap())
+ .collect();
+ assert_eq!(lines.len(), 8, "invalid item never reaches the node");
+ assert_eq!(
+ lines[1]["query"],
+ json!({"term":{"advisory":"CVE-2026-12345"}})
+ );
+ }
+ server.abort();
+ let _ = server.await;
+}
+
+#[tokio::test]
+async fn batch_rejects_invalid_envelopes_before_network() {
+ for args in [
+ json!({"queries":[]}),
+ json!({"queries":"wrong"}),
+ json!({"queries":vec![json!({"query":"x"});51]}),
+ json!({"queries":[{"query":"x"}],"size":0}),
+ json!({"queries":[{"query":"x"}],"prefix":"x","index":"y"}),
+ ] {
+ let result = call("http://127.0.0.1:1", args).await;
+ assert_eq!(result["isError"], true, "{result}");
+ let text = result["content"][0]["text"].as_str().unwrap();
+ assert!(!text.contains("unknown tool"), "{text}");
+ assert!(
+ !text.contains("connect"),
+ "local validation must precede network: {text}"
+ );
+ }
+}
+
+async fn fixture(response: Value, args: Value) -> Value {
+ let app = Router::new().route(
+ "/_msearch",
+ axum::routing::post(move || {
+ let response = response.clone();
+ async move { Json(response) }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let result = call(&url, args).await;
+ server.abort();
+ let _ = server.await;
+ result
+}
+
+#[tokio::test]
+async fn batch_never_turns_failed_or_partial_searches_into_abstentions() {
+ let empty = json!({"hits":{"hits":[]}});
+ for response in [
+ json!({"responses":[{"status":503,"hits":{"hits":[]}},empty]}),
+ json!({"responses":[{"hits":{"total":{"value":1},"hits":[]}},empty]}),
+ json!({"responses":[{"timed_out":true,"hits":{"hits":[]}},empty]}),
+ json!({"responses":[{"_shards":{"failed":1},"hits":{"hits":[]}},empty]}),
+ json!({"responses":[{"unexpected":"shape"},empty]}),
+ json!({"responses":[{"hits":{"hits":[{"_source":{"body":"no identity"}}]}},empty]}),
+ ] {
+ let result = body(
+ &fixture(
+ response,
+ json!({"queries":[
+ {"query":{"match_all":{}}},{"query":{"match_all":{}}}
+ ]}),
+ )
+ .await,
+ );
+ assert_eq!(result["results"][0]["status"], "error", "{result}");
+ assert!(result["results"][0].get("abstain").is_none());
+ assert_eq!(result["results"][1]["status"], "abstain", "{result}");
+ }
+ for response in [
+ json!({"responses":[empty]}),
+ json!({"responses":[]}),
+ json!({"wrong":[]}),
+ ] {
+ let result = body(
+ &fixture(
+ response,
+ json!({"queries":[
+ {"query":{"match_all":{}}},{"query":{"match_all":{}}}
+ ]}),
+ )
+ .await,
+ );
+ assert!(result["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|r| r["status"] == "error"));
+ }
+}
+
+#[tokio::test]
+async fn batch_accepts_fifty_and_budget_never_loses_an_item() {
+ let hit = json!({"_index":"docs","_id":"1","_source":{"body":"word ".repeat(400)}});
+ let response = json!({"hits":{"hits":[hit]}});
+ let args = json!({"queries":vec![json!({"query":{"match_all":{}}});50],"max_tokens":3000});
+ let result = fixture(json!({"responses":vec![response;50]}), args).await;
+ let value = body(&result);
+ assert_eq!(value["results"].as_array().unwrap().len(), 50);
+ assert!(value["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|r| r["status"] == "hits"));
+ use unicode_segmentation::UnicodeSegmentation;
+ assert!(
+ result["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .unicode_words()
+ .count()
+ <= 3000
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn batch_exact_identifier_is_not_a_prefix_or_token_match_on_a_real_node() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = tmp.path().join("data").to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ config.auth.enabled = false;
+ let metrics = xerj_common::metrics::Metrics::new().unwrap();
+ let engine = xerj_engine::Engine::new(config.clone()).unwrap();
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ let app = xerj_api::router::build_es_compat_router(state);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ axum::serve(listener, app.into_make_service())
+ .await
+ .unwrap()
+ });
+ let client = reqwest::Client::new();
+ let response = client
+ .put(format!("{url}/advisories"))
+ .json(&json!({
+ "mappings":{"properties":{"id":{"type":"keyword"},"body":{"type":"text"},
+ "ax_path":{"type":"keyword"},"ax_locator":{"type":"keyword"}}}
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(
+ response.status().is_success(),
+ "{}",
+ response.text().await.unwrap()
+ );
+ for id in ["CVE-2026-12345", "CVE-2026-123456", "CVE-2025-12345"] {
+ let response = client.put(format!("{url}/advisories/_doc/{id}?refresh=true"))
+ .json(&json!({"id":id,"body":"advisory evidence","ax_path":"advisories.jsonl","ax_locator":id}))
+ .send().await.unwrap();
+ assert!(
+ response.status().is_success(),
+ "{}",
+ response.text().await.unwrap()
+ );
+ }
+ let result = body(
+ &call(
+ &url,
+ json!({"index":"advisories","queries":[
+ {"identifier":"CVE-2026-12345","field":"id"},
+ {"identifier":"CVE-2026-1234","field":"id"},
+ {"identifier":"CVE-2026-12345","field":"body"},
+ {"query":"advisory"},
+ {"identifier":"CVE-2026-12345","field":"absent"}
+ ]}),
+ )
+ .await,
+ );
+ assert_eq!(
+ result["results"][0]["hits"].as_array().unwrap().len(),
+ 1,
+ "{result}"
+ );
+ assert_eq!(
+ result["results"][0]["hits"][0]["hit"]["_source"]["id"],
+ "CVE-2026-12345"
+ );
+ assert_eq!(result["results"][1]["status"], "abstain");
+ assert_eq!(result["results"][2]["status"], "error");
+ assert_eq!(result["results"][3]["status"], "hits", "{result}");
+ assert_eq!(result["results"][4]["status"], "error");
+ server.abort();
+ let _ = server.await;
+}
+
+#[tokio::test]
+async fn binding_budget_counts_omitted_hits_and_keeps_the_first_citation() {
+ use unicode_segmentation::UnicodeSegmentation;
+ let response = json!({"responses":[{"hits":{"hits":[
+ {"_index":"docs","_id":"first","_source":{"body":"evidence ".repeat(400)}},
+ {"_index":"docs","_id":"second","_source":{"body":"evidence ".repeat(400)}}
+ ]}}]});
+ let mut args = json!({"queries":[{"query":{"match_all":{}}}]});
+ let mut skeleton = body(&fixture(response.clone(), args.clone()).await);
+ for hit in skeleton["results"][0]["hits"].as_array_mut().unwrap() {
+ hit.as_object_mut().unwrap().remove("hit");
+ }
+ skeleton["_token_budget"] = json!({"tokenizer":"standard-uax29-words","max_tokens":0});
+ // Add an immutable error outcome so the envelope is above the 32-word
+ // floor; choose a budget that fits all outcomes but not both citations.
+ args["queries"]
+ .as_array_mut()
+ .unwrap()
+ .push(json!({"query":17}));
+ let invalid = body(&fixture(json!({"responses":[]}), json!({"queries":[{"query":17}]})).await);
+ let mut error = invalid["results"][0].clone();
+ error["position"] = json!(1);
+ skeleton["results"].as_array_mut().unwrap().push(error);
+ let limit = skeleton.to_string().unicode_words().count() - 1;
+ assert!(limit >= 32);
+ args["max_tokens"] = json!(limit);
+ let result = fixture(response, args).await;
+ let value = body(&result);
+ assert_eq!(
+ value["results"][0]["hits"].as_array().unwrap().len(),
+ 1,
+ "{value}"
+ );
+ assert_eq!(value["results"][0]["hits_omitted"], 1);
+ assert_eq!(value["results"][0]["hits"][0]["citation"]["_id"], "first");
+ assert_eq!(value["results"][1]["status"], "error");
+ assert!(
+ result["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .unicode_words()
+ .count()
+ <= limit
+ );
+}
diff --git a/engine/crates/xerj-rerank/tests/egress_inventory.rs b/engine/crates/xerj-rerank/tests/egress_inventory.rs
index 33886278e..74eb0e1d8 100644
--- a/engine/crates/xerj-rerank/tests/egress_inventory.rs
+++ b/engine/crates/xerj-rerank/tests/egress_inventory.rs
@@ -80,6 +80,13 @@ const KNOWN: &[(&str, Role)] = &[
Role::Node("**Cluster transport**"),
),
("xerj-mcp/src/lib.rs", Role::Client("`xerj mcp`")),
+ // Batch retrieval uses the same operator-selected node URL and auth as
+ // `xerj mcp` (localhost:9200 by default). It sends queries to /_msearch
+ // and optionally reads mappings; it adds no node-side egress path.
+ (
+ "xerj-mcp/src/batch_cli.rs",
+ Role::Client("`xerj batch-search`"),
+ ),
(
"xerj-autoindex/src/esclient.rs",
Role::Client("`xerj autoindex`"),
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 974c45044..99ad847f8 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -172,6 +172,7 @@ fn is_top_level_command(arg: &str) -> bool {
arg,
"index"
| "search"
+ | "batch-search"
| "def"
| "init"
| "gain"
@@ -446,6 +447,7 @@ fn help_text(feedback: bool) -> String {
\x20\x20\x20\x20--version, -V Print version and exit\n\
\n\
SUBCOMMANDS:\n\
+ \x20\x20\x20\x20xerj batch-search --input FILE ordered batch retrieval, JSON in/out (see xerj batch-search --help)\n\
\x20\x20\x20\x20xerj index <opts> direct NDJSON → engine ingest (see xerj index --help)\n\
\x20\x20\x20\x20xerj autoindex <folder> [opts] zero-config folder discovery + indexing (see xerj autoindex --help)\n\
\x20\x20\x20\x20xerj autoindex map print the discovered data map\n\
@@ -2915,6 +2917,14 @@ fn main() -> Result<()> {
let rt = build_runtime(2)?;
return rt.block_on(xerj_mcp::run(&args));
}
+ if matches!(
+ xerj_common::argv::subcommand().as_deref(),
+ Some("batch-search")
+ ) {
+ let args = xerj_common::argv::args_after_subcommand();
+ let rt = build_runtime(2)?;
+ std::process::exit(rt.block_on(xerj_mcp::run_batch_cli(&args)));
+ }
// Cores from the resource policy, so `XERJ_NUM_CPUS` and a container CPU
// quota reach the async runtime the same way they reach every pool (#240).
let cores = xerj_common::resource::cores();
@@ -3491,13 +3501,13 @@ mod decide_flag_tests {
#[test]
fn help_counts_the_mcp_tools_actually_served() {
// The count is `tool_specs()`, the same list `tools/list` returns:
- // eighteen without a hub key, twenty-one with the three hub tools.
+ // nineteen without a hub key, twenty-two with the three hub tools.
let served = super::mcp_tool_count();
if xerj_common::hub::hub_key_configured() {
- assert_eq!(served, 21, "tool_specs() with a hub key: {served}");
+ assert_eq!(served, 22, "tool_specs() with a hub key: {served}");
} else {
assert_eq!(
- served, 18,
+ served, 19,
"a no-key process must not count the hub tools it does not serve"
);
}
diff --git a/engine/crates/xerj-server/tests/batch_search_cli.rs b/engine/crates/xerj-server/tests/batch_search_cli.rs
new file mode 100644
index 000000000..556f287dd
--- /dev/null
+++ b/engine/crates/xerj-server/tests/batch_search_cli.rs
@@ -0,0 +1,97 @@
+//! Real installed-shape CLI and MCP must return the same batch contract.
+use std::process::Stdio;
+
+use axum::{routing::post, Json, Router};
+use serde_json::{json, Value};
+use tokio::io::AsyncWriteExt;
+
+#[tokio::test]
+async fn cli_stdin_file_and_mcp_agree_and_item_errors_have_exit_three() {
+ let app = Router::new().route(
+ "/_msearch",
+ post(|| async {
+ Json(json!({"responses":[
+ {"hits":{"hits":[{"_index":"docs","_id":"1","_source":{"body":"evidence"}}]}},
+ {"error":{"reason":"bad query"},"status":400}
+ ]}))
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let input = json!({"index":"docs","queries":[{"query":{"match_all":{}}},{"query":{"bad":{}}}]});
+ let mcp = xerj_mcp::handle_message_for_test(
+ &url,
+ None,
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
+ "params":{"name":"xerj_batch_search","arguments":input}}),
+ )
+ .await
+ .unwrap();
+ let expected: Value =
+ serde_json::from_str(mcp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("queries.json");
+ std::fs::write(&path, input.to_string()).unwrap();
+ for file in ["-".to_string(), path.to_string_lossy().into_owned()] {
+ let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .args([
+ "--url",
+ &url,
+ "batch-search",
+ "--input",
+ &file,
+ "--disable-feedback",
+ ])
+ .env("XERJ_DISABLE_FEEDBACK", "true")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ let mut stdin = child.stdin.take().unwrap();
+ if file == "-" {
+ stdin.write_all(input.to_string().as_bytes()).await.unwrap();
+ }
+ drop(stdin);
+ let out = child.wait_with_output().await.unwrap();
+ assert_eq!(
+ out.status.code(),
+ Some(3),
+ "{}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ assert_eq!(
+ serde_json::from_slice::<Value>(&out.stdout).unwrap(),
+ expected
+ );
+ }
+ server.abort();
+ let _ = server.await;
+}
+
+#[test]
+fn cli_help_and_malformed_input_never_start_a_node() {
+ let help = std::process::Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .args(["batch-search", "--help", "--disable-feedback"])
+ .output()
+ .unwrap();
+ assert!(help.status.success());
+ assert!(String::from_utf8_lossy(&help.stdout).contains("1..50"));
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("invalid.json");
+ std::fs::write(&path, r#"{"queries":[]}"#).unwrap();
+ let out = std::process::Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .args([
+ "batch-search",
+ "--input",
+ path.to_str().unwrap(),
+ "--url",
+ "http://127.0.0.1:1",
+ ])
+ .output()
+ .unwrap();
+ assert_eq!(out.status.code(), Some(2));
+ assert!(out.stdout.is_empty());
+ assert!(String::from_utf8_lossy(&out.stderr).contains("1..50"));
+}
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index cee820196..39804f094 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -45,6 +45,90 @@
]
}
},
+ {
+ "name": "xerj_batch_search",
+ "description": "Search 1..50 IDs or questions in one call, in input order. Shares the CLI xerj batch-search adapter. Each result has its zero-based position, optional caller key, and status hits, abstain (only a complete empty search), or error. Hits carry citations: index/id plus file/line or record locator when available. This retrieves evidence, not generated answers or calibrated confidence. Use identifier plus an explicitly keyword-mapped field for exact IDs; query takes plain text or an ES query clause. One bad item never discards its siblings; identical inputs remain separate. Uses one _msearch request, plus at most one mapping read. Optional max_tokens caps the entire successful JSON response using StandardTokenizer UAX #29 words, not BPE. Budgeting removes raw hit bodies, then extra hits, retaining each item's status and at least one citation per matched item. If that minimum cannot fit, returns an actionable tool error, never truncated JSON or a false abstention. Errors are not truncated.",
+ "inputSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "queries": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 50,
+ "description": "Ordered queries. Duplicate keys are allowed; position is authoritative. Entire input is limited to 1 MiB.",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "key": {
+ "type": "string",
+ "description": "Optional correlation key, at most 256 UTF-8 bytes."
+ },
+ "query": {
+ "oneOf": [
+ {
+ "type": "string",
+ "minLength": 1
+ },
+ {
+ "type": "object"
+ }
+ ],
+ "description": "Plain text or ES query clause. Cannot be combined with identifier/field."
+ },
+ "identifier": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Exact value, used verbatim in a term query; requires field."
+ },
+ "field": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Flat keyword field for identifier. Must be mapped as keyword wherever present; unreadable, absent or conflicting mappings fail this item."
+ }
+ },
+ "oneOf": [
+ {
+ "required": [
+ "query"
+ ]
+ },
+ {
+ "required": [
+ "identifier",
+ "field"
+ ]
+ }
+ ]
+ }
+ },
+ "index": {
+ "type": "string",
+ "description": "Index or pattern; alternative to prefix. Defaults to ax-*."
+ },
+ "prefix": {
+ "type": "string",
+ "description": "Autoindex prefix, e.g. project searches project-*. Cannot combine with index."
+ },
+ "size": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 50,
+ "default": 3,
+ "description": "Maximum hits per item."
+ },
+ "max_tokens": {
+ "type": "integer",
+ "minimum": 32,
+ "description": "Whole-response budget counted with XERJ's StandardTokenizer (UAX #29 word boundaries) (not BPE); minimum 32. A successful response NEVER exceeds it. Preserves ordered item outcomes and at least one citation per matched item, removing raw bodies first. Refuses if that minimum cannot fit; split the batch or increase the budget. Errors are outside this budget."
+ }
+ },
+ "required": [
+ "queries"
+ ]
+ }
+ },
{
"name": "xerj_search",
"description": "Full-text / keyword / structured search over a XERJ index. Proxies POST /{index}/_search. Pass `prefix` (a `xerj search --prefix` value, resolved by that command) or `index` (a name or pattern) — not both; with neither, searches `ax-*`. Pass `query` as a PLAIN STRING for the definition-first code search (ranks the file that defines a symbol above files that merely mention it — the right default for code), or as an ES query-DSL object (e.g. {\"term\":{\"status\":\"open\"}}, or a bool clause) for structured queries. Omit `query` for match_all. Optional `rerank` adds a second stage that re-judges the top hits with an external relevance model — read that argument's description before using it: it needs a provider the operator configured, and it sends document text off the machine. Optional `judge` re-judges the returned hits LOCALLY (zero tokens, nothing leaves the node) and adds a `_p_relevant` probability per hit — see that argument's description for its honest ceiling. Each hit carries `match_line` when a query term sits in the passage: the absolute 1-based source line of the best-scoring match (a tie takes the earliest line), and `match_lines` for every matched line (capped). Cite `path:match_line`. Both are omitted when no term is located or the passage start line is unknown. `start_line` remains the passage start. Pass `max_tokens` to cap the response at a token budget (never exceeded; see that argument for the tokenizer and the locator-only rule).",