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
fix(mcp): resolve xerj_search prefix the way autoindex stores it (#2235)
xerj-org5ad85724e146
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d20353bf..8f87f9234 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0startup step. Each site logs once. `panic = "abort"` is unchanged([#1122](https://github.com/xerj-org/xerj/issues/1122)).+- `xerj search --prefix`, `xerj def --prefix`, and MCP `xerj_search`'s `prefix`+ argument resolve through one function: the prefix `xerj autoindex` stores.+ `My_Proj` searches `my-proj-*`, and a trailing `-*` is not part of the+ prefix. A prefix that cannot name an index is refused before any request.+ Omitting both `index` and `prefix` on `xerj_search` still searches `ax-*`+ (#2080).+- `xerj corpus add <name> <local-path>` copies the checkout's root`.xerjignore` into the clone when that file is untracked or has uncommittededits. `git clone` only checks out committed files, so the ignore file wasdiff --git a/README.md b/README.mdindex a974a9d00..8667b7db9 100644--- a/README.md+++ b/README.md@@ -469,10 +469,12 @@ Twenty-one tools are exposed. Eleven are thin proxies over an endpoint XERJ alre| `xerj_plan` | a plain-words filter in, validated query DSL out (`POST /_ask`; deterministic and rule-based, not an LLM) |For `xerj_search`, pass `{"prefix":"project","query":"retry policy"}` to search-`project-*`, matching `xerj search --prefix project`. Use `index` for an explicit-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-*`.+`project-*`, matching `xerj search --prefix project`. `prefix` is resolved by+the same function as the CLI: the prefix `xerj autoindex --prefix` stores, so+`My_Proj` searches `my-proj-*`. Use `index` for an explicit index name or+pattern instead; non-empty `index` and `prefix` cannot be combined. An empty+prefix, a prefix with no `[a-z0-9]` character, or a prefix that cannot name an+index is an error. With neither argument, the tool searches `ax-*`.`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}`diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 1f824072d..ac24b7f39 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -350,7 +350,7 @@ DeepSeek Harness 在它的 Cordis 补丁文件里把 MCP 作为插件加载:| `xerj_brain_overview` / `xerj_brain_ego` / `xerj_brain_link` / `xerj_brain_unlink` | 操作“第二大脑”链接索引:查看概况、展开某个节点有证据支持的邻域、建立和撤销链接 || `xerj_plan` | 输入自然语言筛选条件,返回经过校验的查询 DSL(`POST /_ask`;确定性的规则处理,不使用 LLM) |-调用 `xerj_search` 时传入 `{"prefix":"project","query":"retry policy"}` 可搜索 `project-*`,等同于 `xerj search --prefix project`。要指定具体索引名或模式,改用 `index`;`index` 和 `prefix` 不能同时非空。`prefix` 会被去掉首尾空白,且不能为空。两个参数都不传时,工具搜索 `ax-*`。+调用 `xerj_search` 时传入 `{"prefix":"project","query":"retry policy"}` 可搜索 `project-*`,等同于 `xerj search --prefix project`。`prefix` 与 CLI 走同一个解析函数,也就是 `xerj autoindex --prefix` 实际写入的前缀,因此 `My_Proj` 搜索 `my-proj-*`。要指定具体索引名或模式,改用 `index`;`index` 和 `prefix` 不能同时非空。空前缀、不含 `[a-z0-9]` 的前缀,以及无法作为索引名的前缀都会报错。两个参数都不传时,工具搜索 `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` 限制响应大小。diff --git a/engine/crates/xerj-autoindex/src/def.rs b/engine/crates/xerj-autoindex/src/def.rsindex 8a08bf60f..8153bd04d 100644--- a/engine/crates/xerj-autoindex/src/def.rs+++ b/engine/crates/xerj-autoindex/src/def.rs@@ -478,7 +478,7 @@ pub fn run_def_cli() -> i32 {.filter(|s| !s.is_empty()).unwrap_or_default();let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());- let mut prefix = "ax".to_string();+ let mut prefix = crate::search::DEFAULT_SEARCH_PREFIX.to_string();let mut k: usize = 5;let mut kind: Option<String> = None;let mut lang: Option<String> = None;@@ -528,6 +528,18 @@ pub fn run_def_cli() -> i32 {return 2;}};+ let resolved = match crate::search::resolve_prefix(&prefix) {+ Ok(resolved) => resolved,+ Err(e) => {+ eprintln!("xerj def: {e}\n\n{USAGE}");+ return 2;+ }+ };+ if let Some(note) = crate::search::prefix_rewrite_note(&prefix, &resolved) {+ eprintln!("xerj def: {note}");+ }+ let prefix = resolved.prefix;+ let pattern = resolved.pattern;if url.is_empty() {url = "http://localhost:9200".to_string();}@@ -563,7 +575,6 @@ pub fn run_def_cli() -> i32 {return 2;}- 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);if let Some(set) = mapped.as_ref().filter(|s| !s.is_empty()) {diff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex e0ce51d9a..58d89d5f0 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -508,6 +508,69 @@ pub(crate) fn query_failure_message(/// Default `--full` width, and the width suggested when the user asked for 0.const DEFAULT_FULL_CHARS: usize = 600;+/// Default `--prefix` for `xerj search`, `xerj def`, and MCP `xerj_search`+/// when the caller names neither an index nor a prefix. This is the prefix+/// `xerj autoindex` writes when `--prefix` is omitted.+pub const DEFAULT_SEARCH_PREFIX: &str = "ax";++/// A `--prefix` the way `xerj autoindex` stored it, plus the index pattern+/// `xerj search` and `xerj def` query.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ResolvedPrefix {+ /// Prefix autoindex stored (`my-proj`, not `My_Proj`).+ pub prefix: String,+ /// `{prefix}-*` index pattern.+ pub pattern: String,+}++/// Resolve a prefix the way `xerj autoindex --prefix` stores it.+///+/// Autoindex keeps lower-case `[a-z0-9]` runs joined by `-`+/// ([`crate::dataset::sanitize_prefix`]) and refuses a result that cannot+/// name an index ([`crate::dataset::index_prefix_error`]). Searching the+/// characters the caller typed (`My_Proj-*`) misses the corpus those+/// commands wrote (`my-proj-*`). `xerj search`, `xerj def`, and the+/// `xerj_search` MCP tool all call this, so the three cannot drift.+pub fn resolve_prefix(prefix: &str) -> Result<ResolvedPrefix, String> {+ let trimmed = prefix.trim();+ if trimmed.is_empty() {+ return Err(+ "must contain at least one [a-z0-9] character; for example \"project\" searches project-*"+ .into(),+ );+ }+ let sanitized = crate::dataset::sanitize_prefix(trimmed);+ if sanitized.is_empty() {+ return Err(format!(+ "{trimmed:?} keeps no [a-z0-9] character. xerj autoindex --prefix stores \+ lower-case [a-z0-9] runs joined by '-'; for example \"project\" searches project-*"+ ));+ }+ if let Some(err) = crate::dataset::index_prefix_error(&sanitized) {+ // That sentence is about the walk autoindex has not started. Search+ // and def have nothing to walk.+ return Err(err.trim_end_matches(" Nothing was walked.").to_string());+ }+ Ok(ResolvedPrefix {+ pattern: format!("{sanitized}-*"),+ prefix: sanitized,+ })+}++/// Stderr note when the stored prefix is not the characters the caller typed.+/// `None` when they already match, including surrounding whitespace.+pub fn prefix_rewrite_note(given: &str, resolved: &ResolvedPrefix) -> Option<String> {+ let given = given.trim();+ if given == resolved.prefix {+ None+ } else {+ Some(format!(+ "--prefix {given:?} is stored as {:?}; searching {}",+ resolved.prefix, resolved.pattern+ ))+ }+}+/// `-k` / `--full`. A value that does not parse used to be consumed and/// dropped, so `xerj search -k abc` kept the default of 5 and never said so.pub(crate) fn parse_count_arg(flag: &str, next: Option<String>) -> Result<usize, String> {@@ -555,7 +618,7 @@ fn parse_search_cli(mut url: String,mut api_key: Option<String>,) -> Result<SearchCli, String> {- let mut prefix = "ax".to_string();+ let mut prefix = DEFAULT_SEARCH_PREFIX.to_string();let mut k: usize = 5;let mut full: usize = DEFAULT_FULL_CHARS;let mut as_json = false;@@ -637,6 +700,18 @@ pub fn run_search_cli() -> i32 {return 2;}};+ let resolved = match resolve_prefix(&prefix) {+ Ok(resolved) => resolved,+ Err(e) => {+ eprintln!("xerj search: {e}\n\n{USAGE}");+ return 2;+ }+ };+ if let Some(note) = prefix_rewrite_note(&prefix, &resolved) {+ eprintln!("xerj search: {note}");+ }+ let prefix = resolved.prefix;+ let pattern = resolved.pattern;if url.is_empty() {url = "http://localhost:9200".to_string();}@@ -689,7 +764,6 @@ pub fn run_search_cli() -> i32 {// are strict, so the clause is HTTP 400 rather than a silent miss// (#1601). Read the mapping and drop a leg no resolved index maps; an// unreadable mapping keeps the code-shaped query.- 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);// Types are only trusted when the name union was readable. An error body@@ -784,6 +858,50 @@ mod tests {use super::*;use xerj_common::code_query::normalize_code_search_query;+ /// `My_Proj` is stored as `my-proj-*`. Searching the typed characters+ /// misses the corpus. A trailing `-*` is the pattern, not part of the+ /// prefix. A prefix that cannot name an index is refused before HTTP.+ #[test]+ fn resolve_prefix_matches_what_autoindex_stores() {+ let project = resolve_prefix("project").unwrap();+ assert_eq!(project.prefix, "project");+ assert_eq!(project.pattern, "project-*");+ assert!(prefix_rewrite_note("project", &project).is_none());+ assert!(prefix_rewrite_note(" project ", &project).is_none());++ let rewritten = resolve_prefix(" My_Proj ").unwrap();+ assert_eq!(rewritten.prefix, "my-proj");+ assert_eq!(rewritten.pattern, "my-proj-*");+ assert_eq!(+ crate::dataset::sanitize_prefix("My_Proj"),+ rewritten.prefix,+ "resolution must be sanitize_prefix, not a second copy of the rules"+ );+ let note = prefix_rewrite_note("My_Proj", &rewritten).unwrap();+ assert!(note.contains("my-proj-*"), "{note}");++ assert_eq!(+ resolve_prefix("owner--repo").unwrap().pattern,+ "owner--repo-*"+ );+ assert_eq!(resolve_prefix("project-*").unwrap().pattern, "project-*");+ assert_eq!(+ resolve_prefix(DEFAULT_SEARCH_PREFIX).unwrap().pattern,+ "ax-*"+ );++ let empty = resolve_prefix("___").unwrap_err();+ assert!(empty.contains("[a-z0-9]"), "{empty}");+ assert!(resolve_prefix(" ").is_err());+ let digit = resolve_prefix("2042").unwrap_err();+ assert!(digit.contains("2042"), "{digit}");+ assert!(+ !digit.contains("walked"),+ "search must not talk about a walk it does not do: {digit}"+ );+ assert!(digit.contains("lowercase letter"), "{digit}");+ }+#[test]fn help_says_the_default_ranking_is_lexical() {assert!(diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 3dcbceef1..fe6c8d5e1 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -754,7 +754,9 @@ pub fn tool_specs_with(include_hub: bool) -> Value {"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 \+ 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\"}}, \@@ -782,11 +784,15 @@ pub fn tool_specs_with(include_hub: bool) -> Value {},"prefix": {"type": "string",- "description": "Autoindex prefix, like `xerj search --prefix`: \- `project` searches `project-*`. Pass the prefix without the \- `-*` suffix. Leading/trailing whitespace is trimmed; an empty \- prefix is an error. Cannot be combined with a non-empty `index`. \- With neither argument, searches `ax-*`."+ "description": "Autoindex prefix, resolved by the same function as \+ `xerj search --prefix` and `xerj autoindex --prefix`: lower-case \+ [a-z0-9] runs joined by '-', so `project` searches `project-*` and \+ `My_Proj` searches `my-proj-*`. A trailing `-*` is dropped. \+ Whitespace is trimmed. An empty prefix, a prefix with no [a-z0-9] \+ character, or a prefix that cannot name an index is an error before \+ any request. Cannot be combined with a non-empty `index`. With \+ neither argument, searches `ax-*` (the CLI default when `--prefix` \+ is omitted)."},"query": {"type": ["object", "string"],@@ -2267,9 +2273,14 @@ fn build_search(args: &Value) -> Result<BuiltRequest, String> {build_search_with_mapping(args, None)}-/// One scope for both mapping discovery and search. `prefix` follows the-/// CLI's `{prefix}-*` expansion (`xerj-autoindex/src/search.rs`); `index`-/// retains its existing blank-as-absent behavior (#962).+/// One scope for both mapping discovery and search.+///+/// `prefix` is [`xerj_autoindex::search::resolve_prefix`], the function+/// `xerj search --prefix` uses. `index` keeps its blank-as-absent behavior+/// (#962). Neither argument uses the CLI default prefix (`ax`), which is+/// what `xerj search` does when `--prefix` is omitted — an error there would+/// break every caller that searches the default corpus. Both is an error:+/// the two scopes name different things and neither is a safe default.fn search_index(args: &Value) -> Result<String, String> {let index = args.get("index")@@ -2287,8 +2298,14 @@ fn search_index(args: &Value) -> Result<String, String> {.into(),),(Some(index), None) => Ok(index.to_owned()),- (None, Some(prefix)) => Ok(format!("{prefix}-*")),- (None, None) => Ok("ax-*".into()),+ (None, Some(prefix)) => xerj_autoindex::search::resolve_prefix(prefix)+ .map(|resolved| resolved.pattern)+ .map_err(|e| format!("`prefix` {e}")),+ (None, None) => {+ xerj_autoindex::search::resolve_prefix(xerj_autoindex::search::DEFAULT_SEARCH_PREFIX)+ .map(|resolved| resolved.pattern)+ .map_err(|e| format!("`prefix` {e}"))+ }}}@@ -3350,7 +3367,12 @@ mod tests {// call — nothing said the corpus lives under `ax-*`. The default// now matches what autoindex writes (and what `xerj search` uses).let (_, path, _) = built(build_search(&json!({})));- assert_eq!(path, "/ax-*/_search");+ let default_pattern =+ xerj_autoindex::search::resolve_prefix(xerj_autoindex::search::DEFAULT_SEARCH_PREFIX)+ .unwrap()+ .pattern;+ assert_eq!(path, format!("/{default_pattern}/_search"));+ assert_eq!(default_pattern, "ax-*");// Whitespace-only is treated as absent; explicit index still wins.let (_, path, _) = built(build_search(&json!({ "index": " " })));assert_eq!(path, "/ax-*/_search");@@ -3371,6 +3393,16 @@ mod tests {"index": " ", "prefix": "project"})));assert_eq!(path, "/project-*/_search");+ // The pattern is the CLI resolver's, including autoindex's rewrite+ // (`My_Proj` is stored as `my-proj-*`) and a trailing `-*` the caller+ // copied off an index name.+ for prefix in ["My_Proj", " my-proj ", "my-proj-*"] {+ let (_, path, body) = built(build_search(&json!({"prefix": prefix})));+ let resolved = xerj_autoindex::search::resolve_prefix(prefix).unwrap();+ assert_eq!(path, format!("/{}/_search", resolved.pattern), "{prefix}");+ assert_eq!(resolved.pattern, "my-proj-*");+ assert!(body.get("prefix").is_none());+ }}#[test]@@ -3383,6 +3415,8 @@ mod tests {for prefix in [json!(""),json!(" "),+ json!("___"),+ json!("2042"),json!(42),json!(false),json!([]),@@ -3391,6 +3425,9 @@ mod tests {let error = build_search(&json!({"prefix": prefix})).unwrap_err();assert!(error.contains("`prefix`"), "{error}");}+ let digit = build_search(&json!({"prefix": "2042"})).unwrap_err();+ assert!(digit.contains("lowercase letter"), "{digit}");+ assert!(!digit.contains("walked"), "{digit}");let (_, path, _) = built(build_search(&json!({"prefix": null})));assert_eq!(path, "/ax-*/_search");}@@ -4647,6 +4684,8 @@ mod tests {json!({"index": "docs", "prefix": "project", "query": "retry"}),json!({"prefix": false, "query": "retry"}),json!({"prefix": " ", "query": {"match_all": {}}}),+ json!({"prefix": "___", "query": "retry"}),+ json!({"prefix": "2042", "query": "retry"}),] {let result = block_on(call_tool(&ctx,diff --git a/engine/crates/xerj-mcp/tests/search_prefix.rs b/engine/crates/xerj-mcp/tests/search_prefix.rsindex 87477c51b..740317ff4 100644--- a/engine/crates/xerj-mcp/tests/search_prefix.rs+++ b/engine/crates/xerj-mcp/tests/search_prefix.rs@@ -20,7 +20,7 @@ async fn prefix_search_returns_only_its_corpus_for_plain_and_dsl_queries() {.unwrap();});let client = reqwest::Client::new();- for index in ["project-docs", "ax-other"] {+ for index in ["project-docs", "ax-other", "my-proj-docs"] {let response = client.put(format!("{url}/{index}")).json(@@ -50,6 +50,8 @@ async fn prefix_search_returns_only_its_corpus_for_plain_and_dsl_queries() {for query in [json!("retry policy"), json!({"match": {"text": "retry"}})] {for (scope, expected_index) in [(json!({"prefix": "project"}), "project-docs"),+ (json!({"prefix": "My_Proj"}), "my-proj-docs"),+ (json!({"prefix": "project-*"}), "project-docs"),(json!({}), "ax-other"),(json!({"index": "project-docs"}), "project-docs"),] {diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.jsonindex 6d812ec71..7bd3e65cc 100644--- a/landing/docs/agents/schemas/mcp-tools.json+++ b/landing/docs/agents/schemas/mcp-tools.json@@ -47,7 +47,7 @@},{"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).",+ "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. Pass `max_tokens` to cap the response at a token budget (never exceeded; see that argument for the tokenizer and the locator-only rule).","inputSchema": {"type": "object","properties": {@@ -57,7 +57,7 @@},"prefix": {"type": "string",- "description": "Autoindex prefix, like `xerj search --prefix`: `project` searches `project-*`. Pass the prefix without the `-*` suffix. Leading/trailing whitespace is trimmed; an empty prefix is an error. Cannot be combined with a non-empty `index`. With neither argument, searches `ax-*`."+ "description": "Autoindex prefix, resolved by the same function as `xerj search --prefix` and `xerj autoindex --prefix`: lower-case [a-z0-9] runs joined by '-', so `project` searches `project-*` and `My_Proj` searches `my-proj-*`. A trailing `-*` is dropped. Whitespace is trimmed. An empty prefix, a prefix with no [a-z0-9] character, or a prefix that cannot name an index is an error before any request. Cannot be combined with a non-empty `index`. With neither argument, searches `ax-*` (the CLI default when `--prefix` is omitted)."},"query": {"type": [