Files
hx/crates/hx-mcp/src/client.rs
T

317 lines
11 KiB
Rust

//! 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"), HTTP OAuth lives in `oauth.rs`.
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<Mutex<HashMap<i64, oneshot::Sender<Result<Value, String>>>>>;
enum Transport {
Stdio {
stdin: Arc<Mutex<tokio::process::ChildStdin>>,
pending: Pending,
_child: tokio::process::Child,
},
Http {
http: reqwest::Client,
url: String,
headers: Vec<(String, String)>,
session: Mutex<Option<String>>,
cfg: Box<Server>,
},
}
pub struct Client {
t: Transport,
next: AtomicI64,
alive: Arc<AtomicBool>,
/// `instructions` from initialize
pub instructions: Option<String>,
pub capabilities: Value,
}
fn rpc_result(m: &Value) -> Result<Value, String> {
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<tokio::process::ChildStdin>, 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<Self, String> {
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::<Value>(&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),
cfg: Box::new(s.clone()),
},
_ => 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<Option<Value>, String> {
let Transport::Http { headers, cfg, .. } = &self.t else {
unreachable!()
};
// a configured Authorization header wins; otherwise use the stored OAuth token
if headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("authorization"))
{
return self.post_with(v, None).await;
}
let tok = crate::oauth::access(cfg, false).await;
match self.post_with(v, tok.as_deref()).await {
Err(e) if e.starts_with("HTTP 401") => match crate::oauth::access(cfg, true).await {
Some(t) => self.post_with(v, Some(&t)).await,
None => Err(format!(
"{e} (OAuth login needed: run `hx mcp login <server>`)"
)),
},
r => r,
}
}
async fn post_with(&self, v: &Value, bearer: Option<&str>) -> Result<Option<Value>, 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(t) = bearer {
rq = rq.bearer_auth(t);
}
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::<String>()
));
}
let Some(id) = v.get("id") else {
return Ok(None);
};
let msgs: Vec<Value> = 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::<Value>(&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<Value, String> {
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<Vec<Value>, String> {
let mut out = vec![];
let mut cursor: Option<String> = 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),
}
}
}
}