AnyBot/src/mcp.rs

1419 lines
74 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// MCP connectors: the bot can use the tools of Model Context Protocol servers (the original's
// local-exec-daemon has an MCP client with its own permission layer: shouldBlockMcp /
// isMcpFullyAllowlisted, and per-server custom instructions). Here: stdio servers (a command
// AnyBot starts) and HTTP servers (Streamable HTTP, JSON or SSE answers).
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{BTreeMap, HashMap};
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
pub const PROTOCOL: &str = "2025-06-18";
/// Longest wait for one answer (estimated).
pub const CALL_TIMEOUT_SECS: u64 = 120;
/// Tool names the model sees: mcp__<server>__<tool>, at most 64 characters.
pub const PREFIX: &str = "mcp__";
/// Up to this many connector tools ride along with every request, one by one. More (one server
/// can bring 80), and none do: the model gets their list and these two, finds the one it needs
/// and runs it. 170 tools in a request was over many services' limit of 128 and ~100 KB of
/// descriptions each turn, most of them never used.
const DIRECT_TOOLS: usize = 20;
pub const FIND_TOOL: &str = "find_connector_tool";
pub const USE_TOOL: &str = "use_connector_tool";
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Server {
pub name: String,
/// stdio: the command; empty when `url` is used.
#[serde(default)]
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub env: BTreeMap<String, String>,
/// HTTP (Streamable HTTP) address.
#[serde(default)]
pub url: String,
/// e.g. "Authorization: Bearer …" for HTTP servers.
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default = "yes")]
pub enabled: bool,
/// Notes for the bot on how to use this server (the original's MCP custom instructions).
#[serde(default)]
pub instructions: String,
/// 帳號 and 密碼 for a server that logs in with them (a company's own system). They reach
/// the server as [`Server::resolved`] says; the password is kept like a key (never shown
/// to a screen or the phone).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub username: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub password: String,
}
/// Where the 帳號 / 密碼 go when the command, the address, a variable or a header names them.
pub const USER_SLOT: &str = "{username}";
pub const PASS_SLOT: &str = "{password}";
/// The variables a command's server gets them in when nothing names a slot.
pub const USER_ENV: &str = "MCP_USERNAME";
pub const PASS_ENV: &str = "MCP_PASSWORD";
impl Server {
/// The server as it is started or called, with the 帳號 and 密碼 put in:
/// - wherever 「{username}」 / 「{password}」 is written (arguments, variables' values, the
/// address, headers' values), that is where they go, e.g. `SCC_USER={username}`;
/// - written nowhere: a command gets them as MCP_USERNAME / MCP_PASSWORD, an address gets
/// `Authorization: Basic …` — 帳號密碼填了就作數:它換掉標頭裡原有的 Authorization
/// (一條只裝得下一條,人現填的帳號密碼就是要送過去的那條)。
pub fn resolved(&self) -> Server {
let mut s = self.clone();
let (user, pass) = (self.username.trim(), self.password.as_str());
if user.is_empty() && pass.is_empty() {
return s;
}
let mut named = false;
let mut put = |t: &mut String| {
if t.contains(USER_SLOT) || t.contains(PASS_SLOT) {
named = true;
*t = t.replace(USER_SLOT, user).replace(PASS_SLOT, pass);
}
};
s.args.iter_mut().for_each(&mut put);
s.env.values_mut().for_each(&mut put);
s.headers.values_mut().for_each(&mut put);
put(&mut s.url);
if !named {
if s.url.trim().is_empty() {
s.env.entry(USER_ENV.into()).or_insert_with(|| user.to_string());
s.env.entry(PASS_ENV.into()).or_insert_with(|| pass.to_string());
} else {
// 帳號密碼填了就作數:換掉舊的金鑰標頭(一條 Authorization 裝不下兩條)。
use base64::Engine;
s.headers.retain(|k, _| !k.eq_ignore_ascii_case("authorization"));
s.headers.insert("Authorization".into(), format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}"))));
}
}
s
}
/// A 「{…}」 still to be replaced by the person (a market's 「{api_key}」), not one of the slots.
pub fn unfilled(text: &str) -> bool {
text.replace(USER_SLOT, "").replace(PASS_SLOT, "").contains('{')
}
}
fn yes() -> bool {
true
}
#[derive(Clone, Debug)]
pub struct ToolInfo {
pub server: String,
pub name: String,
pub description: String,
pub schema: Value,
}
enum Link {
Stdio { child: Child, stdin: ChildStdin, rx: Receiver<Value> },
Http { url: String, headers: BTreeMap<String, String>, session: Option<String> },
}
/// The part a tool call mutates; locked per server, so one slow call (up to two minutes)
/// never blocks other servers, the UI's status line, or the app's own sync.
struct Live {
link: Link,
next_id: u64,
/// The server no longer knows this session (HTTP 404 on a session, as the spec says it
/// answers): the link has to be made again.
expired: bool,
}
impl Live {
/// The link can't carry calls any more: the server's process has ended, or its session expired.
fn dead(&mut self) -> bool {
match &mut self.link {
// (Its output closed is enough: the process may not have been reaped yet.)
Link::Stdio { child, rx, .. } => self.expired || child.try_wait().ok().flatten().is_some() || matches!(rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Disconnected)),
Link::Http { .. } => self.expired,
}
}
}
struct Conn {
live: Mutex<Live>,
/// Refetched in place when the server sends `notifications/tools/list_changed`.
tools: Mutex<Vec<ToolInfo>>,
config: Server,
}
/// One lock for the table, one lock per server's link.
fn conns() -> &'static Mutex<HashMap<String, Arc<Conn>>> {
static C: OnceLock<Mutex<HashMap<String, Arc<Conn>>>> = OnceLock::new();
C.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn safe(s: &str) -> String {
s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect()
}
/// A server's part of tool names: its name when it's plain ASCII, else a short stable code.
pub fn server_key(server: &str) -> String {
if !server.is_empty() && server.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ' ') {
return safe(server);
}
let h = server.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3));
format!("s{:06x}", h & 0xff_ffff)
}
pub fn tool_name(server: &str, tool: &str) -> String {
let n = format!("{PREFIX}{}__{}", server_key(server), safe(tool));
n.chars().take(64).collect()
}
pub fn is_mcp_tool(name: &str) -> bool {
name.starts_with(PREFIX)
}
fn send_stdio(stdin: &mut ChildStdin, msg: &Value) -> Result<(), String> {
let mut line = msg.to_string();
line.push('\n');
stdin.write_all(line.as_bytes()).and_then(|_| stdin.flush()).map_err(|e| format!("送不出去:{e}"))
}
/// The server's own "my tools changed" notification (no id, so answers never match it).
pub fn is_list_changed(v: &Value) -> bool {
v.get("method").and_then(|m| m.as_str()) == Some("notifications/tools/list_changed")
}
/// Read the answer with this id (skipping notifications and requests from the server).
fn wait_id(rx: &Receiver<Value>, id: u64, secs: u64) -> Result<Value, String> {
let deadline = std::time::Instant::now() + Duration::from_secs(secs);
loop {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
return Err("MCP 伺服器沒有回應".into());
}
match rx.recv_timeout(left) {
Ok(v) if v["id"].as_u64() == Some(id) && v.get("method").is_none() => {
if let Some(e) = v.get("error") {
return Err(format!("MCP 錯誤:{}", e["message"].as_str().unwrap_or(&e.to_string())));
}
return Ok(v["result"].clone());
}
Ok(_) => continue,
Err(_) => return Err("MCP 伺服器沒有回應或已經結束".into()),
}
}
}
/// What an HTTP server's refusal means to the person. A 401 (or a 403 that asks for a login)
/// with no key given is a server that signs people in with OAuth, which AnyBot can't do yet;
/// with a key, the key is wrong or old.
pub fn http_refusal(status: u16, asks_login: bool, has_key: bool, body: &str) -> String {
if status == 401 || (status == 403 && asks_login) {
return if has_key {
format!("金鑰不對或過期了(HTTP {status}):檢查「標頭」裡的金鑰")
} else {
"這個連接器要先登入帳號(OAuth),AnyBot 還不支援;它若也收 API 金鑰,填在「標頭」(例如 Authorization: Bearer …)".into()
};
}
format!("MCP 伺服器回 HTTP {status}:{}", body.chars().take(200).collect::<String>())
}
/// Answers from Streamable HTTP: plain JSON, or SSE with `data:` lines.
pub fn parse_http_answer(body: &str, id: u64) -> Result<Value, String> {
let candidates: Vec<Value> = if body.trim_start().starts_with('{') || body.trim_start().starts_with('[') {
match serde_json::from_str::<Value>(body) {
Ok(Value::Array(a)) => a,
Ok(v) => vec![v],
Err(e) => return Err(e.to_string()),
}
} else {
body.lines().filter_map(|l| l.strip_prefix("data:")).filter_map(|d| serde_json::from_str(d.trim()).ok()).collect()
};
for v in candidates {
if v["id"].as_u64() == Some(id) {
if let Some(e) = v.get("error") {
return Err(format!("MCP 錯誤:{}", e["message"].as_str().unwrap_or(&e.to_string())));
}
return Ok(v["result"].clone());
}
}
Err("MCP 伺服器沒有給答案".into())
}
impl Live {
fn request(&mut self, method: &str, params: Value) -> Result<Value, String> {
let id = self.next_id;
self.next_id += 1;
let msg = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
match &mut self.link {
Link::Stdio { stdin, rx, .. } => {
send_stdio(stdin, &msg)?;
wait_id(rx, id, CALL_TIMEOUT_SECS)
}
Link::Http { url, headers, session } => {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).http_status_as_error(false).build().into();
let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", PROTOCOL);
for (k, v) in headers.iter() {
r = r.header(k.as_str(), v.as_str());
}
if let Some(s) = session.as_ref() {
r = r.header("Mcp-Session-Id", s.as_str());
}
let mut resp = r.send(msg.to_string().as_bytes()).map_err(|e| format!("連不上 MCP 伺服器:{e}"))?;
if let Some(s) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {
*session = Some(s.to_string());
}
let st = resp.status().as_u16();
let asks_login = resp.headers().contains_key("www-authenticate");
let body = resp.body_mut().with_config().limit(16 * 1024 * 1024).read_to_string().unwrap_or_default();
if st == 404 && session.is_some() {
self.expired = true;
}
if !(200..300).contains(&st) {
return Err(http_refusal(st, asks_login, !headers.is_empty(), &body));
}
parse_http_answer(&body, id)
}
}
}
fn notify(&mut self, method: &str) {
let msg = json!({"jsonrpc": "2.0", "method": method});
match &mut self.link {
Link::Stdio { stdin, .. } => {
let _ = send_stdio(stdin, &msg);
}
Link::Http { url, headers, session } => {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(10))).http_status_as_error(false).build().into();
let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream");
for (k, v) in headers.iter() {
r = r.header(k.as_str(), v.as_str());
}
if let Some(s) = session.as_ref() {
r = r.header("Mcp-Session-Id", s.as_str());
}
let _ = r.send(msg.to_string().as_bytes());
}
}
}
}
/// Why a server's program didn't start, in words that say what to do.
fn spawn_error(command: &str, e: &std::io::Error) -> String {
if e.kind() != std::io::ErrorKind::NotFound {
return format!("無法啟動「{command}」:{e}");
}
let base = std::path::Path::new(command.trim()).file_name().and_then(|n| n.to_str()).unwrap_or(command);
match base {
"npx" | "npm" | "node" => format!("這台電腦沒有 Node.js(找不到「{base}」):裝好 Node.js 再按「重新連線」"),
"uvx" | "uv" => format!("這台電腦沒有 uv(找不到「{base}」):裝好 uv 再按「重新連線」"),
_ => format!("這台電腦找不到「{base}」這個程式"),
}
}
/// A folder the server is given that isn't on this computer (its parent isn't either): usually a
/// connector made on another computer, e.g. a Mac's /Users/… on a Linux brain.
fn missing_folder(args: &[String]) -> Option<&str> {
args.iter().map(|a| a.trim()).find(|a| {
let p = std::path::Path::new(a);
p.is_absolute() && !p.exists() && p.parent().is_some_and(|d| d != std::path::Path::new("/") && !d.exists())
})
}
/// The last lines a server wrote to stderr (it says there why it stopped).
type ErrLog = Arc<Mutex<std::collections::VecDeque<String>>>;
fn connect(config: &Server) -> Result<Conn, String> {
// (The table keeps the server as it is written: a change of 帳號 or 密碼 is a change.)
let s = &config.resolved();
let mut errlog: Option<ErrLog> = None;
let link = if !s.url.trim().is_empty() {
let u = s.url.trim();
if crate::web::is_forbidden_browser_url(u) {
return Err("安全規則禁止將 MCP 連接器指向雲端中繼資料或 Docker 內部管理端點。".into());
}
Link::Http { url: u.to_string(), headers: s.headers.clone(), session: None }
} else {
if s.command.trim().is_empty() {
return Err("請給指令或網址".into());
}
if let Some(dir) = missing_folder(&s.args) {
return Err(format!("這台電腦上沒有「{dir}」:這個連接器可能是在別台電腦設定的,改成這台的資料夾,或移除它"));
}
let mut cmd = Command::new(s.command.trim());
for k in crate::tools::KEY_ENV_VARS.into_iter().chain(crate::tools::DANGEROUS_ENV_VARS) {
cmd.env_remove(k);
}
let mut child = cmd
.args(&s.args)
.envs(&s.env)
.env("PATH", crate::cloudbox::tool_path())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| spawn_error(&s.command, &e))?;
let stdin = child.stdin.take().ok_or("沒有標準輸入")?;
let stdout = child.stdout.take().ok_or("沒有標準輸出")?;
// stderr is read all the time (a full pipe would stop the server); the last lines are kept.
if let Some(stderr) = child.stderr.take() {
let log: ErrLog = Arc::default();
errlog = Some(log.clone());
std::thread::spawn(move || {
let mut reader = BufReader::new(stderr);
loop {
let mut line = String::new();
match (&mut reader).take(64 * 1024).read_line(&mut line) {
Ok(0) | Err(_) => break,
Ok(_) => {
let line = line.trim();
if !line.is_empty() {
let mut l = log.lock().unwrap();
l.push_back(line.chars().take(300).collect());
if l.len() > 4 {
l.pop_front();
}
}
}
}
}
});
}
let (tx, rx) = std::sync::mpsc::sync_channel(256);
let watcher = s.name.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(stdout);
loop {
let mut line = String::new();
match (&mut reader).take(16 * 1024 * 1024).read_line(&mut line) {
Ok(0) | Err(_) => break,
Ok(_) => {
if let Ok(v) = serde_json::from_str::<Value>(&line) {
if is_list_changed(&v) {
// Refresh off this thread: it is the only reader of rx, and a
// refresh needs the link lock a running call holds.
let n = watcher.clone();
std::thread::spawn(move || refresh_tools(&n));
continue;
}
if tx.send(v).is_err() {
break;
}
}
}
}
}
});
Link::Stdio { child, stdin, rx }
};
let mut live = Live { link, next_id: 1, expired: false };
match handshake(&mut live, &s.name) {
Ok(tools) => {
// Streamable HTTP pushes only on an open GET stream; keep one per connection.
if let Link::Http { url, headers, session: Some(session) } = &live.link {
spawn_http_listener(url.clone(), headers.clone(), session.clone(), s.name.clone());
}
Ok(Conn { live: Mutex::new(live), tools: Mutex::new(tools), config: config.clone() })
}
Err(e) => {
// A server that didn't come up is ended (it is tried again each half minute, and
// used to be left running each time), and what it said on stderr goes with the error.
if let Link::Stdio { child, .. } = &mut live.link {
let _ = child.kill();
let _ = child.wait();
}
std::thread::sleep(Duration::from_millis(100));
let said: Vec<String> = errlog.map(|l| l.lock().unwrap().iter().cloned().collect()).unwrap_or_default();
Err(if said.is_empty() { e } else { format!("{e}。它說:{}", said.join(" / ")) })
}
}
}
/// initialize, then the server's tools.
fn handshake(live: &mut Live, server: &str) -> Result<Vec<ToolInfo>, String> {
live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?;
live.notify("notifications/initialized");
fetch_tools(live, server)
}
/// The server's whole tool list, following `nextCursor` (a server may page).
fn fetch_tools(live: &mut Live, server: &str) -> Result<Vec<ToolInfo>, String> {
let mut tools = vec![];
let mut cursor: Option<String> = None;
for _ in 0..20 {
let r = live.request("tools/list", match &cursor { Some(x) => json!({"cursor": x}), None => json!({}) })?;
for t in r["tools"].as_array().into_iter().flatten() {
tools.push(ToolInfo { server: server.to_string(), name: t["name"].as_str().unwrap_or("").into(), description: t["description"].as_str().unwrap_or("").into(), schema: t["inputSchema"].clone() });
}
cursor = r["nextCursor"].as_str().map(String::from);
if cursor.is_none() {
break;
}
}
Ok(tools)
}
/// The server said its tools changed: refetch on the spot. A failed refresh keeps the old list.
pub fn refresh_tools(name: &str) {
let conn = conns().lock().unwrap().get(name).cloned();
let Some(conn) = conn else { return };
let mut live = match conn.live.lock() {
Ok(l) => l,
Err(_) => return,
};
if let Ok(tools) = fetch_tools(&mut live, name) {
*conn.tools.lock().unwrap() = tools;
}
}
/// Streamable HTTP has no push channel of its own: a connection keeps one long-lived GET
/// (SSE) open so `notifications/tools/list_changed` reaches us. A dropped stream reconnects
/// every few seconds (the global timeout also bounds the wait, so a server taken out of the
/// table ends this thread within it); a server that answers the GET with an error has no
/// stream to offer, and the thread ends — reconnecting the connector is the manual way.
fn spawn_http_listener(url: String, headers: BTreeMap<String, String>, session: String, name: String) {
std::thread::spawn(move || {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(600))).http_status_as_error(false).build().into();
loop {
// This thread is for one session of one connector: gone, or connected anew under
// the same name (a new session, with a listener of its own), it ends. (An old one
// used to stay, holding its stream open beside the new one, at every reconnect.)
let mine = match conns().lock().unwrap().get(&name).cloned() {
None => false,
Some(c) => match c.live.try_lock() {
Ok(l) => matches!(&l.link, Link::Http { session: Some(s), .. } if *s == session),
// (In the middle of a call: looked at again next round.)
Err(_) => true,
},
};
if !mine {
return;
}
let mut req = agent.get(url.as_str()).header("Accept", "text/event-stream").header("MCP-Protocol-Version", PROTOCOL).header("Mcp-Session-Id", session.as_str());
for (k, v) in headers.iter() {
req = req.header(k.as_str(), v.as_str());
}
let mut resp = match req.call() {
Ok(r) if (200..300).contains(&r.status().as_u16()) => r,
_ => return,
};
for line in BufReader::new(resp.body_mut().as_reader()).lines().map_while(Result::ok) {
if line.contains("notifications/tools/list_changed") {
let n = name.clone();
std::thread::spawn(move || refresh_tools(&n));
}
}
std::thread::sleep(Duration::from_secs(5));
}
});
}
/// A stdio server that names this computer's own folders (its home): it means nothing on another
/// computer, so moving to a brain leaves it here.
pub fn names_this_computer(s: &Server) -> bool {
let home = dirs::home_dir().map(|h| h.display().to_string()).unwrap_or_default();
s.url.trim().is_empty()
&& std::iter::once(&s.command).chain(s.args.iter()).map(|a| a.trim()).any(|a| a.starts_with('~') || (home.len() > 1 && (a == home || a.starts_with(&format!("{home}/")))))
}
/// Start (or keep) the enabled servers; stop the rest. Returns errors per server.
/// Connecting happens outside the table's lock (a slow server must not freeze the UI's
/// status line, which reads that lock every second).
pub fn sync(servers: &[Server]) -> Vec<(String, String)> {
let mut errs = vec![];
let mut to_connect: Vec<Server> = vec![];
{
let mut map = conns().lock().unwrap();
let wanted: Vec<&Server> = servers.iter().filter(|s| s.enabled).collect();
let mut gone = vec![];
map.retain(|name, c| {
let mut keep = wanted.iter().any(|s| &s.name == name && **s == c.config);
// A stdio server whose process died is dropped here and started again below: the
// old link would only ever answer 「the server has ended」. A link in use by a call
// (locked) is alive; it isn't waited for here, under the table's lock.
if keep {
if let Ok(mut live) = c.live.try_lock() {
if let Link::Stdio { child, .. } = &mut live.link {
keep = child.try_wait().ok().flatten().is_none();
}
}
}
if !keep {
gone.push(c.clone());
}
keep
});
// Their processes end off this thread (a call in progress holds its link).
if !gone.is_empty() {
std::thread::spawn(move || {
for c in gone {
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
let _ = child.kill();
let _ = child.wait();
}
}
});
}
for s in wanted {
if !map.contains_key(&s.name) {
to_connect.push(s.clone());
}
}
}
for s in to_connect {
match connect(&s) {
Ok(c) => {
conns().lock().unwrap().insert(s.name.clone(), Arc::new(c));
}
Err(e) => errs.push((s.name.clone(), e)),
}
}
errs
}
/// Drop one server's link (its process ends): the next [`sync`] connects it again. 重新連線,
/// and a link found dead. The process is ended off this thread: a call in progress holds its
/// link for up to two minutes, and the UI must not wait for that.
pub fn forget(name: &str) {
let gone = conns().lock().unwrap().remove(name);
if let Some(c) = gone {
std::thread::spawn(move || {
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
let _ = child.kill();
let _ = child.wait();
}
});
}
}
/// The connected servers' tools.
pub fn tools() -> Vec<ToolInfo> {
conns().lock().unwrap().values().flat_map(|c| c.tools.lock().unwrap().clone()).collect()
}
pub fn status() -> HashMap<String, usize> {
conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.lock().unwrap().len())).collect()
}
/// One tool as the model sees it.
fn spec_of(t: &ToolInfo) -> Value {
let schema = if t.schema.is_object() { t.schema.clone() } else { json!({"type": "object", "properties": {}}) };
json!({"name": tool_name(&t.server, &t.name), "description": format!("[{}] {}", t.server, t.description.chars().take(900).collect::<String>()), "parameters": schema})
}
/// The connected servers' tools in a steady order (server, then tool).
fn sorted_tools() -> Vec<ToolInfo> {
let mut all = tools();
all.sort_by(|a, b| (&a.server, &a.name).cmp(&(&b.server, &b.name)));
all
}
/// Tool specs for the model: each tool when there are few, else [`FIND_TOOL`] and [`USE_TOOL`].
pub fn specs() -> Vec<Value> {
let all = sorted_tools();
if all.len() <= DIRECT_TOOLS {
return all.iter().map(spec_of).collect();
}
let mut by: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for t in &all {
by.entry(t.server.as_str()).or_default().push(t.name.as_str());
}
let list = by.iter().map(|(s, ts)| format!("{s} ({} tool{}, e.g. {})", ts.len(), if ts.len() == 1 { "" } else { "s" }, ts.iter().take(5).copied().collect::<Vec<_>>().join(", "))).collect::<Vec<_>>().join("; ");
let servers: Vec<&str> = by.keys().copied().collect();
vec![
json!({"name": FIND_TOOL,
"description": format!("The person's connectors (MCP servers) and their tools, which aren't listed here one by one: {list}. Find the tool you need by words from its name or what it does (English works best), or give only `server` to list all its tools' names. Each match comes with its full name, what it does and its parameters; then run it with {USE_TOOL}."),
"parameters": {"type": "object", "properties": {
"query": {"type": "string", "description": "Words to look for, e.g. \"system status\" or \"gpu inventory\""},
"server": {"type": "string", "enum": servers, "description": "Only this connector's tools"}}}}),
json!({"name": USE_TOOL,
"description": format!("Run a connector tool found with {FIND_TOOL}: its full name (mcp__…) and the arguments its parameters ask for."),
"parameters": {"type": "object", "properties": {
"tool": {"type": "string", "description": "The tool's full name, e.g. mcp__server__tool"},
"arguments": {"type": "object", "description": "Its arguments"}},
"required": ["tool"]}}),
]
}
/// [`FIND_TOOL`]: the tools matching the words (best first, with their parameters), or every
/// name of one server.
pub fn find(args: &str) -> String {
let a: Value = serde_json::from_str(args).unwrap_or(json!({}));
let server = a["server"].as_str().unwrap_or("").trim();
let all = sorted_tools();
let pool: Vec<&ToolInfo> = all.iter().filter(|t| server.is_empty() || t.server == server || server_key(&t.server) == server).collect();
if pool.is_empty() {
let mut names: Vec<&str> = all.iter().map(|t| t.server.as_str()).collect();
names.dedup();
return format!("沒有叫「{server}」的連接器(有:{})", names.join("、"));
}
let q = a["query"].as_str().unwrap_or("").to_lowercase();
const SMALL: [&str; 16] = ["the", "an", "in", "on", "of", "to", "for", "and", "or", "with", "by", "me", "my", "is", "all", "from"];
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric()).filter(|w| w.chars().count() >= 2 && !SMALL.contains(w)).collect();
if words.is_empty() {
let names: Vec<String> = pool.iter().map(|t| tool_name(&t.server, &t.name)).collect();
return format!("{}\n(用 query 找,會一起給它的說明和參數)", names.join("\n"));
}
let mut hits: Vec<(usize, &ToolInfo)> = pool
.iter()
.map(|t| {
// Whole words; a longer one also inside a word (「status」 in 「systemStatus」).
let has = |text: &str, w: &str| text.split(|c: char| !c.is_alphanumeric()).any(|x| x == w || (w.len() >= 4 && x.contains(w)) || (w.len() == 3 && x.starts_with(w)));
let (name, desc) = (t.name.to_lowercase(), t.description.to_lowercase());
(words.iter().map(|w| if has(&name, w) { 3 } else if has(&desc, w) { 1 } else { 0 }).sum(), *t)
})
.filter(|(score, _)| *score > 0)
.collect();
hits.sort_by_key(|h| std::cmp::Reverse(h.0));
if hits.is_empty() {
return format!("找不到和「{q}」有關的連接器工具。換個說法(英文較準),或只給 server 列出它全部的工具名稱。");
}
let more = hits.len().saturating_sub(8);
let mut out: Vec<String> = hits
.iter()
.take(8)
.map(|(_, t)| {
let schema: String = t.schema.to_string().chars().take(1500).collect();
format!("{}\n {}\n parameters: {schema}", tool_name(&t.server, &t.name), t.description.chars().take(400).collect::<String>().replace('\n', " "))
})
.collect();
if more > 0 {
out.push(format!("(還有 {more} 個也符合:說得更具體一點)"));
}
out.join("\n\n")
}
/// [`USE_TOOL`] as the tool it names: (its model-side name, its arguments). `None` for any other
/// tool; an error when the name is no connector tool.
pub fn unwrap_use(name: &str, args: &str) -> Option<Result<(String, String), String>> {
if name != USE_TOOL {
return None;
}
let a: Value = serde_json::from_str(args).unwrap_or(json!({}));
let want = a["tool"].as_str().unwrap_or("").trim();
let arguments = match &a["arguments"] {
Value::String(s) => s.clone(),
Value::Null => "{}".to_string(),
v => v.to_string(),
};
let all = sorted_tools();
// The full name, or (a slip) the tool's own name.
let found = all.iter().find(|t| tool_name(&t.server, &t.name) == want).or_else(|| all.iter().find(|t| t.name == want || safe(&t.name) == want));
Some(match found {
Some(t) => Ok((tool_name(&t.server, &t.name), arguments)),
None => Err(format!("沒有「{want}」這個連接器工具:先用 {FIND_TOOL} 找出它的完整名稱")),
})
}
/// Instructions the servers' owners wrote for the bot.
pub fn instructions(servers: &[Server]) -> String {
servers.iter().filter(|s| s.enabled && !s.instructions.trim().is_empty()).map(|s| format!("- {}:{}", s.name, s.instructions.trim())).collect::<Vec<_>>().join("\n")
}
/// Which server and tool a model-side name means.
pub fn resolve(name: &str) -> Option<(String, String)> {
tools().into_iter().find(|t| tool_name(&t.server, &t.name) == name).map(|t| (t.server, t.name))
}
/// Call a tool. Returns (text, ok, first picture as base64).
pub fn call(name: &str, args: &str) -> (String, bool, Option<String>) {
let Some((server, tool)) = resolve(name) else { return (format!("沒有「{name}」這個 MCP 工具(伺服器可能已關閉)"), false, None) };
let arguments: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(json!({}));
// Copy the server's own handle out of the table, then lock its link alone: a two-minute
// call to one server used to block every other MCP tool and the UI's status line.
let conn = conns().lock().unwrap().get(&server).cloned();
let Some(conn) = conn else { return ("MCP 伺服器沒有連線".into(), false, None) };
// The link lock is let go before the table's is taken (forget): sync takes them the other
// way round, and a link lock must never be held while taking the table's.
let (result, dead) = {
let mut live = conn.live.lock().unwrap();
let r = live.request("tools/call", json!({"name": tool, "arguments": arguments}));
let dead = r.is_err() && live.dead();
(r, dead)
};
match result {
Ok(r) => {
let mut text = String::new();
let mut image = None;
for part in r["content"].as_array().into_iter().flatten() {
match part["type"].as_str() {
Some("text") => {
text.push_str(part["text"].as_str().unwrap_or(""));
text.push('\n');
}
Some("image") if image.is_none() => image = part["data"].as_str().map(String::from),
Some("resource") => {
text.push_str(part["resource"]["text"].as_str().unwrap_or(""));
text.push('\n');
}
_ => {}
}
}
if text.trim().is_empty() && r.get("structuredContent").is_some() {
text = r["structuredContent"].to_string();
}
let ok = r["isError"].as_bool() != Some(true);
(crate::tools::head_tail(text.trim()), ok, image)
}
Err(e) => {
// A link that died (the server's process ended, or it forgot the session) used to
// stay "connected" and fail every call: drop it, and the next sync connects it again.
if dead {
forget(&server);
return (format!("{e}(連線已中斷,AnyBot 會自動重新連線,稍後再試)"), false, None);
}
(e, false, None)
}
}
}
pub fn shutdown() {
for c in conns().lock().unwrap().values() {
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
let _ = child.kill();
let _ = child.wait();
}
}
}
/// 連接器市集: (name, what it does, command or address, key to fill in — empty when none).
pub const MARKET: [(&str, &str, &str, &str); 8] = [
("files", "讀寫你指定資料夾裡的檔案", "npx -y @modelcontextprotocol/server-filesystem ~/Documents", ""),
("memory", "長期記憶:把人、事、關係記成知識圖", "npx -y @modelcontextprotocol/server-memory", ""),
("thinking", "一步步拆解難題", "npx -y @modelcontextprotocol/server-sequential-thinking", ""),
("fetch", "抓網頁內容轉成文字", "uvx mcp-server-fetch", ""),
("git", "查看和操作 Git 版本庫", "uvx mcp-server-git", ""),
("time", "時間和時區換算", "uvx mcp-server-time", ""),
("playwright", "用瀏覽器自動化操作網頁", "npx -y @playwright/mcp@latest", ""),
("github", "GitHub 的 Issue、PR、程式碼(官方遠端伺服器)", "https://api.githubcopilot.com/mcp/", "Authorization: Bearer 你的 GitHub Token"),
];
// ---------- 公用市集: the official MCP Registry ----------
/// The official MCP Registry: public and searchable, and for each server reached by address it
/// gives the address and the header (a key) it wants. (mcpservers.org and the like are pages
/// for people, behind a browser check, with no list a program may read.)
pub const REGISTRY: &str = "https://registry.modelcontextprotocol.io/v0.1/servers";
/// Results per search.
const REGISTRY_LIMIT: usize = 40;
/// Search the registry: servers reached by address, as [`registry_entries`] gives them.
pub fn registry_search(q: &str) -> Result<Vec<Value>, String> {
let url = format!("{REGISTRY}?version=latest&limit={REGISTRY_LIMIT}&search={}", crate::httpd::url_encode(q.trim()));
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into();
let mut resp = agent.get(&url).header("Accept", "application/json").call().map_err(|e| format!("連不到公用市集:{e}"))?;
let st = resp.status().as_u16();
let body = resp.body_mut().read_to_string().unwrap_or_default();
if !(200..300).contains(&st) {
return Err(format!("公用市集回 HTTP {st}"));
}
let v: Value = serde_json::from_str(&body).map_err(|_| "公用市集的回答看不懂".to_string())?;
Ok(registry_entries(&v))
}
/// The registry's answer as the market lists it: one row per server reached by address (a
/// package would have to run on the brain, which may have no Node or uv), none taken down. Each:
/// {id, title, description, url, header: {name, value, description} | null, variables:
/// [{name, description, choices}], note} — `note` says why it can't be added yet.
pub fn registry_entries(v: &Value) -> Vec<Value> {
let mut out: Vec<Value> = vec![];
for item in v["servers"].as_array().into_iter().flatten() {
let s = &item["server"];
if item["_meta"]["io.modelcontextprotocol.registry/official"]["status"].as_str().is_some_and(|st| st != "active") {
continue;
}
let remotes = s["remotes"].as_array().map(Vec::as_slice).unwrap_or_default();
let Some(r) = remotes.iter().find(|r| r["type"] == "streamable-http").or_else(|| remotes.first()) else { continue };
let id = s["name"].as_str().unwrap_or("");
let url = r["url"].as_str().unwrap_or("");
if id.is_empty() || url.is_empty() || out.iter().any(|o| o["id"] == id) {
continue;
}
let title = s["title"].as_str().map(str::trim).filter(|t| !t.is_empty()).map(String::from).unwrap_or_else(|| short_name(id));
// The key goes where the registry shows its placeholder ("Bearer {api_key}").
let header = r["headers"].as_array().and_then(|h| h.first()).map(|h| {
let value = h["value"].as_str().filter(|v| !v.trim().is_empty()).unwrap_or("{金鑰}");
json!({"name": h["name"].as_str().unwrap_or(""), "value": value, "description": h["description"].as_str().unwrap_or("")})
});
let variables: Vec<Value> = r["variables"].as_object().map(|o| o.iter().map(|(k, x)| json!({"name": k, "description": x["description"].as_str().unwrap_or(""), "choices": x["choices"].as_array().cloned().unwrap_or_default()})).collect()).unwrap_or_default();
let note = if r["type"] == "streamable-http" { "" } else { "舊式 SSE 連線,AnyBot 還不支援" };
out.push(json!({"id": id, "title": title, "description": s["description"].as_str().unwrap_or(""), "url": url, "header": header, "variables": variables, "note": note}));
}
out
}
/// A registry name ("ai.smithery/smithery-notion", "com.notion/mcp") as a person would call it:
/// its last part, or — when that only says "mcp" — whose it is.
fn short_name(id: &str) -> String {
let (owner, last) = id.rsplit_once('/').unwrap_or(("", id));
let plain = matches!(last.to_ascii_lowercase().as_str(), "mcp" | "server" | "mcp-server" | "remote" | "remote-mcp" | "api");
if plain && !owner.is_empty() {
return owner.rsplit('.').next().unwrap_or(owner).to_string();
}
last.to_string()
}
/// A name not taken yet: 「Notion」, then 「Notion 2」…
pub fn free_name(want: &str, servers: &[Server]) -> String {
let want = want.trim();
let taken = |n: &str| servers.iter().any(|s| s.name == n);
if !taken(want) {
return want.to_string();
}
(2..).map(|i| format!("{want} {i}")).find(|n| !taken(n)).unwrap_or_default()
}
/// A 公用市集 row as the 新增連接器 form: (name not taken yet, address, header line, what the
/// person still has to fill in).
pub fn registry_form(e: &Value, servers: &[Server]) -> (String, String, String, String) {
let name = free_name(e["title"].as_str().unwrap_or("連接器"), servers);
let url = e["url"].as_str().unwrap_or("").to_string();
let mut hint = vec![];
let header = match e["header"].as_object() {
Some(h) => {
let about = h.get("description").and_then(Value::as_str).unwrap_or("").trim();
hint.push(if about.is_empty() { "把標頭裡的「{…}」換成你的金鑰。".to_string() } else { format!("把標頭裡的「{{…}}」換成你的金鑰({about})。") });
format!("{}: {}", h.get("name").and_then(Value::as_str).unwrap_or(""), h.get("value").and_then(Value::as_str).unwrap_or(""))
}
None => String::new(),
};
for v in e["variables"].as_array().into_iter().flatten() {
let choices: Vec<&str> = v["choices"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let mut line = format!("把網址裡的「{{{}}}」換成{}", v["name"].as_str().unwrap_or(""), v["description"].as_str().map(|d| format!(":{d}")).unwrap_or_default());
if !choices.is_empty() {
line.push_str(&format!("(可填 {})", choices.join("、")));
}
hint.push(line);
}
hint.push("按「新增」就會連線;要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時會說。".into());
(name, url, header, hint.join(" "))
}
/// A server reached by address, with its one header ("Authorization: Bearer …") if any.
pub fn remote_server(name: &str, url: &str, header: &str) -> Server {
let headers = header.split_once(':').map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).filter(|(k, _)| !k.is_empty()).into_iter().collect();
Server { name: name.trim().to_string(), command: String::new(), args: vec![], env: BTreeMap::new(), url: url.trim().to_string(), headers, enabled: true, instructions: String::new(), username: String::new(), password: String::new() }
}
/// A marketplace entry as a server (home folder spelled out).
pub fn market_server(name: &str, cmd: &str) -> Server {
let parts: Vec<String> = cmd.split_whitespace().map(|w| if w == "~/Documents" { crate::tools::expand_home(w).display().to_string() } else { w.to_string() }).collect();
let command = parts.first().cloned().unwrap_or_default();
let args = if parts.len() > 1 { parts[1..].to_vec() } else { vec![] };
Server { name: name.to_string(), command, args, ..serde_json::from_str("{\"name\":\"x\"}").unwrap() }
}
/// Tests that connect servers share one table: one at a time.
#[cfg(test)]
pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
static L: Mutex<()> = Mutex::new(());
L.lock().unwrap_or_else(|e| e.into_inner())
}
/// A small stdio MCP server for tests (python3): `add` (a + b), `quit` (ends the process), and
/// `many` unrelated tools before them.
#[cfg(test)]
pub(crate) fn fake_server(name: &str, many: usize) -> Server {
const SCRIPT: &str = r#"
import sys, json, os
MANY = int(os.environ.get("FAKE_MANY", "0"))
for line in sys.stdin:
m = json.loads(line)
if "id" not in m:
continue
if m["method"] == "initialize":
r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake"}}
elif m["method"] == "tools/list":
r = {"tools": [{"name": "tool_%02d" % i, "description": "Unrelated thing number %d" % i, "inputSchema": {"type": "object"}} for i in range(MANY)] + [{"name": "add", "description": "Add two numbers", "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}, {"name": "quit", "description": "End the server", "inputSchema": {"type": "object"}}]}
elif m["method"] == "tools/call" and m["params"]["name"] == "quit":
sys.exit(0)
elif m["method"] == "tools/call":
a = m["params"]["arguments"]
r = {"content": [{"type": "text", "text": "sum=%d" % (a["a"] + a["b"])}]}
else:
r = {}
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n")
sys.stdout.flush()
"#;
let dir = std::env::temp_dir().join(format!("anybot-mcp-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let script = dir.join("server.py");
std::fs::write(&script, SCRIPT).unwrap();
let mut env = BTreeMap::new();
env.insert("FAKE_MANY".to_string(), many.to_string());
Server { name: name.into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env, url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new(), username: String::new(), password: String::new() }
}
#[cfg(test)]
mod tests {
use super::*;
/// Same, but a call to 「refresh」 makes the server announce list_changed and add a tool.
const CHANGING_SERVER: &str = r#"
import sys, json
mode = {"n": 1}
base = [{"name": "add", "description": "Add", "inputSchema": {"type": "object", "properties": {}}}]
extra = {"name": "extra", "description": "New tool", "inputSchema": {"type": "object", "properties": {}}}
for line in sys.stdin:
m = json.loads(line)
if "id" not in m:
continue
if m["method"] == "initialize":
r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": True}}, "serverInfo": {"name": "fake"}}
elif m["method"] == "tools/list":
r = {"tools": base + ([extra] if mode["n"] == 2 else [])}
elif m["method"] == "tools/call" and m["params"]["name"] == "refresh":
mode["n"] = 2
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}) + "\n")
sys.stdout.flush()
r = {"content": [{"type": "text", "text": "changed"}]}
else:
r = {}
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n")
sys.stdout.flush()
"#;
#[test]
fn stdio_server_round_trip() {
let _one = test_lock();
let s = Server { instructions: "用來算數學".into(), ..fake_server("計算機", 0) };
let errs = sync(std::slice::from_ref(&s));
assert!(errs.is_empty(), "{errs:?}");
let name = tool_name("計算機", "add");
assert!(name.starts_with("mcp__s") && name.ends_with("__add"), "{name}");
assert_eq!(tool_name("github", "list issues"), "mcp__github__list_issues");
assert!(specs().iter().any(|t| t["name"] == name.as_str()));
let (out, ok, _) = call(&name, r#"{"a": 2, "b": 40}"#);
assert!(ok && out.contains("sum=42"), "{out}");
assert!(instructions(std::slice::from_ref(&s)).contains("用來算數學"));
// 重新連線: dropped, then connected again by the next sync.
forget("計算機");
assert!(!status().contains_key("計算機"));
assert!(sync(std::slice::from_ref(&s)).is_empty());
assert_eq!(status().get("計算機"), Some(&2));
// A server whose process ends mid-call is dropped (not left "connected"), and comes back.
let (out, ok, _) = call(&tool_name("計算機", "quit"), "{}");
assert!(!ok && out.contains("重新連線"), "{out}");
assert!(!status().contains_key("計算機"));
assert!(sync(std::slice::from_ref(&s)).is_empty());
let (out, ok, _) = call(&name, r#"{"a": 1, "b": 1}"#);
assert!(ok && out.contains("sum=2"), "{out}");
sync(&[]);
assert!(tools().is_empty());
}
/// Few connector tools go to the model one by one; many, and only find + use go, with the
/// list of connectors: the bot finds the one it needs and runs it by its full name.
#[test]
fn many_tools_are_found_not_sent() {
let _one = test_lock();
let few = fake_server("calc", 3);
assert!(sync(std::slice::from_ref(&few)).is_empty());
let names: Vec<String> = specs().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect();
assert_eq!(names.len(), 5, "{names:?}");
assert!(names.contains(&tool_name("calc", "add")));
let many = fake_server("calc", 30);
assert!(sync(std::slice::from_ref(&many)).is_empty());
assert_eq!(status().get("calc"), Some(&32));
let sp = specs();
let names: Vec<&str> = sp.iter().map(|t| t["name"].as_str().unwrap()).collect();
assert_eq!(names, [FIND_TOOL, USE_TOOL]);
let about = sp[0]["description"].as_str().unwrap();
assert!(about.contains("calc (32 tools"), "{about}");
assert!(sp.iter().map(|t| t.to_string().len()).sum::<usize>() < 3000, "the list is short");
// Found by words from its description, with its parameters.
let found = find(r#"{"query": "add two numbers"}"#);
assert!(found.starts_with(&tool_name("calc", "add")), "{found}");
assert!(found.contains("\"a\"") && found.contains("Add two numbers"), "{found}");
assert!(find(r#"{"query": "weather in tokyo"}"#).contains("找不到"));
let listed = find(r#"{"server": "calc"}"#);
assert_eq!(listed.lines().filter(|l| l.starts_with(PREFIX)).count(), 32, "{listed}");
assert!(find(r#"{"server": "nope"}"#).contains("calc"));
// use_connector_tool is the tool it names: by its full name, or its own name by mistake.
let full = tool_name("calc", "add");
let (n, a) = unwrap_use(USE_TOOL, &json!({"tool": full, "arguments": {"a": 2, "b": 40}}).to_string()).unwrap().unwrap();
assert_eq!(n, full);
let (out, ok, _) = call(&n, &a);
assert!(ok && out.contains("sum=42"), "{out}");
assert_eq!(unwrap_use(USE_TOOL, r#"{"tool": "add", "arguments": "{\"a\": 1, \"b\": 2}"}"#).unwrap().unwrap(), (full.clone(), r#"{"a": 1, "b": 2}"#.to_string()));
assert!(unwrap_use(USE_TOOL, r#"{"tool": "nope"}"#).unwrap().unwrap_err().contains(FIND_TOOL));
assert!(unwrap_use("shell", "{}").is_none());
sync(&[]);
}
/// A server that doesn't come up says why in words to act on: a missing Node.js or uv, a
/// folder from another computer, or what the server itself printed before it stopped.
#[test]
fn a_server_that_does_not_start_says_why() {
let nf = std::io::Error::from(std::io::ErrorKind::NotFound);
assert!(spawn_error("npx", &nf).contains("Node.js"));
assert!(spawn_error("/usr/bin/uvx", &nf).contains("uv"));
assert!(spawn_error("my-server", &nf).contains("找不到「my-server」"));
let s = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
assert_eq!(missing_folder(&s(&["-y", "x", "/Users-nobody-here/someone/Documents"])), Some("/Users-nobody-here/someone/Documents"));
let tmp = std::env::temp_dir().join("anybot-mcp-new-file.json");
assert_eq!(missing_folder(&s(&[tmp.to_str().unwrap(), "/api", "relative/dir"])), None, "a file to be made, a top-level name and a relative path are fine");
let one = |command: &str, args: &[&str], url: &str| Server { name: "x".into(), command: command.into(), args: s(args), url: url.into(), ..serde_json::from_str("{\"name\":\"x\"}").unwrap() };
let e = connect(&one("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/Users-nobody-here/someone/Documents"], "")).err().unwrap();
assert!(e.contains("/Users-nobody-here/someone/Documents"), "{e}");
let e = connect(&one("sh", &["-c", "echo 'Error: cannot read config' >&2; exit 3"], "")).err().unwrap();
assert!(e.contains("cannot read config"), "{e}");
// Moving to a brain leaves behind what names this computer's own folders.
let home = dirs::home_dir().unwrap().display().to_string();
assert!(names_this_computer(&one("npx", &["-y", "@modelcontextprotocol/server-filesystem", &format!("{home}/Documents")], "")));
assert!(names_this_computer(&one("~/bin/my-server", &[], "")));
assert!(!names_this_computer(&one("uvx", &["mcp-server-time"], "")));
assert!(!names_this_computer(&one("", &[], "http://10.0.0.1:3900/mcp")));
}
/// A server that says 「my tools changed」 is taken at its word: the reader thread hands
/// the refresh to its own thread and the new tool shows up without a reconnect.
#[test]
fn list_changed_refetches_the_tools() {
let _turn = test_lock();
let dir = std::env::temp_dir().join(format!("anybot-mcp-changed-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let script = dir.join("server.py");
std::fs::write(&script, CHANGING_SERVER).unwrap();
let s = Server { name: "庫存".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env: BTreeMap::new(), url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new(), username: String::new(), password: String::new() };
let errs = sync(std::slice::from_ref(&s));
assert!(errs.is_empty(), "{errs:?}");
assert!(!tools().iter().any(|t| t.name == "extra"), "starts without the extra tool");
// Trigger the announcement: the fake server emits list_changed on a call named
// refresh — send it through the server's own handle, like AnyBot's call() does.
{
let conn = conns().lock().unwrap().get("庫存").cloned().unwrap();
let mut live = conn.live.lock().unwrap();
live.request("tools/call", json!({"name": "refresh", "arguments": {}})).unwrap();
}
let mut got = false;
for _ in 0..60 {
if tools().iter().any(|t| t.server == "庫存" && t.name == "extra") {
got = true;
break;
}
std::thread::sleep(Duration::from_millis(50));
}
sync(&[]);
let _ = std::fs::remove_dir_all(&dir);
assert!(got, "the tool list did not refresh after list_changed");
}
/// A stdio server that answers once and then dies: the dying link is evicted by the
/// call that finds it, and the next sync starts a fresh one — no manual reconnect.
const DYING_SERVER: &str = r#"
import sys, json
for line in sys.stdin:
m = json.loads(line)
if "id" not in m:
continue
if m["method"] == "initialize":
r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "dying"}}
elif m["method"] == "tools/list":
r = {"tools": [{"name": "bye", "description": "Answer once, then exit", "inputSchema": {"type": "object", "properties": {}}}]}
elif m["method"] == "tools/call":
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": {"content": [{"type": "text", "text": "bye"}]}}) + "\n")
sys.stdout.flush()
sys.exit(0)
else:
r = {}
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n")
sys.stdout.flush()
"#;
#[test]
fn a_dead_server_is_evicted_and_started_again() {
let _turn = test_lock();
let dir = std::env::temp_dir().join(format!("anybot-mcp-dying-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let script = dir.join("server.py");
std::fs::write(&script, DYING_SERVER).unwrap();
let s = Server { name: "短命".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env: BTreeMap::new(), url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new(), username: String::new(), password: String::new() };
let errs = sync(std::slice::from_ref(&s));
assert!(errs.is_empty(), "{errs:?}");
let name = tool_name("短命", "bye");
// The server exits right after answering this call.
let (out, ok, _) = call(&name, "{}");
assert!(ok && out.contains("bye"), "{out}");
// The next call finds the dead link: it fails, and the server is evicted.
let (out, ok, _) = call(&name, "{}");
assert!(!ok, "{out}");
assert!(!status().contains_key("短命"), "the dead server was not evicted");
// And the next sync brings it back on its own.
let errs = sync(std::slice::from_ref(&s));
assert!(errs.is_empty(), "{errs:?}");
assert_eq!(status().get("短命").copied(), Some(1), "the server did not come back");
// A sync also notices a child that died quietly between calls (try_wait).
let (out, ok, _) = call(&name, "{}");
assert!(ok && out.contains("bye"), "{out}");
std::thread::sleep(Duration::from_millis(300));
let errs = sync(std::slice::from_ref(&s));
assert!(errs.is_empty(), "{errs:?}");
assert_eq!(status().get("短命").copied(), Some(1), "the dead child was not restarted");
sync(&[]);
let _ = std::fs::remove_dir_all(&dir);
}
/// What counts as the change notice, and a notice riding an HTTP answer stream must not
/// be taken for the answer.
#[test]
fn the_change_notice_is_recognised() {
assert!(is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"})));
assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "id": 3, "result": {}})));
assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/message"})));
let sse = "data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\n\ndata: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"tools\":[]}}\n";
assert!(parse_http_answer(sse, 9).unwrap()["tools"].is_array());
}
/// The registry's answer as the 公用市集 lists it: servers reached by address (streamable
/// HTTP first), the key's placeholder kept, none taken down, packages left out, one row each.
#[test]
fn the_registry_lists_what_can_be_reached_by_address() {
let active = json!({"io.modelcontextprotocol.registry/official": {"status": "active"}});
let v = json!({"servers": [
{"server": {"name": "com.notion/mcp", "title": "Notion", "description": "Pages", "remotes": [{"type": "sse", "url": "https://mcp.notion.com/sse"}, {"type": "streamable-http", "url": "https://mcp.notion.com/mcp"}]}, "_meta": active},
{"server": {"name": "ai.smithery/smithery-notion", "description": "Via Smithery", "remotes": [{"type": "streamable-http", "url": "https://server.smithery.ai/@smithery/notion/mcp", "headers": [{"name": "Authorization", "value": "Bearer {smithery_api_key}", "description": "Smithery key", "isRequired": true}]}]}, "_meta": active},
{"server": {"name": "com.example/raw-key", "remotes": [{"type": "streamable-http", "url": "https://x.example/mcp", "headers": [{"name": "X-API-Key", "description": "Your key"}]}]}},
{"server": {"name": "ai.autorfp/mcp", "title": "AutoRFP", "remotes": [{"type": "streamable-http", "url": "https://{api_host}/mcp", "variables": {"api_host": {"description": "Region host", "choices": ["api.autorfp.ai", "api.eu.autorfp.ai"]}}}]}},
{"server": {"name": "io.old/sse-only", "remotes": [{"type": "sse", "url": "https://old.example/sse"}]}},
{"server": {"name": "com.gone/mcp", "remotes": [{"type": "streamable-http", "url": "https://gone.example/mcp"}]}, "_meta": {"io.modelcontextprotocol.registry/official": {"status": "deprecated"}}},
{"server": {"name": "com.pkg/only", "packages": [{"registryType": "npm", "identifier": "x"}]}},
{"server": {"name": "com.notion/mcp", "title": "Notion again", "remotes": [{"type": "streamable-http", "url": "https://mcp.notion.com/mcp"}]}},
]});
let e = registry_entries(&v);
let ids: Vec<&str> = e.iter().map(|x| x["id"].as_str().unwrap()).collect();
assert_eq!(ids, ["com.notion/mcp", "ai.smithery/smithery-notion", "com.example/raw-key", "ai.autorfp/mcp", "io.old/sse-only"]);
assert_eq!((e[0]["title"].as_str(), e[0]["url"].as_str(), e[0]["note"].as_str()), (Some("Notion"), Some("https://mcp.notion.com/mcp"), Some("")));
assert_eq!(e[1]["title"], "smithery-notion", "no title: the last part of its name");
assert_eq!((short_name("com.notion/mcp"), short_name("io.github.someone/remote-mcp"), short_name("x")), ("notion".into(), "someone".into(), "x".into()));
assert_eq!(e[1]["header"]["value"], "Bearer {smithery_api_key}");
assert_eq!(e[2]["header"]["value"], "{金鑰}", "a header with no shape still asks for the key");
assert!(!e[4]["note"].as_str().unwrap().is_empty(), "old SSE can't be added yet");
// 加入 fills the form: a free name, the header to complete, and what to do about it.
let have = vec![remote_server("Notion", "https://other.example/mcp", "")];
let (name, url, header, hint) = registry_form(&e[0], &have);
assert_eq!((name.as_str(), url.as_str(), header.as_str()), ("Notion 2", "https://mcp.notion.com/mcp", ""));
assert!(hint.contains("OAuth"));
let (_, _, header, hint) = registry_form(&e[1], &have);
assert_eq!(header, "Authorization: Bearer {smithery_api_key}");
assert!(hint.contains("Smithery key"));
let (_, url, _, hint) = registry_form(&e[3], &have);
assert_eq!(url, "https://{api_host}/mcp");
assert!(hint.contains("{api_host}") && hint.contains("api.eu.autorfp.ai"), "{hint}");
let s = remote_server("Smithery", "https://server.smithery.ai/x", "Authorization: Bearer sk-1");
assert_eq!(s.headers.get("Authorization").map(String::as_str), Some("Bearer sk-1"));
assert!(remote_server("x", "https://x", "").headers.is_empty());
}
/// A 401 says what to do: no key given means the server signs people in (OAuth, not yet
/// here); with a key, the key is wrong. Anything else reads as before.
#[test]
fn a_refusal_says_what_to_do() {
assert!(http_refusal(401, true, false, "").contains("OAuth"));
assert!(http_refusal(403, true, false, "").contains("OAuth"));
assert!(http_refusal(401, false, true, "").contains("金鑰不對"));
assert!(http_refusal(403, false, false, "forbidden").contains("HTTP 403:forbidden"));
assert!(http_refusal(500, true, false, "boom").contains("HTTP 500"));
}
/// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and
/// shouts list_changed over the SSE stream. Setup:
/// 1. /tmp/openapimcp-live.yaml exists (port 3901, Spec.File /tmp/openapimcp-live.json,
/// ReloadSeconds 60 so only the management endpoint reloads — the openapimcp repo ships one),
/// 2. from the openapimcp repo: ./bin/srv -f /tmp/openapimcp-live.yaml
/// Then: cargo test openapimcp_live -- --ignored --nocapture
/// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE
/// stream and refresh the tools without a reconnect.
#[test]
#[ignore]
fn openapimcp_live() {
const LIVE_SPEC: &str = "/tmp/openapimcp-live.json";
const MANAGE: &str = "http://localhost:3901";
let mini = |extra: &str| {
r#"{"swagger":"2.0","basePath":"/","info":{"title":"Live"},"paths":{"/v1/ping":{"get":{"summary":"Ping","responses":{"200":{"description":"ok"}}}}@}}"#
.replace("@", extra)
};
let post = |path: &str| {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into();
agent.post(&format!("{MANAGE}{path}")).send(()).ok().and_then(|mut r| r.body_mut().read_to_string().ok())
};
let health_tools = || -> Option<usize> {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into();
let b = agent.get(&format!("{MANAGE}/healthz")).call().ok()?.body_mut().read_to_string().ok()?;
Some(serde_json::from_str::<Value>(&b).ok()?.get("tools")?.as_u64()? as usize)
};
let _turn = test_lock();
// Settle the SERVER on the baseline before opening any MCP session, so no ticker
// notification can race with the listener's GET starting: write baseline, reload, wait
// for the health endpoint to report the baseline tool count (ping + api_search + api_call).
std::fs::write(LIVE_SPEC, mini("")).unwrap();
post("/api/reload");
let mut settled = false;
for _ in 0..50 {
if health_tools() == Some(3) {
settled = true;
break;
}
std::thread::sleep(Duration::from_millis(100));
}
let s = remote_server("openapi", "http://localhost:3901/mcp", "");
let errs = sync(&[s]);
if !errs.is_empty() {
eprintln!("openapimcp 沒跑在 :3901 — 先照上方說明啟動:{errs:?}");
sync(&[]);
return;
}
assert!(settled, "server did not settle on the baseline (3 tools)");
assert!(tools().iter().any(|t| t.name == "v1_ping_get"), "tools: {:?}", tools().iter().map(|t| t.name.clone()).collect::<Vec<_>>());
assert!(!tools().iter().any(|t| t.name == "v1_echo_get"));
let (out, ok, _) = call(&tool_name("openapi", "api_search"), r#"{"keyword":"ping"}"#);
assert!(ok && out.contains("v1_ping_get"), "{out}");
// The spec gains a path; ask the server to reload now. It shouts list_changed on the
// open SSE stream; the listener refreshes the tools in place, no reconnect.
std::fs::write(LIVE_SPEC, mini(r#","/v1/echo":{"get":{"summary":"Echo","responses":{"200":{"description":"ok"}}}}"#)).unwrap();
post("/api/reload");
let mut got = false;
for _ in 0..100 {
if tools().iter().any(|t| t.name == "v1_echo_get") {
got = true;
break;
}
std::thread::sleep(Duration::from_millis(100));
}
sync(&[]);
assert!(got, "SSE 監聽沒有刷新工具清單(v1_echo_get 沒出現)");
}
/// Run by hand (it goes out to the internet): `cargo test registry_search_live -- --ignored`.
#[test]
#[ignore]
fn registry_search_live() {
let e = registry_search("notion").unwrap();
assert!(!e.is_empty());
assert!(e.iter().all(|x| x["url"].as_str().unwrap().starts_with("http")));
eprintln!("{} found; first: {} {}", e.len(), e[0]["title"], e[0]["url"]);
// An open server connects and lists its tools; one that signs people in says so.
let open = remote_server("aws-knowledge", "https://knowledge-mcp.global.api.aws", "");
let oauth = remote_server("notion", "https://mcp.notion.com/mcp", "");
let errs = sync(&[open, oauth]);
eprintln!("tools: {:?}\nerrors: {errs:?}", tools().iter().map(|t| format!("{}·{}", t.server, t.name)).collect::<Vec<_>>());
assert!(tools().iter().any(|t| t.server == "aws-knowledge"));
assert!(errs.iter().any(|(n, e)| n == "notion" && e.contains("OAuth")), "{errs:?}");
sync(&[]);
}
#[test]
fn http_answers_json_or_sse() {
assert_eq!(parse_http_answer(r#"{"jsonrpc":"2.0","id":3,"result":{"ok":1}}"#, 3).unwrap()["ok"], 1);
let sse = "event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":4,\"result\":{\"tools\":[]}}\n\n";
assert!(parse_http_answer(sse, 4).unwrap()["tools"].is_array());
assert!(parse_http_answer(r#"{"jsonrpc":"2.0","id":5,"error":{"message":"nope"}}"#, 5).unwrap_err().contains("nope"));
}
/// Downloads and starts every marketplace connector that needs no key (needs the network,
/// Node.js and uv): cargo test --release -- --ignored marketplace --nocapture
#[test]
#[ignore]
fn marketplace_connectors_start() {
let _one = test_lock();
let servers: Vec<Server> = MARKET.iter().filter(|m| m.3.is_empty()).map(|m| market_server(m.0, m.2)).collect();
let errors = sync(&servers);
let st = status();
for s in &servers {
println!("{:<12} {:?}", s.name, st.get(&s.name));
}
assert!(errors.is_empty(), "{errors:?}");
for s in &servers {
assert!(st.get(&s.name).copied().unwrap_or(0) > 0, "{} has no tools", s.name);
}
// And one real call through the bot's tool name.
let (out, ok, _) = call(&tool_name("time", "get_current_time"), r#"{"timezone":"Asia/Taipei"}"#);
println!("time: {out}");
assert!(ok && out.contains("Asia/Taipei"), "{out}");
shutdown();
}
/// A server that tells who it was started as: its 帳號 and 密碼 from the variables it reads.
const LOGIN_SERVER: &str = r#"
import sys, json, os
for line in sys.stdin:
m = json.loads(line)
if "id" not in m:
continue
if m["method"] == "initialize":
r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake"}}
elif m["method"] == "tools/list":
r = {"tools": [{"name": "whoami", "description": "Who am I", "inputSchema": {"type": "object", "properties": {}}}]}
else:
r = {"content": [{"type": "text", "text": "|".join(os.environ.get(k, "-") for k in ["SCC_USER", "SCC_PASS", "MCP_USERNAME", "MCP_PASSWORD"])}]}
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n")
sys.stdout.flush()
"#;
/// 帳號 / 密碼 go where 「{username}」「{password}」 are written; written nowhere, a command
/// gets MCP_USERNAME / MCP_PASSWORD and an address gets Basic.
#[test]
fn the_login_reaches_the_server() {
let blank: Server = serde_json::from_str("{\"name\":\"x\"}").unwrap();
// Slots: in a variable, an argument, the address, a header.
let mut s = Server { command: "srv".into(), args: vec!["--user={username}".into()], username: " amy ".into(), password: "p w".into(), ..blank.clone() };
s.env.insert("SCC_PASS".into(), "{password}".into());
let r = s.resolved();
assert_eq!((r.args[0].as_str(), r.env["SCC_PASS"].as_str()), ("--user=amy", "p w"));
assert!(!r.env.contains_key(PASS_ENV), "named: nothing more is added");
// No slot, a command: the two variables (one the person set stays).
let mut s = Server { command: "srv".into(), username: "amy".into(), password: "pw".into(), ..blank.clone() };
s.env.insert(USER_ENV.into(), "own".into());
let r = s.resolved();
assert_eq!((r.env[USER_ENV].as_str(), r.env[PASS_ENV].as_str()), ("own", "pw"));
// No slot, an address: Basic, replacing a key header (one Authorization only).
let s = Server { url: "https://scc.example/mcp".into(), username: "amy".into(), password: "pw".into(), ..blank.clone() };
assert_eq!(s.resolved().headers["Authorization"], "Basic YW15OnB3");
let mut own = s.clone();
own.headers.insert("authorization".into(), "Bearer k".into());
let r = own.resolved();
assert_eq!(r.headers.len(), 1, "the key header makes way: {r:?}");
assert_eq!(r.headers.values().next().unwrap().as_str(), "Basic YW15OnB3");
let mut slot = s.clone();
slot.headers.insert("X-Auth".into(), "{username}:{password}".into());
assert_eq!(slot.resolved().headers, [("X-Auth".to_string(), "amy:pw".to_string())].into_iter().collect());
// No login: as written. The slots aren't 「still to fill in」; a market's 「{key}」 is.
assert_eq!(blank.resolved(), blank);
assert!(!Server::unfilled("Bearer {password}") && Server::unfilled("Bearer {api_key}"));
// For real: a server started with them, and started again when the password changes.
let _turn = test_lock();
let dir = std::env::temp_dir().join(format!("anybot-mcp-login-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let script = dir.join("server.py");
std::fs::write(&script, LOGIN_SERVER).unwrap();
let mut s = Server { name: "scc-login".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], username: "amy".into(), password: "pw1".into(), ..blank.clone() };
s.env.insert("SCC_USER".into(), "{username}".into());
s.env.insert("SCC_PASS".into(), "{password}".into());
assert!(sync(std::slice::from_ref(&s)).is_empty());
let who = tool_name("scc-login", "whoami");
assert_eq!(call(&who, "{}").0, "amy|pw1|-|-");
s.password = "pw2".into();
assert!(sync(std::slice::from_ref(&s)).is_empty());
assert_eq!(call(&who, "{}").0, "amy|pw2|-|-");
s.env.clear();
assert!(sync(std::slice::from_ref(&s)).is_empty());
assert_eq!(call(&who, "{}").0, "-|-|amy|pw2");
sync(&[]);
let _ = std::fs::remove_dir_all(&dir);
}
}