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.

fix(hub-mcp): hub tools never fetch the catalogue inside a tool call

xerj-org7bc7248f0751
diff --git a/engine/crates/xerj-autoindex/src/init.rs b/engine/crates/xerj-autoindex/src/init.rs
index fdfe4c5a6..67da4aa47 100644
--- a/engine/crates/xerj-autoindex/src/init.rs
+++ b/engine/crates/xerj-autoindex/src/init.rs
@@ -167,6 +167,8 @@ sent to the hosted hub. `xerj hub config hosted off` forbids that.
A hub tool answers only from packs already on this machine; it never downloads one. When a corpus
is not here, the answer is the `xerj hub pull <slug>` line: run it in a shell, then ask again.
+Nor does a hub tool fetch the catalogue: it reads the cached copy. If it says no catalogue is
+cached, run `xerj hub sync` in a shell once, then call the tool again.
Register `xerj mcp` once, then restart the session. Success: `xerj_search` is in the tool list.
Use the absolute path to the binary: an editor started from a desktop icon does not inherit your
@@ -828,6 +830,7 @@ mod tests {
rest = &tail[end..];
}
assert!(HUB_SKILL_MD.contains("never downloads one"));
+ assert!(HUB_SKILL_MD.contains("run `xerj hub sync` in a shell once"));
assert!(!HUB_SKILL_MD.contains("has no hub tool"));
let printed = mcp_registration("/usr/local/bin/xerj", DEFAULT_URL);
assert!(printed.contains("xerj_search"));
diff --git a/engine/crates/xerj-hub/src/ask.rs b/engine/crates/xerj-hub/src/ask.rs
index 3b5c25591..50dea309e 100644
--- a/engine/crates/xerj-hub/src/ask.rs
+++ b/engine/crates/xerj-hub/src/ask.rs
@@ -139,6 +139,12 @@ pub struct AskArgs {
pub k: Option<usize>,
pub json: bool,
pub url: Option<String>,
+ /// Use only the catalogue already cached on this machine; never fetch it,
+ /// however old it is. Not a CLI flag: the MCP tools set it, so an agent's
+ /// tool call never blocks on the hub (the fetch's 10 s connect / 30 s
+ /// timeouts). With no cached copy the outcome is [`NO_CACHED_CATALOGUE`].
+ /// Unlike `offline`, the rest of the flow is unchanged.
+ pub cached_catalogue_only: bool,
}
impl AskArgs {
@@ -155,6 +161,7 @@ impl AskArgs {
k: None,
json: false,
url: None,
+ cached_catalogue_only: false,
}
}
}
@@ -1485,13 +1492,20 @@ pub fn run_ask_with(
.ok()
.filter(|u| !u.is_empty())
.unwrap_or_else(|| DEFAULT_HUB_URL.to_string());
- let catalogue = match load_catalogue(&hub_url, &hub_home, args.offline) {
- Ok(c) => c,
- Err(e) => {
- return AskOutcome::fail(
- EXIT_NO_ANSWER,
- format!("cannot load the hub catalogue: {e:#}"),
- )
+ let catalogue = if args.cached_catalogue_only {
+ match load_cached_catalogue(&hub_home) {
+ Ok(c) => c,
+ Err(msg) => return AskOutcome::fail(EXIT_NO_ANSWER, msg),
+ }
+ } else {
+ match load_catalogue(&hub_url, &hub_home, args.offline) {
+ Ok(c) => c,
+ Err(e) => {
+ return AskOutcome::fail(
+ EXIT_NO_ANSWER,
+ format!("cannot load the hub catalogue: {e:#}"),
+ )
+ }
}
};
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
@@ -1610,16 +1624,27 @@ pub fn find(
}
}
-/// Load the catalogue the way [`run_ask`] does and run [`find`] from the
-/// current directory.
+/// What a caller that never fetches the catalogue (the MCP tools) says when
+/// none is cached on this machine.
+pub const NO_CACHED_CATALOGUE: &str = "no hub catalogue is cached on this machine, and hub tools \
+ never fetch one (a tool call does not wait on the network); run `xerj hub sync` in a shell \
+ once, then call the tool again";
+
+/// The catalogue cached in `hub_home`, with no network access at all, however
+/// old it is (an old copy still warns on stderr). `Err` is
+/// [`NO_CACHED_CATALOGUE`] plus the underlying reason.
+pub fn load_cached_catalogue(hub_home: &Path) -> Result<Catalogue, String> {
+ // `offline = true` never builds an HTTP client; the URL is unused.
+ load_catalogue(DEFAULT_HUB_URL, hub_home, true)
+ .map_err(|e| format!("{NO_CACHED_CATALOGUE} ({e:#})"))
+}
+
+/// Load the catalogue already cached on this machine — never fetching it
+/// ([`load_cached_catalogue`]) — and run [`find`] from the current directory.
+/// Only the MCP `xerj_hub_find` tool calls this.
pub fn run_find(question: &str, k: usize) -> Result<FindOutcome, String> {
let hub_home = cli::hub_home();
- let hub_url = std::env::var("XERJ_HUB_URL")
- .ok()
- .filter(|u| !u.is_empty())
- .unwrap_or_else(|| DEFAULT_HUB_URL.to_string());
- let catalogue = load_catalogue(&hub_url, &hub_home, false)
- .map_err(|e| format!("cannot load the hub catalogue: {e:#}"))?;
+ let catalogue = load_cached_catalogue(&hub_home)?;
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
Ok(find(question, k, &cwd, &hub_home, &catalogue))
}
diff --git a/engine/crates/xerj-mcp/src/hub.rs b/engine/crates/xerj-mcp/src/hub.rs
index 48a65d649..b79ed9e5a 100644
--- a/engine/crates/xerj-mcp/src/hub.rs
+++ b/engine/crates/xerj-mcp/src/hub.rs
@@ -12,7 +12,7 @@
//!
//! The answer flow is the CLI's: local packs first, hosted second (this build
//! has no hosted client, so "hosted" is unavailable exactly as it is for the
-//! CLI), `XERJ_HUB_URL` overrides the catalogue's base URL, and the node is the
+//! CLI), the catalogue is the cached copy (below), and the node is the
//! one this server proxies to (`--url` / `XERJ_URL`), or the automatic hub node.
//! The tool result text is the §1 rendering with the flow's notices on top (MCP
//! has no stderr); the structured content is the [`xerj_hub::Answer`] JSON.
@@ -24,6 +24,11 @@
//! delete) behind an agent's back. Excluded corpora are never pulled or served
//! by the flow itself; approach-only answers carry the licence warning on every
//! hit.
+//!
+//! Nor does a tool call fetch the catalogue: the tools read the copy `xerj hub
+//! sync` (or any CLI `xerj ask` / `xerj hub pull`) cached, however old, and
+//! never block on the hub's 10 s/30 s fetch timeouts inside an agent's turn.
+//! With no cached copy the tool says to run `xerj hub sync`.
use serde_json::{json, Value};
use xerj_hub::ask::{
@@ -50,7 +55,8 @@ pub fn specs() -> Vec<Value> {
"with their pin, licence and whether the pack is already on this machine — not ",
"passages; ask one with xerj_hub_ask. Routed exactly as `xerj ask` routes: your ",
"project's dependencies, the signed catalogue's term sketches, and the exact ",
- "symbol a definition question names (offline; this build has no hosted search). ",
+ "symbol a definition question names (offline: reads the catalogue `xerj hub sync` ",
+ "cached and never fetches it; this build has no hosted search). ",
"Excluded-licence corpora are never listed."),
"inputSchema": {
"type": "object",
@@ -103,7 +109,8 @@ pub fn specs() -> Vec<Value> {
"the offline sketch when omitted) and is always named in the answer; when more than ",
"one corpus fits, the candidates come back and you re-ask with `corpus`. Never ",
"downloads a pack: a corpus not on this machine is answered with the `xerj hub ",
- "pull` line to run. Result text is the hub rendering (corpus, pin date, licence, ",
+ "pull` line to run, and never fetches the catalogue: with none cached it says to run ",
+ "`xerj hub sync`. Result text is the hub rendering (corpus, pin date, licence, ",
"file:line); structured content is the Answer JSON."),
"inputSchema": {
"type": "object",
@@ -239,10 +246,11 @@ async fn ask_tool(ctx: &Ctx, args: &Value) -> Result<Value, String> {
Ok(run(ctx, a).await)
}
-/// Run the CLI's flow for `a` (never fetching) against this server's node and
-/// turn the outcome into a tool result.
+/// Run the CLI's flow for `a` (never fetching a pack or the catalogue) against
+/// this server's node and turn the outcome into a tool result.
async fn run(ctx: &Ctx, mut a: AskArgs) -> Value {
a.no_fetch = true;
+ a.cached_catalogue_only = true;
a.json = false;
a.url = Some(ctx.base_url.clone());
let launcher = match launcher() {
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index 184dfd69b..19d35270e 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -129,7 +129,8 @@ is ALREADY RUNNING. This command does not start a node; start one first with
It also serves three Corpus Hub tools — xerj_hub_find, xerj_hub_def,
xerj_hub_ask — which run the `xerj ask` flow: answered from packs already on
this machine (a tool call never downloads one; it names the `xerj hub pull`
-line instead). Like `xerj ask`, they use the node above when it answers and
+line instead), from the catalogue already cached (never fetched; with none
+cached they say to run `xerj hub sync`). Like `xerj ask`, they use the node above when it answers and
otherwise the automatic hub node.
OPTIONS:
diff --git a/engine/crates/xerj-mcp/tests/hub_tools.rs b/engine/crates/xerj-mcp/tests/hub_tools.rs
index 4ee7ba497..62df42c37 100644
--- a/engine/crates/xerj-mcp/tests/hub_tools.rs
+++ b/engine/crates/xerj-mcp/tests/hub_tools.rs
@@ -390,4 +390,76 @@ async fn hub_tools_answer_from_a_local_pack_and_never_download() {
.await
.unwrap();
assert_eq!(cat.as_array().unwrap().len(), 4, "{cat}");
+
+ // ── a tool call never fetches the catalogue (#B, review of 9dffe9fcc) ──
+ // A hub that accepts and counts connections. Before the fix, a stale or
+ // missing cache sent `xerj_hub_find` and `xerj_hub_ask` to the network
+ // (up to the 10 s/30 s fetch timeouts) from inside an agent's tool call.
+ let hub_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let hub_url = format!("http://{}", hub_listener.local_addr().unwrap());
+ let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ {
+ let hits = hits.clone();
+ std::thread::spawn(move || {
+ for conn in hub_listener.incoming() {
+ hits.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ drop(conn);
+ }
+ });
+ }
+ std::env::set_var("XERJ_HUB_URL", &hub_url);
+ let requests = || hits.load(std::sync::atomic::Ordering::SeqCst);
+
+ // A stale cache (older than the 24 h freshness window) is still served as is.
+ let two_days_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(48 * 3600);
+ std::fs::File::options()
+ .write(true)
+ .open(hub.join("catalogue.json"))
+ .unwrap()
+ .set_modified(two_days_ago)
+ .unwrap();
+ let r = call(
+ &url,
+ "xerj_hub_find",
+ json!({"question": "what is the value of MINI_LIMIT"}),
+ )
+ .await;
+ assert_eq!(r["isError"], false, "{r}");
+ assert_eq!(r["structuredContent"]["corpora"][0]["slug"], "mini-c");
+ let r = call(
+ &url,
+ "xerj_hub_def",
+ json!({"slug": "mini-c", "symbol": "MINI_LIMIT"}),
+ )
+ .await;
+ assert_eq!(r["isError"], false, "{r}");
+ assert_eq!(r["structuredContent"]["hits"][0]["value"], "128");
+ assert_eq!(
+ requests(),
+ 0,
+ "a stale cache made a tool call fetch the catalogue"
+ );
+
+ // No cache at all: every tool says to run `xerj hub sync`, and still fetches nothing.
+ std::fs::remove_file(hub.join("catalogue.json")).unwrap();
+ for (name, args) in [
+ ("xerj_hub_find", json!({"question": "MINI_LIMIT"})),
+ (
+ "xerj_hub_ask",
+ json!({"question": "what is the value of MINI_LIMIT"}),
+ ),
+ (
+ "xerj_hub_def",
+ json!({"slug": "mini-c", "symbol": "MINI_LIMIT"}),
+ ),
+ ] {
+ let r = call(&url, name, args).await;
+ assert_eq!(r["isError"], true, "{name}: {r}");
+ assert!(text(&r).contains("xerj hub sync"), "{name}: {}", text(&r));
+ }
+ assert_eq!(
+ requests(),
+ 0,
+ "a missing cache made a tool call fetch the catalogue"
+ );
}
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index 06429f9e1..ce68e576d 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -607,7 +607,7 @@
},
{
"name": "xerj_hub_find",
- "description": "Discover which hub corpora can answer a question. Returns candidate corpora with their pin, licence and whether the pack is already on this machine — not passages; ask one with xerj_hub_ask. Routed exactly as `xerj ask` routes: your project's dependencies, the signed catalogue's term sketches, and the exact symbol a definition question names (offline; this build has no hosted search). Excluded-licence corpora are never listed.",
+ "description": "Discover which hub corpora can answer a question. Returns candidate corpora with their pin, licence and whether the pack is already on this machine — not passages; ask one with xerj_hub_ask. Routed exactly as `xerj ask` routes: your project's dependencies, the signed catalogue's term sketches, and the exact symbol a definition question names (offline: reads the catalogue `xerj hub sync` cached and never fetches it; this build has no hosted search). Excluded-licence corpora are never listed.",
"inputSchema": {
"type": "object",
"properties": {
@@ -656,7 +656,7 @@
},
{
"name": "xerj_hub_ask",
- "description": "Ask a hub corpus a question in one turn — no clone, no local indexing. Local packs first, hosted second, exactly like `xerj ask`. The corpus is optional (routed by the offline sketch when omitted) and is always named in the answer; when more than one corpus fits, the candidates come back and you re-ask with `corpus`. Never downloads a pack: a corpus not on this machine is answered with the `xerj hub pull` line to run. Result text is the hub rendering (corpus, pin date, licence, file:line); structured content is the Answer JSON.",
+ "description": "Ask a hub corpus a question in one turn — no clone, no local indexing. Local packs first, hosted second, exactly like `xerj ask`. The corpus is optional (routed by the offline sketch when omitted) and is always named in the answer; when more than one corpus fits, the candidates come back and you re-ask with `corpus`. Never downloads a pack: a corpus not on this machine is answered with the `xerj hub pull` line to run, and never fetches the catalogue: with none cached it says to run `xerj hub sync`. Result text is the hub rendering (corpus, pin date, licence, file:line); structured content is the Answer JSON.",
"inputSchema": {
"type": "object",
"properties": {