FOR AI · 03

Endpoint contract

The exact wire contract for the six HTTP agent operations plus the data endpoints they build on, and the three MCP-only Corpus Hub tools. The seventh canonical operation, xerj_autoindex, is a CLI subcommand with no endpoint — its contract is in the zero-config indexing recipe. Everything is on port 9200, JSON in and JSON out. Optional fields are marked ?. Response shapes are shown as they actually come back from a live XERJ.

At a glance

METHOD
PATH
DESCRIPTION
POST
xerj_search — keyword / structured (match, term, bool, range).
POST
xerj_semantic_search — semantic query; server embeds the query text.
POST
xerj_vector_search — top-level knn; HNSW-served with exact rescoring when unfiltered, exact scan when filtered.
POST
xerj_hybrid_search — hybrid query; rrf or linear fusion.
POST
xerj_memory_store — store a memory (text auto-embedded).
POST
xerj_memory_recall — recall top-k by meaning / keyword / vector.
GET
List recent entries in a namespace (bounded, recent first).
DELETE
Forget one memory. DELETE /_memory/:ns drops the namespace.
PUT
Create an index with a mapping (semantic_text, dense_vector, …).
POST/PUT
Index a document. POST = auto-id, PUT /_doc/:id = explicit id.
POST
NDJSON bulk: index, create, update, delete.

Routes: engine/crates/xerj-api/src/router.rs · handlers: es_compat.rs, memory_api.rs

Standard ES query DSL on POST /{index}/_search: match (BM25 full-text), term/terms (exact), range, bool (must/should/must_not/filter), plus from, size, sort, _source, aggs, highlight. See the full query-types reference.

POST /notes/_search
{"query": {"match": {"body": "deployment"}}, "size": 5, "_source": ["body"]}

→ {"hits": {"total": {"value": 1, "relation": "eq"},
            "hits": [{"_id": "1", "_score": 0.28…,
                      "_source": {"body": "How do I roll back a bad deployment?"}}]}}

xerj_semantic_search — retrieve by meaning

Requires a field mapped as semantic_text (see creating an index). XERJ auto-embeds that field on ingest into a companion <field>_vector; the semantic query embeds the query text the same way and ranks by vector similarity — no client-side embedding, no external key.

FieldTypeMeaning
fieldstringThe semantic_text field to search.
querystringNatural-language query. Embedded server-side.
k?intNeighbors to retrieve (default 10).
filter?queryPre-filter clause applied before scoring.
boost?floatScore multiplier for this clause.
POST /notes/_search
{"query": {"semantic": {"field": "body", "query": "undo a failed rollout", "k": 2}},
 "_source": ["body"]}

→ top hit _id "2" — "Reverting a broken release to the previous version." (shares no words)

Honesty: the zero-config built-in embedder is deterministic and lexical, not a large neural model — great for offline, reproducible retrieval. For meaning-based matching, start the node with --embed-mode neural (the built-in BERT encoder) or --embed-mode proxy (your own OpenAI-compatible embeddings service) and re-index; the query shape is unchanged. An inference_id / inference_endpoint in the mapping does not switch the embedder: the create response says so in a warning.

Which embedder answered

GET /v1/embedding/identity names the node's embedder in data.backend (lexical, neural, proxy, onnx-experimental), with no model path, URL or key. On main (not in rc.104), the MCP tools xerj_search, xerj_semantic_search, xerj_hybrid_search and xerj search --json copy it into the response, and add one hint when a natural-language question ran on a lexical node:

"_xerj": {
  "embed_mode": "lexical",
  "hints": [{"code": "lexical_embedder",
             "reason": "This is a keyword search, and this node's embedder is lexical feature hashing (embed_mode: lexical, the default), so semantic and hybrid search would also match words, not meaning. …"}]
}

A lookup (parse_config, Tree::flush, one or two words) gets embed_mode and no hint. A node that does not answer the identity read (an old build, or a key without access) gets neither: the tools never guess the default. Rephrase with the words and identifiers the target text uses, or call xerj_def for a definition.

xerj_vector_search — kNN

Bring your own embeddings: map a dense_vector field, store vectors on each doc, and pass a query_vector as a top-level knn block (ES 8.x shape).

FieldTypeMeaning
fieldstringThe dense_vector field.
query_vectorfloat[]Query embedding (same dims as the field). vector also accepted.
k?intNeighbors to return (default 10).
num_candidates?intAccepted for ES compatibility.
POST /notes/_search
{"knn": {"field": "embedding", "query_vector": [0.1, 0.9, 0.0], "k": 2},
 "_source": ["body"]}

→ [("1", 1.0), ("2", 0.9998)]   # exact cosine scores

Honesty: unfiltered knn is HNSW-served (approximate) with exact rescoring — measured recall@10 1.00 on the official bench query, 100-probe mean 0.976; recall is measured, not guaranteed, and num_candidates sets the beam width (floored at 800). Filtered kNN, non-cosine metrics, SQ8 fields, and indexes under 1,024 docs run the exact brute-force scan (recall 1.00; latency scales with vectors scanned).

xerj_hybrid_search — fuse keyword + vector

Run several sub-queries and fuse their rankings in one call. Each entry in queries is {"query": {…}, "weight"?: float}; fusion is "rrf" (reciprocal-rank fusion, default) or "linear" (weighted score sum).

POST /notes/_search
{"query": {"hybrid": {
   "queries": [
     {"query": {"match": {"body": "rollback deployment"}}},
     {"query": {"knn": {"field": "embedding", "query_vector": [0.1,0.9,0.0], "k": 3}}}
   ],
   "fusion": "rrf"
 }},
 "_source": ["body"]}

→ fused ranking over both sub-queries (RRF k=60)

Honesty: only rrf and linear are implemented. Requesting "fusion":"learned" fails loudly:

→ "reason": "parse error: hybrid fusion learned is not yet supported; use rrf or linear"

xerj_memory_store

POST /_memory/{namespace}. The namespace is created on first store. A memory needs at least text or a vector. Text is always BM25-indexed and auto-embedded (so it is semantically recallable); a supplied vector additionally enables kNN recall.

FieldTypeMeaning
textstringThe memory. Auto-embedded + BM25-indexed.
metadata?objectArbitrary tags; subfields filterable as metadata.x.
vector?float[]Your own embedding; enables kNN recall. Fixes the namespace's vector dims.
id?stringExplicit id; a UUID is generated if omitted.
dedup?boolIf true, skip storing a near-duplicate of an existing memory.
dedup_threshold?floatCosine threshold for dedup (default 0.95).
POST /_memory/agent-demo
{"text": "The user prefers metric units and a dark UI theme.", "metadata": {"kind": "preference"}}

→ 201 {"created": true, "id": "77eff57b-…", "namespace": "agent-demo"}
   # dedup hit → 200 {"created": false, "deduplicated": true, "id": "…", "score": 0.97}

xerj_memory_recall

POST /_memory/{namespace}/_recall. The body picks the mode: an explicit vector → kNN; else "semantic": true with a query → server-side semantic recall; else query alone → BM25; empty body → recent memories.

FieldTypeMeaning
query?stringText query — BM25, or embedded when semantic:true.
semantic?boolEmbed query server-side and recall by similarity.
vector?float[]Recall by kNN against a supplied embedding. Wins over query.
k?intNumber of memories to return (default 10).
filter?queryMetadata pre-filter, e.g. {"term":{"metadata.kind":"preference"}}.
recency_weight?floatBlend recency into ranking in [0,1] (0 = pure relevance).
POST /_memory/agent-demo/_recall
{"query": "what display settings does the user like?", "semantic": true, "k": 2}

→ {"hits": [{"id": "77eff57b-…", "text": "The user prefers metric units and a dark UI theme.",
             "metadata": {"kind": "preference"}, "score": 0.6555…}],
   "namespace": "agent-demo"}

Recall of an unknown namespace returns {"hits": [], "namespace": …} — isolation is structural: each namespace is a physically separate index, so a recall in one can never read another.

List a namespace

GET /_memory/{namespace} returns a bounded, recent-first view for debugging/audit (up to 100 entries) — not a full export.

GET /_memory/agent-demo
→ {"namespace": "agent-demo", "exists": true, "count": 2,
   "entries": [{"id": "…", "text": "…", "metadata": {…}, "score": 1.0}, …]}

Forget

DELETE /_memory/agent-demo/77eff57b-…   → {"forgotten": true,  "id": "77eff57b-…", "namespace": "agent-demo"}
DELETE /_memory/agent-demo              → {"dropped": true, "namespace": "agent-demo"}

Data endpoints the ops build on

To use semantic, knn, or hybrid over your own data you first create an index and put documents in it. These are the standard ES-compatible calls (full reference: ES-compat API).

# create an index with a semantic_text + dense_vector mapping
PUT /notes
{"mappings": {"properties": {
   "body":      {"type": "semantic_text"},
   "embedding": {"type": "dense_vector", "dims": 3, "similarity": "cosine"}
}}}
→ {"acknowledged": true, "shards_acknowledged": true, "index": "notes"}

# index a document with an EXPLICIT id (PUT) …
PUT /notes/_doc/1
{"body": "How do I roll back a bad deployment?", "embedding": [0.1, 0.9, 0.0]}
→ {"_index": "notes", "_id": "1", "result": "created", …}

# … or with an AUTO id (POST, no id in the path)
POST /notes/_doc
{"body": "A note without an id", "embedding": [0.2, 0.7, 0.1]}
→ {"_id": "<uuid>", "result": "created", …}

# bulk NDJSON (Content-Type: application/x-ndjson)
POST /logs/_bulk
{"index":{"_id":"1"}}
{"service":"auth","level":"error","message":"login failed"}
→ {"errors": false, "items": [{"index": {"status": 201, …}}]}

Freshly indexed documents become searchable after a refresh; call POST /{index}/_refresh in a test loop, or rely on the periodic refresh in normal operation.

Corpus Hub tools (MCP only)

Three MCP tools answer from Corpus Hub packs: pinned, signed corpora that CI has already indexed. They have no HTTP endpoint of their own; xerj mcp runs the same flow as the xerj ask command, against the node on XERJ_URL or, when none answers there, the node xerj ask starts. A build with no hub key does not list them.

xerj_hub_ask   {question: string, corpus?: string, mode?: "def"|"how"|"files", max_tokens?: 1..8192}
               → one answer; with no corpus, routed like xerj ask (several candidates come back
                 as a list: re-ask with corpus)
xerj_hub_def   {slug: string, symbol: string, k?: 1..50}
               → the definition: file:line, declaration, value: for a constant or macro
xerj_hub_find  {question: string, k?: 1..10}
               → candidate corpora with pin, licence and whether the pack is cached; no passages

The result text is the same rendering the shell prints; the structured content is the answer JSON (corpus, pin_sha, pin_date, age_days, licence_spdx, licence_class, answered_from, mode, hits[] with file, line, kind, text, value, score, licence_warning, then truncated, warnings). Example, xerj_hub_def {"slug": "lz4", "symbol": "LZ4_VERSION_RELEASE"}:

lz4  pin 2026-10-02 (15 days old)  mixed: BSD-2 (lib) / GPL-2.0+ (rest)  lz4/lib/lz4.h:133
#define LZ4_VERSION_RELEASE  0    /* for tweaks, bug-fixes, or development */
value: 0
  approach-only licence (mixed: BSD-2 (lib) / GPL-2.0+ (rest)): read, do not copy
answered from: local pack
warning: approach-only licence (mixed: BSD-2 (lib) / GPL-2.0+ (rest)): read, do not copy

The tools never download. A tool call does not wait on the network: it reads the catalogue already cached and the packs already on the machine. Until a human or a shell agent has run xerj hub sync once and xerj hub pull <slug> for the corpus, the call returns isError: true with the command to run:

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 (…)
no local pack for 'lz4' and --no-fetch forbids downloading it; run: xerj hub pull lz4 (5.5 MB)

Report that line to the user; do not answer from memory instead. Registration per client, the routing rules and every other message: Corpus Hub · MCP. Schemas: per release, and for main.

Tools: engine/crates/xerj-mcp/src/lib.rs · flow: engine/crates/xerj-hub/src/ask.rs

xerj_references: where an identifier is used (MCP only)

After xerj_def found a definition, xerj_references returns every indexed line that names the exact identifier, with the definitions listed apart. It is lexical, not a call graph: comments and strings count, a call through an alias does not, and two symbols with one name are not told apart. Callers, callees and impact need call edges from the parse; they are a follow-up (#1791).

xerj_references  {symbol: string, prefix?: string, index?: string, from?: int, size?: 1..500, max_tokens?: int}
→ {"symbol": "Opstamp", "total": 78, "files": 18, "from": 0, "size": 2,
   "references": [{"path": "examples/index_from_multiple_threads.rs", "line": 33, "text": "use tantivy::{doc, Index, IndexWriter, Opstamp, TantivyError};"},
                  {"path": "examples/index_from_multiple_threads.rs", "line": 93, "text": "let opstamp: Opstamp = {",
                   "enclosing": {"name": "main", "kind": "function", "line": 35}}],
   "definitions": [{"path": "src/lib.rs", "line": 308, "text": "pub type Opstamp = u64;"}],
   "unlocated_total": 0, "unlocated": [], "next_from": 2, "truncated": false, …}

How: the node finds the files whose stored text holds the identifier, as a phrase or inside a longer token such as searcher.doc_freq; each file is then scanned line by line, case-sensitive, with word boundaries as grep -w draws them. A line that declares the name (from the file's symbol catalogue) goes to definitions. A mention in a stored block whose lines cannot be mapped back to the file goes to unlocated with its path and text, never with a guessed line.

Measured against ripgrep (rg -n -w -F, every line it prints counted as truth; ours = references + definitions), main 4b90a220e + this change, 2026-11-20:

Tool: engine/crates/xerj-mcp/src/references.rs

MCP tool schemas, per release

Two files, both generated from a real tools/list, never written by hand:

Read the file that matches xerj --version. To check it against the binary you hold, from a checkout of the release tag:

XERJ_BIN="$(command -v xerj)" scripts/mcp-schema-check.sh --release
→ RESULT: PASS — published schema matches the binary (24 tools)

The xerj_status tool also lists the tools the running binary serves, with its version.

Computer-use tools and AI-coworker apps

xerj mcp is a stdio server. These setups were checked against each project's own docs on 2026-11-19; xerj init prints them with your binary's absolute path and writes none of them.

agent-desktop and agent-browser (vercel-labs). Both are MCP servers themselves (agent-desktop mcp, agent-browser mcp), not clients: they run inside a coding agent. Register xerj in that agent's mcpServers, beside them, so the agent that drives the desktop or the browser can also search the project and the files it downloaded:

{"mcpServers": {
  "agent-browser": {"command": "agent-browser", "args": ["mcp"]},
  "agent-desktop": {"command": "agent-desktop", "args": ["mcp"]},
  "xerj": {"command": "/abs/path/to/xerj", "args": ["mcp"]}
}}

Index what they produce like any folder: xerj autoindex ~/Downloads --prefix downloads, then search with --prefix downloads. Restart the agent; success: xerj_search is in its tool list next to desktop_snapshot or the browser tools.

OpenMausBot. Open Plugins → MCP servers → Add server and paste:

{"mcpServers": {"xerj": {"command": "/abs/path/to/xerj", "args": ["mcp"]}}}

Success: the row says Connected: <N> tools. The registry is ~/.openmausbot/config.json. If xerj is already registered in Claude Code, OpenMausBot's first-run import copies it in switched off: turn xerj on in Plugins → MCP servers. For a node that is not on localhost:9200, add "env": {"XERJ_URL": "http://host:port"}, and "XERJ_AUTH": "ApiKey <key>" when it is not a loopback node.

CopilotKit OpenBot. It adds MCP servers by URL only (Connections → Add server), and refuses localhost, IP literals and plain http. Serve xerj mcp --http with a token, publish it through a tunnel (Remote MCP below), and enter https://<tunnel-host>/mcp. OpenBot first asks the server with no credential; xerj answers 401 with no OAuth sign-in, so OpenBot asks for a key: paste the token. In the team edition only an admin may give a key. OPENBOT_ALLOW_LOOPBACK_MCP=1 admits http://127.0.0.1:9330/mcp for development only. Checked against OpenBot's docs/plugins/mcp-by-url.md on 2026-11-20, not yet against a running OpenBot.

nightly-labs OpenBot. Not yet tested: whether its per-workspace Codex and Claude agents read a project .mcp.json is still open (#2756). Until then, register once per agent with that agent's own user-scope command (for Claude Code: claude mcp add --scope user xerj -- /abs/path/to/xerj mcp).

Printed by: engine/crates/xerj-autoindex/src/init.rs (desktop_agent_registration, remote_registration)

Remote MCP: xerj mcp --http for cloud agents

Cloud agents, hosted chat apps and URL-only clients cannot start a local process. xerj mcp --http serves the same tools over MCP Streamable HTTP (spec 2025-06-18): one endpoint, /mcp, JSON-RPC over POST, the same handlers as stdio. stdio stays the default.

export XERJ_MCP_TOKEN="$(openssl rand -hex 32)"   # or --token-file <path>
xerj mcp --http                                   # http://127.0.0.1:9330/mcp
→ xerj-mcp v… — MCP Streamable HTTP server at http://127.0.0.1:9330/mcp, proxying to http://localhost:9200
→ xerj-mcp: 15 tools served (read-only; --allow-writes serves the rest); auth: bearer token required (from XERJ_MCP_TOKEN)

Verify from the same machine:

curl -s http://127.0.0.1:9330/mcp -H "Authorization: Bearer $XERJ_MCP_TOKEN" \
  -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '.result.tools | length'
→ 15

What is enforced.

Publish it (pick one; each gives an https:// host):

tailscale serve --bg 9330                      # your tailnet only; `tailscale funnel 9330` for the internet
cloudflared tunnel --url http://127.0.0.1:9330  # prints https://<name>.trycloudflare.com
ngrok http 9330                                 # prints https://<name>.ngrok-free.app

Give the agent https://<tunnel-host>/mcp and the header Authorization: Bearer <token>. Client shapes:

claude mcp add --transport http xerj https://<tunnel-host>/mcp --header "Authorization: Bearer <token>"
{"mcpServers": {"xerj": {"type": "http", "url": "https://<tunnel-host>/mcp",
                         "headers": {"Authorization": "Bearer <token>"}}}}

Verify through the tunnel with the same curl, host swapped; expect the same tool count. xerj init prints these lines with your binary's path. Clients that only do OAuth sign-in, with no way to send a static header, cannot use this endpoint yet.

Transport: engine/crates/xerj-mcp/src/http.rs · flags: xerj mcp --help