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): expose local definition lookup (#2080)

Jarvisdf61f3b52dfa
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bec6f99d6..82b8d2a34 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -851,6 +851,9 @@ jobs:
working-directory: engine
run: cargo build --profile ci-test -p xerj-server -p xerj-mcp
+ - name: Local definition CLI and MCP parity
+ run: python3 scripts/mcp-def-smoke.py engine/target/ci-test/xerj
+
# Drives the demo/usecases scripts themselves, so the thing CI gates is
# the same thing a reader runs. No browser, no model, no network.
- name: Use-case smoke (brain transcript, MCP tools, autoindex discovery)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14d85bf9a..aa623ccec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- MCP `xerj_def` exposes local definition lookup, completing #2080 after the
+ `xerj_search` prefix support. It shares `xerj def --json` query construction,
+ mapping guards, ranking and location deduplication; accepts `symbol`,
+ `prefix`/`index`, `kind`, `lang`, `k` (1–50) and `max_tokens`. No match is a
+ successful empty hit list; invalid arguments are rejected before HTTP.
+
- MCP `xerj_search` accepts `prefix` as an alternative to `index`, matching
`xerj search --prefix`: `project` searches `project-*`. Conflicting scope
arguments and empty or non-string prefixes are rejected before HTTP requests.
diff --git a/README.md b/README.md
index e916ff0be..d2a57cdbe 100644
--- a/README.md
+++ b/README.md
@@ -453,7 +453,7 @@ the other direction: it hosts an MCP endpoint other agents connect to, and its s
their servers from the harness underneath. Grok Bot has no documented local stdio registration; the
Grok CLI does, which is the `grok` row above.
-Twenty tools are exposed. Eleven are thin proxies over an endpoint XERJ already serves:
+Twenty-one tools are exposed. Eleven are thin proxies over an endpoint XERJ already serves:
| Tool | What it does |
|---|---|
@@ -471,6 +471,17 @@ index name or pattern instead; non-empty `index` and `prefix` cannot be combined
The prefix is trimmed and must be non-empty. With neither argument, the tool
searches `ax-*`.
+`xerj_def` finds local definitions with the same query, ranking and location deduplication
+as `xerj def --json`. For example, `{"symbol":"Cache","prefix":"project","kind":"struct","lang":"rust","k":5}`
+searches `project-*`; `index` can replace `prefix`, with the same scope rules as `xerj_search`.
+`symbol` also accepts capability phrases. `k` must be 1–50 (default 5); optional `max_tokens`
+caps the response. Results are ES JSON: declarations live in `hits.hits[]._source.code`,
+locations in `ax_path`/`path` and `line`/`start_line`; older file hits may use `fields._passage`.
+`hits.total` counts engine matches before deduplication. No match returns an empty hit list.
+As in the CLI, kind/language filters are ignored when no target index maps the field
+or any target index maps it as numeric. Ranking is lexical. This tool queries the configured node;
+`xerj_hub_def` instead looks up definitions in a named Hub pack.
+
Two more are not plain proxies: `xerj_map` returns the per-index field map from the autoindex
catalog (trimmed to a byte cap, otherwise verbatim), and `xerj_code_search` runs the `xerj code`
reference-coding pipeline ([`tools/xerj-code/`](tools/xerj-code/)) and returns its rendered text.
diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rs
index 9f68b8b6c..4eb6f216e 100644
--- a/engine/crates/xerj-autoindex/src/def.rs
+++ b/engine/crates/xerj-autoindex/src/def.rs
@@ -172,6 +172,46 @@ fn def_query(
built
}
+/// Build the CLI/MCP definition query, including the wider local-rerank window.
+/// An unreadable mapping keeps the historical code query; numeric fields on
+/// any index in the scope are excluded from text lookups and filters.
+pub fn definition_query(
+ query: &str,
+ kind: Option<&str>,
+ lang: Option<&str>,
+ k: usize,
+ mapping: Option<&Value>,
+) -> Value {
+ let mapped = mapping.and_then(mapped_property_names);
+ let numeric = mapped.as_ref().and(mapping.map(numeric_property_names));
+ def_query(
+ query,
+ kind,
+ lang,
+ def_collect_size(k),
+ mapped.as_ref(),
+ numeric.as_ref(),
+ )
+}
+
+/// Rank the fetched window, keep the best hit per location, and return `k`
+/// definitions. Only `hits.hits` is replaced: totals still describe engine
+/// matches before deduplication, just as in `xerj def --json`.
+pub fn finalize_definition_response(response: &mut Value, k: usize) -> Vec<Value> {
+ let mut hits = response
+ .pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ rerank_def_hits(&mut hits);
+ let mut hits = unique_locations(hits);
+ hits.truncate(k);
+ if let Some(slot) = response.pointer_mut("/hits/hits") {
+ *slot = Value::Array(hits.clone());
+ }
+ hits
+}
+
fn build_def_query(
query: &str,
kind: Option<&str>,
@@ -522,9 +562,6 @@ pub fn run_def_cli() -> i32 {
let pattern = format!("{prefix}-*");
let raw_mapping = es.get_json(&format!("/{pattern}/_mapping")).ok();
let mapped = raw_mapping.as_ref().and_then(mapped_property_names);
- let numeric = mapped
- .as_ref()
- .and(raw_mapping.as_ref().map(numeric_property_names));
if let Some(set) = mapped.as_ref().filter(|s| !s.is_empty()) {
if kind.is_some() && !set.contains("kind") {
eprintln!("xerj def: --kind ignored; no index under this prefix maps `kind`");
@@ -533,17 +570,13 @@ pub fn run_def_cli() -> i32 {
eprintln!("xerj def: --lang ignored; no index under this prefix maps `language`");
}
}
- let mut body = def_query(
+ let body = definition_query(
&query,
kind.as_deref(),
lang.as_deref(),
k,
- mapped.as_ref(),
- numeric.as_ref(),
+ raw_mapping.as_ref(),
);
- // Fetch a window wider than `-k`, then rerank locally. The engine's
- // function_score path scored every match (422ms vs 6ms on tokio).
- body["size"] = json!(def_collect_size(k));
let mut resp = match es.search(&pattern, &body) {
Ok(v) => v,
Err(e) => {
@@ -552,20 +585,7 @@ pub fn run_def_cli() -> i32 {
}
};
- let mut hits = resp
- .pointer("/hits/hits")
- .and_then(Value::as_array)
- .cloned()
- .unwrap_or_default();
- // Rerank the wide window locally, then collapse duplicate locations and
- // trim to `-k`. Dedupe after rerank so the best-ranked hit at each
- // path:line is the one kept.
- rerank_def_hits(&mut hits);
- let mut hits = unique_locations(hits);
- hits.truncate(k);
- if let Some(slot) = resp.pointer_mut("/hits/hits") {
- *slot = Value::Array(hits.clone());
- }
+ let hits = finalize_definition_response(&mut resp, k);
if as_json {
println!(
diff --git a/engine/crates/xerj-mcp/src/def.rs b/engine/crates/xerj-mcp/src/def.rs
new file mode 100644
index 000000000..c7c217804
--- /dev/null
+++ b/engine/crates/xerj-mcp/src/def.rs
@@ -0,0 +1,113 @@
+//! Local `xerj def` adapter. The CLI owns the query and result ordering;
+//! this module validates MCP arguments and uses the configured node/auth.
+use serde_json::{json, Value};
+use xerj_autoindex::def::{definition_query, finalize_definition_response};
+
+use crate::{
+ engine_request, fetch_mapping, opt_u64, search_index, token_budget, tool_text, Ctx, Method,
+};
+
+pub(crate) fn spec() -> Value {
+ json!({
+ "name": "xerj_def",
+ "description": concat!(
+ "Find a symbol's definition in local autoindexed data, like `xerj def --json`. ",
+ "Lexical ranking, not neural: shares the CLI's mapping-aware query, preferred-kind ",
+ "and public-declaration ranking, location deduplication and bounded candidate window. ",
+ "Returns ES JSON with declarations in hits.hits[]._source.code and locations in ",
+ "ax_path/path plus line/start_line (page/cell for documents); older file-level hits ",
+ "may carry fields._passage instead. hits.total counts engine matches before deduplication. ",
+ "No match is a successful empty hits list. Unlike xerj_hub_def, this queries the ",
+ "configured node, not a Hub pack. Optional max_tokens caps the response; see its ",
+ "tokenizer and locator-only rule."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "symbol": {"type":"string", "minLength":1,
+ "description":"Symbol name or capability phrase, as in `xerj def Cache`. Must not be blank."},
+ "prefix": {"type":"string",
+ "description":"Autoindex prefix: project searches project-*. Trimmed, must not be empty. Cannot be combined with a non-empty index. Defaults to ax when neither scope is given."},
+ "index": {"type":"string",
+ "description":"Explicit index name or pattern instead of prefix, as in xerj_search. A blank string is treated as absent."},
+ "kind": {"type":"string",
+ "description":"Symbol kind, e.g. function, struct or class. Like the CLI, ignored when no index maps kind or any maps it as numeric."},
+ "lang": {"type":"string",
+ "description":"Language, e.g. rust or python. Like the CLI, ignored when no index maps language or any maps it as numeric."},
+ "k": {"type":"integer", "minimum":1, "maximum":50, "default":5,
+ "description":"Maximum unique definitions to return (1..=50, default 5)."},
+ "max_tokens": crate::max_tokens_arg_schema()
+ },
+ "required":["symbol"]
+ }
+ })
+}
+
+fn optional_text<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, String> {
+ match args.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(s)),
+ _ => Err(format!("`{key}` must be a non-empty string")),
+ }
+}
+
+pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {
+ // Validate all locally knowable inputs before the first mapping request.
+ let validated = (|| {
+ let symbol = optional_text(args, "symbol")?
+ .ok_or("`symbol` is required, for example {\"symbol\":\"Cache\"}")?;
+ if args
+ .get("index")
+ .is_some_and(|v| !v.is_null() && !v.is_string())
+ {
+ return Err("`index` must be a string".to_string());
+ }
+ let index = search_index(args)?;
+ let kind = optional_text(args, "kind")?;
+ let lang = optional_text(args, "lang")?;
+ let k = opt_u64(args, "k")?.unwrap_or(5);
+ if !(1..=50).contains(&k) {
+ return Err("`k` must be an integer from 1 to 50".into());
+ }
+ let budget = token_budget::opt_max_tokens(args)?;
+ Ok((symbol, index, kind, lang, k as usize, budget))
+ })();
+ let (symbol, index, kind, lang, k, budget) = match validated {
+ Ok(args) => args,
+ Err(error) => return tool_text(error, true),
+ };
+ let mapping = fetch_mapping(ctx, &index).await;
+ let body = definition_query(symbol, kind, lang, k, mapping.as_ref());
+ let result = engine_request(
+ ctx,
+ Method::Post,
+ &format!("/{index}/_search"),
+ Some(body),
+ None,
+ None,
+ )
+ .await;
+ if result["isError"] == true {
+ return result;
+ }
+ let text = result["content"][0]["text"].as_str().unwrap_or_default();
+ let mut response: Value = match serde_json::from_str(text) {
+ Ok(value) => value,
+ Err(_) => return tool_text("XERJ returned invalid JSON for definition lookup", true),
+ };
+ if !response.pointer("/hits/hits").is_some_and(Value::is_array) {
+ return tool_text(
+ "XERJ returned a definition response without hits.hits",
+ true,
+ );
+ }
+ finalize_definition_response(&mut response, k);
+ let text = response.to_string();
+ tool_text(
+ match budget {
+ Some(max_tokens) => token_budget::budget_json_response(&text, max_tokens),
+ None => text,
+ },
+ false,
+ )
+}
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index b36c3d39e..619d82a0a 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
-//! tools: seventeen without a hub key, and three Corpus Hub tools
+//! agent host (Claude Desktop, IDE agents, custom orchestrators) as twenty-one
+//! tools: eighteen without a hub key, and three Corpus Hub tools
//! (`xerj_hub_*`) that run the `xerj ask` flow itself. Thirteen of those
-//! seventeen construct exactly the request the running engine already accepts
+//! eighteen 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
@@ -23,10 +23,11 @@
//! when GitHub is unavailable. It sends by default; `confirm: false` previews,
//! and `--disable-feedback` / `XERJ_DISABLE_FEEDBACK=true` turn sending off.
//!
-//! ## The thirteen canonical agent operations
+//! ## Canonical agent operations
//!
//! | MCP tool | XERJ endpoint | Real capability |
//! |------------------------|---------------------------------------|-----------------|
+//! | `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_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) |
@@ -64,8 +65,8 @@
//! understanding, no query language, no unbounded traversal. Every brain
//! tool description says both things, and engine refusals (e.g. the hops
//! cap) are passed back to the agent verbatim.
-//! * This proxy adds **no** capabilities of its own — whatever the engine
-//! returns (including errors) is passed straight back to the agent.
+//! * `xerj_def` shares the CLI definition query and local result ranking;
+//! engine errors are passed back unchanged.
//!
//! ## Configuration (environment)
//!
@@ -93,12 +94,13 @@
//!
//! ## Token budgets (#1058)
//!
-//! The five search tools accept `max_tokens` and are held to it: the response
+//! The six search tools accept `max_tokens` and are held to it: the response
//! text NEVER exceeds the budget. Enforcement lives in [`token_budget`],
//! counted with one named tokenizer (XERJ's `StandardTokenizer`, UAX #29
//! words), with overlapping file:line passages deduped before budgeting and
//! over-budget hits reduced to locators.
+mod def;
mod hub;
mod map;
mod token_budget;
@@ -698,7 +700,7 @@ fn judge_arg_schema(query_required: bool) -> Value {
}
/// JSON-schema fragment for the optional `max_tokens` argument, shared by all
-/// five search tools (`xerj_search`, `xerj_hybrid_search`,
+/// six search tools (`xerj_def`, `xerj_search`, `xerj_hybrid_search`,
/// `xerj_semantic_search`, `xerj_vector_search`, `xerj_code_search`) so the
/// budget contract cannot drift between them.
///
@@ -747,6 +749,7 @@ pub fn tool_specs() -> Value {
/// do not have to mutate `XERJ_HUB_PUBKEY`, which is process-global.
pub fn tool_specs_with(include_hub: bool) -> Value {
let mut specs = json!([
+ def::spec(),
{
"name": "xerj_search",
"description":
@@ -1838,6 +1841,7 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {
// the response hits are penalized and trimmed back to `page`.
let mut demote_page: Option<usize> = None;
let result = match name {
+ "xerj_def" => return def::run(ctx, &args).await,
"xerj_search" => {
// Resolve before even the mapping GET: conflicting or malformed
// scope arguments must never silently query a different corpus.
@@ -4036,9 +4040,10 @@ mod tests {
}
#[test]
- fn exactly_the_five_search_tools_advertise_max_tokens() {
+ fn exactly_the_six_search_tools_advertise_max_tokens() {
let specs = tool_specs();
let search_tools = [
+ "xerj_def",
"xerj_search",
"xerj_hybrid_search",
"xerj_semantic_search",
@@ -5057,7 +5062,7 @@ mod tests {
}
#[test]
- fn tools_list_has_all_eighteen() {
+ fn tools_list_has_all_tools() {
let specs = tool_specs_with(true);
let names: Vec<&str> = specs
.as_array()
@@ -5065,8 +5070,9 @@ mod tests {
.iter()
.map(|t| t["name"].as_str().unwrap())
.collect();
- assert_eq!(names.len(), 20);
+ assert_eq!(names.len(), 21);
for n in [
+ "xerj_def",
"xerj_search",
"xerj_semantic_search",
"xerj_vector_search",
@@ -5165,23 +5171,23 @@ mod tests {
.collect()
};
let without = names(false);
- assert_eq!(without.len(), 17, "{without:?}");
+ assert_eq!(without.len(), 18, "{without:?}");
assert!(
without.iter().all(|n| !n.starts_with("xerj_hub_")),
"{without:?}"
);
let with = names(true);
- assert_eq!(with.len(), 20, "{with:?}");
+ assert_eq!(with.len(), 21, "{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 17 tools"), "{help}");
+ assert!(help.contains("proxies 18 tools"), "{help}");
assert!(!help.contains("xerj_hub_"), "{help}");
assert!(help.contains("~/xerj-data"), "{help}");
let help = tools_paragraph(true);
- assert!(help.contains("proxies 20 tools"), "{help}");
+ assert!(help.contains("proxies 21 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/local_def.rs b/engine/crates/xerj-mcp/tests/local_def.rs
new file mode 100644
index 000000000..dc4a271f2
--- /dev/null
+++ b/engine/crates/xerj-mcp/tests/local_def.rs
@@ -0,0 +1,349 @@
+//! Local definition lookup must use the CLI's ranking and stay in its corpus.
+use serde_json::{json, Value};
+use std::sync::{Arc, Mutex};
+
+type Requests = Arc<Mutex<Vec<(String, String, Value)>>>;
+
+async fn mock_node(
+ mapping: Value,
+ status: axum::http::StatusCode,
+ response: String,
+) -> (String, tokio::task::JoinHandle<()>, Requests) {
+ let requests: Requests = Arc::default();
+ let captured = requests.clone();
+ let app = axum::Router::new().fallback(move |request: axum::extract::Request| {
+ let captured = captured.clone();
+ let mapping = mapping.clone();
+ let response = response.clone();
+ async move {
+ let path = request.uri().path().to_string();
+ let auth = request
+ .headers()
+ .get("Authorization")
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .to_owned();
+ let bytes = axum::body::to_bytes(request.into_body(), 1024 * 1024)
+ .await
+ .unwrap();
+ let body = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ captured.lock().unwrap().push((path.clone(), auth, body));
+ if path.ends_with("/_mapping") {
+ (axum::http::StatusCode::OK, mapping.to_string())
+ } else {
+ (status, 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() });
+ (url, server, requests)
+}
+
+#[tokio::test]
+async fn local_def_mapping_guards_scope_auth_and_legacy_passages() {
+ for (properties, numeric) in [
+ (json!({"body":{"type":"text"}}), false),
+ (
+ json!({"body":{"type":"text"},"name":{"type":"long"},
+ "kind":{"type":"integer"},"language":{"type":"long"}}),
+ true,
+ ),
+ ] {
+ let mut mapping = json!({"project-prose":{"mappings":{"properties":properties}}});
+ if numeric {
+ mapping["project-code"] = json!({"mappings":{"properties":{
+ "name":{"type":"keyword"},"kind":{"type":"keyword"},
+ "language":{"type":"keyword"},"code":{"type":"text"}}}});
+ }
+ let legacy = json!({"_id":"legacy","_score":1.0,"_source":{"ax_path":"guide.md"},
+ "fields":{"_passage":[{"text":"Cache declaration", "start_line":12}]}});
+ let (url, server, requests) = mock_node(
+ mapping,
+ axum::http::StatusCode::OK,
+ json!({"hits":{"total":{"value":1},"hits":[legacy.clone()]}}).to_string(),
+ )
+ .await;
+ let response = lookup(
+ &url,
+ json!({"symbol":"Cache", "prefix":" project ",
+ "kind":"struct", "lang":"rust"}),
+ )
+ .await;
+ assert_eq!(response["hits"]["hits"], json!([legacy]));
+ let requests = requests.lock().unwrap();
+ assert_eq!(requests.len(), 2);
+ assert_eq!(requests[0].0, "/project-*/_mapping");
+ assert_eq!(requests[1].0, "/project-*/_search");
+ assert!(requests.iter().all(|r| r.1 == "ApiKey fixture"));
+ let body = &requests[1].2;
+ assert_eq!(body["size"], 45, "fetch a wider window before reranking");
+ assert_eq!(body["query"]["bool"]["filter"], json!([]));
+ let query = body["query"].to_string();
+ assert!(!query.contains("\"name\""), "{query}");
+ assert!(!query.contains("name^"), "{query}");
+ assert!(
+ query.contains(if numeric { "code^2" } else { "body" }),
+ "{query}"
+ );
+ server.abort();
+ }
+}
+
+#[tokio::test]
+async fn local_def_preserves_errors_and_refuses_malformed_success() {
+ use axum::http::StatusCode;
+ for (status, body, expected) in [
+ (
+ StatusCode::UNAUTHORIZED,
+ "denied",
+ "HTTP 401 Unauthorized: denied",
+ ),
+ (
+ StatusCode::BAD_REQUEST,
+ "strict field refusal",
+ "HTTP 400 Bad Request: strict field refusal",
+ ),
+ (StatusCode::OK, "not json", "invalid JSON"),
+ (StatusCode::OK, "{}", "without hits.hits"),
+ ] {
+ let (url, server, requests) = mock_node(json!({}), status, body.to_owned()).await;
+ let response = xerj_mcp::handle_message_for_test(
+ &url,
+ Some("ApiKey fixture".into()),
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
+ "params":{"name":"xerj_def","arguments":{"symbol":"Cache"}}}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response["result"]["isError"], true, "{response}");
+ assert!(
+ response["result"]["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .contains(expected),
+ "{response}"
+ );
+ // Unreadable mappings keep the historical CLI query, not match_all.
+ let requests = requests.lock().unwrap();
+ assert_eq!(
+ requests[1].2["query"]["bool"]["should"][0]["term"]["name"]["value"],
+ "Cache"
+ );
+ server.abort();
+ }
+}
+
+#[tokio::test]
+async fn local_def_applies_token_budget_after_ranking() {
+ use unicode_segmentation::UnicodeSegmentation;
+ let hit = json!({"_id":"real", "_score":1, "_source":{
+ "ax_path":"src/cache.rs", "line":7, "kind":"struct",
+ "code":format!("pub struct Cache {}", "many words ".repeat(500))}});
+ let (url, server, _) = mock_node(
+ json!({}),
+ axum::http::StatusCode::OK,
+ json!({"hits":{"hits":[hit]}}).to_string(),
+ )
+ .await;
+ let response = xerj_mcp::handle_message_for_test(
+ &url,
+ Some("ApiKey fixture".into()),
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call", "params":{
+ "name":"xerj_def","arguments":{"symbol":"Cache","max_tokens":128}}}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response["result"]["isError"], false, "{response}");
+ let text = response["result"]["content"][0]["text"].as_str().unwrap();
+ assert!(text.unicode_words().count() <= 128, "{text}");
+ assert!(text.contains("src/cache.rs"), "{text}");
+ server.abort();
+}
+
+#[tokio::test]
+async fn local_def_rejects_invalid_arguments_before_http() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ for (args, field) in [
+ (json!({}), "symbol"),
+ (json!({"symbol":" "}), "symbol"),
+ (json!({"symbol":{}}), "symbol"),
+ (json!({"symbol":"Cache","prefix":" "}), "prefix"),
+ (json!({"symbol":"Cache","index":42}), "index"),
+ (
+ json!({"symbol":"Cache","prefix":"project","index":"ax-*"}),
+ "prefix",
+ ),
+ (json!({"symbol":"Cache","kind":42}), "kind"),
+ (json!({"symbol":"Cache","lang":" "}), "lang"),
+ (json!({"symbol":"Cache","k":0}), "k"),
+ (json!({"symbol":"Cache","k":51}), "k"),
+ (json!({"symbol":"Cache","k":1.5}), "k"),
+ (json!({"symbol":"Cache","max_tokens":0}), "max_tokens"),
+ ] {
+ let response = xerj_mcp::handle_message_for_test(
+ &url,
+ Some("ApiKey fixture".into()),
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
+ "params":{"name":"xerj_def","arguments":args}}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response["result"]["isError"], true, "{response}");
+ let text = response["result"]["content"][0]["text"].as_str().unwrap();
+ assert!(text.contains(&format!("`{field}`")), "{text}");
+ assert!(matches!(listener.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock));
+ }
+}
+
+async fn lookup(url: &str, arguments: Value) -> Value {
+ let response = xerj_mcp::handle_message_for_test(
+ url,
+ Some("ApiKey fixture".into()),
+ json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
+ "params":{"name":"xerj_def","arguments":arguments}}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response["result"]["isError"], false, "{response}");
+ serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap()
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn local_def_returns_ranked_unique_declarations_in_the_requested_scope() {
+ 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();
+ for index in ["project-code", "ax-code"] {
+ let response = client
+ .put(format!("{url}/{index}"))
+ .json(&json!({
+ "settings":{"index":{"strict_unknown_fields":true}},
+ "mappings":{"properties":{
+ "name":{"type":"keyword"}, "kind":{"type":"keyword"},
+ "language":{"type":"keyword"}, "code":{"type":"text"},
+ "ax_path":{"type":"keyword"}, "line":{"type":"integer"}
+ }}
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(
+ response.status().is_success(),
+ "{}",
+ response.text().await.unwrap()
+ );
+ for (id, path, kind, language, code) in [
+ ("test", "tests/cache.rs", "struct", "rust", "struct Cache"),
+ (
+ "alias",
+ "src/alias.rs",
+ "type",
+ "rust",
+ "type Cache = Store;",
+ ),
+ ("real", "src/cache.rs", "struct", "rust", "pub struct Cache"),
+ (
+ "duplicate",
+ "src/cache.rs",
+ "struct",
+ "rust",
+ "pub struct Cache",
+ ),
+ ("python", "src/cache.py", "class", "python", "class Cache:"),
+ ] {
+ let response = client
+ .put(format!("{url}/{index}/_doc/{id}?refresh=true"))
+ .json(&json!({"name":"Cache","kind":kind,"language":language,
+ "code":code,"ax_path":path,"line":7}))
+ .send()
+ .await
+ .unwrap();
+ assert!(
+ response.status().is_success(),
+ "{}",
+ response.text().await.unwrap()
+ );
+ }
+ }
+ for (scope, index) in [
+ (json!({"prefix":"project"}), "project-code"),
+ (json!({"index":"project-code"}), "project-code"),
+ (json!({}), "ax-code"),
+ ] {
+ let mut args = scope;
+ args["symbol"] = json!("Cache");
+ let result = lookup(&url, args.clone()).await;
+ let hits = result["hits"]["hits"].as_array().unwrap();
+ assert_eq!(hits.len(), 4, "{result}");
+ assert!(hits.iter().all(|h| h["_index"] == index), "{result}");
+ assert_eq!(hits[0]["_source"]["ax_path"], "src/cache.rs");
+ assert_eq!(hits[0]["_source"]["line"], 7);
+ assert_eq!(hits[0]["_source"]["code"], "pub struct Cache");
+ args["k"] = json!(1);
+ assert_eq!(
+ lookup(&url, args.clone()).await["hits"]["hits"],
+ json!([hits[0]])
+ );
+ args["kind"] = json!("class");
+ args["lang"] = json!("python");
+ let filtered = lookup(&url, args.clone()).await;
+ assert_eq!(
+ filtered["hits"]["hits"][0]["_source"]["ax_path"],
+ "src/cache.py"
+ );
+ args["symbol"] = json!("MissingIdentifier");
+ assert_eq!(lookup(&url, args).await["hits"]["hits"], json!([]));
+ }
+ // Numeric homonyms in another dataset must not poison a wildcard lookup.
+ let response = client
+ .put(format!("{url}/project-metrics"))
+ .json(&json!({
+ "settings":{"index":{"strict_unknown_fields":true}},
+ "mappings":{"properties":{
+ "name":{"type":"long"},"kind":{"type":"integer"},
+ "language":{"type":"long"},"body":{"type":"text"}
+ }}
+ }))
+ .send()
+ .await
+ .unwrap();
+ assert!(
+ response.status().is_success(),
+ "{}",
+ response.text().await.unwrap()
+ );
+ let response = lookup(
+ &url,
+ json!({"symbol":"Cache", "prefix":"project",
+ "kind":"struct", "lang":"rust"}),
+ )
+ .await;
+ let hits = response["hits"]["hits"].as_array().unwrap();
+ assert_eq!(
+ hits.len(),
+ 4,
+ "numeric kind/language filters are ignored: {response}"
+ );
+ assert_eq!(hits[0]["_source"]["ax_path"], "src/cache.rs");
+ server.abort();
+ let _ = server.await;
+}
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index 76d84ec62..ea9b3dc0a 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -1,5 +1,50 @@
{
"tools": [
+ {
+ "name": "xerj_def",
+ "description": "Find a symbol's definition in local autoindexed data, like `xerj def --json`. Lexical ranking, not neural: shares the CLI's mapping-aware query, preferred-kind and public-declaration ranking, location deduplication and bounded candidate window. Returns ES JSON with declarations in hits.hits[]._source.code and locations in ax_path/path plus line/start_line (page/cell for documents); older file-level hits may carry fields._passage instead. hits.total counts engine matches before deduplication. No match is a successful empty hits list. Unlike xerj_hub_def, this queries the configured node, not a Hub pack. Optional max_tokens caps the response; see its tokenizer and locator-only rule.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "symbol": {
+ "type": "string",
+ "minLength": 1,
+ "description": "Symbol name or capability phrase, as in `xerj def Cache`. Must not be blank."
+ },
+ "prefix": {
+ "type": "string",
+ "description": "Autoindex prefix: project searches project-*. Trimmed, must not be empty. Cannot be combined with a non-empty index. Defaults to ax when neither scope is given."
+ },
+ "index": {
+ "type": "string",
+ "description": "Explicit index name or pattern instead of prefix, as in xerj_search. A blank string is treated as absent."
+ },
+ "kind": {
+ "type": "string",
+ "description": "Symbol kind, e.g. function, struct or class. Like the CLI, ignored when no index maps kind or any maps it as numeric."
+ },
+ "lang": {
+ "type": "string",
+ "description": "Language, e.g. rust or python. Like the CLI, ignored when no index maps language or any maps it as numeric."
+ },
+ "k": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 50,
+ "default": 5,
+ "description": "Maximum unique definitions to return (1..=50, default 5)."
+ },
+ "max_tokens": {
+ "type": "integer",
+ "minimum": 32,
+ "description": "Token budget for this response: the returned text NEVER exceeds it. Tokens are counted with XERJ's StandardTokenizer (UAX #29 word boundaries) — the same word split the engine's own analyzer uses for BM25. Honest scope: that under-counts model-context subwords (snake_case is ONE token here), so treat it as a deterministic proxy, not a BPE count. The budget covers the whole response text (JSON keys and syntax included). Overlapping file:line passages are deduped first (higher-ranked wins). Hits that no longer fit are listed as LOCATORS ONLY (file:line, index/id) rather than dropped, and the response's `_token_budget` block accounts for every hit: kept, locator-only, deduped, dropped. Errors are never truncated — a refusal you cannot read end-to-end is worse than a long response. Minimum 32."
+ }
+ },
+ "required": [
+ "symbol"
+ ]
+ }
+ },
{
"name": "xerj_search",
"description": "Full-text / keyword / structured search over a XERJ index. Proxies POST /{index}/_search. 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. Pass `max_tokens` to cap the response at a token budget (never exceeded; see that argument for the tokenizer and the locator-only rule).",
diff --git a/scripts/mcp-def-smoke.py b/scripts/mcp-def-smoke.py
new file mode 100644
index 000000000..23d04c8ab
--- /dev/null
+++ b/scripts/mcp-def-smoke.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Compare the real CLI and MCP over a deterministic HTTP fixture (#2080).
+
+Usage: python3 scripts/mcp-def-smoke.py engine/target/ci-test/xerj
+No real node, external corpus or model is needed. Engine behavior is covered
+separately by `cargo test -p xerj-mcp --test local_def`.
+"""
+import json
+import subprocess
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+
+def main():
+ binary = sys.argv[1]
+ requests = []
+ mapping = {"project-code": {"mappings": {"properties": {
+ "name": {"type": "keyword"}, "kind": {"type": "keyword"},
+ "language": {"type": "keyword"}, "code": {"type": "text"},
+ "impl": {"type": "text"}, "ax_path": {"type": "keyword"},
+ "line": {"type": "integer"},
+ }}}}
+ hits = [{"_id": name, "_score": score, "_source": {
+ "ax_path": path, "line": 7, "kind": kind, "code": code,
+ }} for name, score, path, kind, code in [
+ ("alias", 12, "src/alias.rs", "type", "type Cache = Store;"),
+ ("test", 11, "tests/cache.rs", "struct", "struct Cache"),
+ ("real", 10, "src/cache.rs", "struct", "pub struct Cache"),
+ ("duplicate", 9, "src/cache.rs", "struct", "pub struct Cache"),
+ ]]
+
+ 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):
+ self.respond(mapping if self.path.endswith("/_mapping") else {})
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ requests.append((self.path, body))
+ self.respond({"hits": {"total": {"value": len(hits)}, "hits": hits}})
+
+ 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 run(args, stdin=None):
+ return subprocess.run([binary, *args], input=stdin, text=True,
+ capture_output=True, timeout=30, check=True).stdout
+
+ try:
+ for symbol, filters in [("Cache", {}), ("cache entries", {}),
+ ("Cache", {"kind": "struct", "lang": "rust"})]:
+ requests.clear()
+ cli_args = ["def", "--url", url, "--api-key", "fixture",
+ "--prefix", "project", "-k", "2", "--json",
+ "--disable-feedback", symbol]
+ for key, value in filters.items():
+ cli_args += [f"--{key}", value]
+ cli = json.loads(run(cli_args))
+ messages = [
+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},
+ {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {
+ "name": "xerj_def", "arguments": {
+ "symbol": symbol, "prefix": "project", "k": 2, **filters}}},
+ ]
+ stdout = run(["mcp", "--url", url, "--auth", "ApiKey fixture",
+ "--disable-feedback"],
+ "".join(json.dumps(m) + "\n" for m in messages))
+ reply = next(m for m in map(json.loads, stdout.splitlines()) if m.get("id") == 2)
+ assert reply["result"]["isError"] is False, reply
+ mcp = json.loads(reply["result"]["content"][0]["text"])
+ assert len(requests) == 2 and requests[0] == requests[1], requests
+ assert requests[0][0] == "/project-*/_search", requests
+ assert cli == mcp, (cli, mcp)
+ assert [h["_id"] for h in mcp["hits"]["hits"]] == ["real", "alias"], mcp
+ print(f"PASS CLI/MCP request and ranked response parity: {symbol!r} {filters}")
+ finally:
+ server.shutdown()
+ thread.join(timeout=5)
+
+
+if __name__ == "__main__":
+ main()