Files
hx/crates/hx-mcp/src/serve.rs
T
johannesandClaude Sonnet 5.5 a94632ea3d chore: delete code comments, add ratchet lint and ADRs
Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:37:32 +01:00

136 lines
5.1 KiB
Rust

use hx_core::tool::{Registry, ToolCtx};
use serde_json::{Value, json};
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
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;
};
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;
#[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);
}
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
}
}