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.

11.0 KB
Raw Blame

Corpus Hub v2 — gRPC + MCP implementer notes

Internal note for the step-7 implementer of docs/CORPUS_HUB_V2_IMPLEMENTATION.md (discussion #1374). It records the gRPC wire contract this change locks, the MCP tool specs to add later, and the one rule both surfaces must obey. It is not user documentation.

This PR (branch feat/hub-v2-grpc-contract, based on feat/hub-v2-base) does only the contract: it adds the XerjHub service and its messages to engine/proto/xerj.proto. The service trait and client are generated by engine/crates/xerj-server/build.rs (tonic/prost), but the server impl, the add_service registration in grpc.rs/main.rs, and the MCP tools are deferred to step 5/7. Generated-but-unimplemented scaffolding is intentional.

Opt-in answer evidence receipts (#1789, #1786)

The implemented MCP xerj_hub_ask and xerj_hub_def tools accept an optional evidence object with required session_id and tool_call_id strings and an optional p_min probability (default 0.8). Identities are caller supplied; each result is a standalone, one-entry report, not a persisted session log. When an answer is available, this adds only structuredContent.evidence_receipt, a xerj-trace-evidence/v1 report; omitting the option preserves the entire existing result. Routing hints and errors without an answer remain unchanged. The receipt records the exact MCP text, including notices.

The shared Rust bridge is Answer::evidence_report(AnswerEvidence, resolve); Hit::pinned_citation anchors an exact excerpt on its declared one-based line. The resolver must provide original UTF-8 bytes from the answer's immutable pin_sha and hit file, plus the repository identity. Byte offsets and SHA-256 hashes retain CRLF and multibyte characters without normalization. A mismatched excerpt, invalid pin/path or resolver error returns an error. An unavailable source is represented by None and yields an explicit coverage gap. TraceEvidenceReport::to_jcs emits RFC 8785 canonical JSON; verify rechecks the receipt and resolves each citation against the pinned file bytes.

Claims bind retrieved excerpt text, not semantic entailment. Callers must separately assess question coverage and provide a held-out, in-domain Confidence; ranking scores are never converted to probabilities. Empty hits, missing source/calibration, low calibrated confidence, coverage gaps, truncated answers, and separately rendered values without an assessment abstain and escalate. Current MCP index records do not contain original pinned files or an in-domain calibration assessment, so MCP receipts conservatively abstain and escalate even when hits exist. MCP does not read working-tree files, fetch source files, or accept caller-supplied confidence/bytes. This is additive wiring, not a new calibration study or completion of either issue's evaluation gates. No gRPC field or default Answer/Hit field changes.

Why the fields are frozen

Proto field numbers are a permanent wire contract. Step 11 of the plan lists "renumber proto fields" under do not. The numbers below are chosen once, contiguously, and must never be renumbered, reused, or repurposed. A new field may only be appended with the next free number in its message. Every message in the proto carries a comment recording its live field-number range.

Proto ↔ xerj-common::hub mapping

The messages mirror the shared Rust types in engine/crates/xerj-common/src/hub.rs one-to-one, so gRPC, the MCP tools and the CLI all speak one vocabulary.

HubAnswer ↔ hub::Answer (11 fields, 1–11)

proto field (#) Answer field Rust type Wire form / note
corpus (1) corpus String
pin_sha (2) pin_sha String
pin_date (3) pin_date String YYYY-MM-DD
age_days (4) age_days u32 proto uint32
licence_spdx (5) licence_spdx String
licence_class (6) licence_class LicenceClass serde kebab-case: adapt-with-attribution | approach-only | excluded
answered_from (7) answered_from AnsweredFrom serde snake_case: local_pack | hosted | local_index (NOT the .label() prose)
mode (8) mode AnswerMode serde snake_case: def | how | files
hits (9) hits Vec<Hit> repeated HubHit
truncated (10) truncated bool
warnings (11) warnings Vec<String> repeated string, one line each

Enums carry the serde string form (serde_json::to_value(..)), not the human-printed AnsweredFrom::label() ("local pack"/"hosted hub"/"local index"), which is for the step-1 renderer only.

HubHit ↔ hub::Hit (7 fields, 1–7)

proto field (#) Hit field Rust type Wire form / note
file (1) file String
line (2) line u32 proto uint32, 1-based
kind (3) kind String
text (4) text String
value (5) value Option<String> None ↔ "" (see below)
score (6) score f32 proto float
licence_warning (7) licence_warning Option<String> None ↔ "" (see below)

Option<String> ↔ proto3 string. proto3 scalar strings have no presence: a plain string cannot be null. The chosen contract (matching step 7's proto, which does not mark these optional) is None ↔ "". The step-7 conversion code maps None → "" on the way out and "" → None on the way in, for both value and licence_warning. This is lossless in practice: a present value (a const/macro literal) or a present licence_warning (a licence name) is never legitimately the empty string. If a future need arises to distinguish "absent" from "empty", add optional then — do not renumber.

Request / catalogue messages

message fields (#) maps to
HubAskRequest question (1), corpus (2), mode (3), max_tokens (4) the step-5 ask flow params; corpus/mode empty = auto, max_tokens 0 = default
HubDefRequest slug (1), symbol (2), k (3) the def lookup; k 0 = default
HubCatalogueRequest (none) a catalogue fetch takes no arguments
HubCatalogueResponse catalogue_json (1, bytes), signature (2, bytes) catalogue_json = serialized hub::Catalogue as the exact bytes the ed25519 signature covers (verify before trusting)

MCP tools to add to xerj-mcp tool_specs() (step 7, DEFERRED)

Add these three to tool_specs() (and the dispatch) in engine/crates/xerj-mcp/src/lib.rs. They follow the existing spec shape (name, description, inputSchema with type: "object", properties, required). xerj_hub_ask/xerj_hub_def return an Answer; the tool result text is the step-1 hub::render output and the structured content is the Answer JSON. xerj_hub_find returns the step-6 /search corpus grouping (candidate corpora, not passages — it is discovery, not an Answer).

{
  "name": "xerj_hub_find",
  "description": "Discover which hub corpora can answer a question (the step-6 /search grouping). Returns candidate corpora with their pin/licence, not passages. Local packs first, hosted second — exactly like the CLI.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "question": { "type": "string", "description": "What the agent is working on; a corpus name is never required here." },
      "k": { "type": "integer", "description": "Max candidate corpora to return (default engine value)." }
    },
    "required": ["question"]
  }
}
{
  "name": "xerj_hub_def",
  "description": "Look up one definition in a named hub corpus: its kind, signature, and the literal value for a const/macro/define. Returns an Answer in def mode (no passages).",
  "inputSchema": {
    "type": "object",
    "properties": {
      "slug": { "type": "string", "description": "Corpus slug to resolve the symbol in." },
      "symbol": { "type": "string", "description": "Exact definition name." },
      "k": { "type": "integer", "description": "Max hits to return (default engine value)." }
    },
    "required": ["slug", "symbol"]
  }
}
{
  "name": "xerj_hub_ask",
  "description": "Ask a hub corpus a question in one turn — no clone, no local indexing. Local packs first, hosted second. The corpus is optional (routed by the offline sketch when omitted) and is always named in the answer. Result text is the hub.rs rendering; structured content is the Answer JSON.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "question": { "type": "string", "description": "Natural-language question." },
      "corpus": { "type": "string", "description": "Optional explicit corpus slug; omit to route by sketch." },
      "mode": { "type": "string", "enum": ["def", "how", "files"], "description": "Answer shape; omit for auto." },
      "max_tokens": { "type": "integer", "description": "Soft output budget for the rendered answer." }
    },
    "required": ["question"]
  }
}

The one rule both surfaces obey

gRPC XerjHub::ask/def and MCP xerj_hub_ask/xerj_hub_def MUST call the single xerj_hub::ask / xerj_hub::def flow that lands in step 5 — they do NOT reimplement download / verify / restore / route. Each surface only converts its request into the shared params and converts the returned hub::Answer into its own wire form (HubAnswer for gRPC, rendered text + Answer JSON for MCP). XERJ_HUB_URL overrides the hosted base URL for both. This mirrors how the CLI and the xerj_code_search MCP tool already share xccode::run_code_query.

Step-7 wiring checklist

Status: items 1, 2 and 4's gRPC tests are implemented in engine/crates/xerj-server/src/grpc_hub.rs (the service is a thin adapter over xerj_api::hub_api::{def_answer, ask_answer, catalogue_signed} — the same def_core/code_core the /_hub/v1 routes run, and for Ask the xerj_hub::ask::ask flow itself with a read-only backend). Item 3 (MCP) ships separately.

  1. Implement the XerjHub trait in engine/crates/xerj-server/src/grpc.rs, converting HubAnswer ↔ hub::Answer per the tables above.
  2. Register XerjHubServer::with_interceptor(..) with .add_service(..) next to XerjSearchServer, behind the same interceptor (grpc.rs ~L478).
  3. Add the three tool specs + dispatch to xerj-mcp.
  4. Tests (from plan §7): tools/list contains the three names; xerj_hub_def against the fixture pack returns the fixture value; gRPC Def returns the same HubAnswer as the HTTP route (field by field); grpc_h2c_fail_closed.rs still passes.