diff --git a/deploy/server/Dockerfile b/deploy/server/Dockerfile index 0eea7c6..22e72ee 100644 --- a/deploy/server/Dockerfile +++ b/deploy/server/Dockerfile @@ -18,9 +18,17 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ && cp target/release/anybot /anybot FROM debian:bookworm-slim +# nodejs/npm (npx) and python3 + uv (uvx): the 連接器 (MCP servers) the bots use run here, at the +# brain, and the market's are started with `npx -y …` or `uvx …`. Without them every such +# connector failed to start and the bots had none of their tools. RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git ripgrep poppler-utils docker.io openssh-client libasound2 \ + nodejs npm python3 \ && rm -rf /var/lib/apt/lists/* +COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /uvx /usr/local/bin/ COPY --from=build /anybot /usr/local/bin/anybot ENV ANYBOT_DATA_DIR=/data +# What npx and uvx download stays on the data volume: a rebuilt brain starts its connectors +# without fetching them all again. +ENV NPM_CONFIG_CACHE=/data/cache/npm UV_CACHE_DIR=/data/cache/uv UV_PYTHON_INSTALL_DIR=/data/cache/uv-python VOLUME /data CMD ["anybot", "--serve"] diff --git a/mobile/index.html b/mobile/index.html index e56a9a0..a6ad7f1 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1973,7 +1973,7 @@ function drawSettings(kind, quiet) { if (kind === "integrations") { const dot = (ok, on) => ``; h += group("訊息管道", (st.channels || []).map((c) => `
${dot(c.ok, c.enabled)}
${esc(c.kind)} · ${esc(c.name)}
由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}
${isOwner() ? `` : ""}
`).join("") || `
還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。
`); - h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : "")); + h += group("連接器(MCP)", ((st.mcp || []).map((m) => `
${dot(m.tools != null, m.enabled)}
${esc(m.name)}
${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}
${isOwner() ? `${m.enabled ? `` : ""}` : ""}
`).join("") || `
還沒有連接器
`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : "")); const skRows = (st.skills || []).map((k, i) => { const tags = [...(k.resources && k.resources.length ? [`${k.resources.length} 檔`] : []), ...(k.steps ? [`可重播 ${k.steps} 步`] : [])].join(" · "); return `
${esc(k.name)}${tags ? ` ${esc(tags)}` : ""}
${esc(k.description)}
${isOwner() ? `` : ""}
`; @@ -2095,6 +2095,7 @@ function wireSettings(kind, st) { on("[data-ch]", "onchange", async (x) => { if (!await act("channel", {id: +x.dataset.ch, enabled: x.checked})) x.checked = !x.checked; else again(); }); on("[data-chrm]", "onclick", async (x) => { if (await confirmSheet("移除這個管道?", "", "移除") && await act("channel", {id: +x.dataset.chrm, remove: true}, "已移除")) again(); }); on("[data-mcp]", "onchange", async (x) => { if (!await act("mcp", {name: x.dataset.mcp, enabled: x.checked})) x.checked = !x.checked; else again(); }); + on("[data-mcpre]", "onclick", async (x) => { if (await act("mcp", {name: x.dataset.mcpre, reconnect: true}, "重新連線中…")) { again(); setTimeout(again, 4000); } }); on("[data-mcprm]", "onclick", async (x) => { if (await confirmSheet("移除這個連接器?", "", "移除") && await act("mcp", {name: x.dataset.mcprm, remove: true}, "已移除")) again(); }); on("[data-prov]", "onclick", (x) => { const p = st.providers[+x.dataset.prov]; diff --git a/src/agent.rs b/src/agent.rs index 3e22ce7..f19cbfa 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -2000,12 +2000,28 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< finish(&mut history, &output, status, None); continue; } + // Connectors with many tools: finding one is only a look at their list. + if call.name == crate::mcp::FIND_TOOL { + started(); + let out = crate::mcp::find(&call.args); + finish(&mut history, &out, ToolStatus::Done, None); + continue; + } // MCP connectors: asked once per server (or always allowed), like the original's - // MCP allow-list; direct mode doesn't ask. - if crate::mcp::is_mcp_tool(&call.name) { - let (server, tool) = crate::mcp::resolve(&call.name).unwrap_or_default(); + // MCP allow-list; direct mode doesn't ask. A tool run through use_connector_tool + // is that tool: the same question, the same call. + let mcp_step = if crate::mcp::is_mcp_tool(&call.name) { Some(Ok((call.name.clone(), call.args.clone()))) } else { crate::mcp::unwrap_use(&call.name, &call.args) }; + if let Some(step) = mcp_step { + let (mcp_name, mcp_args) = match step { + Ok(x) => x, + Err(e) => { + finish(&mut history, &e, ToolStatus::Failed, None); + continue; + } + }; + let (server, tool) = crate::mcp::resolve(&mcp_name).unwrap_or_default(); let grant = format!("mcp:{server}"); - let args_short: String = call.args.chars().take(160).collect(); + let args_short: String = mcp_args.chars().take(160).collect(); let mut allowed = job.direct.load(Ordering::Relaxed) || grants.contains(&grant); if !allowed { match ask_person(ApprovalKind::Action, format!("使用連接器「{server}」的工具:{tool} {args_short}"), grant.clone()) { @@ -2022,7 +2038,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } let (output, status, img) = if allowed { started(); - let (o, ok, img) = crate::mcp::call(&call.name, &call.args); + let (o, ok, img) = crate::mcp::call(&mcp_name, &mcp_args); (o, if ok { ToolStatus::Done } else { ToolStatus::Failed }, img) } else { ("使用者拒絕了這個操作。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事;告訴他你停在哪裡,問他想怎麼做。".to_string(), ToolStatus::Denied, None) @@ -2853,6 +2869,89 @@ mod tests { assert!(!shown.iter().any(|(_, t)| t.contains("快速模型")), "the set-aside answer was never shown: {shown:?}"); } + /// A connector with many tools, end to end: the model gets only find + use, finds the tool, + /// runs it through use_connector_tool, and the person is asked first, as for the tool itself. + #[test] + fn a_bot_finds_and_runs_a_connector_tool() { + use std::io::{Read, Write}; + let _one = crate::mcp::test_lock(); + assert!(crate::mcp::sync(&[crate::mcp::fake_server("calc-e2e", 30)]).is_empty()); + let full = crate::mcp::tool_name("calc-e2e", "add"); + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let offered = Arc::new(Mutex::new(Vec::>::new())); + let seen = offered.clone(); + let use_args = serde_json::json!({"tool": full, "arguments": {"a": 2, "b": 40}}).to_string(); + std::thread::spawn(move || { + let tool = |id: &str, name: &str, args: String| serde_json::json!({"tool_calls": [{"index": 0, "id": id, "function": {"name": name, "arguments": args}}]}); + let replies = [ + tool("f", crate::mcp::FIND_TOOL, serde_json::json!({"query": "add numbers"}).to_string()), + tool("u", crate::mcp::USE_TOOL, use_args), + serde_json::json!({"content": "是 42"}), + ]; + for delta in replies { + let (mut s, _) = l.accept().unwrap(); + let mut req = Vec::new(); + let mut buf = [0u8; 16384]; + let body = loop { + let n = s.read(&mut buf).unwrap_or(0); + if n == 0 { + break String::new(); + } + req.extend_from_slice(&buf[..n]); + let t = String::from_utf8_lossy(&req).to_string(); + if let Some(end) = t.find("\r\n\r\n") { + let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); + if req.len() >= end + 4 + len { + break t[end + 4..].to_string(); + } + } + }; + let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); + seen.lock().unwrap().push(v["tools"].as_array().into_iter().flatten().filter_map(|t| t["function"]["name"].as_str().or(t["name"].as_str()).map(String::from)).collect()); + let out = format!("data: {}\n\ndata: [DONE]\n\n", serde_json::json!({"choices": [{"delta": delta}]})); + let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n"); + let _ = s.write_all(out.as_bytes()); + } + }); + let w = std::env::temp_dir().join(format!("anybot-mcp-e2e-{}", std::process::id())); + std::fs::create_dir_all(&w).unwrap(); + let job = Job { + req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("2 加 40 是多少?用計算機")], tools: crate::mcp::specs(), session: String::new() }, + computers: vec![tools::Target { name: crate::model::THIS_COMPUTER_NAME.into(), place: tools::Place::Local { workdir: w.clone() } }], + default_computer: crate::model::THIS_COMPUTER_NAME.into(), + local_execution: true, + tools_enabled: true, + direct: Arc::new(AtomicBool::new(false)), + ..test_job() + }; + let (tx, rx) = channel(); + spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default()); + let (mut asked, mut results, mut last) = (vec![], vec![], String::new()); + loop { + match rx.recv_timeout(Duration::from_secs(20)).expect("loop stalled") { + (_, StreamEvent::NeedApproval(a)) => { + asked.push(a.reason.clone()); + let _ = a.reply.send(ApprovalAnswer::Once); + } + (_, StreamEvent::ToolResult(m)) => results.push(m.text.clone()), + (_, StreamEvent::StepDone(m)) => last = m.text.clone(), + (_, StreamEvent::Done) => break, + (_, StreamEvent::Error(e)) => panic!("{e}"), + _ => {} + } + } + crate::mcp::sync(&[]); + let first = offered.lock().unwrap()[0].clone(); + assert!(first.contains(&crate::mcp::FIND_TOOL.to_string()) && first.contains(&crate::mcp::USE_TOOL.to_string()), "{first:?}"); + assert!(!first.iter().any(|n| n.starts_with(crate::mcp::PREFIX)), "the 32 tools themselves didn't ride along: {first:?}"); + assert_eq!(asked.len(), 1, "finding asks nothing; running asks once: {asked:?}"); + assert!(asked[0].contains("calc-e2e") && asked[0].contains("add"), "{asked:?}"); + assert!(results[0].contains(&full), "found: {results:?}"); + assert!(results[1].contains("sum=42"), "ran: {results:?}"); + assert_eq!(last, "是 42"); + } + /// AppleScript run outside the sandbox drives the person's apps: asked the first time even /// in direct mode, and not again once they chose 「一律允許」. #[test] diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index b127cae..b610264 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -5,6 +5,9 @@ use super::*; use crate::channels::{self, Channel, Incoming, Kind, ReplyTo}; use std::collections::VecDeque; +/// How long a connector that is on but not connected waits before it is tried again. +const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(60); + pub struct ChannelUi { pub tx: Sender, pub rx: Receiver, @@ -27,9 +30,12 @@ pub struct ChannelUi { new_tenant: String, /// Teams sign-in: the code to show, and the refresh token when done. ms_login: Arc)>>, - mcp_sig: String, + pub(super) mcp_sig: String, pub(super) mcp_errors: Arc>>, - mcp_busy: Arc, + pub(super) mcp_busy: Arc, + /// When the servers were last connected (one that is on but not connected is tried again + /// a minute later). + mcp_tried: Option, new_mcp: (String, String, String, String), /// What the form needs from the person, for a server picked from the 公用市集. new_mcp_hint: String, @@ -58,7 +64,7 @@ impl Default for ChannelUi { fn default() -> Self { let (tx, rx) = channel(); let (trig_tx, trig_rx) = channel(); - ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), sub: 0, adding: false, focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), focus_form: false, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } + ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), mcp_tried: None, new_mcp: Default::default(), sub: 0, adding: false, focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), focus_form: false, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } } } @@ -407,13 +413,23 @@ impl App { // ---------- 連接器 (MCP) ---------- impl App { - /// Connect the configured MCP servers when they change (in the background). + /// Connect the configured MCP servers when they change (in the background), and once a + /// minute again the ones that are on but not connected: a server that wasn't up yet, or whose + /// link died, used to stay down until its settings were changed. fn mcp_poll(&mut self, ctx: &egui::Context) { + if self.ch.mcp_busy.load(Ordering::SeqCst) { + return; + } let sig = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default(); - if sig == self.ch.mcp_sig || self.ch.mcp_busy.load(Ordering::SeqCst) { + let retry = self.ch.mcp_tried.is_some_and(|t| t.elapsed() >= MCP_RETRY) && { + let up = crate::mcp::status(); + self.state.mcp_servers.iter().any(|s| s.enabled && !up.contains_key(&s.name)) + }; + if sig == self.ch.mcp_sig && !retry { return; } self.ch.mcp_sig = sig; + self.ch.mcp_tried = Some(Instant::now()); let servers = self.state.mcp_servers.clone(); let (errs, busy, c) = (self.ch.mcp_errors.clone(), self.ch.mcp_busy.clone(), ctx.clone()); busy.store(true, Ordering::SeqCst); @@ -424,6 +440,29 @@ impl App { }); } + /// 重新連線 (here, or asked by a screen or the phone): drop the server's link and connect it + /// again now; its line says 連線中… until the answer. + pub(super) fn mcp_reconnect(&mut self, name: &str) { + crate::mcp::forget(name); + self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != name); + self.ch.mcp_sig.clear(); + } + + /// The servers' state as 連接器 shows it: {servers: {name: {tools, error}}, busy, tools: + /// [[server, tool, description]]}. A screen gets the brain's (its own would say 未連線). + pub(super) fn mcp_state(&self) -> serde_json::Value { + let status = crate::mcp::status(); + let errors = self.ch.mcp_errors.lock().unwrap().clone(); + let servers: serde_json::Map = self + .state + .mcp_servers + .iter() + .map(|s| (s.name.clone(), serde_json::json!({"tools": status.get(&s.name), "error": errors.iter().find(|e| e.0 == s.name).map(|e| e.1.clone())}))) + .collect(); + let tools: Vec = crate::mcp::tools().iter().take(60).map(|t| serde_json::json!([t.server, t.name, t.description.chars().take(300).collect::()])).collect(); + serde_json::json!({"servers": servers, "busy": self.ch.mcp_busy.load(Ordering::SeqCst), "tools": tools}) + } + /// 連接器 (`part` 1: the servers, their tools, the markets, the form) and 技能 (`part` 2). pub(super) fn connectors_page(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, part: u8) { let p = self.pal; @@ -433,16 +472,20 @@ impl App { setting_title(ui, "連接器(MCP)", "接上 Model Context Protocol 伺服器,Bot 就能用它的工具(例如 GitHub、Notion、資料庫、你公司的內部系統)。每個連接器第一次被使用時會先問你。", p); hint(ui, "本機伺服器填指令(例如 npx -y @modelcontextprotocol/server-filesystem ~/Documents);遠端伺服器填網址(Streamable HTTP),需要時加上 Authorization 標頭。", p); }); - let status = crate::mcp::status(); - let errors = self.ch.mcp_errors.lock().unwrap().clone(); - let busy = self.ch.mcp_busy.load(Ordering::SeqCst); + // On a screen the servers run at the brain: its state, not this computer's. + let st = if self.mir.on { self.mir.mcp_state.clone() } else { self.mcp_state() }; + let busy = st["busy"].as_bool().unwrap_or(false); + // (「這台電腦沒有 Node.js」 from the brain means the brain, not the computer in front.) + let at = if self.mir.on { "在大腦上:" } else { "" }; let mut remove = None; + let mut reconnect = None; for (i, s) in self.state.mcp_servers.iter_mut().enumerate() { setting_card(ui, p, |ui| { - let (col, text) = match (s.enabled, status.get(&s.name), errors.iter().find(|e| e.0 == s.name)) { + let one = &st["servers"][s.name.as_str()]; + let (col, text) = match (s.enabled, one["tools"].as_u64(), one["error"].as_str()) { (false, _, _) => (p.text3, "已關閉".to_string()), (_, Some(n), _) => (Color32::from_rgb(0x14, 0xc3, 0x70), format!("已連上,{n} 個工具")), - (_, _, Some(e)) => (p.danger, e.1.clone()), + (_, _, Some(e)) => (p.danger, format!("{at}{e}")), _ if busy => (p.text3, "連線中…".to_string()), _ => (p.text3, "未連線".to_string()), }; @@ -454,6 +497,9 @@ impl App { remove = Some(i); } ui.add(computers_ui::toggle(&mut s.enabled)).on_hover_text(t("開啟")); + if s.enabled && ui.add(egui::Button::new(RichText::new(t("重新連線")).size(12.0).color(p.text2)).frame(false)).on_hover_text(t("再連一次,看連不連得上")).clicked() { + reconnect = Some(name.clone()); + } }, |ui| { ui.label(RichText::new(&name).strong().family(crate::bold()).size(FONT_BASE)); @@ -471,12 +517,20 @@ impl App { if let Some(i) = remove { self.state.mcp_servers.remove(i); } - let tools = crate::mcp::tools(); + if let Some(name) = reconnect { + if self.mir.on { + self.mirror_mcp_reconnect(&name); + } else { + self.mcp_reconnect(&name); + } + } + let tools: Vec<&serde_json::Value> = st["tools"].as_array().into_iter().flatten().collect(); if !tools.is_empty() { setting_card(ui, p, |ui| { setting_title(ui, "可以用的工具", "", p); - for t in tools.iter().take(60) { - ui.label(RichText::new(format!("{} · {}", t.server, t.name)).size(FONT_XS).color(p.text2)).on_hover_text(&t.description); + for t in tools { + let s = |i: usize| t[i].as_str().unwrap_or(""); + ui.label(RichText::new(format!("{} · {}", s(0), s(1))).size(FONT_XS).color(p.text2)).on_hover_text(s(2)); } }); } diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs index 1180b68..7a89409 100644 --- a/src/app/chat_ui.rs +++ b/src/app/chat_ui.rs @@ -184,8 +184,10 @@ fn doing(name: &str, args: &str, place: Option<&str>) -> String { crate::macapps::SEND_MESSAGE => "正在傳訊息".into(), tools::HANDOFF_TOOL => "正在等你接手".into(), crate::ask::TOOL => "正在等你回答".into(), - // mcp____: the connector by its name. + // mcp____: the connector by its name (also when run through use_connector_tool). n if n.starts_with(crate::mcp::PREFIX) => with("正在用連接器", n[crate::mcp::PREFIX.len()..].split("__").next().unwrap_or("").to_string()), + crate::mcp::USE_TOOL => with("正在用連接器", s("tool").strip_prefix(crate::mcp::PREFIX).and_then(|r| r.split("__").next()).unwrap_or("").to_string()), + crate::mcp::FIND_TOOL => "正在找連接器的工具".into(), n => match crate::remote::tool_label(n) { "工具" | "App 操作" | "網頁" | "瀏覽器" | "Mac App" => "正在處理".into(), l => format!("正在{l}"), diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index e2fbcdf..2950559 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -409,6 +409,8 @@ enum Out { Move { ops: Vec, n: usize, skills: Vec }, /// 技能 on a screen: done at the brain (see [`App::mirror_skill`]); the answer goes to `note`. Skill { body: Value, note: SkillNote, busy: Arc }, + /// 連接器 › 重新連線 on a screen: the servers run at the brain. + McpReconnect(String), } /// Where a skill request's answer is shown: (worked, words). @@ -485,6 +487,8 @@ pub struct Mirror { pub(super) box_state: Value, /// Each bot's computers on the brain, by bot id: {names: [{name, kind}], current, missing}. pub(super) computers: HashMap, + /// The connectors at the brain, as [`App::mcp_state`] gives them. + pub(super) mcp_state: Value, /// When each bot's last turn ended, as last heard (a newer one ending well is read aloud). settled: HashMap, } @@ -637,6 +641,8 @@ impl App { json!({"bot": id, "call_id": a.call_id, "tool": a.tool, "reason": a.reason, "grant": a.grant, "kind": kind}) }) .collect(); + // The connectors run here too: whether each is connected, or why not. + out["mcp"] = self.mcp_state(); // The bots' computer lives here; a screen shows its state, not its own computer's. let run = crate::cloudbox::run_state(); out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy()}); @@ -1149,6 +1155,9 @@ impl App { if v["box"].is_object() { self.mir.box_state = v["box"].clone(); } + if v["mcp"].is_object() { + self.mir.mcp_state = v["mcp"].clone(); + } if let Some(c) = v["computers"].as_object() { self.mir.computers = c.iter().filter_map(|(k, x)| Some((k.parse().ok()?, x.clone()))).collect(); } @@ -1259,6 +1268,11 @@ impl App { *err.lock().unwrap() = format!("大腦沒有收到:{e}"); } } + Out::McpReconnect(name) => { + if let Err(e) = remote::sync_post(&s, "mcp", &json!({"name": name})) { + *err.lock().unwrap() = format!("大腦沒有重新連線:{e}"); + } + } Out::Send { bot, text, atts, memories } => { let mut paths = vec![]; for a in &atts { @@ -1316,6 +1330,20 @@ impl App { self.mirror_out(Out::Act(body)); } + /// 連接器 › 重新連線 on a screen: the brain connects it again; its line says 連線中… until + /// the brain's next word on it. + pub(super) fn mirror_mcp_reconnect(&mut self, name: &str) { + if !self.mir.online { + *self.mir.error.lock().unwrap() = "連不到大腦,現在只能看。".into(); + return; + } + if self.mir.mcp_state["servers"].is_object() { + self.mir.mcp_state["servers"][name] = json!({}); + } + self.mir.mcp_state["busy"] = json!(true); + self.mirror_out(Out::McpReconnect(name.to_string())); + } + /// 技能 on a screen — add one from the market, install from an address or a folder here, /// delete one — is done by the brain: the bots read skills from the brain's disk, and a /// folder left there would bring a deleted skill back when the brain restarts. Turning one @@ -1377,9 +1405,11 @@ impl App { ops.push(json!({"op": "bot_add", "bot": v})); } let top = serde_json::to_value(&local).unwrap_or(Value::Null); - for k in ["providers", "mcp_servers"] { - ops.push(json!({"op": "merge", "key": k, "value": top[k]})); - } + ops.push(json!({"op": "merge", "key": "providers", "value": top["providers"]})); + // Connectors run at the brain: one that names this computer's own folders (e.g. + // 「files」 on ~/Documents) would fail there, so it stays here. + let servers: Vec<&crate::mcp::Server> = local.mcp_servers.iter().filter(|s| !crate::mcp::names_this_computer(s)).collect(); + ops.push(json!({"op": "merge", "key": "mcp_servers", "value": servers})); // Skills the brain doesn't have yet go up with their files (a bare entry in the list // would leave its scripts on this computer). let skills: Vec = local.skills.iter().filter(|k| !self.state.skills.iter().any(|b| b.name == k.name)).cloned().collect(); diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs index b2c22a2..cdda6a6 100644 --- a/src/app/remote_ui.rs +++ b/src/app/remote_ui.rs @@ -268,6 +268,11 @@ impl App { (id, online).hash(&mut h); } crate::cloudbox::run_state().label().hash(&mut h); + // A connector connected or failing: screens and phones hear of it now, not at the next + // long poll's end. + let mut up: Vec<(String, usize)> = crate::mcp::status().into_iter().collect(); + up.sort(); + (up, self.ch.mcp_errors.lock().unwrap().clone(), self.ch.mcp_busy.load(Ordering::SeqCst)).hash(&mut h); for pg in &self.state.pages { (pg.id, pg.revision, pg.updated, &pg.title).hash(&mut h); } @@ -1321,6 +1326,10 @@ impl App { if !self.state.mcp_servers.iter().any(|m| m.name == name) { return fail("找不到這個連接器"); } + if b["reconnect"].as_bool().unwrap_or(false) { + self.mcp_reconnect(&name); + return done("重新連線中…"); + } // (mcp_poll connects or drops it when the list changes.) if b["remove"].as_bool().unwrap_or(false) { self.state.mcp_servers.retain(|m| m.name != name); @@ -1667,6 +1676,20 @@ mod phone_act_tests { assert!(app.phone_act(&ctx, "mcp", &add("x", "https://{host}/mcp", ""), "owner")["error"].is_string()); assert!(app.phone_act(&ctx, "mcp", &add("x", "npx -y evil", ""), "owner")["error"].is_string()); assert!(app.phone_act(&ctx, "mcp", &add("x", "https://y.example/mcp", ""), "admin")["error"].is_string()); + + // 重新連線: its old error goes, and the next poll connects it again (owner only). + app.ch.mcp_errors.lock().unwrap().push(("Smithery".into(), "連不上".into())); + app.ch.mcp_sig = "connected before".into(); + assert!(app.phone_act(&ctx, "mcp", &json!({"name": "Smithery", "reconnect": true}), "admin")["error"].is_string()); + let r = app.phone_act(&ctx, "mcp", &json!({"name": "Smithery", "reconnect": true}), "owner"); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ch.mcp_errors.lock().unwrap().is_empty() && app.ch.mcp_sig.is_empty()); + assert!(app.state.mcp_servers.iter().any(|m| m.name == "Smithery"), "reconnecting keeps it"); + // What 連接器 shows (here, and at a screen of this brain). + app.ch.mcp_errors.lock().unwrap().push(("Smithery 2".into(), "HTTP 401".into())); + let st = app.mcp_state(); + assert_eq!(st["servers"]["Smithery 2"]["error"], "HTTP 401"); + assert!(st["servers"]["Smithery"]["tools"].is_null() && st["servers"]["Smithery"]["error"].is_null()); } #[test] diff --git a/src/i18n_table.rs b/src/i18n_table.rs index df9c204..b0e59e0 100644 --- a/src/i18n_table.rs +++ b/src/i18n_table.rs @@ -641,6 +641,8 @@ pub const ROWS: &[(&str, &str, &str)] = &[ ("你好,我是你的 Bot。", "Hi, I'm your bot.", "こんにちは、あなたの Bot です。"), ("在大腦「{name}」上", "On the brain “{name}”", "ブレイン「{name}」上"), ("連線中…", "Connecting…", "接続中…"), + ("重新連線", "Reconnect", "再接続"), + ("再連一次,看連不連得上", "Connect again to see whether it works", "もう一度接続して、つながるか確かめます"), ("看「{name}」的螢幕,也可以取得控制權自己操作", "Watch the screen of “{name}”; you can also take control", "「{name}」の画面を見ます。操作を代わることもできます"), ("叫醒「{name}」並看它的螢幕", "Wake “{name}” and watch its screen", "「{name}」を起こして画面を見ます"), ("要 {name} 在哪台電腦做事", "Which computer {name} works on", "{name} が作業するコンピューター"), diff --git a/src/mcp.rs b/src/mcp.rs index f452f5e..a004714 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -17,6 +17,13 @@ pub const PROTOCOL: &str = "2025-06-18"; pub const CALL_TIMEOUT_SECS: u64 = 120; /// Tool names the model sees: mcp____, 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 { @@ -63,6 +70,20 @@ enum Link { 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 { @@ -188,6 +209,9 @@ impl Live { 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)); } @@ -217,7 +241,33 @@ impl Live { } } +/// 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>>; + fn connect(s: &Server) -> Result { + let mut errlog: Option = None; let link = if !s.url.trim().is_empty() { let u = s.url.trim(); if crate::web::is_forbidden_browser_url(u) { @@ -228,6 +278,9 @@ fn connect(s: &Server) -> Result { 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); @@ -238,11 +291,35 @@ fn connect(s: &Server) -> Result { .env("PATH", crate::cloudbox::tool_path()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) - .stderr(Stdio::null()) + .stderr(Stdio::piped()) .spawn() - .map_err(|e| format!("無法啟動「{}」:{e}", s.command))?; + .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); std::thread::spawn(move || { let mut reader = BufReader::new(stdout); @@ -262,7 +339,25 @@ fn connect(s: &Server) -> Result { }); Link::Stdio { child, stdin, rx } }; - let mut live = Live { link, next_id: 1 }; + let mut live = Live { link, next_id: 1, expired: false }; + match handshake(&mut live, &s.name) { + Ok(tools) => Ok(Conn { live: Mutex::new(live), tools, config: s.clone() }), + Err(e) => { + // A server that didn't come up is ended (retried each minute, it 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 = 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 (all pages). +fn handshake(live: &mut Live, server: &str) -> Result, String> { live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?; live.notify("notifications/initialized"); let mut tools = vec![]; @@ -270,14 +365,22 @@ fn connect(s: &Server) -> Result { 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: s.name.clone(), name: t["name"].as_str().unwrap_or("").into(), description: t["description"].as_str().unwrap_or("").into(), schema: t["inputSchema"].clone() }); + 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(Conn { live: Mutex::new(live), tools, config: s.clone() }) + Ok(tools) +} + +/// 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. @@ -316,6 +419,21 @@ pub fn sync(servers: &[Server]) -> Vec<(String, String)> { 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 { conns().lock().unwrap().values().flat_map(|c| c.tools.clone()).collect() @@ -325,15 +443,114 @@ pub fn status() -> HashMap { conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.len())).collect() } -/// Tool specs for the model. +/// 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::()), "parameters": schema}) +} + +/// The connected servers' tools in a steady order (server, then tool). +fn sorted_tools() -> Vec { + 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 { - tools() - .into_iter() + 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::>().join(", "))).collect::>().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 = 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| { - 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::()), "parameters": schema}) + // 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) }) - .collect() + .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 = 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::().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> { + 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. @@ -379,7 +596,16 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { let ok = r["isError"].as_bool() != Some(true); (crate::tools::head_tail(text.trim()), ok, image) } - Err(e) => (e, false, None), + 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 app connects it again. + if live.dead() { + drop(live); + forget(&server); + return (format!("{e}(連線已中斷,AnyBot 會自動重新連線,稍後再試)"), false, None); + } + (e, false, None) + } } } @@ -519,12 +745,20 @@ pub fn market_server(name: &str, cmd: &str) -> Server { 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)] -mod tests { - use super::*; +pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> { + static L: Mutex<()> = Mutex::new(()); + L.lock().unwrap_or_else(|e| e.into_inner()) +} - const FAKE_SERVER: &str = r#" -import sys, json +/// 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: @@ -532,7 +766,9 @@ for line in sys.stdin: if m["method"] == "initialize": r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "fake"}} elif m["method"] == "tools/list": - r = {"tools": [{"name": "add", "description": "Add two numbers", "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}]} + 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"])}]} @@ -541,14 +777,24 @@ for line in sys.stdin: 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() } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] fn stdio_server_round_trip() { - 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, FAKE_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: "用來算數學".into() }; + 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"); @@ -558,9 +804,87 @@ for line in sys.stdin: 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()); - let _ = std::fs::remove_dir_all(&dir); + } + + /// 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 = 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::() < 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::>(); + 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"))); } /// The registry's answer as the 公用市集 lists it: servers reached by address (streamable @@ -646,6 +970,7 @@ for line in sys.stdin: #[test] #[ignore] fn marketplace_connectors_start() { + let _one = test_lock(); let servers: Vec = MARKET.iter().filter(|m| m.3.is_empty()).map(|m| market_server(m.0, m.2)).collect(); let errors = sync(&servers); let st = status(); diff --git a/src/remote.rs b/src/remote.rs index f04df58..6081620 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -689,6 +689,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp { // 技能 from a screen: add, install, hand over a folder, delete — done here, where the // bots read them (the files land on this disk, and a deleted one's folder goes too). ("POST", ["api", "sync", "skill"]) => phone_act_for("skill", req.json(), "owner", 55), + // 連接器 › 重新連線 from a screen (the list itself changes through edits). + ("POST", ["api", "sync", "mcp"]) => phone_act_for("mcp", json!({"name": req.json()["name"], "reconnect": true}), "owner", 10), ("POST", ["api", "sync", "act"]) => { let b = req.json(); let bot = b["bot"].as_u64().unwrap_or(0); diff --git a/src/tools.rs b/src/tools.rs index 43dade6..ff48d7e 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -96,6 +96,8 @@ pub fn label(name: &str) -> &'static str { "browser_fill_login" => "用保險庫登入", "browser_fill_card" => "填入卡片", "browser_fill_contact" => "填入聯絡資訊", + crate::mcp::FIND_TOOL => "找連接器的工具", + n if n.starts_with(crate::mcp::PREFIX) || n == crate::mcp::USE_TOOL => "用連接器", _ => "工具", } }