AnyBot/src/mcp.rs

1939 lines
104 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, Default, 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,
/// 連接器登入 (mcp_oauth.rs): the connector whose OAuth token this link sends, renewed once
/// when the server says it is no longer good (401).
oauth: Option<String>,
}
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")
}
/// A stdio server's process and everything it started (`npx`/`uvx` run the real server as a child
/// of their own: killing only the direct child used to leave that one running).
fn end(child: &mut Child) {
crate::tools::kill_tree(child.id());
let _ = child.kill();
let _ = child.wait();
}
/// What a connector call says when the person pressed 停止.
pub const STOPPED: &str = "已停止:使用者按了停止,沒有等連接器的回答。";
/// Read the answer with this id (skipping notifications and requests from the server). A stop
/// (`cancel`) ends the wait within a fifth of a second; the server's late answer is skipped by
/// the next wait.
fn wait_id(rx: &Receiver<Value>, id: u64, secs: u64, cancel: Option<&std::sync::atomic::AtomicBool>) -> 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());
}
if cancel.is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed)) {
return Err(STOPPED.into());
}
match rx.recv_timeout(left.min(Duration::from_millis(200))) {
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
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):在聊天裡請 Bot 幫你登入(manage_connectors 的 login),或在 設定 › 整合 › 連接器 按「登入」;它若也收 API 金鑰,也可以填在「標頭」(例如 Authorization: Bearer …)".into()
};
}
format!("MCP 伺服器回 HTTP {status}:{}", body.chars().take(200).collect::<String>())
}
/// A request's params, to send it again.
fn params_again(msg: &Value) -> Value {
msg["params"].clone()
}
/// 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> {
self.request_until(method, params, None)
}
/// A request a stop can end (a stdio server's; an HTTP one waits its timeout out).
fn request_until(&mut self, method: &str, params: Value, cancel: Option<&std::sync::atomic::AtomicBool>) -> 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, cancel)
}
Link::Http { url, headers, session } => {
let agent: ureq::Agent = crate::net::config().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;
}
// 連接器登入: the token ran out — a new one with the refresh token, and once more.
if st == 401 {
if let Some(name) = self.oauth.take() {
if let Ok(t) = crate::mcp_oauth::renew(&name) {
headers.insert("Authorization".into(), format!("Bearer {t}"));
// (Once per request; the next time it runs out it is renewed again.)
let again = self.request_until(method, params_again(&msg), cancel);
self.oauth = Some(name);
return again;
}
self.oauth = Some(name.clone());
return Err(format!("「{name}」的登入過期了:重新登入(在聊天裡請 Bot 用 manage_connectors 的 login,或 設定 › 整合 › 連接器 按「登入」)。"));
}
}
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 = crate::net::config().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. Not for a server
/// that runs somewhere else (`docker exec box /home/…`, `ssh host /opt/…`): its paths are there.
fn missing_folder<'a>(command: &str, args: &'a [String]) -> Option<&'a str> {
const ELSEWHERE: [&str; 8] = ["docker", "podman", "nerdctl", "kubectl", "ssh", "wsl", "orb", "lxc"];
let program = std::path::Path::new(command.trim()).file_name().and_then(|n| n.to_str()).unwrap_or("");
if ELSEWHERE.contains(&program.trim_end_matches(".exe")) {
return None;
}
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 mut oauth: Option<String> = 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());
}
let mut headers = s.headers.clone();
// 連接器登入: logged in with OAuth (and no key of its own given): its token.
if !headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) {
if let Some(t) = crate::mcp_oauth::bearer(&s.name, u) {
headers.insert("Authorization".into(), format!("Bearer {t}"));
oauth = Some(s.name.clone());
}
}
Link::Http { url: u.to_string(), headers, session: None }
} else {
if s.command.trim().is_empty() {
return Err("請給指令或網址".into());
}
if let Some(dir) = missing_folder(&s.command, &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, oauth };
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 {
end(child);
}
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 = crate::net::config().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 {
end(child);
}
}
});
}
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 {
end(child);
}
});
}
}
/// The connected servers' tools.
/// What to tell the person adding a 「connector(…)」 rule that no connector tool answers to — it
/// is compared with the part of a tool's name after `mcp__`: the connector's key (its name when
/// plain ASCII, else a code like s1a2b3c), two underscores, the tool, cut at 64 characters, case
/// counting. None: a connected tool answers to it, it names a connector not connected now (its
/// tools aren't known), or it isn't a connector rule.
pub fn rule_names_nothing(rule: &str, servers: &[Server]) -> Option<String> {
let inner = rule.trim().strip_prefix("connector(")?.strip_suffix(')')?.trim();
let known = tools();
if known.iter().any(|t| crate::gate::glob(inner, &tool_name(&t.server, &t.name)[PREFIX.len()..], false)) {
return None;
}
let server_part = inner.split("__").next().unwrap_or(inner);
if servers.iter().any(|s| !known.iter().any(|t| t.server == s.name) && crate::gate::glob(server_part, &server_key(&s.name), false)) {
return None;
}
let have: Vec<String> = servers.iter().take(6).map(|s| format!("{}__*", server_key(&s.name))).collect();
Some(if have.is_empty() {
format!("「{rule}」現在對不上任何連接器:還沒有連接器。")
} else {
format!("「{rule}」對不上任何連接器的工具:比對的是工具名稱 mcp__ 後面那段(連接器的代號__工具),大小寫要一樣。現在有:{}", have.join("、"))
})
}
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). (A turn uses `call_until`.)
#[cfg(test)]
pub fn call(name: &str, args: &str) -> (String, bool, Option<String>) {
call_until(name, args, &std::sync::atomic::AtomicBool::new(false))
}
/// Call a tool; the person's 停止 (`cancel`) ends the wait.
pub fn call_until(name: &str, args: &str, cancel: &std::sync::atomic::AtomicBool) -> (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_until("tools/call", json!({"name": tool, "arguments": arguments}), Some(cancel));
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 {
end(child);
}
}
}
/// 連接器市集: (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 = crate::net::config().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)的連接器連線時會說,按它的「登入」或請 Bot 幫你登入。".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() }
}
// ---------- 管理連接器: a bot does what 設定 › 整合 › 連接器 does ----------
/// Which connector tools there are now (a turn notices one added or gone while it runs).
pub fn tools_sig() -> String {
sorted_tools().iter().map(|t| format!("{}/{}", t.server, t.name)).collect::<Vec<_>>().join("|")
}
/// A tool spec that comes from the connectors (one of theirs, or the two that find and use them).
pub fn is_connector_spec(name: &str) -> bool {
is_mcp_tool(name) || name == FIND_TOOL || name == USE_TOOL
}
/// The tool a bot lists, adds, changes, reconnects and removes connectors with. They land in the
/// brain's own list (the one 設定 › 整合 › 連接器 shows, on every screen and the phone): the turn
/// runs on the brain, so there is no other place they could go.
pub const MANAGE_TOOL: &str = "manage_connectors";
pub fn manage_spec() -> Value {
json!({"name": MANAGE_TOOL,
"description": "List, add, change (including turning on or off), reconnect or remove the person's connectors (MCP servers) — what 設定 › 整合 › 連接器 does. They run on the brain (this AnyBot) and every bot with the 連接器 ability gets their tools; a connector added now can be used from your next step. Adding, changing and removing show the person a card first (a command runs on the brain). A local server is a command (`npx -y …`, `uvx …`; the brain needs Node.js or uv); a remote one is a URL (Streamable HTTP). Secrets go in env, headers or password, never in instructions. Try a command once on your computer before adding it. After adding, the answer says whether it connected (a first start may download packages for a minute; check again with action=list).",
"parameters": {"type": "object", "properties": {
"action": {"type": "string", "enum": ["list", "add", "update", "remove", "reconnect", "login", "logout"], "description": "login: a remote connector that signs people in (OAuth) — gives the address the person opens to log in (open it for them with open_for_person, or give it to them); once they have, it connects by itself. When that page couldn't load (the browser on another computer), they paste its address to you: login again with callback = that address."},
"callback": {"type": "string", "description": "login: the address the browser came back to after logging in (http://127.0.0.1:…/callback?code=…)."},
"name": {"type": "string", "description": "The connector's name (short, e.g. gitlab). Needed for everything but list."},
"command": {"type": "string", "description": "A local server's command line, e.g. `npx -y @zereight/mcp-gitlab`. Not with url."},
"url": {"type": "string", "description": "A remote server's address (http:// or https://). Not with command."},
"env": {"type": "object", "additionalProperties": {"type": "string"}, "description": "Environment variables for a local server, e.g. {\"GITLAB_API_URL\": \"https://gitlab.example.com/api/v4\"}. With update, the whole set."},
"headers": {"type": "object", "additionalProperties": {"type": "string"}, "description": "Headers for a remote server, e.g. {\"Authorization\": \"Bearer …\"}. With update, the whole set."},
"username": {"type": "string", "description": "For a server that signs in with an account (see {username} in the connector help)."},
"password": {"type": "string", "description": "Its password (kept like a key, never shown)."},
"instructions": {"type": "string", "description": "Notes for bots on how to use it."},
"enabled": {"type": "boolean", "description": "update: false turns it off, true on."}},
"required": ["action"]}})
}
/// What a `manage_connectors` call asks for, checked against the list as it is. (One lives for
/// a call, so an update carrying two servers is fine unboxed.)
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
List,
Add(Server),
Update { before: Server, after: Server },
Remove(Server),
Reconnect(String),
/// 連接器登入 (mcp_oauth.rs): start (the address for the person), or finish with the address
/// the browser came back to.
Login { name: String, url: String, callback: Option<String> },
Logout(String),
}
/// `{"K": "v"}`, or 「K=v K2=v2」 as the form takes it.
fn pairs_of(v: &Value, sep: char) -> Option<BTreeMap<String, String>> {
match v {
Value::Object(o) => Some(o.iter().map(|(k, v)| (k.trim().to_string(), v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).filter(|(k, _)| !k.is_empty()).collect()),
Value::String(s) if sep == '=' => Some(s.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect()),
Value::String(s) => Some(s.lines().filter_map(|kv| kv.split_once(sep)).map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).collect()),
_ => None,
}
}
/// A command line or an address into the server, as the 新增連接器 form does it.
fn set_place(s: &mut Server, command: Option<&str>, url: Option<&str>) -> Result<(), String> {
match (command.map(str::trim).filter(|c| !c.is_empty()), url.map(str::trim).filter(|u| !u.is_empty())) {
(Some(_), Some(_)) => Err("command 和 url 只能給一個:本機伺服器給 command,遠端伺服器給 url。".into()),
(Some(c), None) if c.starts_with("http://") || c.starts_with("https://") => set_place(s, None, Some(c)),
(Some(c), None) => {
let mut it = c.split_whitespace();
s.command = it.next().unwrap_or_default().to_string();
s.args = it.map(String::from).collect();
s.url.clear();
Ok(())
}
(None, Some(u)) if u.starts_with("http://") || u.starts_with("https://") => {
s.url = u.to_string();
s.command.clear();
s.args.clear();
Ok(())
}
(None, Some(u)) => Err(format!("url 要是 http:// 或 https:// 開頭的網址(收到「{u}」)。")),
(None, None) => Ok(()),
}
}
/// The `manage_connectors` call, checked: what it would change (nothing yet).
pub fn parse_change(args: &str, servers: &[Server]) -> Result<Change, String> {
let v: Value = serde_json::from_str(args).map_err(|_| "manage_connectors 的參數不是 JSON 物件。".to_string())?;
let action = v["action"].as_str().unwrap_or("").trim();
let name = v["name"].as_str().unwrap_or("").trim().to_string();
let find = |n: &str| servers.iter().find(|s| s.name == n || s.name.eq_ignore_ascii_case(n)).cloned();
let names = || {
let all: Vec<&str> = servers.iter().map(|s| s.name.as_str()).collect();
if all.is_empty() { "目前一個連接器都沒有".to_string() } else { format!("現有的:{}", all.join("、")) }
};
let existing = || find(&name).ok_or_else(|| format!("沒有叫「{name}」的連接器({})。", names()));
let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
let fill = |s: &mut Server| -> Result<(), String> {
if let Some(e) = v.get("env").filter(|x| !x.is_null()) {
s.env = pairs_of(e, '=').ok_or("env 要是 {\"變數\": \"值\"}。")?;
}
if let Some(h) = v.get("headers").filter(|x| !x.is_null()) {
s.headers = pairs_of(h, ':').ok_or("headers 要是 {\"標頭\": \"值\"}。")?;
}
if let Some(u) = text("username") {
s.username = u.trim().to_string();
}
if let Some(p) = text("password") {
s.password = p;
}
if let Some(i) = text("instructions") {
s.instructions = i.trim().to_string();
}
if let Some(e) = v["enabled"].as_bool() {
s.enabled = e;
}
let shown = format!("{} {} {}", s.command_line(), s.url, s.headers.values().cloned().collect::<Vec<_>>().join(" "));
if Server::unfilled(&shown) {
return Err("指令、網址或標頭裡還有「{…}」沒換成真的值({username}、{password} 以外的)。".into());
}
Ok(())
};
match action {
"list" | "" => Ok(Change::List),
"add" => {
if name.is_empty() {
return Err("新增要給 name(短的名字,例如 gitlab)。".into());
}
if name.chars().count() > 40 {
return Err("name 太長了(最多 40 字)。".into());
}
if let Some(s) = find(&name) {
return Err(format!("已經有叫「{}」的連接器:要改它用 action=update,或換個名字。", s.name));
}
let mut s = Server { name, enabled: true, ..Default::default() };
set_place(&mut s, text("command").as_deref(), text("url").as_deref())?;
if s.command.is_empty() && s.url.is_empty() {
return Err("新增要給 command(本機伺服器的指令,例如 npx -y …)或 url(遠端伺服器的網址)。".into());
}
fill(&mut s)?;
Ok(Change::Add(s))
}
"update" => {
let before = existing()?;
let mut after = before.clone();
set_place(&mut after, text("command").as_deref(), text("url").as_deref())?;
// A new place: the password isn't sent there unless given again (as the form does).
if (after.command_line() != before.command_line() || after.url != before.url) && text("password").is_none() {
after.password.clear();
}
fill(&mut after)?;
if after == before {
return Err(format!("「{}」沒有要改的:給要改的欄位(command、url、env、headers、username、password、instructions 或 enabled)。", before.name));
}
Ok(Change::Update { before, after })
}
"remove" => Ok(Change::Remove(existing()?)),
"reconnect" => Ok(Change::Reconnect(existing()?.name)),
"login" => {
let s = existing()?;
if s.url.trim().is_empty() {
return Err(format!("「{}」是在這台跑的程式(不是網址),沒有帳號登入:它的金鑰填在 env。", s.name));
}
Ok(Change::Login { name: s.name, url: s.url, callback: text("callback").map(|c| c.trim().to_string()).filter(|c| !c.is_empty()) })
}
"logout" => Ok(Change::Logout(existing()?.name)),
other => Err(format!("action「{other}」看不懂:用 list、add、update、remove、reconnect、login 或 logout。")),
}
}
impl Server {
/// The command as one line (empty for a remote server).
pub fn command_line(&self) -> String {
std::iter::once(self.command.as_str()).chain(self.args.iter().map(String::as_str)).filter(|x| !x.is_empty()).collect::<Vec<_>>().join(" ")
}
}
/// A name that holds a secret (a key, a token, a password): its value isn't shown on a card.
fn secret_name(k: &str) -> bool {
let k = k.to_ascii_uppercase();
["TOKEN", "KEY", "SECRET", "PASS", "AUTH", "CREDENTIAL", "COOKIE", "PAT"].iter().any(|w| k.contains(w))
}
fn shown_pairs(m: &BTreeMap<String, String>, sep: &str) -> String {
m.iter().map(|(k, v)| if secret_name(k) && !v.is_empty() { format!("{k}{sep}••••(已填)") } else { format!("{k}{sep}{v}") }).collect::<Vec<_>>().join("、")
}
/// One connector's settings as lines for a card (secrets hidden).
fn server_lines(s: &Server) -> Vec<String> {
let mut out = vec![];
if s.url.is_empty() {
out.push(format!("指令(在大腦上執行):{}", s.command_line()));
} else {
out.push(format!("網址:{}", s.url));
}
if !s.env.is_empty() {
out.push(format!("環境變數:{}", shown_pairs(&s.env, "=")));
}
if !s.headers.is_empty() {
out.push(format!("標頭:{}", shown_pairs(&s.headers, ": ")));
}
if !s.username.is_empty() || !s.password.is_empty() {
out.push(format!("帳號:{} · 密碼:{}", if s.username.is_empty() { "(沒填)" } else { &s.username }, if s.password.is_empty() { "(沒填)" } else { "••••(已填)" }));
}
if !s.instructions.is_empty() {
out.push(format!("給 Bot 的說明:{}", s.instructions.chars().take(120).collect::<String>()));
}
out
}
/// What the person is asked before the change (None: nothing to ask — a list or a reconnect).
pub fn change_question(c: &Change) -> Option<String> {
match c {
Change::List | Change::Reconnect(_) | Change::Login { .. } => None,
Change::Logout(n) => Some(format!("登出連接器「{n}」:它的登入刪掉,要再登入才能用它的工具。")),
Change::Add(s) => Some(format!("新增連接器「{}」(加在大腦的 設定 › 整合 › 連接器):\n- {}", s.name, server_lines(s).join("\n- "))),
Change::Update { before, after } => {
let (b, a) = (server_lines(before), server_lines(after));
let mut lines: Vec<String> = a.iter().filter(|l| !b.contains(l)).cloned().collect();
lines.extend(b.iter().filter(|l| !a.iter().any(|x| x.split_once(':').map(|p| p.0) == l.split_once(':').map(|p| p.0))).map(|l| format!("拿掉 {}", l.split_once(':').map(|p| p.0).unwrap_or(l))));
if before.enabled != after.enabled {
lines.push(if after.enabled { "打開".into() } else { "關閉(它的工具暫時不能用)".into() });
}
if !before.password.is_empty() && after.password.is_empty() {
lines.push("密碼清掉(換了指令或網址,舊密碼不送過去)".into());
}
if lines.is_empty() {
lines.push("密碼換新".into());
}
Some(format!("修改連接器「{}」:\n- {}", before.name, lines.join("\n- ")))
}
Change::Remove(s) => Some(format!("移除連接器「{}」:它的工具就不能用了,設定(指令、金鑰)一起刪掉。", s.name)),
}
}
/// Make the change in the list (the person said yes). The answer for the bot.
pub fn apply_change(c: &Change, servers: &mut Vec<Server>) -> String {
match c {
Change::List => String::new(),
Change::Add(s) => {
servers.push(s.clone());
format!("已新增連接器「{}」,正在連線。", s.name)
}
Change::Update { before, after } => {
if let Some(x) = servers.iter_mut().find(|x| x.name == before.name) {
*x = after.clone();
}
if after.enabled { format!("已修改連接器「{}」,正在重新連線。", after.name) } else { format!("已關閉連接器「{}」。", after.name) }
}
Change::Remove(s) => {
servers.retain(|x| x.name != s.name);
format!("已移除連接器「{}」。", s.name)
}
Change::Reconnect(n) => format!("正在重新連線「{n}」。"),
// (A login is done by the window, on a thread: it goes over the network.)
Change::Login { .. } => String::new(),
Change::Logout(n) => match crate::mcp_oauth::logout(n) {
Ok(()) => format!("已登出「{n}」。"),
Err(e) => format!("登出「{n}」時出錯:{e}"),
},
}
}
/// The connectors as the bot reads them: each one's state, where it runs and how (secrets hidden).
pub fn list_text(servers: &[Server], status: &HashMap<String, usize>, errors: &[(String, String)], busy: bool) -> String {
if servers.is_empty() {
return "還沒有連接器(設定 › 整合 › 連接器 是空的)。用 action=add 新增。".into();
}
let mut out = String::from("連接器(大腦的 設定 › 整合 › 連接器):");
for s in servers {
let state = if !s.enabled {
"已關閉".to_string()
} else if let Some(n) = status.get(&s.name) {
format!("已連上,{n} 個工具")
} else if let Some((_, e)) = errors.iter().find(|e| e.0 == s.name) {
format!("連不上:{e}")
} else if busy {
"連線中…".into()
} else {
"未連線".into()
};
out.push_str(&format!("\n- {}:{state}\n {}", s.name, server_lines(s).join("\n ")));
}
out
}
/// How the change came out, once the connector has had its chance to connect.
pub fn connected_text(name: &str, status: &HashMap<String, usize>, errors: &[(String, String)]) -> Option<(String, bool)> {
if let Some(n) = status.get(name) {
let names: Vec<String> = tools().iter().filter(|t| t.server == name).take(8).map(|t| t.name.clone()).collect();
let more = if *n > names.len() { "…" } else { "" };
return Some((format!("「{name}」已連上,{n} 個工具({}{more})。從下一步起就能用(工具多時先用 {FIND_TOOL} 找)。", names.join("、")), true));
}
errors.iter().find(|e| e.0 == name).map(|(_, e)| (format!("「{name}」連不上:{e}\n設定已經存好了:修好原因後用 action=update 改,或 action=reconnect 再試。"), false))
}
/// 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"}}] + ([{"name": "slow", "description": "Take three seconds", "inputSchema": {"type": "object"}}] if os.environ.get("FAKE_SLOW") else [])}
elif m["method"] == "tools/call" and m["params"]["name"] == "quit":
sys.exit(0)
elif m["method"] == "tools/call" and m["params"]["name"] == "slow":
import time
time.sleep(3)
r = {"content": [{"type": "text", "text": "slow done"}]}
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("npx", &s(&["-y", "x", "/Users-nobody-here/someone/Documents"])), Some("/Users-nobody-here/someone/Documents"));
// A server in a container or on another host: its paths are there, not here.
assert_eq!(missing_folder("docker", &s(&["exec", "-i", "box", "/home-nobody-here/bot/.local/bin/cua-driver", "mcp"])), None);
assert_eq!(missing_folder("/usr/bin/ssh", &s(&["host", "/opt-nobody-here/srv/mcp"])), None);
let tmp = std::env::temp_dir().join("anybot-mcp-new-file.json");
assert_eq!(missing_folder("npx", &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: /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); from the openapimcp repo run
/// `./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 = crate::net::config().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 = crate::net::config().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);
}
}
#[cfg(test)]
mod manage_tests {
use super::*;
fn gitlab() -> String {
json!({"action": "add", "name": "gitlab", "command": "npx -y @zereight/mcp-gitlab@2.3.28", "env": {"GITLAB_PERSONAL_ACCESS_TOKEN": "glpat-SECRET", "GITLAB_API_URL": "https://gitlab.example.com/api/v4"}, "instructions": "查 MR 先用 list_merge_requests"}).to_string()
}
/// 管理連接器: an add lands as the form would make it; the card shows what runs and where,
/// never the secret.
#[test]
fn a_connector_added_from_chat_is_what_the_form_makes() {
let c = parse_change(&gitlab(), &[]).unwrap();
let Change::Add(s) = &c else { panic!("{c:?}") };
assert_eq!((s.command.as_str(), s.args.clone()), ("npx", vec!["-y".to_string(), "@zereight/mcp-gitlab@2.3.28".into()]));
assert!(s.enabled && s.url.is_empty());
assert_eq!(s.env["GITLAB_PERSONAL_ACCESS_TOKEN"], "glpat-SECRET");
let q = change_question(&c).unwrap();
assert!(q.contains("新增連接器「gitlab」") && q.contains("指令(在大腦上執行):npx -y @zereight/mcp-gitlab@2.3.28"), "{q}");
assert!(q.contains("GITLAB_PERSONAL_ACCESS_TOKEN=••••(已填)") && q.contains("GITLAB_API_URL=https://gitlab.example.com/api/v4"), "{q}");
assert!(!q.contains("glpat-SECRET"), "{q}");
let mut list = vec![];
assert_eq!(apply_change(&c, &mut list), "已新增連接器「gitlab」,正在連線。");
assert_eq!(list.len(), 1);
// Remote, with a header given as one line; its secret hidden too.
let r = parse_change(&json!({"action": "add", "name": "notion", "url": "https://mcp.example.com/mcp", "headers": "Authorization: Bearer abc"}).to_string(), &list).unwrap();
let Change::Add(n) = &r else { panic!() };
assert_eq!((n.url.as_str(), n.headers["Authorization"].as_str(), n.command.as_str()), ("https://mcp.example.com/mcp", "Bearer abc", ""));
assert!(change_question(&r).unwrap().contains("Authorization: ••••(已填)"));
}
#[test]
fn a_change_that_cant_be_made_says_why_before_asking() {
let list = vec![fake_server("gitlab", 0)];
let err = |a: Value| parse_change(&a.to_string(), &list).unwrap_err();
assert!(err(json!({"action": "add", "name": "GitLab", "command": "x"})).contains("已經有叫「gitlab」"));
assert!(err(json!({"action": "add", "name": "x"})).contains("command"));
assert!(err(json!({"action": "add", "name": "x", "command": "a", "url": "https://b"})).contains("只能給一個"));
assert!(err(json!({"action": "add", "name": "x", "url": "ftp://b"})).contains("http"));
assert!(err(json!({"action": "add", "name": "x", "url": "https://b/{tenant}"})).contains("{…}"));
assert!(err(json!({"action": "remove", "name": "nope"})).contains("現有的:gitlab"));
assert!(err(json!({"action": "update", "name": "gitlab"})).contains("沒有要改的"));
assert!(err(json!({"action": "zap"})).contains("list"));
assert!(parse_change("{}", &[]).is_ok_and(|c| c == Change::List));
// {username} and {password} are slots, not leftovers.
assert!(parse_change(&json!({"action": "add", "name": "scc", "command": "scc-mcp --user {username}", "username": "amy", "password": "pw"}).to_string(), &list).is_ok());
}
#[test]
fn an_update_turns_off_moves_and_forgets_the_old_password() {
let mut list = vec![Server { password: "old".into(), username: "amy".into(), ..fake_server("scc", 0) }];
let off = parse_change(&json!({"action": "update", "name": "scc", "enabled": false}).to_string(), &list).unwrap();
assert!(change_question(&off).unwrap().contains("關閉"));
assert_eq!(apply_change(&off, &mut list), "已關閉連接器「scc」。");
assert!(!list[0].enabled && list[0].password == "old");
let moved = parse_change(&json!({"action": "update", "name": "scc", "url": "https://new.example.com/mcp", "enabled": true}).to_string(), &list).unwrap();
let q = change_question(&moved).unwrap();
assert!(q.contains("網址:https://new.example.com/mcp") && q.contains("拿掉 指令") && q.contains("密碼清掉") && q.contains("打開"), "{q}");
apply_change(&moved, &mut list);
assert!(list[0].command.is_empty() && list[0].password.is_empty() && list[0].username == "amy");
let gone = parse_change(&json!({"action": "remove", "name": "scc"}).to_string(), &list).unwrap();
assert!(change_question(&gone).unwrap().contains("移除連接器「scc」"));
apply_change(&gone, &mut list);
assert!(list.is_empty());
assert!(change_question(&parse_change(&json!({"action": "list"}).to_string(), &list).unwrap()).is_none());
}
#[test]
fn the_list_says_how_each_stands_without_secrets() {
let mut a = fake_server("calc", 0);
a.env.insert("API_KEY".into(), "k-123".into());
let b = Server { enabled: false, ..fake_server("off", 0) };
let c = fake_server("broken", 0);
let status: HashMap<String, usize> = [("calc".to_string(), 2)].into_iter().collect();
let t = list_text(&[a, b, c], &status, &[("broken".into(), "找不到 npx".into())], false);
assert!(t.contains("- calc:已連上,2 個工具") && t.contains("- off:已關閉") && t.contains("- broken:連不上:找不到 npx"), "{t}");
assert!(t.contains("API_KEY=••••(已填)") && !t.contains("k-123"));
assert!(list_text(&[], &status, &[], false).contains("還沒有連接器"));
assert!(connected_text("broken", &status, &[("broken".into(), "x".into())]).is_some_and(|(t, ok)| !ok && t.contains("action=update")));
assert!(connected_text("nope", &status, &[]).is_none());
}
}
#[cfg(test)]
mod stop_tests {
use super::*;
/// E5: 停止 ends a connector call at once (it used to wait up to two minutes for the server).
#[test]
fn a_stop_ends_a_connector_call_at_once() {
let _l = test_lock();
sync(&[]);
let mut slow = fake_server("slowpoke", 0);
slow.env.insert("FAKE_SLOW".into(), "1".into());
assert!(sync(&[slow]).is_empty());
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let c2 = cancel.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(300));
c2.store(true, std::sync::atomic::Ordering::Relaxed);
});
let t0 = std::time::Instant::now();
let (text, ok, _) = call_until(&tool_name("slowpoke", "slow"), "{}", &cancel);
assert!(!ok && text == STOPPED, "{text}");
assert!(t0.elapsed() < Duration::from_secs(2), "{:?}", t0.elapsed());
// The server is still there for the next call (its late answer is skipped).
assert_eq!(call(&tool_name("slowpoke", "add"), r#"{"a": 1, "b": 2}"#).0.trim(), "sum=3");
sync(&[]);
}
/// E5: a connector started through a launcher (npx, uvx, sh) is ended with everything it
/// started — the real server under the launcher used to stay running.
#[cfg(unix)]
#[test]
fn a_connector_ends_with_what_it_started() {
let _l = test_lock();
sync(&[]);
let mut s = fake_server("launched", 0);
let marker = format!("sleep {}", 4000 + std::process::id() % 1000);
let inner = std::iter::once(s.command.clone()).chain(s.args.iter().cloned()).collect::<Vec<_>>().join(" ");
s.command = "sh".into();
s.args = vec!["-c".into(), format!("{marker} & exec {inner}")];
assert!(sync(&[s]).is_empty());
let running = || std::process::Command::new("pgrep").args(["-f", &marker]).output().map(|o| !o.stdout.is_empty()).unwrap_or(false);
assert!(running(), "the launcher's child runs while connected");
forget("launched");
let t0 = std::time::Instant::now();
while running() && t0.elapsed() < Duration::from_secs(5) {
std::thread::sleep(Duration::from_millis(100));
}
assert!(!running(), "still running after the connector was ended: {marker}");
sync(&[]);
}
}