537 lines
18 KiB
Rust
537 lines
18 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::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<Option<Arc<Client>>>,
|
|
restarts: std::sync::atomic::AtomicU32,
|
|
pub tools: Vec<Value>,
|
|
pub prompts: Vec<Value>,
|
|
pub resources: Vec<Value>,
|
|
pub instructions: Option<String>,
|
|
pub error: Option<String>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct Hub {
|
|
pub servers: BTreeMap<String, Slot>,
|
|
}
|
|
|
|
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<String, Server>) -> 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<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)?
|
|
.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::<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> {
|
|
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::<Vec<_>>()
|
|
.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<String> = 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<String> {
|
|
let idx: BTreeMap<String, String> = self.index().into_iter().collect();
|
|
self.servers
|
|
.iter()
|
|
.map(|(n, s)| {
|
|
if let Some(e) = &s.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(&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<Self>, 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::<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."
|
|
.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<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;
|