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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
Complete the MCP compatibility and executable contract audit
xerj-org27b689dc3923
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 53e2acf5f..c36417c1f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -859,6 +859,9 @@ jobs:- name: Local definition CLI and MCP parityrun: python3 scripts/mcp-def-smoke.py engine/target/ci-test/xerj+ - name: MCP query compatibility and default response budget+ run: python3 scripts/mcp-search-contract-smoke.py engine/target/ci-test/xerj+- name: MCP authentication discovery diagnosticsrun: python3 scripts/auth-discovery-smoke.py engine/target/ci-test/xerjdiff --git a/README.md b/README.mdindex 259f905b4..cae920eff 100644--- a/README.md+++ b/README.md@@ -491,7 +491,7 @@ the other direction: it hosts an MCP endpoint other agents connect to, and its stheir servers from the harness underneath. Grok Bot has no documented local stdio registration; theGrok CLI does, which is the `grok` row above.-Twenty-one tools are exposed. Eleven are thin proxies over an endpoint XERJ already serves:+Twenty-three tools are exposed when Hub tools are enabled. Eleven are thin proxies over an endpoint XERJ already serves:| Tool | What it does ||---|---|@@ -511,12 +511,17 @@ pattern instead; non-empty `index` and `prefix` cannot be combined. An emptyprefix, a prefix with no `[a-z0-9]` character, or a prefix that cannot name anindex is an error. With neither argument, the tool searches `ax-*`.-`query` is a plain string, and a structured ES query-DSL clause goes in-`query_dsl` instead — `{"index":"docs","query_dsl":{"match_all":{}}}`. One of-the two is required and they cannot be combined, so a call with neither is an-error naming both rather than a silent `match_all` that returns nothing. The-fields are separate because a union-typed `query` (`["object","string"]`) is-what made some models emit invalid arguments for this tool alone (#2549).+For new callers, `query` is a plain string and structured ES query-DSL goes in+`query_dsl` — `{"index":"docs","query_dsl":{"match_all":{}}}`. Do not combine+both fields. The published schema separates the types to simplify tool calls+(#2549); it cannot guarantee a model emits valid JSON. Existing callers may+still pass an object in `query`, and omitting both fields retains `match_all`+browsing. Prefer an explicit `query_dsl` clause when browsing is intended.++Search tools and `xerj batch-search` default to an 8,000 UAX #29 word budget+when `max_tokens` is omitted or null. A larger integer requests more evidence;+accounting explains any trimming. This is not a byte cap or a model/BPE token+limit. Errors remain untruncated.`xerj_def` finds local definitions with the same query, ranking and location deduplicationas `xerj def --json`. For example, `{"symbol":"Cache","prefix":"project","kind":"struct","lang":"rust","k":5}`@@ -535,6 +540,10 @@ reference-coding pipeline ([`tools/xerj-code/`](tools/xerj-code/)) and returns i`xerj_index_budget` counts a folder and estimates its index against the node's disk budgetbefore `xerj autoindex` hashes anything (it does not index). `xerj_autoindex_remove` dropsone autoindexed folder after listing it, and deletes nothing unless `confirm` is true.+`xerj_status` probes the node banner, cluster health and visible indices with+up to three bounded reads. A missing autoindex catalog does not mean the node+has no data; refused or malformed probes remain errors or unknown status.+`xerj_batch_search` retrieves ordered batches with per-item outcomes and citations.`xerj_corpus_feedback` rates a hub corpus.`xerj_field_report` files a field report, and `xerj_hub_find`, `xerj_hub_def` and `xerj_hub_ask`answer from Corpus Hub packs already on the machine (the `xerj ask` flow).diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 04840a0c0..5694c88cc 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -984,7 +984,8 @@ pub fn tool_specs_with(include_hub: bool) -> Value {"query": {"type": "string","description": "What to search for, in plain words — the definition-first code search \- `xerj search` runs. REQUIRED unless you pass `query_dsl` instead."+ `xerj search` runs. Use `query_dsl` for a structured clause. Omit both for \+ legacy match_all browsing; explicit query_dsl: {match_all: {}} is clearer."},"query_dsl": {"type": "object",@@ -2077,6 +2078,9 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {Ok(index) => index,Err(msg) => return tool_text(msg, true),};+ if let Err(msg) = search_query(&args) {+ return tool_text(msg, true);+ }// #1961: a plain-string query is shaped from the target's mapping,// exactly like `xerj search` (#1602). Without this, a prose corpus// answers HTTP 400 `strict_unknown_fields` because the body names@@ -2552,6 +2556,32 @@ fn search_index(args: &Value) -> Result<String, String> {}}+/// Resolve the new query fields before any mapping request while accepting+/// legacy object-valued `query` and omitted-query browsing.+fn search_query(args: &Value) -> Result<Option<&Value>, String> {+ let dsl = match args.get("query_dsl") {+ None | Some(Value::Null) => None,+ Some(v @ Value::Object(_)) => Some(v),+ Some(_) => return Err(+ "`query_dsl` must be a JSON object, for example {\"query_dsl\": {\"match_all\": {}}}"+ .into(),+ ),+ };+ let query = args.get("query").filter(|v| !v.is_null());+ if dsl.is_some() && query.is_some() {+ return Err(+ "pass either `query` (plain words) or `query_dsl` (an ES query-DSL clause), not both"+ .into(),+ );+ }+ match dsl.or(query) {+ None => Ok(None),+ Some(v @ Value::Object(_)) => Ok(Some(v)),+ Some(v @ Value::String(q)) if !q.trim().is_empty() => Ok(Some(v)),+ Some(_) => Err("`query` must be non-empty plain search text; use `query_dsl` for a structured ES query-DSL clause, for example {\"query_dsl\": {\"match_all\": {}}}".into()),+ }+}+/// [`build_search`] with the target's `GET /{index}/_mapping` body (#1961).////// A plain-string query is shaped by `xerj_common::code_query` — the same@@ -2566,64 +2596,22 @@ fn build_search_with_mapping(let index = search_index(args)?;let mut body = serde_json::Map::new();let mut plain_string = false;- // #2549: `query` is a plain string and `query_dsl` is the structured- // variant, so neither is union-typed. A model whose function-calling- // serialized a string into the old `["object", "string"]` field unquoted- // produced invalid JSON on one transport and `{}` on another, while every- // scalar-schema sibling tool round-tripped. The two fields are also- // mutually exclusive and one of them is required, so an empty-argument- // call fails loudly instead of searching for nothing and returning 0 hits.- let dsl = match args.get("query_dsl") {- None | Some(Value::Null) => None,- Some(v @ Value::Object(_)) => Some(v),- Some(_) => {- return Err("`query_dsl` must be a JSON object, for example \- {\"query_dsl\": {\"match_all\": {}}}"- .into())+ match search_query(args)? {+ Some(Value::String(q)) if !q.trim().is_empty() => {+ plain_string = true;+ // The same mapping-aware, definition-first shape as `xerj search`.+ let mapped = mapping.and_then(mapped_property_names);+ let numeric = mapping.map(numeric_property_names);+ let built = search_query_body_for_mapping(q, 10, mapped.as_ref(), numeric.as_ref());+ body.insert("query".into(), built["query"].clone());}- };- let plain = match args.get("query") {- None | Some(Value::Null) => None,- Some(Value::String(q)) if q.trim().is_empty() => None,- Some(Value::String(q)) => Some(q.clone()),- Some(_) => {- return Err(- "`query` must be plain search text; pass a structured ES query-DSL \- clause as `query_dsl`, for example {\"query_dsl\": {\"match_all\": {}}}"- .into(),- )+ Some(q @ Value::Object(_)) => {+ body.insert("query".into(), q.clone());}- };- if let Some(dsl) = dsl {- if plain.is_some() {- return Err(- "pass either `query` (plain words) or `query_dsl` (an ES query-DSL \- clause), not both"- .into(),- );+ None => {+ body.insert("query".into(), json!({ "match_all": {} }));}- body.insert("query".into(), dsl.clone());- } else if let Some(q) = plain {- // A plain string gets the definition-first shape `xerj search` uses- // (measured 38%→94% correct-file-at-rank-1 on cross-file lookups vs a- // bare body match). Agents should never have to hand-write ES DSL for- // the common "find me this code" case; `query_dsl` stays available for- // structured queries.- plain_string = true;- // #1961: the mapping-aware body the CLI builds (#1601/#1602),- // including the #1759 exact-phrase leg. A prose corpus drops the- // `defs`/`name` clauses instead of 400ing on them; a code corpus- // (or an unreadable mapping) keeps the historical shape. `10`- // only fills the discarded `size` member.- let mapped = mapping.and_then(mapped_property_names);- let numeric = mapping.map(numeric_property_names);- let built = search_query_body_for_mapping(&q, 10, mapped.as_ref(), numeric.as_ref());- body.insert("query".into(), built["query"].clone());- } else {- return Err("pass `query` (plain words, e.g. {\"query\": \"rotate keys\"}) or \- `query_dsl` (an ES query-DSL clause, e.g. {\"query_dsl\": {\"match_all\": {}}}); \- a search with neither returns nothing, so it is an error"- .into());+ Some(_) => return Err("`query` must be non-empty plain search text; use `query_dsl` for a structured ES query-DSL clause, for example {\"query_dsl\": {\"match_all\": {}}}".into()),}if let Some(n) = opt_u64(args, "size")? {body.insert("size".into(), json!(n));@@ -4217,42 +4205,58 @@ mod tests {assert!(body["query"].is_object(), "{body}");}- /// #2549: `query` is a plain string and the ES DSL moved to `query_dsl`,- /// so neither field is union-typed. A model that serialized a string into- /// the old `["object", "string"]` field unquoted sent invalid JSON on one- /// transport and `{}` on another; a call with no query at all is now an- /// error naming both fields instead of a silent 0-hit `match_all`.#[test]- fn search_names_the_missing_or_mistyped_query() {- let err = build_search(&json!({ "index": "docs" })).unwrap_err();- assert!(- err.contains("`query`") && err.contains("`query_dsl`"),- "{err}"+ fn search_defaults_to_match_all_and_retains_legacy_dsl() {+ for args in [json!({}), json!({"index":"docs"}), json!({"query":null})] {+ let (_, _, body) = built(build_search(&args));+ assert_eq!(body["query"], json!({"match_all":{}}));+ }+ let clause = json!({"bool":{"filter":{"term":{"kind":"guide"}},"must_not":{"term":{"hidden":true}}}});+ let (_, _, old) = built(build_search(+ &json!({"index":"docs","query":clause,"size":2,"from":1}),+ ));+ let (_, _, new) = built(build_search(+ &json!({"index":"docs","query_dsl":clause,"size":2,"from":1}),+ ));+ assert_eq!(old["query"], clause);+ assert_eq!(+ new, old,+ "the new DSL field must preserve structured query semantics");+ }- let err = build_search(&json!({ "index": "docs", "query": " " })).unwrap_err();- assert!(err.contains("`query_dsl`"), "{err}");+ #[test]+ fn search_names_mistyped_or_conflicting_query_fields() {+ for bad in [json!(" "), json!(42), json!(false), json!([])] {+ let err = build_search(&json!({"query":bad})).unwrap_err();+ assert!(+ err.contains("`query`") && err.contains("`query_dsl`"),+ "{err}"+ );+ }+ for query in [json!("rust"), json!(""), json!({"match_all":{}})] {+ let err =+ build_search(&json!({"query":query,"query_dsl":{"match_all":{}}})).unwrap_err();+ assert!(err.contains("not both"), "{err}");+ }+ let err = build_search(&json!({"query_dsl":"match_all"})).unwrap_err();+ assert!(err.contains("must be a JSON object"), "{err}");+ }- let err = build_search(&json!({- "index": "docs",- "query": { "match": { "body": "rust" } }- }))- .unwrap_err();- assert!(- err.contains("`query_dsl`") && err.contains("must be plain search text"),- "{err}"+ #[test]+ fn search_advertises_distinct_query_types_without_removing_legacy_runtime() {+ let specs = tool_specs_with(true);+ let spec = specs+ .as_array()+ .unwrap()+ .iter()+ .find(|t| t["name"] == "xerj_search")+ .unwrap();+ assert_eq!(spec["inputSchema"]["properties"]["query"]["type"], "string");+ assert_eq!(+ spec["inputSchema"]["properties"]["query_dsl"]["type"],+ "object");-- let err = build_search(&json!({- "index": "docs",- "query": "rust",- "query_dsl": { "match_all": {} }- }))- .unwrap_err();- assert!(err.contains("not both"), "{err}");-- let err = build_search(&json!({ "index": "docs", "query_dsl": "match_all" })).unwrap_err();- assert!(err.contains("must be a JSON object"), "{err}");}#[test]diff --git a/scripts/mcp-search-contract-smoke.py b/scripts/mcp-search-contract-smoke.pynew file mode 100644index 000000000..911d818e2--- /dev/null+++ b/scripts/mcp-search-contract-smoke.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""Exercise search query compatibility and default budgets through real MCP stdio.++Usage: python3 scripts/mcp-search-contract-smoke.py engine/target/ci-test/xerj+Only an isolated HTTP fixture is contacted; no index or external service is used.+"""+import json+from pathlib import Path+import subprocess+import sys+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+++def main():+ binary = str(Path(sys.argv[1]).resolve(strict=True))+ requests = []+ hits = [{"_index": "docs", "_id": str(i), "_source": {+ "body": "search evidence " * 500, "path": f"source/{i}.txt",+ }} for i in range(20)]++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_):+ pass++ def respond(self, body):+ data = json.dumps(body).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ requests.append(("GET", self.path, None))+ self.respond({"docs": {"mappings": {"properties": {"body": {"type": "text"}}}}})++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append(("POST", self.path, body))+ selected = [] if self.path == "/autoindex-catalog/_search" else hits+ self.respond({"hits": {"total": {"value": len(selected)}, "hits": selected}})++ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ url = f"http://127.0.0.1:{server.server_port}"++ def call(args):+ requests.clear()+ messages = [+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},+ {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {+ "name": "xerj_search", "arguments": args}},+ ]+ run = subprocess.run([binary, "mcp", "--url", url, "--auth", "ApiKey fixture",+ "--disable-feedback"], text=True, capture_output=True,+ input="".join(json.dumps(m) + "\n" for m in messages),+ check=True, timeout=30)+ reply = next(m for m in map(json.loads, run.stdout.splitlines()) if m.get("id") == 2)+ return reply["result"]++ def successful(args):+ result = call(args)+ assert result["isError"] is False, result+ return json.loads(result["content"][0]["text"])++ try:+ clause = {"bool": {"filter": {"term": {"kind": "guide"}}}}+ for field in ("query_dsl", "query"):+ response = successful({"index": "docs", field: clause, "max_tokens": 100000})+ assert requests == [("POST", "/docs/_search", {"query": clause})], requests+ assert response["hits"]["hits"] == hits, "nonbinding budget must retain full evidence"+ print("PASS new query_dsl and legacy object query send identical structured requests")++ for args, path in [({"index": "docs"}, "/docs/_search"), ({}, "/ax-*/_search")]:+ successful(args)+ searches = [r for r in requests if r[1] == path]+ assert len(searches) == 1 and searches[0][2]["query"] == {"match_all": {}}, requests+ print("PASS omitted-query browsing and default scope remain available")++ for args in ({"query": "rust", "query_dsl": clause},+ {"query": clause, "query_dsl": clause},+ {"query_dsl": "not an object"}, {"query": 42}):+ response = call(args)+ assert response["isError"] is True, response+ assert not requests, "invalid arguments must fail before any node request"+ print("PASS conflicting and mistyped query fields refuse before HTTP")++ for extra in ({}, {"max_tokens": None}):+ response = successful({"index": "docs", "query_dsl": clause, **extra})+ accounting = response["_token_budget"]+ assert accounting["max_tokens"] == 8000 and accounting["tokens_used"] <= 8000, accounting+ print("PASS absent/null budget applies 8000 words with explicit trimming accounting")+ finally:+ server.shutdown()+ thread.join(timeout=5)+++if __name__ == "__main__":+ main()