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

713 lines
24 KiB
Rust

//! 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 oauth;
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::sync::RwLock;
use std::time::Duration;
use tokio::sync::{Mutex, watch};
/// 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(10);
const MAX_RESTARTS: u32 = 3;
/// Cached server data; filled by the connect task. `pending` until that task finished.
#[derive(Default)]
pub struct State {
pub pending: bool,
pub tools: Vec<Value>,
pub prompts: Vec<Value>,
pub resources: Vec<Value>,
pub instructions: Option<String>,
pub error: Option<String>,
}
pub struct Slot {
pub cfg: Server,
client: Mutex<Option<Arc<Client>>>,
restarts: std::sync::atomic::AtomicU32,
state: RwLock<State>,
}
impl Slot {
fn new(cfg: Server, pending: bool) -> Self {
Slot {
cfg,
client: Mutex::new(None),
restarts: Default::default(),
state: RwLock::new(State {
pending,
..Default::default()
}),
}
}
/// Read guard; never hold across an `.await`.
pub fn st(&self) -> std::sync::RwLockReadGuard<'_, State> {
self.state.read().unwrap_or_else(|e| e.into_inner())
}
}
pub struct Hub {
pub servers: BTreeMap<String, Slot>,
/// bumped whenever a server finishes connecting
done: watch::Sender<u64>,
}
impl Default for Hub {
fn default() -> Self {
Hub {
servers: BTreeMap::new(),
done: watch::channel(0).0,
}
}
}
fn timeout_of(s: &Server) -> Duration {
Duration::from_secs(s.timeout_secs.unwrap_or(60))
}
/// Connect and list tools/prompts/resources. Returns the live client on success.
async fn load(cfg: &Server) -> (State, Option<Arc<Client>>) {
let mut st = State::default();
match Client::connect(cfg, CONNECT_TIMEOUT).await {
Ok(c) => {
// startup listing must not stall a server for the full tool-call timeout
let t = CONNECT_TIMEOUT;
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) => {
st.tools = v
.into_iter()
.filter(|x| {
cfg.allow.is_empty()
|| x["name"]
.as_str()
.is_some_and(|n| cfg.allow.iter().any(|a| a == n))
})
.collect()
}
Err(e) => st.error = Some(format!("tools/list: {e}")),
}
st.prompts = prompts.unwrap_or_default();
st.resources = resources.unwrap_or_default();
st.instructions = c.instructions.clone();
(st, Some(Arc::new(c)))
}
Err(e) => {
st.error = Some(e);
(st, None)
}
}
}
impl Hub {
/// Connect to all servers in parallel and wait for every one (CLI commands, tests).
pub async fn start(cfgs: BTreeMap<String, Server>) -> Self {
let slots = futures::future::join_all(cfgs.into_iter().map(|(name, cfg)| async move {
let (st, c) = load(&cfg).await;
let slot = Slot::new(cfg, false);
*slot.state.write().unwrap_or_else(|e| e.into_inner()) = st;
*slot.client.lock().await = c;
(name, slot)
}))
.await;
Self {
servers: slots.into_iter().collect(),
..Default::default()
}
}
/// Return at once; each server connects in its own task. Slots stay `pending` until done.
pub fn spawn(cfgs: BTreeMap<String, Server>) -> Arc<Self> {
let hub = Arc::new(Self {
servers: cfgs
.into_iter()
.map(|(n, c)| (n, Slot::new(c, true)))
.collect(),
..Default::default()
});
let names: Vec<String> = hub.servers.keys().cloned().collect();
for name in names {
let hub = hub.clone();
tokio::spawn(async move {
let slot = &hub.servers[&name];
let (mut st, c) = load(&slot.cfg).await;
st.pending = false;
*slot.client.lock().await = c;
*slot.state.write().unwrap_or_else(|e| e.into_inner()) = st;
hub.done.send_modify(|v| *v += 1);
});
}
hub
}
pub fn pending(&self) -> Vec<String> {
self.servers
.iter()
.filter(|(_, s)| s.st().pending)
.map(|(n, _)| n.clone())
.collect()
}
/// Wait until no server is pending, or `d` passed.
pub async fn wait_all(&self, d: Duration) {
let mut rx = self.done.subscribe();
let _ = tokio::time::timeout(d, async {
while !self.pending().is_empty() {
if rx.changed().await.is_err() {
break;
}
}
})
.await;
}
/// Wait until `server` finished connecting (bounded by connect + list timeouts).
async fn settled(&self, server: &str) {
let Some(s) = self.servers.get(server) else {
return;
};
let mut rx = self.done.subscribe();
let d = CONNECT_TIMEOUT + timeout_of(&s.cfg) + Duration::from_secs(1);
let _ = tokio::time::timeout(d, async {
while s.st().pending {
if rx.changed().await.is_err() {
break;
}
}
})
.await;
}
/// Live client for `server`, reconnecting (bounded) if the process died.
async fn client(&self, server: &str) -> Result<(Arc<Client>, &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)?
.st()
.tools
.iter()
.find(|t| t["name"] == tool)
.cloned()
}
pub fn is_eager(&self, server: &str) -> bool {
self.servers.get(server).is_some_and(|s| {
let st = s.st();
s.cfg
.eager
.unwrap_or(spec_tokens(&st.tools) <= EAGER_MAX_TOKENS)
&& !st.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 {
self.settled(server).await;
let Some(spec) = self.tool(server, tool) else {
if self.servers.get(server).is_some_and(|s| s.st().pending) {
return ToolResult::err(format!(
"MCP server `{server}` is still connecting; retry shortly"
));
}
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 {
self.settled(server).await;
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::<Vec<_>>()
.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<String, String> {
self.settled(server).await;
let (c, slot) = self.client(server).await?;
let p = slot
.st()
.prompts
.iter()
.find(|p| p["name"] == name)
.cloned()
.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::<Vec<_>>()
.join("\n\n"))
}
/// Index block for one ready lazy-or-eager server.
fn index_of(n: &str, st: &State) -> String {
let mut out = String::new();
for t in &st.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()
));
}
out
}
/// 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.st().tools.is_empty() && !self.is_eager(n))
.map(|(n, s)| (n.clone(), Self::index_of(n, &s.st())))
.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 pend = self.pending();
if !pend.is_empty() {
s.push_str(&format!(
"\n# MCP servers still connecting: {}\nCall `mcp_describe` with just `server` to list a server's tools once ready; `mcp_call` works as soon as it is.\n",
pend.join(", ")
));
}
let res: Vec<String> = self
.servers
.iter()
.flat_map(|(n, s)| {
s.st()
.resources
.iter()
.take(20)
.map(|r| {
format!(
"- {n}: {} ({})",
r["uri"].as_str().unwrap_or_default(),
r["name"].as_str().unwrap_or_default()
)
})
.collect::<Vec<_>>()
})
.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
.st()
.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<String> {
let idx: BTreeMap<String, String> = self.index().into_iter().collect();
self.servers
.iter()
.map(|(n, s)| {
let st = s.st();
if st.pending {
return format!("{n}: connecting…");
}
if let Some(e) = &st.error {
let auth = if s.cfg.url.is_some() && e.contains("HTTP 401") && !oauth::logged_in(&s.cfg) {
format!(" (run `hx mcp login {n}`)")
} else {
String::new()
};
return format!("{n}: error: {e}{auth}");
}
let eager_tok = spec_tokens(&st.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)",
st.tools.len(),
st.prompts.len(),
st.resources.len(),
if self.is_eager(n) { "eager" } else { "lazy" }
)
})
.collect()
}
/// Prompts of ready servers: (server, prompt json).
pub fn prompts(&self) -> Vec<(String, Value)> {
self.servers
.iter()
.flat_map(|(n, s)| {
s.st()
.prompts
.iter()
.map(|p| (n.clone(), p.clone()))
.collect::<Vec<_>>()
})
.collect()
}
/// Register agent tools: eager native tools, plus mcp_describe/mcp_call/mcp_read when needed.
pub fn register(self: &Arc<Self>, reg: &mut hx_core::tool::Registry) {
let mut lazy = false;
for (n, s) in &self.servers {
let st = s.st();
if st.pending {
lazy = true; // late servers are reached through mcp_describe/mcp_call
} else if self.is_eager(n) {
for t in &st.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 !st.tools.is_empty() {
lazy = true;
}
}
if lazy {
reg.add(Describe { hub: self.clone() });
reg.add(Call { hub: self.clone() });
}
// resources may appear late too
if self.servers.values().any(|s| {
let st = s.st();
st.pending || !st.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::<usize>()
/ 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<String> = 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<Hub>,
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<Hub>,
}
#[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. Without `tool`: list that server's tools (use for servers still connecting).".into(),
input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"tool":{"type":"string"}},"required":["server"]}),
}
}
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.settled(s).await;
let Some(slot) = self.hub.servers.get(s) else {
return ToolResult::err(format!("unknown MCP server `{s}`"));
};
if t.is_empty() {
let st = slot.st();
return match (&st.error, st.pending) {
(_, true) => ToolResult::err(format!(
"MCP server `{s}` is still connecting; retry shortly"
)),
(Some(e), _) => ToolResult::err(format!("MCP server `{s}` failed: {e}")),
_ => ToolResult::ok(Hub::index_of(s, &st)),
};
}
match self.hub.tool(s, t) {
Some(x) => ToolResult::ok(
json!({"description": x["description"], "arguments": x["inputSchema"]}).to_string(),
),
None if slot.st().pending => ToolResult::err(format!(
"MCP server `{s}` is still connecting; retry shortly"
)),
None => ToolResult::err(format!("unknown tool `{s}.{t}`")),
}
}
}
struct Call {
hub: Arc<Hub>,
}
#[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<Hub>,
}
#[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;