Files
hx/crates/hx-mcp/src/serve.rs
T
hermes 99dc90fd3b
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
M6: native MCP client, lazy index, mcp-serve (closes #42-#51)
2026-09-30 15:51:25 +00:00

141 lines
5.5 KiB
Rust

//! `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::<Value>();
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::<Value>(&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<Value, (i64, String)>| 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<Value> = 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<i64, Value> = out
.lines()
.map(|l| serde_json::from_str::<Value>(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
}
}