From 99dc90fd3b35fbf520b27bdc66c597998ab149fa Mon Sep 17 00:00:00 2001 From: hermes Date: Wed, 30 Sep 2026 15:51:25 +0000 Subject: [PATCH] M6: native MCP client, lazy index, mcp-serve (closes #42-#51) --- .gitea/workflows/ci.yml | 2 + Cargo.lock | 12 + README.md | 38 +++ crates/hx-cli/Cargo.toml | 3 +- crates/hx-cli/src/main.rs | 88 ++++++ crates/hx-lens/src/lib.rs | 2 + crates/hx-lens/src/manager.rs | 6 +- crates/hx-mcp/Cargo.toml | 12 + crates/hx-mcp/src/client.rs | 287 +++++++++++++++++ crates/hx-mcp/src/config.rs | 125 ++++++++ crates/hx-mcp/src/lib.rs | 538 +++++++++++++++++++++++++++++++- crates/hx-mcp/src/serve.rs | 140 +++++++++ crates/hx-mcp/src/tests.rs | 234 ++++++++++++++ crates/hx-mcp/tests/fake_mcp.py | 92 ++++++ crates/hx-tui/src/lib.rs | 43 ++- tests/all.sh | 5 +- tests/fake_m6.py | 69 ++++ tests/m6_e2e.sh | 49 +++ 18 files changed, 1723 insertions(+), 22 deletions(-) create mode 100644 crates/hx-mcp/src/client.rs create mode 100644 crates/hx-mcp/src/config.rs create mode 100644 crates/hx-mcp/src/serve.rs create mode 100644 crates/hx-mcp/src/tests.rs create mode 100644 crates/hx-mcp/tests/fake_mcp.py create mode 100644 tests/fake_m6.py create mode 100644 tests/m6_e2e.sh diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 96006b4..2e50164 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -15,3 +15,5 @@ jobs: - run: python3 tests/tui_smoke.py - run: sh tests/lens_e2e.sh - run: pip install ruff && sh tests/m4_e2e.sh + - run: sh tests/m5_e2e.sh + - run: sh tests/m6_e2e.sh diff --git a/Cargo.lock b/Cargo.lock index f11722e..e4762b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -986,6 +986,7 @@ dependencies = [ "hx-ai", "hx-core", "hx-lens", + "hx-mcp", "hx-tools", "hx-tui", "serde", @@ -1024,6 +1025,17 @@ dependencies = [ [[package]] name = "hx-mcp" version = "0.1.0" +dependencies = [ + "async-trait", + "futures", + "hx-ai", + "hx-core", + "reqwest", + "serde", + "serde_json", + "tempfile", + "tokio", +] [[package]] name = "hx-tools" diff --git a/README.md b/README.md index a82b0b6..1990d71 100644 --- a/README.md +++ b/README.md @@ -66,3 +66,41 @@ Existing Claude Code (`~/.claude/.credentials.json`) and Codex CLI (`~/.codex/au Credentials are stored in `~/.hx/auth.json` (mode 0600) and refreshed automatically. On a headless box, open the printed URL elsewhere and paste the final redirect URL back into the terminal. + +## MCP + +Servers come from `~/.hx/mcp.json` and `.hx/mcp.json` (project entries replace global ones with the same +name), in the Claude Code `mcpServers` shape. `${VAR}` and `${VAR:-default}` are expanded. + +```json +{"mcpServers": { + "fs": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "${HOME}/src"]}, + "web": {"type": "http", "url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ${TOKEN}"}, + "allow": ["search"], "eager": true, "timeoutSecs": 30} +}} +``` + +Transports: stdio and streamable HTTP (static headers; no OAuth). hx extras: `allow` (tool allowlist), +`eager`, `timeoutSecs` (per call, default 60), `disabled`. Output is capped at 30k chars; a crashed stdio +server is restarted on the next call (at most 3 times). + +Lazy by default: the system prompt carries one line per tool (`server.tool: description`); the model gets the +schema with `mcp_describe` and calls through `mcp_call` (arguments are checked against the cached schema). +Servers whose full schemas cost at most ~400 tokens are registered as native tools instead (`server__tool`); +`eager: true|false` overrides. Resources are listed in the prompt and read with `mcp_read`; prompts become +slash commands (`/server:prompt args`). `/mcp` in the TUI and `hx mcp` show tools and token costs. + +Measured (`hx mcp`, bytes/4): + +| server | tools | lazy index | eager schemas | +|-------------|------:|-----------:|--------------:| +| context7 | 2 | ~63 tok | ~1147 tok | +| everything | 13 | ~319 tok | ~1235 tok | +| filesystem | 14 | ~453 tok | ~1996 tok | +| playwright | 25 | ~537 tok | ~4397 tok | + +Lazy costs one extra round trip (`mcp_describe`) per tool on first use in a session. Since tool count is a +poor proxy (context7: 2 tools, 1.1k tokens), the eager rule is schema size, not count. + +`hx mcp-serve` runs hx as a stdio MCP server exposing the `lsp` tool (diagnostics, definition, references, +hover, symbols) to other clients. diff --git a/crates/hx-cli/Cargo.toml b/crates/hx-cli/Cargo.toml index 0de7023..78f2980 100644 --- a/crates/hx-cli/Cargo.toml +++ b/crates/hx-cli/Cargo.toml @@ -16,9 +16,10 @@ hx-ai = { version = "0.1.0", path = "../hx-ai" } hx-core = { version = "0.1.0", path = "../hx-core" } hx-lens = { version = "0.1.0", path = "../hx-lens" } hx-tools = { version = "0.1.0", path = "../hx-tools" } +hx-mcp = { version = "0.1.0", path = "../hx-mcp" } hx-tui = { version = "0.1.0", path = "../hx-tui" } serde = { version = "1.0.229", features = ["derive"] } -tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal"] } +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "signal", "io-std", "io-util"] } toml = "1.1.6" [lints] diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 989010c..6964de4 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -37,6 +37,10 @@ enum Cmd { Login { provider: Kind }, /// Remove stored credentials for a provider. Logout { provider: Kind }, + /// Connect to configured MCP servers and print tools + index/eager token cost. + Mcp, + /// Serve lens diagnostics + LSP navigation as an MCP server over stdio. + McpServe, } /// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project. @@ -202,6 +206,40 @@ async fn main() -> Result<()> { return Ok(()); } Some(Cmd::Logout { provider }) => return Ok(auth::logout(provider)?), + Some(Cmd::Mcp) => { + let cwd = std::env::current_dir()?; + let hub = hx_mcp::Hub::start( + hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?, + ) + .await; + for l in hub.status() { + println!("{l}"); + } + print!("{}", hub.system_prompt()); + return Ok(()); + } + Some(Cmd::McpServe) => { + let cwd = std::env::current_dir()?; + let mgr = Arc::new(hx_lens::manager::Manager::new( + cwd.clone(), + hx_lens::manager::default_servers(), + )); + let mut reg = hx_core::tool::Registry::default(); + reg.add(hx_lens::LspTool { mgr: mgr.clone() }); + let cx = ToolCtx { + cwd, + state: Default::default(), + }; + hx_mcp::serve::serve( + reg, + cx, + tokio::io::BufReader::new(tokio::io::stdin()), + tokio::io::stdout(), + ) + .await?; + mgr.shutdown().await; + return Ok(()); + } None => {} } let cwd = std::env::current_dir()?; @@ -240,6 +278,23 @@ async fn main() -> Result<()> { ); agent.model = model; agent.system = context::system_prompt(cfg.system_prompt.as_deref(), &context::hx_home(), &cwd); + let mcp = Arc::new( + hx_mcp::Hub::start( + hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?, + ) + .await, + ); + mcp.register(&mut agent.tools); + let idx = mcp.system_prompt(); + if !idx.is_empty() { + agent.system.push_str("\n\n"); + agent.system.push_str(&idx); + } + for (n, s) in &mcp.servers { + if let Some(e) = &s.error { + eprintln!("[mcp] {n}: {e}"); + } + } if let Some(n) = cfg.compact_at { agent.compact_at = n; } @@ -305,6 +360,39 @@ async fn main() -> Result<()> { make_provider: Box::new(provider), default_model, pricing, + commands: { + let mcp = mcp.clone(); + Box::new(move |name: &str, arg: &str| { + let (mcp, name, arg) = (mcp.clone(), name.to_string(), arg.to_string()); + if name == "mcp" { + return Some(Box::pin(async move { + let mut v = mcp.status(); + for (n, s) in &mcp.servers { + v.extend(s.prompts.iter().map(|p| { + format!( + " /{n}:{} {}", + p["name"].as_str().unwrap_or_default(), + p["description"].as_str().unwrap_or_default() + ) + })); + } + Ok(hx_tui::CmdOut::Show(if v.is_empty() { + "mcp: no servers configured (~/.hx/mcp.json, .hx/mcp.json)".into() + } else { + format!("mcp:\n{}", v.join("\n")) + })) + }) as _); + } + let (server, prompt) = name.split_once(':')?; + let (server, prompt) = (server.to_string(), prompt.to_string()); + mcp.servers.get(&server)?; + Some(Box::pin(async move { + mcp.prompt(&server, &prompt, &arg) + .await + .map(hx_tui::CmdOut::Send) + }) as _) + }) + }, lsp_status: { let (m, l) = (mgr.clone(), lens_ref.clone()); Box::new(move || { diff --git a/crates/hx-lens/src/lib.rs b/crates/hx-lens/src/lib.rs index c2469a6..f124f3d 100644 --- a/crates/hx-lens/src/lib.rs +++ b/crates/hx-lens/src/lib.rs @@ -670,6 +670,8 @@ mod tests { // nothing changed: silent assert_eq!(lens.on(&Event::TurnEnd).await, HookAction::Continue); + // cargo's freshness check uses mtimes; keep the fix clearly newer than the last check's start + std::thread::sleep(Duration::from_millis(1100)); std::fs::write(&f, "pub fn f() -> u32 { 1 }\npub fn g() -> u32 { f() }\n").unwrap(); lens.on(&Event::ToolResult { id: "2".into(), diff --git a/crates/hx-lens/src/manager.rs b/crates/hx-lens/src/manager.rs index 13214e9..956e9ef 100644 --- a/crates/hx-lens/src/manager.rs +++ b/crates/hx-lens/src/manager.rs @@ -302,12 +302,12 @@ impl Manager { }; // For rust-analyzer, didSave triggers a flycheck. Wait until either: // - A flycheck completes (checks_done > checks_before and !checks_active), OR - // - 5s passes without flycheck ever starting (e.g. non-cargo file or checkOnSave disabled). + // - 15s passes without flycheck ever starting (checkOnSave disabled; queued checks start later under load). let settle_for = Duration::from_millis(300); // rust-analyzer publishes flycheck results after progress `end`: once the check ends, // wait (max 3s) for a publish that arrives after it. let mut after_end: Option<(i64, Instant)> = None; - let check_wait_deadline = Instant::now() + Duration::from_secs(5); + let check_wait_deadline = Instant::now() + Duration::from_secs(15); loop { let n = cl.diag_notify.notified(); let cur = cl.diagnostics(&u).await; @@ -320,7 +320,7 @@ impl Manager { after_end = Some((cl.diag_seq.load(Ordering::SeqCst), Instant::now())); } let published = after_end.is_some_and(|(seq, t)| { - cl.diag_seq.load(Ordering::SeqCst) > seq || t.elapsed() >= Duration::from_secs(3) + cl.diag_seq.load(Ordering::SeqCst) > seq || t.elapsed() >= Duration::from_secs(10) }); let checked = !is_rust || (check_finished && published) || check_never_started; if fresh(&cur) && checked && cl.busy.load(Ordering::SeqCst) <= 0 { diff --git a/crates/hx-mcp/Cargo.toml b/crates/hx-mcp/Cargo.toml index 3a3cf7f..9c1a516 100644 --- a/crates/hx-mcp/Cargo.toml +++ b/crates/hx-mcp/Cargo.toml @@ -5,6 +5,18 @@ edition.workspace = true license.workspace = true [dependencies] +async-trait = "0.1.92" +futures = "0.3.34" +hx-ai = { version = "0.1.0", path = "../hx-ai" } +hx-core = { version = "0.1.0", path = "../hx-core" } +reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "rustls", "http2"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +tokio = { version = "1.53.1", features = ["process", "io-util", "sync", "time", "rt", "macros"] } [lints] workspace = true + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.53.1", features = ["macros", "rt-multi-thread"] } diff --git a/crates/hx-mcp/src/client.rs b/crates/hx-mcp/src/client.rs new file mode 100644 index 0000000..46b9648 --- /dev/null +++ b/crates/hx-mcp/src/client.rs @@ -0,0 +1,287 @@ +//! Minimal MCP client: JSON-RPC 2.0 over stdio (newline-delimited) or streamable HTTP (JSON or SSE replies). +//! +//! ponytail: hand-rolled instead of `rmcp` (~1 dep tree less); covers initialize, tools, resources, prompts, +//! ping. No server->client sampling/elicitation/roots (answered with "method not found"), no HTTP OAuth. + +use crate::config::Server; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::sync::{Mutex, oneshot}; + +pub const PROTOCOL: &str = "2025-06-18"; + +type Pending = Arc>>>>; + +enum Transport { + Stdio { + stdin: Arc>, + pending: Pending, + _child: tokio::process::Child, + }, + Http { + http: reqwest::Client, + url: String, + headers: Vec<(String, String)>, + session: Mutex>, + }, +} + +pub struct Client { + t: Transport, + next: AtomicI64, + alive: Arc, + /// `instructions` from initialize + pub instructions: Option, + pub capabilities: Value, +} + +fn rpc_result(m: &Value) -> Result { + match m.get("error") { + Some(e) => Err(format!( + "{} (code {})", + e["message"].as_str().unwrap_or("error"), + e["code"] + )), + None => Ok(m["result"].clone()), + } +} + +async fn write_line(w: &Mutex, v: &Value) -> Result<(), String> { + let mut s = serde_json::to_vec(v).map_err(|e| e.to_string())?; + s.push(b'\n'); + let mut w = w.lock().await; + w.write_all(&s).await.map_err(|e| e.to_string())?; + w.flush().await.map_err(|e| e.to_string()) +} + +impl Client { + pub async fn connect(s: &Server, timeout: Duration) -> Result { + let alive = Arc::new(AtomicBool::new(true)); + let t = match (&s.command, &s.url) { + (Some(cmd), _) => { + let mut c = tokio::process::Command::new(cmd); + c.args(&s.args) + .envs(&s.env) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true); + let mut child = c.spawn().map_err(|e| format!("spawn {cmd}: {e}"))?; + let stdin = Arc::new(Mutex::new(child.stdin.take().ok_or("no stdin")?)); + let stdout = child.stdout.take().ok_or("no stdout")?; + let pending: Pending = Default::default(); + let (p, a, w) = (pending.clone(), alive.clone(), stdin.clone()); + tokio::spawn(async move { + let mut lines = BufReader::new(stdout).lines(); + while let Ok(Some(l)) = lines.next_line().await { + let Ok(m) = serde_json::from_str::(&l) else { + continue; + }; + match (m.get("id"), m.get("method")) { + (Some(id), None) => { + if let Some(i) = id.as_i64() + && let Some(tx) = p.lock().await.remove(&i) + { + let _ = tx.send(rpc_result(&m)); + } + } + // server->client request: answer ping, refuse the rest + (Some(id), Some(meth)) => { + let r = if meth == "ping" { + json!({"jsonrpc":"2.0","id":id,"result":{}}) + } else { + json!({"jsonrpc":"2.0","id":id,"error":{"code":-32601,"message":"method not found"}}) + }; + let _ = write_line(&w, &r).await; + } + _ => {} // notifications: ignored + } + } + a.store(false, Ordering::SeqCst); + for (_, tx) in p.lock().await.drain() { + let _ = tx.send(Err("server exited".into())); + } + }); + Transport::Stdio { + stdin, + pending, + _child: child, + } + } + (None, Some(url)) => Transport::Http { + http: reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| e.to_string())?, + url: url.clone(), + headers: s + .headers + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + session: Mutex::new(None), + }, + _ => return Err("server needs `command` or `url`".into()), + }; + let mut c = Self { + t, + next: AtomicI64::new(1), + alive, + instructions: None, + capabilities: Value::Null, + }; + c.handshake(timeout).await?; + Ok(c) + } + + async fn handshake(&mut self, timeout: Duration) -> Result<(), String> { + let r = self + .request( + "initialize", + json!({"protocolVersion": PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")}}), + timeout, + ) + .await?; + self.instructions = r["instructions"].as_str().map(String::from); + self.capabilities = r["capabilities"].clone(); + self.notify("notifications/initialized", json!({})).await + } + + pub fn alive(&self) -> bool { + self.alive.load(Ordering::SeqCst) + } + + async fn send(&self, v: &Value) -> Result<(), String> { + match &self.t { + Transport::Stdio { stdin, .. } => write_line(stdin, v).await, + Transport::Http { .. } => self.post(v).await.map(|_| ()), + } + } + + /// POST one message; returns the JSON-RPC response matching its id (if it had one). + async fn post(&self, v: &Value) -> Result, String> { + let Transport::Http { + http, + url, + headers, + session, + } = &self.t + else { + unreachable!() + }; + let mut rq = http + .post(url) + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", PROTOCOL) + .json(v); + for (k, x) in headers { + rq = rq.header(k, x); + } + if let Some(s) = session.lock().await.as_ref() { + rq = rq.header("mcp-session-id", s); + } + let r = rq.send().await.map_err(|e| e.to_string())?; + if let Some(s) = r + .headers() + .get("mcp-session-id") + .and_then(|h| h.to_str().ok()) + { + *session.lock().await = Some(s.to_string()); + } + let status = r.status(); + let ct = r + .headers() + .get("content-type") + .and_then(|h| h.to_str().ok()) + .unwrap_or_default() + .to_string(); + let body = r.text().await.map_err(|e| e.to_string())?; + if !status.is_success() { + return Err(format!( + "HTTP {status}: {}", + body.chars().take(300).collect::() + )); + } + let Some(id) = v.get("id") else { + return Ok(None); + }; + let msgs: Vec = if ct.starts_with("text/event-stream") { + body.lines() + .filter_map(|l| l.strip_prefix("data:")) + .filter_map(|d| serde_json::from_str(d.trim()).ok()) + .collect() + } else { + serde_json::from_str::(&body) + .map(|m| match m { + Value::Array(a) => a, + m => vec![m], + }) + .map_err(|e| format!("bad response: {e}"))? + }; + msgs.into_iter() + .find(|m| m.get("id") == Some(id) && m.get("method").is_none()) + .map(Some) + .ok_or_else(|| "no response for request".into()) + } + + pub async fn notify(&self, method: &str, params: Value) -> Result<(), String> { + self.send(&json!({"jsonrpc":"2.0","method":method,"params":params})) + .await + } + + pub async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + ) -> Result { + if !self.alive() { + return Err("server exited".into()); + } + let id = self.next.fetch_add(1, Ordering::SeqCst); + let msg = json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}); + let fut = async { + match &self.t { + Transport::Stdio { pending, .. } => { + let (tx, rx) = oneshot::channel(); + pending.lock().await.insert(id, tx); + self.send(&msg).await?; + rx.await.map_err(|_| "server exited".to_string())? + } + Transport::Http { .. } => rpc_result(&self.post(&msg).await?.ok_or("no response")?), + } + }; + let r = tokio::time::timeout(timeout, fut) + .await + .map_err(|_| format!("{method} timed out after {}s", timeout.as_secs())); + if let (Transport::Stdio { pending, .. }, Err(_)) = (&self.t, &r) { + pending.lock().await.remove(&id); + } + r? + } + + /// Follows `nextCursor` pagination for list methods. + pub async fn list( + &self, + method: &str, + key: &str, + timeout: Duration, + ) -> Result, String> { + let mut out = vec![]; + let mut cursor: Option = None; + loop { + let p = cursor.as_ref().map_or(json!({}), |c| json!({"cursor": c})); + let r = self.request(method, p, timeout).await?; + out.extend(r[key].as_array().cloned().unwrap_or_default()); + match r["nextCursor"].as_str() { + Some(c) if !c.is_empty() && out.len() < 10_000 => cursor = Some(c.into()), + _ => return Ok(out), + } + } + } +} diff --git a/crates/hx-mcp/src/config.rs b/crates/hx-mcp/src/config.rs new file mode 100644 index 0000000..cf7c300 --- /dev/null +++ b/crates/hx-mcp/src/config.rs @@ -0,0 +1,125 @@ +//! MCP config: `~/.hx/mcp.json` + `.hx/mcp.json` (project wins per server), Claude Code `mcpServers` shape. + +use serde::Deserialize; +use std::collections::BTreeMap; +use std::path::Path; + +#[derive(Debug, Clone, PartialEq, Deserialize, Default)] +#[serde(default, rename_all = "camelCase")] +pub struct Server { + /// stdio: program + args + pub command: Option, + pub args: Vec, + pub env: BTreeMap, + /// streamable HTTP endpoint + pub url: Option, + pub headers: BTreeMap, + /// "stdio" | "http" | "sse"; inferred when absent + #[serde(rename = "type")] + pub kind: Option, + /// hx: register tools as native tools instead of the lazy index + pub eager: Option, + /// hx: only these tools are exposed (empty = all) + pub allow: Vec, + /// hx: per-call timeout (`timeoutSecs` or `timeout_secs`) + #[serde(alias = "timeout_secs")] + pub timeout_secs: Option, + pub disabled: bool, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct File { + #[serde(default)] + mcp_servers: BTreeMap, +} + +/// `${VAR}` / `${VAR:-default}` from the environment; unknown vars become "". +pub fn interpolate(s: &str, env: &dyn Fn(&str) -> Option) -> String { + let mut out = String::new(); + let mut rest = s; + while let Some(i) = rest.find("${") { + out.push_str(&rest[..i]); + let Some(j) = rest[i..].find('}') else { + out.push_str(&rest[i..]); + return out; + }; + let expr = &rest[i + 2..i + j]; + let (name, def) = expr.split_once(":-").unwrap_or((expr, "")); + out.push_str(&env(name).unwrap_or_else(|| def.to_string())); + rest = &rest[i + j + 1..]; + } + out.push_str(rest); + out +} + +fn expand(mut s: Server, env: &dyn Fn(&str) -> Option) -> Server { + let f = |x: &str| interpolate(x, env); + s.command = s.command.as_deref().map(f); + s.url = s.url.as_deref().map(f); + s.args = s.args.iter().map(|a| f(a)).collect(); + s.env = s.env.iter().map(|(k, v)| (k.clone(), f(v))).collect(); + s.headers = s.headers.iter().map(|(k, v)| (k.clone(), f(v))).collect(); + s +} + +pub fn parse(json: &str) -> Result, String> { + serde_json::from_str::(json) + .map(|f| f.mcp_servers) + .map_err(|e| e.to_string()) +} + +/// Global then project; a project entry replaces the global one with the same name. Disabled are dropped. +pub fn load(home: &Path, cwd: &Path) -> Result, String> { + let mut all = BTreeMap::new(); + for p in [home.join("mcp.json"), cwd.join(".hx/mcp.json")] { + let Ok(s) = std::fs::read_to_string(&p) else { + continue; + }; + all.extend(parse(&s).map_err(|e| format!("{}: {e}", p.display()))?); + } + let env = |k: &str| std::env::var(k).ok(); + Ok(all + .into_iter() + .filter(|(_, s)| !s.disabled) + .map(|(k, s)| (k, expand(s, &env))) + .collect()) +} + +#[cfg(test)] +mod t { + use super::*; + + #[test] + fn parse_merge_interpolate() { + let d = tempfile::tempdir().unwrap(); + let (home, cwd) = (d.path().join("h"), d.path().join("p")); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(cwd.join(".hx")).unwrap(); + std::fs::write( + home.join("mcp.json"), + r#"{"mcpServers":{ + "fs":{"command":"npx","args":["-y","fs","${HOME}"]}, + "web":{"type":"http","url":"https://x/mcp","headers":{"Authorization":"Bearer ${HX_T_TOKEN:-none}"}}, + "off":{"command":"x","disabled":true}}}"#, + ) + .unwrap(); + std::fs::write( + cwd.join(".hx/mcp.json"), + r#"{"mcpServers":{"fs":{"command":"fs-server","eager":true,"allow":["read"]}}}"#, + ) + .unwrap(); + let m = load(&home, &cwd).unwrap(); + assert_eq!(m.keys().collect::>(), ["fs", "web"]); + assert_eq!(m["fs"].command.as_deref(), Some("fs-server")); + assert!(m["fs"].args.is_empty() && m["fs"].eager == Some(true)); + assert_eq!(m["web"].headers["Authorization"], "Bearer none"); + + let env = |k: &str| (k == "A").then(|| "1".to_string()); + assert_eq!(interpolate("x${A}y${B:-d}z${C}", &env), "x1ydz"); + assert_eq!(interpolate("open ${A", &env), "open ${A"); + assert!(parse("{").is_err()); + std::fs::write(cwd.join(".hx/mcp.json"), "{nope").unwrap(); + assert!(load(&home, &cwd).unwrap_err().contains(".hx/mcp.json")); + } +} diff --git a/crates/hx-mcp/src/lib.rs b/crates/hx-mcp/src/lib.rs index b93cf3f..ddfbf5d 100644 --- a/crates/hx-mcp/src/lib.rs +++ b/crates/hx-mcp/src/lib.rs @@ -1,14 +1,530 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right +//! MCP: config, client, hub (connections + cached lists + restart), and agent tools. +//! +//! Lazy by default: the system prompt gets a one-line-per-tool index; the model fetches a schema with +//! `mcp_describe` and calls through `mcp_call`. Servers whose schemas are small (<= `EAGER_MAX_TOKENS`) +//! or `eager: true` register their tools natively instead. + +pub mod client; +pub mod config; +pub mod serve; + +use async_trait::async_trait; +use client::Client; +use config::Server; +use hx_ai::ToolSpec; +use hx_core::tool::{Tool, ToolCtx, ToolResult}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Mutex; + +/// Servers whose full tool schemas cost at most this many tokens are registered eagerly: below this the +/// saved prompt tokens don't pay for the extra `mcp_describe` round trip. See README "MCP" for the numbers. +pub const EAGER_MAX_TOKENS: usize = 400; +/// Max characters of tool output returned to the model. +pub const OUTPUT_CAP: usize = 30_000; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_RESTARTS: u32 = 3; + +pub struct Slot { + pub cfg: Server, + client: Mutex>>, + restarts: std::sync::atomic::AtomicU32, + pub tools: Vec, + pub prompts: Vec, + pub resources: Vec, + pub instructions: Option, + pub error: Option, +} + +#[derive(Default)] +pub struct Hub { + pub servers: BTreeMap, +} + +fn timeout_of(s: &Server) -> Duration { + Duration::from_secs(s.timeout_secs.unwrap_or(60)) +} + +impl Hub { + /// Connect to all servers in parallel and cache their tool/prompt/resource lists. + pub async fn start(cfgs: BTreeMap) -> Self { + let slots = futures::future::join_all(cfgs.into_iter().map(|(name, cfg)| async move { + let mut slot = Slot { + cfg, + client: Mutex::new(None), + restarts: Default::default(), + tools: vec![], + prompts: vec![], + resources: vec![], + instructions: None, + error: None, + }; + match Client::connect(&slot.cfg, CONNECT_TIMEOUT).await { + Ok(c) => { + let t = timeout_of(&slot.cfg); + let caps = c.capabilities.clone(); + let (tools, prompts, resources) = tokio::join!( + c.list("tools/list", "tools", t), + async { + if caps.get("prompts").is_some() { + c.list("prompts/list", "prompts", t).await + } else { + Ok(vec![]) + } + }, + async { + if caps.get("resources").is_some() { + c.list("resources/list", "resources", t).await + } else { + Ok(vec![]) + } + } + ); + match tools { + Ok(v) => { + slot.tools = v + .into_iter() + .filter(|x| { + slot.cfg.allow.is_empty() + || x["name"] + .as_str() + .is_some_and(|n| slot.cfg.allow.iter().any(|a| a == n)) + }) + .collect() + } + Err(e) => slot.error = Some(format!("tools/list: {e}")), + } + slot.prompts = prompts.unwrap_or_default(); + slot.resources = resources.unwrap_or_default(); + slot.instructions = c.instructions.clone(); + *slot.client.get_mut() = Some(Arc::new(c)); + } + Err(e) => slot.error = Some(e), + } + (name, slot) + })) + .await; + Self { + servers: slots.into_iter().collect(), + } + } + + /// Live client for `server`, reconnecting (bounded) if the process died. + async fn client(&self, server: &str) -> Result<(Arc, &Slot), String> { + let slot = self + .servers + .get(server) + .ok_or_else(|| format!("unknown MCP server `{server}`"))?; + let mut g = slot.client.lock().await; + if let Some(c) = g.as_ref().filter(|c| c.alive()) { + return Ok((c.clone(), slot)); + } + let n = slot + .restarts + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if n >= MAX_RESTARTS { + return Err(format!( + "MCP server `{server}` keeps crashing; gave up after {MAX_RESTARTS} restarts" + )); + } + let c = Arc::new(Client::connect(&slot.cfg, CONNECT_TIMEOUT).await?); + *g = Some(c.clone()); + Ok((c, slot)) + } + + pub fn tool(&self, server: &str, tool: &str) -> Option<&Value> { + self.servers + .get(server)? + .tools + .iter() + .find(|t| t["name"] == tool) + } + + pub fn is_eager(&self, server: &str) -> bool { + self.servers.get(server).is_some_and(|s| { + s.cfg + .eager + .unwrap_or(spec_tokens(&s.tools) <= EAGER_MAX_TOKENS) + && !s.tools.is_empty() + }) + } + + /// Validate against the cached schema, call, and flatten the result for the model. + pub async fn call(&self, server: &str, tool: &str, args: Value) -> ToolResult { + let Some(spec) = self.tool(server, tool) else { + return ToolResult::err(format!( + "unknown tool `{server}.{tool}` (not listed or not allowed); see the MCP index" + )); + }; + let args = if args.is_null() { json!({}) } else { args }; + if let Err(e) = hx_core::tool::validate(&spec["inputSchema"], &args) { + return ToolResult::err(format!("{e}. Schema: {}", spec["inputSchema"])); + } + let (c, slot) = match self.client(server).await { + Ok(x) => x, + Err(e) => return ToolResult::err(e), + }; + match c + .request( + "tools/call", + json!({"name": tool, "arguments": args}), + timeout_of(&slot.cfg), + ) + .await + { + Ok(r) => { + let text = render(&r); + if r["isError"] == true { + ToolResult::err(text) + } else { + ToolResult::ok(text) + } + } + Err(e) => ToolResult::err(format!("{server}.{tool}: {e}")), + } + } + + pub async fn read(&self, server: &str, uri: &str) -> ToolResult { + let (c, slot) = match self.client(server).await { + Ok(x) => x, + Err(e) => return ToolResult::err(e), + }; + match c + .request("resources/read", json!({"uri": uri}), timeout_of(&slot.cfg)) + .await + { + Ok(r) => ToolResult::ok(cap(r["contents"] + .as_array() + .into_iter() + .flatten() + .map(|x| match x["text"].as_str() { + Some(t) => t.to_string(), + None => format!( + "[binary {} {}]", + x["mimeType"].as_str().unwrap_or(""), + x["uri"].as_str().unwrap_or("") + ), + }) + .collect::>() + .join("\n"))), + Err(e) => ToolResult::err(e), + } + } + + /// Expand prompt `server:name` with `args` (`key=value` pairs or one free-text value for the first + /// argument) into user text. + pub async fn prompt(&self, server: &str, name: &str, args: &str) -> Result { + let (c, slot) = self.client(server).await?; + let p = slot + .prompts + .iter() + .find(|p| p["name"] == name) + .ok_or_else(|| format!("unknown prompt {server}:{name}"))?; + let names: Vec<&str> = p["arguments"] + .as_array() + .into_iter() + .flatten() + .filter_map(|a| a["name"].as_str()) + .collect(); + let mut map = serde_json::Map::new(); + if args.contains('=') { + for kv in args.split_whitespace() { + if let Some((k, v)) = kv.split_once('=') { + map.insert(k.into(), v.into()); + } + } + } else if let (Some(first), false) = (names.first(), args.is_empty()) { + map.insert((*first).into(), args.into()); + } + let r = c + .request( + "prompts/get", + json!({"name": name, "arguments": map}), + timeout_of(&slot.cfg), + ) + .await?; + Ok(r["messages"] + .as_array() + .into_iter() + .flatten() + .map(|m| render(&json!({"content": [m["content"].clone()]}))) + .collect::>() + .join("\n\n")) + } + + /// Per-server index blocks for the system prompt: (server, text). Eager servers are omitted. + pub fn index(&self) -> Vec<(String, String)> { + self.servers + .iter() + .filter(|(n, s)| !s.tools.is_empty() && !self.is_eager(n)) + .map(|(n, s)| { + let mut out = String::new(); + for t in &s.tools { + let d = t["description"].as_str().unwrap_or_default(); + let d = d.lines().next().unwrap_or_default(); + let d: String = d.chars().take(100).collect(); + out.push_str(&format!( + "- {n}.{}: {d}\n", + t["name"].as_str().unwrap_or_default() + )); + } + (n.clone(), out) + }) + .collect() + } + + pub fn system_prompt(&self) -> String { + let idx = self.index(); + let mut s = String::new(); + if !idx.is_empty() { + s.push_str("# MCP tools\nCall with `mcp_call` (server, tool, arguments). Use `mcp_describe` first to get the argument schema.\n"); + for (_, b) in idx { + s.push_str(&b); + } + } + let res: Vec = self + .servers + .iter() + .flat_map(|(n, s)| { + s.resources.iter().take(20).map(move |r| { + format!( + "- {n}: {} ({})", + r["uri"].as_str().unwrap_or_default(), + r["name"].as_str().unwrap_or_default() + ) + }) + }) + .collect(); + if !res.is_empty() { + s.push_str("\n# MCP resources\nRead with `mcp_read` (server, uri).\n"); + s.push_str(&res.join("\n")); + s.push('\n'); + } + for (n, sl) in &self.servers { + if let Some(i) = sl.instructions.as_deref().filter(|i| !i.trim().is_empty()) { + let i: String = i.chars().take(1500).collect(); + s.push_str(&format!( + "\n# MCP server `{n}` instructions\n{}\n", + i.trim() + )); + } + } + s + } + + /// Status lines: tools, eager/lazy, index vs eager token cost (bytes/4), errors. + pub fn status(&self) -> Vec { + let idx: BTreeMap = self.index().into_iter().collect(); + self.servers + .iter() + .map(|(n, s)| { + if let Some(e) = &s.error { + return format!("{n}: error: {e}"); + } + let eager_tok = spec_tokens(&s.tools); + let idx_tok = idx.get(n).map_or(0, |b| b.len() / 4); + format!( + "{n}: {} tools, {} prompts, {} resources; {} (index ~{idx_tok} tok, eager schemas ~{eager_tok} tok)", + s.tools.len(), + s.prompts.len(), + s.resources.len(), + if self.is_eager(n) { "eager" } else { "lazy" } + ) + }) + .collect() + } + + /// Register agent tools: eager native tools, plus mcp_describe/mcp_call/mcp_read when needed. + pub fn register(self: &Arc, reg: &mut hx_core::tool::Registry) { + let mut lazy = false; + for (n, s) in &self.servers { + if self.is_eager(n) { + for t in &s.tools { + reg.add(Native { + hub: self.clone(), + server: n.clone(), + tool: t["name"].as_str().unwrap_or_default().to_string(), + spec: ToolSpec { + name: native_name(n, t["name"].as_str().unwrap_or_default()), + description: t["description"].as_str().unwrap_or_default().to_string(), + input_schema: t["inputSchema"].clone(), + }, + }); + } + } else if !s.tools.is_empty() { + lazy = true; + } + } + if lazy { + reg.add(Describe { hub: self.clone() }); + reg.add(Call { hub: self.clone() }); + } + if self.servers.values().any(|s| !s.resources.is_empty()) { + reg.add(Read { hub: self.clone() }); + } + } +} + +fn spec_tokens(tools: &[Value]) -> usize { + tools + .iter() + .map(|t| { + json!({"name": t["name"], "description": t["description"], "input_schema": t["inputSchema"]}) + .to_string() + .len() + }) + .sum::() + / 4 +} + +/// `server__tool`, restricted to [a-zA-Z0-9_-], max 64 chars (provider limit). +pub fn native_name(server: &str, tool: &str) -> String { + let s: String = format!("{server}__{tool}") + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' || c == '-' { + c + } else { + '_' + } + }) + .collect(); + s.chars().take(64).collect() +} + +fn cap(s: String) -> String { + if s.len() <= OUTPUT_CAP { + return s; + } + let mut i = OUTPUT_CAP; + while !s.is_char_boundary(i) { + i -= 1; + } + format!( + "{}\n… [truncated {} of {} bytes]", + &s[..i], + s.len() - i, + s.len() + ) +} + +/// Flatten a `tools/call` / prompt result into text. +pub fn render(r: &Value) -> String { + let mut parts: Vec = r["content"] + .as_array() + .into_iter() + .flatten() + .map(|c| match c["type"].as_str() { + Some("text") => c["text"].as_str().unwrap_or_default().to_string(), + Some("resource") => c["resource"]["text"] + .as_str() + .map(String::from) + .unwrap_or_else(|| { + format!("[resource {}]", c["resource"]["uri"].as_str().unwrap_or("")) + }), + Some("resource_link") => format!("[resource link {}]", c["uri"].as_str().unwrap_or("")), + Some(t) => format!("[{t} {}]", c["mimeType"].as_str().unwrap_or("")), + None => String::new(), + }) + .filter(|s| !s.is_empty()) + .collect(); + if parts.is_empty() && !r["structuredContent"].is_null() { + parts.push(r["structuredContent"].to_string()); + } + cap(parts.join("\n")) +} + +struct Native { + hub: Arc, + server: String, + tool: String, + spec: ToolSpec, +} + +#[async_trait] +impl Tool for Native { + fn spec(&self) -> ToolSpec { + self.spec.clone() + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + self.hub.call(&self.server, &self.tool, a).await + } +} + +struct Describe { + hub: Arc, +} + +#[async_trait] +impl Tool for Describe { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "mcp_describe".into(), + description: "Full description and argument schema of an MCP tool from the MCP index." + .into(), + input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"tool":{"type":"string"}},"required":["server","tool"]}), + } + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + let (s, t) = ( + a["server"].as_str().unwrap_or_default(), + a["tool"].as_str().unwrap_or_default(), + ); + match self.hub.tool(s, t) { + Some(x) => ToolResult::ok( + json!({"description": x["description"], "arguments": x["inputSchema"]}).to_string(), + ), + None => ToolResult::err(format!("unknown tool `{s}.{t}`")), + } + } +} + +struct Call { + hub: Arc, +} + +#[async_trait] +impl Tool for Call { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "mcp_call".into(), + description: "Call an MCP tool from the MCP index. `arguments` must match the tool's schema (see mcp_describe).".into(), + input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"tool":{"type":"string"},"arguments":{"type":"object"}},"required":["server","tool"]}), + } + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + let (s, t) = ( + a["server"].as_str().unwrap_or_default(), + a["tool"].as_str().unwrap_or_default(), + ); + self.hub.call(s, t, a["arguments"].clone()).await + } +} + +struct Read { + hub: Arc, +} + +#[async_trait] +impl Tool for Read { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "mcp_read".into(), + description: "Read an MCP resource by server and uri.".into(), + input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"uri":{"type":"string"}},"required":["server","uri"]}), + } + } + async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult { + self.hub + .read( + a["server"].as_str().unwrap_or_default(), + a["uri"].as_str().unwrap_or_default(), + ) + .await + } } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} +mod tests; diff --git a/crates/hx-mcp/src/serve.rs b/crates/hx-mcp/src/serve.rs new file mode 100644 index 0000000..194d382 --- /dev/null +++ b/crates/hx-mcp/src/serve.rs @@ -0,0 +1,140 @@ +//! `hx mcp-serve`: expose a tool registry as an MCP server over stdio (newline-delimited JSON-RPC). + +use hx_core::tool::{Registry, ToolCtx}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt}; + +/// Serve until EOF. Tool calls run concurrently; replies are written as they finish. +pub async fn serve( + reg: Registry, + cx: ToolCtx, + input: impl AsyncBufRead + Unpin, + output: impl AsyncWrite + Unpin + Send + 'static, +) -> std::io::Result<()> { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + let writer = tokio::spawn(async move { + let mut out = output; + while let Some(v) = rx.recv().await { + let mut b = serde_json::to_vec(&v).unwrap_or_default(); + b.push(b'\n'); + if out.write_all(&b).await.is_err() || out.flush().await.is_err() { + break; + } + } + }); + let mut lines = input.lines(); + while let Some(l) = lines.next_line().await? { + let Ok(m) = serde_json::from_str::(&l) else { + let _ = tx.send( + json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"parse error"}}), + ); + continue; + }; + let Some(id) = m.get("id").cloned() else { + continue; // notification + }; + let p = &m["params"]; + let reply = |r: Result| match r { + Ok(r) => json!({"jsonrpc":"2.0","id":id,"result":r}), + Err((c, e)) => json!({"jsonrpc":"2.0","id":id,"error":{"code":c,"message":e}}), + }; + match m["method"].as_str().unwrap_or_default() { + "initialize" => { + let _ = tx.send(reply(Ok(json!({ + "protocolVersion": p["protocolVersion"].as_str().unwrap_or(crate::client::PROTOCOL), + "capabilities": {"tools": {}}, + "serverInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")} + })))); + } + "ping" => { + let _ = tx.send(reply(Ok(json!({})))); + } + "tools/list" => { + let tools: Vec = reg + .specs() + .into_iter() + .map(|s| json!({"name": s.name, "description": s.description, "inputSchema": s.input_schema})) + .collect(); + let _ = tx.send(reply(Ok(json!({"tools": tools})))); + } + "tools/call" => { + let (reg, cx, tx) = (reg.clone(), cx.clone(), tx.clone()); + let name = p["name"].as_str().unwrap_or_default().to_string(); + let args = if p["arguments"].is_null() { + json!({}) + } else { + p["arguments"].clone() + }; + tokio::spawn(async move { + let r = reg.call(&name, args, &cx).await; + let _ = tx.send(json!({"jsonrpc":"2.0","id":id,"result":{ + "content":[{"type":"text","text":r.content}],"isError":r.is_error}})); + }); + } + other => { + let _ = tx.send(reply(Err((-32601, format!("method not found: {other}"))))); + } + } + } + drop(tx); + let _ = writer.await; + Ok(()) +} + +#[cfg(test)] +mod t { + use super::*; + use crate::{Hub, config::Server}; + use std::collections::BTreeMap; + + /// Drive the server with raw JSON-RPC lines over an in-memory pipe. + #[tokio::test] + async fn serves_registry() { + let reg = hx_tools_like(); + let input = concat!( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#, + "\n", + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + "\n", + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#, + "\n", + r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"f__echo","arguments":{"message":"x"}}}"#, + "\n", + r#"{"jsonrpc":"2.0","id":4,"method":"nope"}"#, + "\n", + ); + let (w, r) = tokio::io::duplex(1 << 16); + let cx = ToolCtx { + cwd: ".".into(), + state: Default::default(), + }; + serve(reg.await, cx, input.as_bytes(), w).await.unwrap(); + let mut out = String::new(); + use tokio::io::AsyncReadExt; + let mut r = r; + r.read_to_string(&mut out).await.unwrap(); + let msgs: BTreeMap = out + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .map(|v| (v["id"].as_i64().unwrap(), v)) + .collect(); + assert_eq!(msgs[&1]["result"]["serverInfo"]["name"], "hx"); + assert_eq!(msgs[&2]["result"]["tools"][0]["name"], "f__add"); + assert_eq!(msgs[&3]["result"]["content"][0]["text"], "echo: x"); + assert_eq!(msgs[&4]["error"]["code"], -32601); + } + + /// a registry with real tools: eager MCP tools proxied from the fake server + async fn hx_tools_like() -> Registry { + let s: Server = serde_json::from_value(json!({ + "command": "python3", + "args": [concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fake_mcp.py")], + "allow": ["echo", "add"] + })) + .unwrap(); + let h = std::sync::Arc::new(Hub::start(BTreeMap::from([("f".into(), s)])).await); + let mut reg = Registry::default(); + h.register(&mut reg); + reg + } +} diff --git a/crates/hx-mcp/src/tests.rs b/crates/hx-mcp/src/tests.rs new file mode 100644 index 0000000..f41874e --- /dev/null +++ b/crates/hx-mcp/src/tests.rs @@ -0,0 +1,234 @@ +use super::*; +use std::path::PathBuf; + +fn fake() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_mcp.py") +} + +fn stdio(extra: &str) -> Server { + let mut s: Server = serde_json::from_str(&format!( + r#"{{"command":"python3","args":["{}"]{extra}}}"#, + fake().display() + )) + .unwrap(); + s.timeout_secs.get_or_insert(10); + s +} + +async fn hub(extra: &str) -> Arc { + Arc::new(Hub::start(BTreeMap::from([("f".to_string(), stdio(extra))])).await) +} + +fn cx() -> ToolCtx { + ToolCtx { + cwd: ".".into(), + state: Default::default(), + } +} + +#[tokio::test] +async fn stdio_lazy_index_describe_call() { + let h = hub(r#","eager":false"#).await; + let s = &h.servers["f"]; + assert_eq!(s.error, None); + assert_eq!(s.tools.len(), 5, "pagination followed"); + assert!(!h.is_eager("f")); + let sp = h.system_prompt(); + assert!(sp.contains("- f.echo: Echo a message back\n"), "{sp}"); + assert!(!sp.contains("second line")); + assert!(sp.contains("mem://notes") && sp.contains("Use echo for tests.")); + let st = h.status(); + assert!( + st[0].contains("5 tools") && st[0].contains("lazy") && st[0].contains("index ~"), + "{st:?}" + ); + + let mut reg = hx_core::tool::Registry::default(); + h.register(&mut reg); + let names: Vec = reg.specs().into_iter().map(|s| s.name).collect(); + assert_eq!(names, ["mcp_call", "mcp_describe", "mcp_read"]); + let d = reg + .call("mcp_describe", json!({"server":"f","tool":"add"}), &cx()) + .await; + assert!(d.content.contains("\"required\":[\"a\",\"b\"]"), "{d:?}"); + let r = reg + .call( + "mcp_call", + json!({"server":"f","tool":"add","arguments":{"a":2,"b":3}}), + &cx(), + ) + .await; + assert_eq!(r, ToolResult::ok("5")); + // validation against cached schema: missing + wrong type, no server round trip + let r = reg + .call( + "mcp_call", + json!({"server":"f","tool":"add","arguments":{"a":"x"}}), + &cx(), + ) + .await; + assert!( + r.is_error && r.content.contains("missing required argument `b`"), + "{r:?}" + ); + let r = reg + .call("mcp_call", json!({"server":"f","tool":"nope"}), &cx()) + .await; + assert!(r.is_error && r.content.contains("unknown tool")); + let r = reg + .call("mcp_read", json!({"server":"f","uri":"mem://notes"}), &cx()) + .await; + assert_eq!(r, ToolResult::ok("note body")); + assert_eq!( + h.prompt("f", "review", "src/a.rs").await.unwrap(), + "Please review src/a.rs" + ); + assert_eq!( + h.prompt("f", "review", "path=b.rs").await.unwrap(), + "Please review b.rs" + ); +} + +#[tokio::test] +async fn eager_and_allowlist() { + // small schemas -> native tools, no mcp_call + assert!(spec_tokens(&hub("").await.servers["f"].tools) <= EAGER_MAX_TOKENS); + let h = hub(r#","allow":["echo","add"]"#).await; + assert!(h.is_eager("f")); + let mut reg = hx_core::tool::Registry::default(); + h.register(&mut reg); + let names: Vec = reg.specs().into_iter().map(|s| s.name).collect(); + assert_eq!(names, ["f__add", "f__echo", "mcp_read"]); + assert!(!h.system_prompt().contains("# MCP tools")); + let r = reg.call("f__echo", json!({"message":"hi"}), &cx()).await; + assert_eq!(r, ToolResult::ok("echo: hi")); + // disallowed tool is not callable + assert!(h.call("f", "crash", json!({})).await.is_error); + // explicit eager=false wins over size + let h = hub(r#","allow":["echo"],"eager":false"#).await; + assert!(!h.is_eager("f")); + // explicit eager=true / size rule with a tiny budget + assert!(hub(r#","eager":true"#).await.is_eager("f")); + assert_eq!(native_name("my.srv", "a/b"), "my_srv__a_b"); +} + +#[tokio::test] +async fn safety_cap_timeout_restart() { + let h = hub(r#","timeoutSecs":1"#).await; + let r = h.call("f", "big", json!({})).await; + assert!( + r.content.len() < OUTPUT_CAP + 100 && r.content.contains("[truncated"), + "{}", + r.content.len() + ); + // stdio servers answer in order, so the timeout test gets its own process + let r = hub(r#","timeoutSecs":1"#) + .await + .call("f", "slow", json!({})) + .await; + assert!(r.is_error && r.content.contains("timed out"), "{r:?}"); + // kill the server; next call reconnects + let r = h.call("f", "crash", json!({})).await; + assert!(r.is_error && r.content.contains("server exited"), "{r:?}"); + let r = h.call("f", "echo", json!({"message":"back"})).await; + assert_eq!(r, ToolResult::ok("echo: back")); + // bounded restarts + for _ in 0..MAX_RESTARTS { + h.call("f", "crash", json!({})).await; + } + let r = h.call("f", "echo", json!({"message":"x"})).await; + assert!(r.content.contains("gave up"), "{r:?}"); +} + +#[tokio::test] +async fn http_transport() { + let port = 30000 + std::process::id() % 20000; + let mut srv = tokio::process::Command::new("python3") + .arg(fake()) + .args(["http", &port.to_string()]) + .kill_on_drop(true) + .spawn() + .unwrap(); + let cfg: Server = serde_json::from_value(json!({ + "type": "http", "url": format!("http://127.0.0.1:{port}/mcp"), + "headers": {"Authorization": "Bearer t0k"} + })) + .unwrap(); + let mut h = Hub::default(); + for _ in 0..50 { + h = Hub::start(BTreeMap::from([("w".to_string(), cfg.clone())])).await; + if h.servers["w"].error.is_none() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(h.servers["w"].error, None); + assert_eq!(h.servers["w"].tools.len(), 5); + assert_eq!( + h.call("w", "echo", json!({"message":"sse"})).await, + ToolResult::ok("echo: sse") + ); + // wrong token -> clear error + let mut bad = cfg.clone(); + bad.headers + .insert("Authorization".into(), "Bearer no".into()); + let h = Hub::start(BTreeMap::from([("w".to_string(), bad)])).await; + assert!( + h.servers["w"] + .error + .as_deref() + .unwrap_or("") + .contains("401"), + "{:?}", + h.servers["w"].error + ); + let _ = srv.kill().await; +} + +/// Reference server (@modelcontextprotocol/server-everything), only when npx has it cached. +#[tokio::test] +async fn reference_server_everything() { + let home = std::env::var("HOME").unwrap_or_default(); + let cached = std::fs::read_dir(format!("{home}/.npm/_npx")) + .into_iter() + .flatten() + .flatten() + .any(|d| { + d.path() + .join("node_modules/@modelcontextprotocol/server-everything") + .exists() + }); + if !cached { + eprintln!("skip: server-everything not cached"); + return; + } + let cfg: Server = serde_json::from_value(json!({ + "command": "npx", "args": ["-y", "--offline", "@modelcontextprotocol/server-everything"] + })) + .unwrap(); + let h = Hub::start(BTreeMap::from([("e".to_string(), cfg)])).await; + assert_eq!(h.servers["e"].error, None); + assert!(h.tool("e", "echo").is_some() && h.tool("e", "get-sum").is_some()); + assert_eq!( + h.call("e", "echo", json!({"message":"ref"})).await, + ToolResult::ok("Echo: ref") + ); + assert!( + h.call("e", "get-sum", json!({"a":2,"b":3})) + .await + .content + .contains('5') + ); + assert!(!h.servers["e"].prompts.is_empty() && !h.servers["e"].resources.is_empty()); + assert!( + h.prompt("e", "simple-prompt", "") + .await + .unwrap() + .contains("simple prompt") + ); + let uri = h.servers["e"].resources[0]["uri"] + .as_str() + .unwrap() + .to_string(); + assert!(!h.read("e", &uri).await.is_error); +} diff --git a/crates/hx-mcp/tests/fake_mcp.py b/crates/hx-mcp/tests/fake_mcp.py new file mode 100644 index 0000000..3611381 --- /dev/null +++ b/crates/hx-mcp/tests/fake_mcp.py @@ -0,0 +1,92 @@ +"""Tiny MCP server for tests. stdio (default) or streamable HTTP: `fake_mcp.py http PORT`. +Tools: echo(message), add(a,b), crash() (exits the process), big() (large output), slow(). One prompt, one resource. +""" +import json, sys, time + +TOOLS = [ + {"name": "echo", "description": "Echo a message back\nsecond line ignored in index", + "inputSchema": {"type": "object", "properties": {"message": {"type": "string"}}, "required": ["message"]}}, + {"name": "add", "description": "Add two integers", + "inputSchema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}, + {"name": "crash", "description": "Kill the server", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "big", "description": "Large output", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "slow", "description": "Sleeps 5s", "inputSchema": {"type": "object", "properties": {}}}, +] + + +def handle(m): + meth, p, i = m.get("method"), m.get("params") or {}, m.get("id") + if i is None: + return None + r = None + if meth == "initialize": + r = {"protocolVersion": p.get("protocolVersion"), "serverInfo": {"name": "fake", "version": "1"}, + "capabilities": {"tools": {}, "prompts": {}, "resources": {}}, "instructions": "Use echo for tests."} + elif meth == "tools/list": + # paginate: first page 2 tools + if p.get("cursor") == "p2": + r = {"tools": TOOLS[2:]} + else: + r = {"tools": TOOLS[:2], "nextCursor": "p2"} + elif meth == "tools/call": + n, a = p["name"], p.get("arguments") or {} + if n == "echo": + r = {"content": [{"type": "text", "text": "echo: " + a["message"]}]} + elif n == "add": + r = {"content": [{"type": "text", "text": str(a["a"] + a["b"])}]} + elif n == "crash": + sys.exit(3) + elif n == "big": + r = {"content": [{"type": "text", "text": "x" * 100000}]} + elif n == "slow": + time.sleep(5) + r = {"content": [{"type": "text", "text": "late"}]} + else: + r = {"content": [{"type": "text", "text": "no such tool"}], "isError": True} + elif meth == "prompts/list": + r = {"prompts": [{"name": "review", "description": "Review a file", "arguments": [{"name": "path", "required": True}]}]} + elif meth == "prompts/get": + r = {"messages": [{"role": "user", "content": {"type": "text", "text": "Please review " + p["arguments"].get("path", "?")}}]} + elif meth == "resources/list": + r = {"resources": [{"uri": "mem://notes", "name": "notes"}]} + elif meth == "resources/read": + r = {"contents": [{"uri": p["uri"], "text": "note body"}]} + else: + return {"jsonrpc": "2.0", "id": i, "error": {"code": -32601, "message": "method not found"}} + return {"jsonrpc": "2.0", "id": i, "result": r} + + +if len(sys.argv) > 1 and sys.argv[1] == "http": + import http.server + + class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + if self.headers.get("authorization") != "Bearer t0k": + self.send_response(401); self.end_headers(); return + m = json.loads(self.rfile.read(int(self.headers["content-length"]))) + if m.get("method") != "initialize" and self.headers.get("mcp-session-id") != "s1": + self.send_response(400); self.end_headers(); return + r = handle(m) + if r is None: + self.send_response(202); self.end_headers(); return + self.send_response(200) + self.send_header("mcp-session-id", "s1") + # answer tools/call as SSE, everything else as JSON + if m.get("method") == "tools/call": + self.send_header("content-type", "text/event-stream"); self.end_headers() + self.wfile.write(b'event: message\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{}}\n\n') + self.wfile.write(("event: message\ndata: " + json.dumps(r) + "\n\n").encode()) + else: + self.send_header("content-type", "application/json"); self.end_headers() + self.wfile.write(json.dumps(r).encode()) + + http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[2])), H).serve_forever() +else: + for line in sys.stdin: + r = handle(json.loads(line)) + if r is not None: + sys.stdout.write(json.dumps(r) + "\n") + sys.stdout.flush() diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index b3f5c31..6eef748 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -33,8 +33,26 @@ pub struct Setup { pub pricing: fn(&str) -> Option, /// `/lsp` status lines. pub lsp_status: LspStatus, + /// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine, + /// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error. + pub commands: Commands, } +pub enum CmdOut { + Send(String), + Show(String), +} + +pub type Commands = Box< + dyn Fn( + &str, + &str, + ) -> Option< + std::pin::Pin> + Send>>, + > + Send + + Sync, +>; + pub type LspStatus = Box< dyn Fn() -> std::pin::Pin> + Send>> + Send, >; @@ -113,6 +131,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { default_model, pricing, lsp_status, + commands, } = setup; let (tx, mut rx) = mpsc::unbounded_channel(); agent.bus.add(Forward(tx.clone())); @@ -160,6 +179,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { default_model, cwd: &cwd, lsp_status: &lsp_status, + commands: &commands, }; let mut term = ratatui::init(); let mut keys = EventStream::new(); @@ -315,9 +335,10 @@ struct Ctx<'a> { default_model: fn(Kind) -> String, cwd: &'a std::path::Path, lsp_status: &'a LspStatus, + commands: &'a Commands, } -async fn submit(app: &mut App, line: String, c: &Ctx<'_>) { +async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { let Ctx { agent, tx, @@ -325,9 +346,10 @@ async fn submit(app: &mut App, line: String, c: &Ctx<'_>) { default_model, cwd, lsp_status, + commands, } = *c; app.scroll = 0; - if let Some(cmd) = line.strip_prefix('/') { + if let Some(cmd) = line.clone().strip_prefix('/') { let (c, arg) = cmd .split_once(' ') .map_or((cmd, ""), |(a, b)| (a, b.trim())); @@ -389,11 +411,20 @@ async fn submit(app: &mut App, line: String, c: &Ctx<'_>) { app.ctx_tokens = 0; app.t.push(Item::Info("cleared".into())); } - _ => app - .t - .push(Item::Error(format!("unknown command /{c}; /help"))), + _ => match commands(c, arg) { + None => app + .t + .push(Item::Error(format!("unknown command /{c}; /help"))), + Some(f) => match f.await { + Ok(CmdOut::Show(t)) => app.t.push(Item::Info(t)), + Ok(CmdOut::Send(t)) => line = t, + Err(e) => app.t.push(Item::Error(e)), + }, + }, + } + if line.starts_with('/') { + return; } - return; } if app.busy { app.t.push(Item::Info(format!( diff --git a/tests/all.sh b/tests/all.sh index baab092..b406648 100755 --- a/tests/all.sh +++ b/tests/all.sh @@ -6,7 +6,9 @@ set -e cargo fmt --all --check cargo clippy -q --workspace --all-targets -- -D warnings log=$(mktemp) -cargo test -q --workspace >"$log" 2>&1 || { grep -E 'FAILED|panicked' -A4 "$log"; exit 1; } +# rust-analyzer test runs alone: under parallel cargo load its flycheck can publish stale results (see issue) +cargo test -q --workspace -- --skip rust_analyzer_turn_end >"$log" 2>&1 || { grep -E 'FAILED|panicked' -A4 "$log"; exit 1; } +cargo test -q -p hx-lens rust_analyzer_turn_end >>"$log" 2>&1 || { grep -E 'FAILED|panicked' -A4 "$log"; exit 1; } grep -oE 'ok. [0-9]+ passed' "$log" | awk '{s+=$2} END {print s" unit tests ok"}' cargo build -q sh tests/e2e.sh @@ -14,3 +16,4 @@ python3 tests/tui_smoke.py | grep -q FAIL && { echo "tui smoke FAIL"; exit 1; } sh tests/lens_e2e.sh sh tests/m4_e2e.sh sh tests/m5_e2e.sh +sh tests/m6_e2e.sh diff --git a/tests/fake_m6.py b/tests/fake_m6.py new file mode 100644 index 0000000..9d0a2c2 --- /dev/null +++ b/tests/fake_m6.py @@ -0,0 +1,69 @@ +"""M6 e2e fake model: discovers an MCP tool from the system-prompt index, describes it, calls it. +turn 1: expect "- f.add:" in system prompt -> mcp_describe(f, add) +turn 2: expect schema in tool result -> mcp_call(f, add, {a:2,b:40}) +turn 3: expect "42" -> finish +Usage: python3 tests/fake_m6.py PORT +""" +import http.server, json, sys + +LOG = [] + + +def sse(ev, d): + return f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() + + +def texts(msg): + out = [] + for b in msg["content"]: + if b.get("type") == "text": + out.append(b["text"]) + if b.get("type") == "tool_result": + c = b["content"] + if isinstance(c, list): + c = "".join(x.get("text", "") for x in c) + out.append(("ERR:" if b.get("is_error") else "OK:") + c) + return "\n".join(out) + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["content-length"]))) + system = json.dumps(body.get("system", "")) + tools = [t["name"] for t in body.get("tools", [])] + last = texts(body["messages"][-1]) + LOG.append({"last": last, "tools": tools, "index": "- f.add: Add two integers" in system}) + n = len(LOG) + if n == 1 and LOG[0]["index"] and "mcp_describe" in tools: + turn = ("mcp_describe", {"server": "f", "tool": "add"}) + elif n == 2 and '"required":["a","b"]' in last: + turn = ("mcp_call", {"server": "f", "tool": "add", "arguments": {"a": 2, "b": 40}}) + else: + turn = None + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.end_headers() + w = self.wfile.write + w(sse("message_start", {"message": {"usage": {"input_tokens": 1, "output_tokens": 1}}})) + if turn is None: + w(sse("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}})) + w(sse("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": "FINISHED " + last[:40]}})) + stop = "end_turn" + else: + w(sse("content_block_start", {"index": 0, "content_block": {"type": "tool_use", "id": f"t{n}", "name": turn[0], "input": {}}})) + w(sse("content_block_delta", {"index": 0, "delta": {"type": "input_json_delta", "partial_json": json.dumps(turn[1])}})) + stop = "tool_use" + w(sse("content_block_stop", {"index": 0})) + w(sse("message_delta", {"delta": {"stop_reason": stop}, "usage": {"output_tokens": 1}})) + w(sse("message_stop", {})) + + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps(LOG).encode()) + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() diff --git a/tests/m6_e2e.sh b/tests/m6_e2e.sh new file mode 100644 index 0000000..9db852e --- /dev/null +++ b/tests/m6_e2e.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# M6 e2e: model discovers an MCP tool via the lazy index, describes and calls it; `hx mcp` reports costs; +# `hx mcp-serve` answers another MCP client (hx itself, configured as a server) with lens tools. +set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +tmp=$(mktemp -d) +trap 'kill $srv 2>/dev/null; rm -rf "$tmp"' EXIT +port=$((20000 + $$ % 20000)) +python3 "$root/tests/fake_m6.py" $port & srv=$! +mkdir -p "$tmp/home/.hx" "$tmp/repo/.hx" +echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999}}' > "$tmp/home/.hx/auth.json" +printf '[lsp]\nmode = "off"\ntests = "off"\n' > "$tmp/home/.hx/config.toml" +cat > "$tmp/repo/.hx/mcp.json" < "$tmp/out" 2> "$tmp/err" || { cat "$tmp/err"; exit 1; } +grep -q "FINISHED OK:42" "$tmp/out" || { echo "--- out"; cat "$tmp/out"; echo "--- log"; curl -s "http://127.0.0.1:$port/"; echo "--- err"; cat "$tmp/err"; exit 1; } +"$root/target/debug/hx" mcp > "$tmp/st" +grep -q "f: 5 tools.*lazy (index ~[0-9]* tok, eager schemas ~[0-9]* tok)" "$tmp/st" || { cat "$tmp/st"; exit 1; } +# mcp-serve: hx as MCP server, consumed by hx as MCP client +printf 'fn main() {}\n' > main.rs +cat > "$tmp/repo/.hx/mcp.json" < "$tmp/st2" +grep -q "hx.lsp: Language server queries" "$tmp/st2" || { cat "$tmp/st2"; exit 1; } +# a foreign client (python, raw JSON-RPC) gets pyright diagnostics through hx mcp-serve +if command -v pyright-langserver >/dev/null; then + printf 'x: int = "no"\n' > bad.py + python3 - "$root/target/debug/hx" > "$tmp/diag" <<'PY' +import json, subprocess, sys +p = subprocess.Popen([sys.argv[1], "mcp-serve"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) +def rpc(i, m, params): + p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": m, "params": params}) + "\n"); p.stdin.flush() + while True: + r = json.loads(p.stdout.readline()) + if r.get("id") == i: + return r +rpc(1, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}) +r = rpc(2, "tools/call", {"name": "lsp", "arguments": {"action": "diagnostics", "path": "bad.py"}}) +print(r["result"]["content"][0]["text"]) +p.stdin.close(); p.wait(timeout=30) +PY + grep -q 'error.*not assignable' "$tmp/diag" || { echo "--- diag"; cat "$tmp/diag"; exit 1; } +fi +echo "m6 e2e ok"