8000 feat(mcp): expose local definition lookup by Jarvis636431 · Pull Request #2166 · xerj-org/xerj · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 16 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,13 @@ 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 tools: `xerj_search`, `xerj_semantic_search`, `xerj_vector_search`,
Twenty-one 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`. The first eleven are each a *thin
proxy*: they build exactly the request the ES-compatible surface already accepts
`xerj_hub_find`, `xerj_hub_def`, `xerj_hub_ask`, `xerj_def`. 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
their own, so anything you can do over MCP you can also do with `curl`, and vice
Expand All @@ -188,6 +188,18 @@ 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_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}`
searches `project-*`; `index` can replace `prefix`. With neither scope argument,
it searches `ax-*`. `k` is 1–50 (default 5); `max_tokens` optionally caps the response.
Declarations are 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 is a successful
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. Unlike
`xerj_hub_def`, this queries the configured node rather than a named Hub pack.

The remaining seven are not proxies either. `xerj_index_budget` counts a folder
and estimates its index against the node's flood-stage budget before
`xerj autoindex` hashes anything; it does not index. `xerj_autoindex_remove`
Expand All @@ -196,7 +208,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 seventeen.
no hub key omits the three hub tools and serves eighteen.

Two honesty notes that bind how you describe results: `xerj_semantic_search`
embeds server-side with the **lexical feature-hashing** embedder unless the node
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand All @@ -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.
Expand Down
10 changes: 9 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ DeepSeek Harness 在它的 Cordis 补丁文件里把 MCP 作为插件加载:

最初名单里有三个候选被有意排除。Aider 完全没有 MCP 客户端支持([Aider-AI/aider#3314](https://github.com/Aider-AI/aider/issues/3314) 仍未关闭)。T3 Code 方向相反:它自己托管一个供其他智能体连接的 MCP 端点,其会话从底层 harness 继承服务配置。Grok Bot 没有文档记载的本地 stdio 注册方式;Grok CLI 有,见上表对应一行。

共提供二十个工具,其中十一个是已有 XERJ 端点的薄代理:
共提供二十一个工具,其中十一个是已有 XERJ 端点的薄代理:

| 工具 | 用途 |
|---|---|
Expand All @@ -352,6 +352,14 @@ DeepSeek Harness 在它的 Cordis 补丁文件里把 MCP 作为插件加载:

调用 `xerj_search` 时传入 `{"prefix":"project","query":"retry policy"}` 可搜索 `project-*`,等同于 `xerj search --prefix project`。要指定具体索引名或模式,改用 `index`;`index` 和 `prefix` 不能同时非空。`prefix` 会被去掉首尾空白,且不能为空。两个参数都不传时,工具搜索 `ax-*`。

`xerj_def` 查找本地定义,复用 `xerj def --json` 的查询、排序和位置去重逻辑。例如,`{"symbol":"Cache","prefix":"project","kind":"struct","lang":"rust","k":5}` 搜索 `project-*`;也可以用 `index` 替代 `prefix`,作用域规则与 `xerj_search` 相同。`symbol` 也接受描述能力的短语。`k` 必须为 1–50,默认 5;可选的 `max_tokens` 限制响应大小。

结果采用 ES JSON:声明位于 `hits.hits[]._source.code`,文件位置使用 `ax_path`/`path` 和 `line`/`start_line`,旧版文件级结果可能使用 `fields._passage`。`hits.total` 是去重前的引擎匹配数;没有匹配时成功返回空列表。

与 CLI 相同,如果所有目标索引都未映射筛选字段,或任一目标索引将它映射为数值类型,则忽略相应的类型或语言筛选。排序基于词法匹配。此工具查询配置的节点;`xerj_hub_def` 则在指定的 Hub 语料包中查找定义。

未包含 Hub key 的二进制程序不提供三个 Hub 工具,共提供十八个工具。

另外两个工具不只是简单代理:`xerj_map` 从 autoindex 目录读取各索引的字段映射,除按字节上限裁剪外原样返回;`xerj_code_search` 执行 `xerj code` 参考代码检索流程([`tools/xerj-code/`](tools/xerj-code/)),返回渲染后的文本。`xerj_index_budget` 在 `xerj autoindex` 计算哈希之前统计文件夹,按节点的磁盘预算估算索引大小,本身不做索引。`xerj_autoindex_remove` 删除一个已 autoindex 的文件夹,删前先列出其内容,`confirm` 不为 true 时什么都不删。`xerj_corpus_feedback` 为 hub 语料评分。`xerj_field_report` 提交使用反馈;`xerj_hub_find`、`xerj_hub_def` 和 `xerj_hub_ask` 用本机已有的 Corpus Hub 语料包作答(即 `xerj ask` 流程)。

`xerj mcp --help` 会输出相同的配置示例及完整选项。机器可读的工具 schema 发布在 [xerj.org/docs/agents/schemas/mcp-tools.json](https://xerj.org/docs/agents/schemas/mcp-tools.json),由实际运行的 `tools/list` 生成,并通过 CI 中的 `scripts/mcp-schema-check.sh` 和单元测试检查,防止公开列表与服务实际提供的工具不一致。
Expand Down
66 changes: 43 additions & 23 deletions engine/crates/xerj-autoindex/src/def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>,
Expand Down Expand Up @@ -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`");
Expand All @@ -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) => {
Expand All @@ -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!(
Expand Down
113 changes: 113 additions & 0 deletions engine/crates/xerj-mcp/src/def.rs
Original file line number Diff line number Diff line change
@@ -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,
)
}
Loading
Loading
0