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.

feat(feedback): xerj feedback --submit and MCP xerj_field_report (#1770)

xerj-org8a365e792263
diff --git a/engine/crates/xerj-autoindex/src/feedback.rs b/engine/crates/xerj-autoindex/src/feedback.rs
index 181ebcd8c..a0c32b2c5 100644
--- a/engine/crates/xerj-autoindex/src/feedback.rs
+++ b/engine/crates/xerj-autoindex/src/feedback.rs
@@ -83,6 +83,14 @@ pub struct Cfg {
pub output: Option<PathBuf>,
pub open_pr: bool,
pub dry_run: bool,
+ /// POST the report to the field-report endpoint. Sends only with [`Cfg::yes`].
+ pub submit: bool,
+ /// The user has agreed. Without this, `--submit` prints the report and the
+ /// exact command and does not open a connection.
+ pub yes: bool,
+ /// Where `--submit` POSTs. From `XERJ_FIELD_REPORT_URL` or the production
+ /// default. Tests set this to a local mock so nothing reaches xerj.org.
+ pub endpoint: String,
/// Skip the running-node catalog probe entirely — for a fully offline draft
/// (and for tests, so they never touch a real endpoint).
pub no_autofill: bool,
@@ -140,6 +148,9 @@ pub fn parse(args: Vec<String>) -> Result<Option<Cfg>, String> {
output: None,
open_pr: false,
dry_run: false,
+ submit: false,
+ yes: false,
+ endpoint: xerj_common::field_report::endpoint_from_env(),
no_autofill: false,
};
while let Some(arg) = it.next() {
@@ -158,6 +169,8 @@ pub fn parse(args: Vec<String>) -> Result<Option<Cfg>, String> {
"-o" | "--output" => cfg.output = Some(PathBuf::from(next("--output")?)),
"--open-pr" => cfg.open_pr = true,
"--dry-run" => cfg.dry_run = true,
+ "--submit" => cfg.submit = true,
+ "--yes" => cfg.yes = true,
"--no-autofill" => cfg.no_autofill = true,
// Scanned out of band by `xerj_common::feedback`; accepted here so
// it is not "unknown".
@@ -176,12 +189,32 @@ pub fn parse(args: Vec<String>) -> Result<Option<Cfg>, String> {
.into(),
);
}
+ if cfg.open_pr && cfg.submit {
+ return Err(
+ "--open-pr and --submit are different ways to file the report. Drop one of the two"
+ .into(),
+ );
+ }
+ if cfg.dry_run && cfg.yes {
+ return Err(
+ "--dry-run and --yes contradict each other: --yes sends the report and --dry-run \
+ only prints it. Drop one of the two"
+ .into(),
+ );
+ }
+ if cfg.yes && !cfg.submit {
+ return Err(
+ "--yes sends a field report, and it only does that together with --submit. \
+ Drop --yes, or pass --submit --yes after the user has seen the report"
+ .into(),
+ );
+ }
Ok(Some(cfg))
}
-/// Resolve the draft, render it, and act on the mode (`--dry-run`, `--open-pr`,
-/// or the default stdout/`-o`).
-fn run(cfg: &Cfg) -> i32 {
+/// Resolve the draft, render it, and act on the mode (`--dry-run`, `--submit`,
+/// `--open-pr`, or the default stdout/`-o`).
+pub fn run(cfg: &Cfg) -> i32 {
let date = today();
// Auto-fill "what was indexed" only when asked to and only from a node that
// actually answers; any failure leaves `None` → placeholder, never a
@@ -203,8 +236,12 @@ fn run(cfg: &Cfg) -> i32 {
let mut out = io::stdout().lock();
let _ = writeln!(out, "{report}");
let _ = writeln!(out, "\n{commands}");
+ let _ = writeln!(out, "\n{}", xerj_common::feedback::PERMISSION_LINE);
return 0;
}
+ if cfg.submit {
+ return submit_report(cfg, &draft, &report);
+ }
if cfg.open_pr {
return open_pr(&draft, &report, &commands);
}
@@ -542,6 +579,10 @@ fn open_pr_at(dir: Option<&Path>, draft: &Draft, report: &str, commands: &str) -
fork it, push `{branch}` to your fork and open the PR with \
`gh pr create --repo xerj-org/xerj --head YOUR_LOGIN:{branch}`."
);
+ eprintln!(
+ "No GitHub account: {}. Then, if they agree, `xerj feedback --submit --yes`.",
+ xerj_common::feedback::PERMISSION_LINE
+ );
eprintln!("The report and the exact commands to run there:\n");
println!("{report}");
println!("\n{commands}");
@@ -553,7 +594,11 @@ fn open_pr_at(dir: Option<&Path>, draft: &Draft, report: &str, commands: &str) -
if let Err(reason) = gh_ready() {
eprintln!("error: cannot open the pull request automatically: {reason}");
eprintln!(
- "Falling back to the exact commands — run these yourself (the sandboxed-agent path):\n"
+ "Falling back to the exact commands — run these yourself (the sandboxed-agent path)."
+ );
+ eprintln!(
+ "No GitHub account: {}. Then, if they agree, `xerj feedback --submit --yes`.\n",
+ xerj_common::feedback::PERMISSION_LINE
);
println!("{commands}");
return 1;
@@ -881,6 +926,114 @@ fn current_branch(dir: Option<&Path>) -> Result<String, String> {
Ok(name)
}
+/// `--submit` without `--yes` prints this and posts nothing. `--yes` is the
+/// send. The JSON verdict is capped at 80 characters (the endpoint's schema);
+/// `notes` carries the full rendered report.
+fn submit_report(cfg: &Cfg, draft: &Draft, report: &str) -> i32 {
+ let payload =
+ xerj_common::field_report::Payload::from_input(&xerj_common::field_report::Input {
+ agent: &draft.agent,
+ used_for: &draft.used_for,
+ verdict: &draft.verdict,
+ version: &draft.version,
+ os: &draft.platform,
+ indexed: &draft.pointed_at,
+ notes: report,
+ });
+ let body = payload.json_string();
+ let command = submit_command(draft);
+ let curl = xerj_common::field_report::curl_command(&cfg.endpoint, &body);
+
+ if !cfg.yes {
+ print!("{}", unsent_message(&cfg.endpoint, report, &body, &command));
+ return 0;
+ }
+
+ if draft.agent == PH_AGENT || draft.used_for == PH_USED_FOR || draft.verdict == PH_VERDICT {
+ eprintln!(
+ "error: --submit --yes needs --agent, --used-for and --verdict filled in. \
+ Refusing to post a placeholder."
+ );
+ println!("{report}");
+ println!();
+ println!("{}", xerj_common::feedback::PERMISSION_LINE);
+ return 2;
+ }
+ if !payload.missing_required().is_empty() {
+ eprintln!(
+ "error: --submit --yes is missing {}",
+ payload.missing_required().join(", ")
+ );
+ return 2;
+ }
+
+ match post_field_report(&cfg.endpoint, &body) {
+ Ok((status, text)) if (200..300).contains(&status) => {
+ println!("{text}");
+ eprintln!("sent field report to {} (HTTP {status})", cfg.endpoint);
+ 0
+ }
+ Ok((status, text)) => {
+ eprintln!("error: field report endpoint returned HTTP {status}: {text}");
+ 1
+ }
+ Err(err) => {
+ eprintln!("error: could not send the field report: {err}");
+ eprintln!("Nothing was stored. The exact command, once the endpoint answers:");
+ println!("{command}");
+ println!("{curl}");
+ 1
+ }
+ }
+}
+
+/// What `--submit` prints when `--yes` was not passed. No connection is opened.
+fn unsent_message(endpoint: &str, report: &str, body: &str, command: &str) -> String {
+ let curl = xerj_common::field_report::curl_command(endpoint, body);
+ format!(
+ "{report}\n\n{permission}\nNot sent. Nothing was posted.\n\
+ HTTP body (verdict is capped at 80 characters; the report is in notes):\n\
+ {body}\n\nAfter the user agrees, send with:\n{command}\n{curl}\n",
+ permission = xerj_common::feedback::PERMISSION_LINE,
+ )
+}
+
+/// The command that sends this draft. Keeps `--agent` when one was passed.
+fn submit_command(d: &Draft) -> String {
+ let agent = if d.agent == PH_AGENT {
+ String::new()
+ } else {
+ format!(" \\\n --agent {:?}", d.agent)
+ };
+ format!(
+ "xerj feedback --submit --yes{agent} \\\n --used-for {:?} \\\n --verdict {:?}",
+ d.used_for, d.verdict
+ )
+}
+
+/// POST `body` as JSON. Does not send an `Authorization` header: the admin
+/// key belongs to the local node, not to this endpoint. No GitHub token is
+/// read.
+fn post_field_report(url: &str, body: &str) -> Result<(u16, String), String> {
+ if !(url.starts_with("https://") || url.starts_with("http://")) {
+ return Err(format!("field report URL must be http or https, got {url}"));
+ }
+ let client = reqwest::blocking::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()
+ .map_err(|e| e.to_string())?;
+ let response = client
+ .post(url)
+ .header("content-type", "application/json")
+ .header("user-agent", "xerj-feedback")
+ .body(body.to_string())
+ .send()
+ .map_err(|e| e.to_string())?;
+ let status = response.status().as_u16();
+ let text = response.text().unwrap_or_default();
+ Ok((status, text))
+}
+
pub fn print_help() {
println!("{}", help_text(xerj_common::feedback::enabled()));
}
@@ -894,6 +1047,7 @@ pub fn help_text(feedback: bool) -> String {
USAGE:\n\
xerj feedback [OPTIONS] draft a field report to stdout\n\
xerj feedback -o <PATH> [OPTIONS] also write it to <PATH>\n\
+ xerj feedback --submit [--yes] POST the report; sends only with --yes\n\
xerj feedback --open-pr [OPTIONS] commit ONLY the report + open a PR\n\
xerj feedback --dry-run [OPTIONS] print the report AND the commands; do nothing\n\
\n\
@@ -917,6 +1071,13 @@ pub fn help_text(feedback: bool) -> String {
-o, --output <PATH> also write the report to <PATH>\n\
--slug <TEXT> filename slug (default: derived from --used-for/--pointed-at);\n\
the file lands at {dir}/<YYYY-MM-DD>-<slug>.md\n\
+ --submit POST the report to the field-report endpoint\n\
+ (default https://xerj.org/api/field-report, override\n\
+ with XERJ_FIELD_REPORT_URL). Needs no GitHub token,\n\
+ no gh, and no checkout. Without --yes it prints the\n\
+ report, the JSON body and the exact command, and\n\
+ sends nothing\n\
+ --yes with --submit, send. Show the user the report first\n\
--open-pr create branch field-report/<slug>, commit ONLY that one file,\n\
and run `gh pr create --repo xerj-org/xerj`. Requires a\n\
checkout whose `origin` IS xerj-org/xerj; in any other\n\
@@ -926,9 +1087,10 @@ pub fn help_text(feedback: bool) -> String {
xerj-org/xerj when this account cannot push, and pushes\n\
that fork. If a later step fails, the local branch is\n\
removed. If gh is missing/unauth it FAILS LOUDLY and\n\
- prints the exact commands to run by hand\n\
+ prints the exact commands to run by hand. Prefer --submit\n\
+ when there is no GitHub account\n\
--dry-run print the report AND the exact commands, and do nothing\n\
- (opens no PR, writes no file)\n\
+ (opens no PR, writes no file, sends nothing)\n\
\n\
READING THE CATALOG (auto-fill source):\n\
--url <U> ES-compat endpoint (default http://localhost:9200)\n\
@@ -965,6 +1127,9 @@ mod tests {
output: None,
open_pr: false,
dry_run: false,
+ submit: false,
+ yes: false,
+ endpoint: "http://127.0.0.1:9/api/field-report".into(),
no_autofill: true,
}
}
@@ -1236,6 +1401,65 @@ mod tests {
assert!(err.contains("contradict"), "{err}");
}
+ #[test]
+ fn submit_contradictions_are_refused() {
+ let err = parse(vec!["--open-pr".into(), "--submit".into()]).unwrap_err();
+ assert!(err.contains("Drop one"), "{err}");
+ let err = parse(vec!["--dry-run".into(), "--yes".into()]).unwrap_err();
+ assert!(err.contains("contradict"), "{err}");
+ let err = parse(vec!["--yes".into()]).unwrap_err();
+ assert!(err.contains("--submit"), "{err}");
+ let cfg = parse(vec![
+ "--submit".into(),
+ "--no-autofill".into(),
+ "--agent".into(),
+ "Claude Code".into(),
+ ])
+ .unwrap()
+ .unwrap();
+ assert!(cfg.submit);
+ assert!(!cfg.yes);
+ assert_eq!(cfg.agent.as_deref(), Some("Claude Code"));
+ }
+
+ #[test]
+ fn submit_without_yes_shows_the_report_and_the_exact_command() {
+ let draft = resolve_draft(
+ &Cfg {
+ agent: Some("Claude Code".into()),
+ used_for: Some("a local mock".into()),
+ verdict: Some("the preview posts nothing".into()),
+ ..base_cfg()
+ },
+ None,
+ "2026-08-18",
+ );
+ let report = render_report(&draft);
+ let text = unsent_message(
+ "http://127.0.0.1:9/api/field-report",
+ &report,
+ "{\"agent\":\"Claude Code\"}",
+ &submit_command(&draft),
+ );
+ assert!(text.contains(PROVENANCE), "{text}");
+ assert!(text.contains("the preview posts nothing"), "{text}");
+ assert!(
+ text.contains(xerj_common::feedback::PERMISSION_LINE),
+ "{text}"
+ );
+ assert!(text.contains("Not sent. Nothing was posted."), "{text}");
+ assert!(
+ text.contains("xerj feedback --submit --yes"),
+ "the send command must be printed:\n{text}"
+ );
+ assert!(
+ text.contains("--agent \"Claude Code\""),
+ "--agent must survive into the send command:\n{text}"
+ );
+ assert!(text.contains("curl -sS -X POST"), "{text}");
+ assert!(!text.contains("git push"), "{text}");
+ }
+
#[test]
fn unknown_flags_are_refused_and_help_short_circuits() {
assert!(parse(vec!["--nope".into()])
@@ -1270,6 +1494,10 @@ mod tests {
for expected in [
"--open-pr",
"--dry-run",
+ "--submit",
+ "--yes",
+ "Needs no GitHub",
+ "XERJ_FIELD_REPORT_URL",
"--verdict",
"--pointed-at",
"first line states an AI agent wrote it",
diff --git a/engine/crates/xerj-autoindex/tests/feedback_offline.rs b/engine/crates/xerj-autoindex/tests/feedback_offline.rs
new file mode 100644
index 000000000..b7500d075
--- /dev/null
+++ b/engine/crates/xerj-autoindex/tests/feedback_offline.rs
@@ -0,0 +1,179 @@
+//! `xerj feedback --submit` against a local mock, with no GitHub token.
+//!
+//! The preview (`--submit` without `--yes`) must not open a connection. The
+//! send (`--submit --yes`) POSTs the JSON body and must not attach a GitHub
+//! token or an `Authorization` header — the admin key belongs to the local
+//! node, not to this endpoint.
+
+use std::io::{Read, Write};
+use std::net::TcpListener;
+use std::sync::Mutex;
+use std::time::Duration;
+
+use xerj_autoindex::feedback::{parse, run, Cfg};
+
+static ENV_LOCK: Mutex<()> = Mutex::new(());
+
+struct EnvVar {
+ key: &'static str,
+ previous: Option<std::ffi::OsString>,
+}
+
+impl EnvVar {
+ fn set(key: &'static str, value: &str) -> Self {
+ let previous = std::env::var_os(key);
+ std::env::set_var(key, value);
+ Self { key, previous }
+ }
+}
+
+impl Drop for EnvVar {
+ fn drop(&mut self) {
+ match self.previous.take() {
+ Some(value) => std::env::set_var(self.key, value),
+ None => std::env::remove_var(self.key),
+ }
+ }
+}
+
+fn filled(endpoint: &str, yes: bool) -> Cfg {
+ let mut cfg = parse(vec![
+ "--submit".into(),
+ "--no-autofill".into(),
+ "--agent".into(),
+ "Test Agent".into(),
+ "--used-for".into(),
+ "a local mock, no GitHub".into(),
+ "--verdict".into(),
+ "offline submit works".into(),
+ ])
+ .expect("parse")
+ .expect("cfg");
+ if yes {
+ cfg.yes = true;
+ }
+ cfg.endpoint = endpoint.to_string();
+ cfg
+}
+
+fn read_one_http(listener: TcpListener) -> String {
+ let (mut sock, _) = listener.accept().expect("accept");
+ sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let mut buf = Vec::new();
+ let mut tmp = [0u8; 4096];
+ loop {
+ match sock.read(&mut tmp) {
+ Ok(0) => break,
+ Ok(n) => {
+ buf.extend_from_slice(&tmp[..n]);
+ if let Some(header_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&buf[..header_end]);
+ let length = headers.lines().find_map(|line| {
+ let (name, rest) = line.split_once(':')?;
+ if !name.eq_ignore_ascii_case("content-length") {
+ return None;
+ }
+ rest.trim().parse::<usize>().ok()
+ });
+ let body_at = header_end + 4;
+ if let Some(length) = length {
+ while buf.len() < body_at + length {
+ match sock.read(&mut tmp) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => buf.extend_from_slice(&tmp[..n]),
+ }
+ }
+ }
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ let response_body = r#"{"ok":true,"stored":true}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response_body}",
+ response_body.len()
+ );
+ let _ = sock.write_all(response.as_bytes());
+ String::from_utf8_lossy(&buf).into_owned()
+}
+
+#[test]
+fn submit_without_yes_does_not_connect_and_needs_no_github_token() {
+ let _lock = ENV_LOCK.lock().unwrap();
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let endpoint = format!("http://127.0.0.1:{port}/api/field-report");
+ let _gh = EnvVar::set("GH_TOKEN", "ghp_should_not_appear");
+ let _github = EnvVar::set("GITHUB_TOKEN", "ghp_should_not_appear");
+ let code = run(&filled(&endpoint, false));
+ assert_eq!(code, 0);
+ match listener.accept() {
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}
+ other => panic!("--submit without --yes must not connect: {other:?}"),
+ }
+}
+
+#[test]
+fn submit_yes_posts_json_and_sends_no_github_token() {
+ let _lock = ENV_LOCK.lock().unwrap();
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let endpoint = format!("http://127.0.0.1:{port}/api/field-report");
+ let token = "ghp_should_not_appear";
+ let _gh = EnvVar::set("GH_TOKEN", token);
+ let _github = EnvVar::set("GITHUB_TOKEN", token);
+ let server = std::thread::spawn(move || read_one_http(listener));
+ let code = run(&filled(&endpoint, true));
+ let request = server.join().expect("server thread");
+ assert_eq!(code, 0, "request was:\n{request}");
+ let header = request
+ .split("\r\n\r\n")
+ .next()
+ .unwrap()
+ .to_ascii_lowercase();
+ assert!(
+ header.starts_with("post /api/field-report http/1.1"),
+ "{header}"
+ );
+ assert!(
+ header.contains("content-type: application/json"),
+ "{header}"
+ );
+ assert!(header.contains("user-agent: xerj-feedback"), "{header}");
+ assert!(
+ !header.contains("authorization"),
+ "the node key must not be sent:\n{header}"
+ );
+ assert!(!request.contains(token), "{request}");
+ assert!(request.contains("\"agent\":\"Test Agent\""), "{request}");
+ assert!(
+ request.contains("\"verdict\":\"offline submit works\""),
+ "{request}"
+ );
+ assert!(
+ request.contains("\"used_for\":\"a local mock, no GitHub\""),
+ "{request}"
+ );
+}
+
+#[test]
+fn submit_yes_refuses_placeholders_without_connecting() {
+ let _lock = ENV_LOCK.lock().unwrap();
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let mut cfg = parse(vec!["--submit".into(), "--no-autofill".into()])
+ .unwrap()
+ .unwrap();
+ cfg.yes = true;
+ cfg.endpoint = format!("http://127.0.0.1:{port}/api/field-report");
+ let code = run(&cfg);
+ assert_eq!(code, 2);
+ match listener.accept() {
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}
+ other => panic!("a placeholder report must not be posted: {other:?}"),
+ }
+}
diff --git a/engine/crates/xerj-common/src/feedback.rs b/engine/crates/xerj-common/src/feedback.rs
index 356380b52..bf9f37c08 100644
--- a/engine/crates/xerj-common/src/feedback.rs
+++ b/engine/crates/xerj-common/src/feedback.rs
@@ -14,6 +14,11 @@
//! Turning it off: [`DISABLE_FLAG`] anywhere in the argument list, or
//! [`DISABLE_ENV`] in the environment.
+/// The one sentence every field-report surface uses. An agent shows the draft
+/// and waits. Nothing is posted, pushed, or opened until the user agrees.
+pub const PERMISSION_LINE: &str =
+ "Show your user the report (`xerj feedback --dry-run`) and ask before sending.";
+
/// Where a defect goes. Verified against the README badges and clone URL.
pub const ISSUES_URL: &str = "https://github.com/xerj-org/xerj/issues";
diff --git a/engine/crates/xerj-common/src/field_report.rs b/engine/crates/xerj-common/src/field_report.rs
new file mode 100644
index 000000000..f3a2aa4ab
--- /dev/null
+++ b/engine/crates/xerj-common/src/field_report.rs
@@ -0,0 +1,171 @@
+//! JSON body for `POST /api/field-report`.
+//!
+//! Shared by `xerj feedback --submit` and the MCP tool `xerj_field_report` so
+//! the two cannot disagree about field names or the length caps the Pages
+//! function enforces (`functions/api/field-report.js`,
+//! `landing/docs/agents/schemas/field-report.json`).
+//!
+//! The HTTP call itself stays in the caller: this crate does not depend on
+//! reqwest. A caller that posts must not attach the node's `Authorization`
+//! header — that key is for the local engine, not for xerj.org.
+
+use serde_json::{json, Value};
+
+/// Production intake. Override with [`URL_ENV`] for a mock or a staging host.
+pub const URL_DEFAULT: &str = "https://xerj.org/api/field-report";
+
+/// Process environment that replaces [`URL_DEFAULT`]. Empty is unset.
+pub const URL_ENV: &str = "XERJ_FIELD_REPORT_URL";
+
+const CAP_AGENT: usize = 120;
+const CAP_USED_FOR: usize = 1000;
+/// The published schema caps `verdict` at 80. The long text goes in `notes`.
+const CAP_VERDICT: usize = 80;
+const CAP_VERSION: usize = 80;
+const CAP_OS: usize = 120;
+const CAP_INDEXED: usize = 200;
+const CAP_NOTES: usize = 4000;
+
+/// What the caller knows, before caps. Empty strings become empty fields.
+#[derive(Debug, Clone)]
+pub struct Input<'a> {
+ pub agent: &'a str,
+ pub used_for: &'a str,
+ pub verdict: &'a str,
+ pub version: &'a str,
+ pub os: &'a str,
+ pub indexed: &'a str,
+ pub notes: &'a str,
+}
+
+/// The body that will be posted, after control-character stripping and caps.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Payload {
+ pub agent: String,
+ pub used_for: String,
+ pub verdict: String,
+ pub version: String,
+ pub os: String,
+ pub indexed: String,
+ pub notes: String,
+}
+
+impl Payload {
+ pub fn from_input(input: &Input<'_>) -> Self {
+ Self {
+ agent: cap(input.agent, CAP_AGENT),
+ used_for: cap(input.used_for, CAP_USED_FOR),
+ verdict: cap(input.verdict, CAP_VERDICT),
+ version: cap(input.version, CAP_VERSION),
+ os: cap(input.os, CAP_OS),
+ indexed: cap(input.indexed, CAP_INDEXED),
+ notes: cap(input.notes, CAP_NOTES),
+ }
+ }
+
+ /// Required fields the endpoint would reject. Empty after capping.
+ pub fn missing_required(&self) -> Vec<&'static str> {
+ let mut missing = Vec::new();
+ if self.agent.is_empty() {
+ missing.push("agent");
+ }
+ if self.used_for.is_empty() {
+ missing.push("used_for");
+ }
+ if self.verdict.is_empty() {
+ missing.push("verdict");
+ }
+ missing
+ }
+
+ pub fn to_json(&self) -> Value {
+ json!({
+ "agent": self.agent,
+ "used_for": self.used_for,
+ "verdict": self.verdict,
+ "version": self.version,
+ "os": self.os,
+ "indexed": self.indexed,
+ "notes": self.notes,
+ })
+ }
+
+ pub fn json_string(&self) -> String {
+ self.to_json().to_string()
+ }
+}
+
+/// `XERJ_FIELD_REPORT_URL` when it is non-empty, otherwise [`URL_DEFAULT`].
+pub fn endpoint_from_env() -> String {
+ match std::env::var(URL_ENV) {
+ Ok(value) if !value.trim().is_empty() => value.trim().to_string(),
+ _ => URL_DEFAULT.to_string(),
+ }
+}
+
+/// A copy-pasteable `curl` for `body`. Single-quoted so the shell does not
+/// expand anything inside the JSON.
+pub fn curl_command(url: &str, body: &str) -> String {
+ format!(
+ "curl -sS -X POST {} -H 'Content-Type: application/json' --data {}",
+ shell_single(url),
+ shell_single(body)
+ )
+}
+
+fn cap(value: &str, max_chars: usize) -> String {
+ let cleaned: String = value
+ .chars()
+ .map(|c| if c.is_control() { ' ' } else { c })
+ .collect();
+ cleaned.trim().chars().take(max_chars).collect()
+}
+
+fn shell_single(value: &str) -> String {
+ format!("'{}'", value.replace('\'', "'\\''"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn caps_and_control_chars_match_the_endpoint() {
+ let payload = Payload::from_input(&Input {
+ agent: " Agent\nName ",
+ used_for: "used",
+ verdict: &"v".repeat(200),
+ version: "xerj v1",
+ os: "linux x86_64",
+ indexed: &"i".repeat(500),
+ notes: &"n".repeat(5000),
+ });
+ assert_eq!(payload.agent, "Agent Name");
+ assert_eq!(payload.verdict.chars().count(), CAP_VERDICT);
+ assert_eq!(payload.indexed.chars().count(), CAP_INDEXED);
+ assert_eq!(payload.notes.chars().count(), CAP_NOTES);
+ assert!(payload.missing_required().is_empty());
+ }
+
+ #[test]
+ fn empty_required_fields_are_named() {
+ let payload = Payload::from_input(&Input {
+ agent: " ",
+ used_for: "",
+ verdict: "ok",
+ version: "",
+ os: "",
+ indexed: "",
+ notes: "",
+ });
+ assert_eq!(payload.missing_required(), ["agent", "used_for"]);
+ }
+
+ #[test]
+ fn curl_quotes_single_quotes_in_the_body() {
+ let curl = curl_command("http://127.0.0.1:9/api/field-report", r#"{"agent":"a'b"}"#);
+ assert!(curl.contains("http://127.0.0.1:9/api/field-report"));
+ assert!(curl.contains("'\\''"), "{curl}");
+ assert!(curl.contains("Content-Type: application/json"));
+ }
+}
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index da8b7d4ab..341119ca4 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -45,6 +45,7 @@ pub mod config;
pub mod error;
pub mod feedback;
pub mod field_coercion;
+pub mod field_report;
pub mod fsio;
pub mod home;
pub mod hub;
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index 60144420d..837757a62 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -9,11 +9,13 @@
//!
//! It speaks the MCP **stdio transport**: newline-delimited
//! JSON-RPC 2.0 messages on stdin/stdout. It exposes XERJ to any MCP-capable
-//! agent host (Claude Desktop, IDE agents, custom orchestrators) as sixteen
-//! tools: thirteen that map 1:1 onto XERJ's real, verified REST surface, and
-//! three Corpus Hub tools (`xerj_hub_*`) that run the `xerj ask` flow itself. Every tool is
-//! a *thin proxy*: it constructs exactly the request the running engine
-//! already accepts and forwards it to a configurable base URL.
+//! agent host (Claude Desktop, IDE agents, custom orchestrators) as seventeen
+//! tools: fourteen without a hub key, and three Corpus Hub tools
+//! (`xerj_hub_*`) that run the `xerj ask` flow itself. Thirteen of those
+//! fourteen construct exactly the request the running engine already accepts
+//! and forward it to a configurable base URL. `xerj_field_report` does not:
+//! it posts a field report to the web endpoint, not to the node, and it sends
+//! nothing until `confirm` is true.
//!
//! ## The thirteen canonical agent operations
//!
@@ -30,6 +32,7 @@
//! | `xerj_brain_unlink` | `DELETE /_graph/{brain}/link/{id}` | retire a link (soft-invalidate; never deletes) |
//! | `xerj_brain_overview` | `GET /_graph/{brain}/overview` | whole-brain orientation: counts, hubs, detectors, timeline |
//! | `xerj_plan` | `POST /_ask` | natural-language prompt in, VALIDATED query DSL out (deterministic planner, not an LLM) |
+//! | `xerj_field_report` | `POST /api/field-report` (xerj.org) | file an agent field report; posts only when `confirm` is true |
//! | `xerj_map` | `POST /autoindex-catalog/_search` | per-index field map from the autoindex catalog (#1055) |
//! | `xerj_hub_find` / `xerj_hub_def` / `xerj_hub_ask` | the `xerj ask` flow (`src/hub.rs`) | which hub corpus answers; one definition; one question — from local packs, never downloading |
//!
@@ -493,7 +496,12 @@ fn initialize_result(msg: &Value) -> Value {
evidence-carrying link index built by `xerj brain <folder>`): \
xerj_brain_overview to orient, then xerj_brain_ego for one node's \
neighborhood, then xerj_brain_link / xerj_brain_unlink to assert \
- or retire links — retired links stay replayable via as_of.",
+ or retire links — retired links stay replayable via as_of. \
+ xerj_field_report posts an agent field report to the web \
+ endpoint (not to this node) and does not send the node's \
+ Authorization header. Show your user the report (`xerj feedback \
+ --dry-run`) and ask before sending. Without confirm it returns \
+ the draft and posts nothing; confirm: true sends.",
})
}
@@ -1147,6 +1155,62 @@ pub fn tool_specs_with(include_hub: bool) -> Value {
},
"required": ["prompt"]
}
+ },
+ {
+ "name": "xerj_field_report",
+ "description": format!(
+ "File an agent field report. POSTs JSON to the field-report endpoint \
+ (default https://xerj.org/api/field-report, override with the endpoint \
+ argument or XERJ_FIELD_REPORT_URL). Needs no GitHub account, no gh, and \
+ no checkout. Show the returned draft to the user. Nothing is posted unless \
+ you call again with the same arguments and confirm set to true. \
+ Honesty: this does not talk to the local XERJ node and does not send the \
+ node's Authorization header. The endpoint caps verdict at 80 characters; \
+ put the long report in notes. {}",
+ xerj_common::feedback::PERMISSION_LINE
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "agent": {
+ "type": "string",
+ "description": "The model or tool writing the report. A placeholder such as '<model / tool>' is refused when confirm is true."
+ },
+ "used_for": {
+ "type": "string",
+ "description": "What XERJ was used for, in one sentence."
+ },
+ "verdict": {
+ "type": "string",
+ "description": "What worked and what did not. Capped at 80 characters on the wire; put the long text in notes."
+ },
+ "version": {
+ "type": "string",
+ "description": "xerj version, if known. Optional."
+ },
+ "os": {
+ "type": "string",
+ "description": "OS and architecture. Optional."
+ },
+ "indexed": {
+ "type": "string",
+ "description": "What was indexed. Optional."
+ },
+ "notes": {
+ "type": "string",
+ "description": "The full report. Optional, capped at 4000 characters."
+ },
+ "confirm": {
+ "type": "boolean",
+ "description": "Send the report. Omit or false to get the draft back with nothing posted. Set true only after the user has seen the draft and agreed."
+ },
+ "endpoint": {
+ "type": "string",
+ "description": "Override the POST URL. Default https://xerj.org/api/field-report, or XERJ_FIELD_REPORT_URL when that is set. Must be http or https."
+ }
+ },
+ "required": ["agent", "used_for", "verdict"]
+ }
}
]);
if include_hub {
@@ -1157,6 +1221,182 @@ pub fn tool_specs_with(include_hub: bool) -> Value {
specs
}
+/// `xerj_field_report`. Without `confirm: true` this returns the draft and
+/// posts nothing. With it, it POSTs to the field-report endpoint on a fresh
+/// client that has no `Authorization` header — `Ctx::auth` is the local node's
+/// key and must not be sent to xerj.org.
+async fn call_field_report(args: &Value) -> Value {
+ let agent = match req_str(args, "agent") {
+ Ok(v) => v.to_string(),
+ Err(msg) => return tool_text(msg, true),
+ };
+ let used_for = match req_str(args, "used_for") {
+ Ok(v) => v.to_string(),
+ Err(msg) => return tool_text(msg, true),
+ };
+ let verdict = match req_str(args, "verdict") {
+ Ok(v) => v.to_string(),
+ Err(msg) => return tool_text(msg, true),
+ };
+ let version = match opt_text(args, "version") {
+ Ok(v) => v,
+ Err(msg) => return tool_text(msg, true),
+ };
+ let os = match opt_text(args, "os") {
+ Ok(v) => v,
+ Err(msg) => return tool_text(msg, true),
+ };
+ let indexed = match opt_text(args, "indexed") {
+ Ok(v) => v,
+ Err(msg) => return tool_text(msg, true),
+ };
+ let notes = match opt_text(args, "notes") {
+ Ok(v) => v,
+ Err(msg) => return tool_text(msg, true),
+ };
+ let confirm = match args.get("confirm") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(v)) => *v,
+ Some(_) => return tool_text(
+ "`confirm` must be a boolean. Omit it to preview; set true only after the user agrees.",
+ true,
+ ),
+ };
+ let endpoint = match args.get("endpoint") {
+ None | Some(Value::Null) => xerj_common::field_report::endpoint_from_env(),
+ Some(Value::String(s)) if s.trim().is_empty() => {
+ xerj_common::field_report::endpoint_from_env()
+ }
+ Some(Value::String(s)) => s.trim().to_string(),
+ Some(_) => return tool_text("`endpoint` must be a string", true),
+ };
+
+ let payload =
+ xerj_common::field_report::Payload::from_input(&xerj_common::field_report::Input {
+ agent: &agent,
+ used_for: &used_for,
+ verdict: &verdict,
+ version: &version,
+ os: &os,
+ indexed: &indexed,
+ notes: &notes,
+ });
+ let body = payload.json_string();
+ let curl = xerj_common::field_report::curl_command(&endpoint, &body);
+ let draft = field_report_draft(&payload);
+
+ if !confirm {
+ return tool_text(
+ format!(
+ "{draft}\n\n{}\nNot sent. Nothing was posted.\n\
+ After the user agrees, call xerj_field_report again with the same \
+ arguments and confirm set to true.\n{curl}",
+ xerj_common::feedback::PERMISSION_LINE
+ ),
+ false,
+ );
+ }
+
+ if let Some(slot) = [&agent, &used_for, &verdict]
+ .into_iter()
+ .find(|s| is_placeholder(s))
+ {
+ return tool_text(
+ format!(
+ "refusing to post a placeholder value: {slot}\n{draft}\n\n{}",
+ xerj_common::feedback::PERMISSION_LINE
+ ),
+ true,
+ );
+ }
+ if !payload.missing_required().is_empty() {
+ return tool_text(
+ format!("missing {}", payload.missing_required().join(", ")),
+ true,
+ );
+ }
+ if !(endpoint.starts_with("https://") || endpoint.starts_with("http://")) {
+ return tool_text(
+ format!("field report URL must be http or https, got {endpoint}"),
+ true,
+ );
+ }
+
+ let client = match reqwest::Client::builder()
+ .timeout(Duration::from_secs(30))
+ .build()
+ {
+ Ok(client) => client,
+ Err(err) => return tool_text(format!("could not build HTTP client: {err}"), true),
+ };
+ match client
+ .post(&endpoint)
+ .header("content-type", "application/json")
+ .header("user-agent", "xerj-feedback")
+ .body(body)
+ .send()
+ .await
+ {
+ Ok(response) => {
+ let status = response.status().as_u16();
+ let text = response.text().await.unwrap_or_default();
+ if (200..300).contains(&status) {
+ tool_text(
+ format!("sent field report to {endpoint} (HTTP {status})\n{text}"),
+ false,
+ )
+ } else {
+ tool_text(
+ format!("field report endpoint returned HTTP {status}: {text}"),
+ true,
+ )
+ }
+ }
+ Err(err) => tool_text(
+ format!("could not send the field report: {err}\nNothing was stored.\n{curl}"),
+ true,
+ ),
+ }
+}
+
+fn opt_text(args: &Value, key: &str) -> Result<String, String> {
+ match args.get(key) {
+ None | Some(Value::Null) => Ok(String::new()),
+ Some(Value::String(s)) => Ok(s.clone()),
+ Some(_) => Err(format!("`{key}` must be a string")),
+ }
+}
+
+/// Template slots copied from the field-report README. Posting one would file
+/// an unfilled report.
+fn is_placeholder(value: &str) -> bool {
+ let trimmed = value.trim();
+ trimmed.starts_with('<') && trimmed.ends_with('>')
+}
+
+fn field_report_draft(payload: &xerj_common::field_report::Payload) -> String {
+ format!(
+ "Field report draft\n\
+ agent: {agent}\n\
+ used_for: {used_for}\n\
+ verdict: {verdict}\n\
+ version: {version}\n\
+ os: {os}\n\
+ indexed: {indexed}\n\
+ notes: {notes}\n\
+ HTTP body (verdict is capped at 80 characters; the long text is in notes):\n\
+ {body}",
+ agent = payload.agent,
+ used_for = payload.used_for,
+ verdict = payload.verdict,
+ version = payload.version,
+ os = payload.os,
+ indexed = payload.indexed,
+ notes = payload.notes,
+ body = payload.json_string(),
+ )
+}
+
/// Dispatch a `tools/call` to the matching proxy. Any bad-argument or transport
/// problem is returned as an `isError:true` tool result (not a protocol error),
/// which is the MCP convention for tool-execution failures.
@@ -1204,6 +1444,9 @@ async fn call_tool(ctx: &Ctx, msg: &Value) -> Value {
"xerj_brain_overview" => build_brain_overview(&args),
// #1056: prompt in, validated DSL out — a plain engine proxy.
"xerj_plan" => build_plan(&args),
+ // Posts to the web endpoint, not the node. `ctx` is unused on purpose:
+ // the node's Authorization header must not leave the machine.
+ "xerj_field_report" => return call_field_report(&args).await,
// #1055: the catalog read is a proxy-with-post-processing, like
// code_search — it renders the per-index field map itself, so it
// returns a tool result directly instead of a BuiltRequest.
@@ -3040,10 +3283,175 @@ mod tests {
let res = initialize_result(&msg);
assert_eq!(res["protocolVersion"], "2024-11-05");
assert_eq!(res["serverInfo"]["name"], "xerj-mcp");
+ let instructions = res["instructions"].as_str().unwrap();
+ assert!(
+ instructions.contains(xerj_common::feedback::PERMISSION_LINE),
+ "{instructions}"
+ );
+ assert!(instructions.contains("xerj_field_report"), "{instructions}");
+ }
+
+ fn tool_body(result: &Value) -> String {
+ result["content"][0]["text"]
+ .as_str()
+ .unwrap_or("")
+ .to_string()
+ }
+
+ /// One HTTP/1.1 request, then a tiny JSON 200. Reads Content-Length so the
+ /// client is not left waiting on a half-consumed body.
+ fn read_one_http(listener: std::net::TcpListener) -> String {
+ use std::io::{Read, Write};
+ let (mut sock, _) = listener.accept().expect("accept");
+ sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
+ .unwrap();
+ let mut buf = Vec::new();
+ let mut tmp = [0u8; 4096];
+ loop {
+ match sock.read(&mut tmp) {
+ Ok(0) => break,
+ Ok(n) => {
+ buf.extend_from_slice(&tmp[..n]);
+ if let Some(header_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&buf[..header_end]);
+ let length = headers.lines().find_map(|line| {
+ let rest = line
+ .split_once(':')
+ .filter(|(name, _)| name.eq_ignore_ascii_case("content-length"))?
+ .1;
+ rest.trim().parse::<usize>().ok()
+ });
+ let body_at = header_end + 4;
+ if let Some(length) = length {
+ while buf.len() < body_at + length {
+ match sock.read(&mut tmp) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => buf.extend_from_slice(&tmp[..n]),
+ }
+ }
+ }
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ let response_body = r#"{"ok":true,"stored":true}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response_body}",
+ response_body.len()
+ );
+ let _ = sock.write_all(response.as_bytes());
+ String::from_utf8_lossy(&buf).into_owned()
+ }
+
+ fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("runtime")
+ .block_on(future)
}
#[test]
- fn tools_list_has_all_sixteen() {
+ fn field_report_without_confirm_posts_nothing() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let result = block_on(call_field_report(&json!({
+ "agent": "Test Agent",
+ "used_for": "mock",
+ "verdict": "works offline",
+ "endpoint": format!("http://127.0.0.1:{port}/api/field-report"),
+ })));
+ assert_eq!(result["isError"], false, "{result}");
+ let text = tool_body(&result);
+ assert!(
+ text.contains(xerj_common::feedback::PERMISSION_LINE),
+ "{text}"
+ );
+ assert!(text.contains("Not sent. Nothing was posted."), "{text}");
+ assert!(text.contains("Test Agent"), "{text}");
+ assert!(text.contains("confirm"), "{text}");
+ match listener.accept() {
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}
+ other => panic!("preview must not connect: {other:?}"),
+ }
+ }
+
+ #[test]
+ fn field_report_confirm_posts_without_node_auth_or_a_github_token() {
+ let _lock = ENV_LOCK.lock().unwrap();
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let token = "ghp_should_not_appear";
+ let prev_gh = std::env::var_os("GH_TOKEN");
+ let prev_github = std::env::var_os("GITHUB_TOKEN");
+ std::env::set_var("GH_TOKEN", token);
+ std::env::set_var("GITHUB_TOKEN", token);
+ let server = std::thread::spawn(move || read_one_http(listener));
+ let result = block_on(call_field_report(&json!({
+ "agent": "Test Agent",
+ "used_for": "mock",
+ "verdict": "works offline",
+ "notes": "full report",
+ "confirm": true,
+ "endpoint": format!("http://127.0.0.1:{port}/api/field-report"),
+ })));
+ let request = server.join().expect("server thread");
+ match prev_gh {
+ Some(value) => std::env::set_var("GH_TOKEN", value),
+ None => std::env::remove_var("GH_TOKEN"),
+ }
+ match prev_github {
+ Some(value) => std::env::set_var("GITHUB_TOKEN", value),
+ None => std::env::remove_var("GITHUB_TOKEN"),
+ }
+ assert_eq!(result["isError"], false, "{result}");
+ let text = tool_body(&result);
+ assert!(text.contains("HTTP 200"), "{text}");
+ let header = request
+ .split("\r\n\r\n")
+ .next()
+ .unwrap()
+ .to_ascii_lowercase();
+ assert!(
+ header.starts_with("post /api/field-report http/1.1"),
+ "{header}"
+ );
+ assert!(
+ header.contains("content-type: application/json"),
+ "{header}"
+ );
+ assert!(header.contains("user-agent: xerj-feedback"), "{header}");
+ assert!(!header.contains("authorization"), "{header}");
+ assert!(!request.contains(token), "{request}");
+ assert!(request.contains("\"agent\":\"Test Agent\""), "{request}");
+ assert!(request.contains("\"notes\":\"full report\""), "{request}");
+ }
+
+ #[test]
+ fn field_report_confirm_refuses_a_placeholder_without_connecting() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let result = block_on(call_field_report(&json!({
+ "agent": "<model / tool>",
+ "used_for": "mock",
+ "verdict": "works",
+ "confirm": true,
+ "endpoint": format!("http://127.0.0.1:{port}/api/field-report"),
+ })));
+ assert_eq!(result["isError"], true, "{result}");
+ assert!(tool_body(&result).contains("placeholder"), "{result}");
+ match listener.accept() {
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}
+ other => panic!("a placeholder must not be posted: {other:?}"),
+ }
+ }
+
+ #[test]
+ fn tools_list_has_all_seventeen() {
let specs = tool_specs_with(true);
let names: Vec<&str> = specs
.as_array()
@@ -3051,7 +3459,7 @@ mod tests {
.iter()
.map(|t| t["name"].as_str().unwrap())
.collect();
- assert_eq!(names.len(), 16);
+ assert_eq!(names.len(), 17);
for n in [
"xerj_search",
"xerj_semantic_search",
@@ -3070,13 +3478,40 @@ mod tests {
"xerj_code_search",
// #1056: prompt in, validated DSL out.
"xerj_plan",
- // Corpus Hub v2 (plan §7), appended after the thirteen.
+ // Field report: posts to xerj.org, not the node. Before the hub tools.
+ "xerj_field_report",
+ // Corpus Hub v2 (plan §7), appended after the fourteen.
"xerj_hub_find",
"xerj_hub_def",
"xerj_hub_ask",
] {
assert!(names.contains(&n), "missing tool {n}");
}
+ let at = |name: &str| names.iter().position(|n| *n == name).unwrap();
+ assert!(at("xerj_plan") < at("xerj_field_report"));
+ assert!(at("xerj_field_report") < at("xerj_hub_find"));
+ let field = specs
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|t| t["name"] == "xerj_field_report")
+ .unwrap();
+ assert!(
+ field["description"]
+ .as_str()
+ .unwrap()
+ .contains(xerj_common::feedback::PERMISSION_LINE),
+ "the tool description must carry the permission line"
+ );
+ assert_eq!(
+ field["inputSchema"]["required"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_str().unwrap())
+ .collect::<Vec<_>>(),
+ ["agent", "used_for", "verdict"]
+ );
// Deliberately NOT exposed: raw traversal, bulk dumps, operator actions.
for forbidden in ["graph_expand", "autoindex", "dump"] {
assert!(
@@ -3100,23 +3535,23 @@ mod tests {
.collect()
};
let without = names(false);
- assert_eq!(without.len(), 13, "{without:?}");
+ assert_eq!(without.len(), 14, "{without:?}");
assert!(
without.iter().all(|n| !n.starts_with("xerj_hub_")),
"{without:?}"
);
let with = names(true);
- assert_eq!(with.len(), 16, "{with:?}");
+ assert_eq!(with.len(), 17, "{with:?}");
for n in ["xerj_hub_find", "xerj_hub_def", "xerj_hub_ask"] {
assert!(with.iter().any(|name| name == n), "missing {n}");
}
let help = tools_paragraph(false);
- assert!(help.contains("proxies 13 tools"), "{help}");
+ assert!(help.contains("proxies 14 tools"), "{help}");
assert!(!help.contains("xerj_hub_"), "{help}");
assert!(help.contains("~/xerj-data"), "{help}");
let help = tools_paragraph(true);
- assert!(help.contains("proxies 16 tools"), "{help}");
+ assert!(help.contains("proxies 17 tools"), "{help}");
assert!(help.contains("xerj_hub_ask"), "{help}");
assert!(help.contains("serves 3 Corpus Hub tools"), "{help}");
}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 8b23321e6..5fb2d50fb 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -2558,12 +2558,13 @@ mod decide_flag_tests {
#[test]
fn help_counts_the_mcp_tools_actually_served() {
// #1443: the help said "exposes 13 tools" while `tools/list` served 16.
+ // `xerj_field_report` is a fourteenth non-hub tool (seventeen with the hub).
let served = super::mcp_tool_count();
if xerj_common::hub::hub_key_configured() {
- assert!(served >= 16, "tool_specs() shrank to {served}");
+ assert!(served >= 17, "tool_specs() shrank to {served}");
} else {
assert_eq!(
- served, 13,
+ served, 14,
"a no-key process must not count the hub tools it does not serve"
);
}
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index 5ece614bd..d986e9f6e 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -620,6 +620,56 @@
]
}
},
+ {
+ "name": "xerj_field_report",
+ "description": "File an agent field report. POSTs JSON to the field-report endpoint (default https://xerj.org/api/field-report, override with the endpoint argument or XERJ_FIELD_REPORT_URL). Needs no GitHub account, no gh, and no checkout. Show the returned draft to the user. Nothing is posted unless you call again with the same arguments and confirm set to true. Honesty: this does not talk to the local XERJ node and does not send the node's Authorization header. The endpoint caps verdict at 80 characters; put the long report in notes. Show your user the report (`xerj feedback --dry-run`) and ask before sending.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "agent": {
+ "type": "string",
+ "description": "The model or tool writing the report. A placeholder such as '<model / tool>' is refused when confirm is true."
+ },
+ "used_for": {
+ "type": "string",
+ "description": "What XERJ was used for, in one sentence."
+ },
+ "verdict": {
+ "type": "string",
+ "description": "What worked and what did not. Capped at 80 characters on the wire; put the long text in notes."
+ },
+ "version": {
+ "type": "string",
+ "description": "xerj version, if known. Optional."
+ },
+ "os": {
+ "type": "string",
+ "description": "OS and architecture. Optional."
+ },
+ "indexed": {
+ "type": "string",
+ "description": "What was indexed. Optional."
+ },
+ "notes": {
+ "type": "string",
+ "description": "The full report. Optional, capped at 4000 characters."
+ },
+ "confirm": {
+ "type": "boolean",
+ "description": "Send the report. Omit or false to get the draft back with nothing posted. Set true only after the user has seen the draft and agreed."
+ },
+ "endpoint": {
+ "type": "string",
+ "description": "Override the POST URL. Default https://xerj.org/api/field-report, or XERJ_FIELD_REPORT_URL when that is set. Must be http or https."
+ }
+ },
+ "required": [
+ "agent",
+ "used_for",
+ "verdict"
+ ]
+ }
+ },
{
"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: reads the catalogue `xerj hub sync` cached and never fetches it; this build has no hosted search). Excluded-licence corpora are never listed.",