AnyBot/src/mcp.rs

666 lines
33 KiB
Rust
Raw Normal View History

// 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};
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
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__";
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Server {
pub name: String,
/// stdio: the command; empty when `url` is used.
#[serde(default)]
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub env: BTreeMap<String, String>,
/// HTTP (Streamable HTTP) address.
#[serde(default)]
pub url: String,
/// e.g. "Authorization: Bearer …" for HTTP servers.
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default = "yes")]
pub enabled: bool,
/// Notes for the bot on how to use this server (the original's MCP custom instructions).
#[serde(default)]
pub instructions: String,
}
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,
}
struct Conn {
live: Mutex<Live>,
tools: 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}"))
}
/// Read the answer with this id (skipping notifications and requests from the server).
fn wait_id(rx: &Receiver<Value>, id: u64, secs: u64) -> Result<Value, String> {
let deadline = std::time::Instant::now() + Duration::from_secs(secs);
loop {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
return Err("MCP 伺服器沒有回應".into());
}
match rx.recv_timeout(left) {
Ok(v) if v["id"].as_u64() == Some(id) && v.get("method").is_none() => {
if let Some(e) = v.get("error") {
return Err(format!("MCP 錯誤:{}", e["message"].as_str().unwrap_or(&e.to_string())));
}
return Ok(v["result"].clone());
}
Ok(_) => continue,
Err(_) => return Err("MCP 伺服器沒有回應或已經結束".into()),
}
}
}
連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone - 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API): servers reached by address only (a package would have to run on the brain, which may have no Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name that only says "mcp" (com.notion/mcp) reads as whose it is (notion). - 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown unmasked with what to put there (the key's description, an address variable's choices). 新增 stays off while a 「{…}」 is left. - The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key or the address part and the brain adds it (the 「mcp」 action's new `add`). - A server that answers 401 (or a 403 asking for a login) with no key given now says it signs people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old. - mcpservers.org and the like are pages for people behind a browser check, with no list a program may read, so the market uses the registry. - Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`. - Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:12:12 +00:00
/// What an HTTP server's refusal means to the person. A 401 (or a 403 that asks for a login)
/// with no key given is a server that signs people in with OAuth, which AnyBot can't do yet;
/// with a key, the key is wrong or old.
pub fn http_refusal(status: u16, asks_login: bool, has_key: bool, body: &str) -> String {
if status == 401 || (status == 403 && asks_login) {
return if has_key {
format!("金鑰不對或過期了(HTTP {status}):檢查「標頭」裡的金鑰")
} else {
"這個連接器要先登入帳號(OAuth),AnyBot 還不支援;它若也收 API 金鑰,填在「標頭」(例如 Authorization: Bearer …)".into()
};
}
format!("MCP 伺服器回 HTTP {status}:{}", body.chars().take(200).collect::<String>())
}
/// Answers from Streamable HTTP: plain JSON, or SSE with `data:` lines.
pub fn parse_http_answer(body: &str, id: u64) -> Result<Value, String> {
let candidates: Vec<Value> = if body.trim_start().starts_with('{') || body.trim_start().starts_with('[') {
match serde_json::from_str::<Value>(body) {
Ok(Value::Array(a)) => a,
Ok(v) => vec![v],
Err(e) => return Err(e.to_string()),
}
} else {
body.lines().filter_map(|l| l.strip_prefix("data:")).filter_map(|d| serde_json::from_str(d.trim()).ok()).collect()
};
for v in candidates {
if v["id"].as_u64() == Some(id) {
if let Some(e) = v.get("error") {
return Err(format!("MCP 錯誤:{}", e["message"].as_str().unwrap_or(&e.to_string())));
}
return Ok(v["result"].clone());
}
}
Err("MCP 伺服器沒有給答案".into())
}
impl Live {
fn request(&mut self, method: &str, params: Value) -> Result<Value, String> {
let id = self.next_id;
self.next_id += 1;
let msg = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
match &mut self.link {
Link::Stdio { stdin, rx, .. } => {
send_stdio(stdin, &msg)?;
wait_id(rx, id, CALL_TIMEOUT_SECS)
}
Link::Http { url, headers, session } => {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).http_status_as_error(false).build().into();
let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream").header("MCP-Protocol-Version", PROTOCOL);
for (k, v) in headers.iter() {
r = r.header(k.as_str(), v.as_str());
}
if let Some(s) = session.as_ref() {
r = r.header("Mcp-Session-Id", s.as_str());
}
let mut resp = r.send(msg.to_string().as_bytes()).map_err(|e| format!("連不上 MCP 伺服器:{e}"))?;
if let Some(s) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {
*session = Some(s.to_string());
}
let st = resp.status().as_u16();
連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone - 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API): servers reached by address only (a package would have to run on the brain, which may have no Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name that only says "mcp" (com.notion/mcp) reads as whose it is (notion). - 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown unmasked with what to put there (the key's description, an address variable's choices). 新增 stays off while a 「{…}」 is left. - The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key or the address part and the brain adds it (the 「mcp」 action's new `add`). - A server that answers 401 (or a 403 asking for a login) with no key given now says it signs people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old. - mcpservers.org and the like are pages for people behind a browser check, with no list a program may read, so the market uses the registry. - Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`. - Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:12:12 +00:00
let asks_login = resp.headers().contains_key("www-authenticate");
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let body = resp.body_mut().with_config().limit(16 * 1024 * 1024).read_to_string().unwrap_or_default();
if !(200..300).contains(&st) {
連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone - 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API): servers reached by address only (a package would have to run on the brain, which may have no Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name that only says "mcp" (com.notion/mcp) reads as whose it is (notion). - 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown unmasked with what to put there (the key's description, an address variable's choices). 新增 stays off while a 「{…}」 is left. - The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key or the address part and the brain adds it (the 「mcp」 action's new `add`). - A server that answers 401 (or a 403 asking for a login) with no key given now says it signs people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old. - mcpservers.org and the like are pages for people behind a browser check, with no list a program may read, so the market uses the registry. - Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`. - Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:12:12 +00:00
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 } => {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(10))).http_status_as_error(false).build().into();
let mut r = agent.post(url.as_str()).header("Content-Type", "application/json").header("Accept", "application/json, text/event-stream");
for (k, v) in headers.iter() {
r = r.header(k.as_str(), v.as_str());
}
if let Some(s) = session.as_ref() {
r = r.header("Mcp-Session-Id", s.as_str());
}
let _ = r.send(msg.to_string().as_bytes());
}
}
}
}
fn connect(s: &Server) -> Result<Conn, String> {
let link = if !s.url.trim().is_empty() {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let u = s.url.trim();
if crate::web::is_forbidden_browser_url(u) {
return Err("安全規則禁止將 MCP 連接器指向雲端中繼資料或 Docker 內部管理端點。".into());
}
Link::Http { url: u.to_string(), headers: s.headers.clone(), session: None }
} else {
if s.command.trim().is_empty() {
return Err("請給指令或網址".into());
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
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::null())
.spawn()
.map_err(|e| format!("無法啟動「{}」:{e}", s.command))?;
let stdin = child.stdin.take().ok_or("沒有標準輸入")?;
let stdout = child.stdout.take().ok_or("沒有標準輸出")?;
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let (tx, rx) = std::sync::mpsc::sync_channel(256);
std::thread::spawn(move || {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
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 tx.send(v).is_err() {
break;
}
}
}
}
}
});
Link::Stdio { child, stdin, rx }
};
let mut live = Live { link, next_id: 1 };
live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?;
live.notify("notifications/initialized");
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: s.name.clone(), 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() })
}
/// 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();
map.retain(|name, c| {
let keep = wanted.iter().any(|s| &s.name == name && **s == c.config);
if !keep {
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
let _ = child.kill();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let _ = child.wait();
}
}
keep
});
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
}
/// The connected servers' tools.
pub fn tools() -> Vec<ToolInfo> {
conns().lock().unwrap().values().flat_map(|c| c.tools.clone()).collect()
}
pub fn status() -> HashMap<String, usize> {
conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.len())).collect()
}
/// Tool specs for the model.
pub fn specs() -> Vec<Value> {
tools()
.into_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::<String>()), "parameters": schema})
})
.collect()
}
/// Instructions the servers' owners wrote for the bot.
pub fn instructions(servers: &[Server]) -> String {
servers.iter().filter(|s| s.enabled && !s.instructions.trim().is_empty()).map(|s| format!("- {}:{}", s.name, s.instructions.trim())).collect::<Vec<_>>().join("\n")
}
/// Which server and tool a model-side name means.
pub fn resolve(name: &str) -> Option<(String, String)> {
tools().into_iter().find(|t| tool_name(&t.server, &t.name) == name).map(|t| (t.server, t.name))
}
/// Call a tool. Returns (text, ok, first picture as base64).
pub fn call(name: &str, args: &str) -> (String, bool, Option<String>) {
let Some((server, tool)) = resolve(name) else { return (format!("沒有「{name}」這個 MCP 工具(伺服器可能已關閉)"), false, None) };
let arguments: Value = serde_json::from_str(if args.trim().is_empty() { "{}" } else { args }).unwrap_or(json!({}));
// Copy the server's own handle out of the table, then lock its link alone: a two-minute
// call to one server used to block every other MCP tool and the UI's status line.
let conn = conns().lock().unwrap().get(&server).cloned();
let Some(conn) = conn else { return ("MCP 伺服器沒有連線".into(), false, None) };
let mut live = conn.live.lock().unwrap();
match live.request("tools/call", json!({"name": tool, "arguments": arguments})) {
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) => (e, false, None),
}
}
pub fn shutdown() {
for c in conns().lock().unwrap().values() {
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
let _ = child.kill();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let _ = child.wait();
}
}
}
/// 連接器市集: (name, what it does, command or address, key to fill in — empty when none).
pub const MARKET: [(&str, &str, &str, &str); 8] = [
("files", "讀寫你指定資料夾裡的檔案", "npx -y @modelcontextprotocol/server-filesystem ~/Documents", ""),
("memory", "長期記憶:把人、事、關係記成知識圖", "npx -y @modelcontextprotocol/server-memory", ""),
("thinking", "一步步拆解難題", "npx -y @modelcontextprotocol/server-sequential-thinking", ""),
("fetch", "抓網頁內容轉成文字", "uvx mcp-server-fetch", ""),
("git", "查看和操作 Git 版本庫", "uvx mcp-server-git", ""),
("time", "時間和時區換算", "uvx mcp-server-time", ""),
("playwright", "用瀏覽器自動化操作網頁", "npx -y @playwright/mcp@latest", ""),
("github", "GitHub 的 Issue、PR、程式碼(官方遠端伺服器)", "https://api.githubcopilot.com/mcp/", "Authorization: Bearer 你的 GitHub Token"),
];
連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone - 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API): servers reached by address only (a package would have to run on the brain, which may have no Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name that only says "mcp" (com.notion/mcp) reads as whose it is (notion). - 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown unmasked with what to put there (the key's description, an address variable's choices). 新增 stays off while a 「{…}」 is left. - The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key or the address part and the brain adds it (the 「mcp」 action's new `add`). - A server that answers 401 (or a 403 asking for a login) with no key given now says it signs people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old. - mcpservers.org and the like are pages for people behind a browser check, with no list a program may read, so the market uses the registry. - Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`. - Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:12:12 +00:00
// ---------- 公用市集: the official MCP Registry ----------
/// The official MCP Registry: public and searchable, and for each server reached by address it
/// gives the address and the header (a key) it wants. (mcpservers.org and the like are pages
/// for people, behind a browser check, with no list a program may read.)
pub const REGISTRY: &str = "https://registry.modelcontextprotocol.io/v0.1/servers";
/// Results per search.
const REGISTRY_LIMIT: usize = 40;
/// Search the registry: servers reached by address, as [`registry_entries`] gives them.
pub fn registry_search(q: &str) -> Result<Vec<Value>, String> {
let url = format!("{REGISTRY}?version=latest&limit={REGISTRY_LIMIT}&search={}", crate::httpd::url_encode(q.trim()));
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into();
let mut resp = agent.get(&url).header("Accept", "application/json").call().map_err(|e| format!("連不到公用市集:{e}"))?;
let st = resp.status().as_u16();
let body = resp.body_mut().read_to_string().unwrap_or_default();
if !(200..300).contains(&st) {
return Err(format!("公用市集回 HTTP {st}"));
}
let v: Value = serde_json::from_str(&body).map_err(|_| "公用市集的回答看不懂".to_string())?;
Ok(registry_entries(&v))
}
/// The registry's answer as the market lists it: one row per server reached by address (a
/// package would have to run on the brain, which may have no Node or uv), none taken down. Each:
/// {id, title, description, url, header: {name, value, description} | null, variables:
/// [{name, description, choices}], note} — `note` says why it can't be added yet.
pub fn registry_entries(v: &Value) -> Vec<Value> {
let mut out: Vec<Value> = vec![];
for item in v["servers"].as_array().into_iter().flatten() {
let s = &item["server"];
if item["_meta"]["io.modelcontextprotocol.registry/official"]["status"].as_str().is_some_and(|st| st != "active") {
continue;
}
let remotes = s["remotes"].as_array().map(Vec::as_slice).unwrap_or_default();
let Some(r) = remotes.iter().find(|r| r["type"] == "streamable-http").or_else(|| remotes.first()) else { continue };
let id = s["name"].as_str().unwrap_or("");
let url = r["url"].as_str().unwrap_or("");
if id.is_empty() || url.is_empty() || out.iter().any(|o| o["id"] == id) {
continue;
}
let title = s["title"].as_str().map(str::trim).filter(|t| !t.is_empty()).map(String::from).unwrap_or_else(|| short_name(id));
// The key goes where the registry shows its placeholder ("Bearer {api_key}").
let header = r["headers"].as_array().and_then(|h| h.first()).map(|h| {
let value = h["value"].as_str().filter(|v| !v.trim().is_empty()).unwrap_or("{金鑰}");
json!({"name": h["name"].as_str().unwrap_or(""), "value": value, "description": h["description"].as_str().unwrap_or("")})
});
let variables: Vec<Value> = r["variables"].as_object().map(|o| o.iter().map(|(k, x)| json!({"name": k, "description": x["description"].as_str().unwrap_or(""), "choices": x["choices"].as_array().cloned().unwrap_or_default()})).collect()).unwrap_or_default();
let note = if r["type"] == "streamable-http" { "" } else { "舊式 SSE 連線,AnyBot 還不支援" };
out.push(json!({"id": id, "title": title, "description": s["description"].as_str().unwrap_or(""), "url": url, "header": header, "variables": variables, "note": note}));
}
out
}
/// A registry name ("ai.smithery/smithery-notion", "com.notion/mcp") as a person would call it:
/// its last part, or — when that only says "mcp" — whose it is.
fn short_name(id: &str) -> String {
let (owner, last) = id.rsplit_once('/').unwrap_or(("", id));
let plain = matches!(last.to_ascii_lowercase().as_str(), "mcp" | "server" | "mcp-server" | "remote" | "remote-mcp" | "api");
if plain && !owner.is_empty() {
return owner.rsplit('.').next().unwrap_or(owner).to_string();
}
last.to_string()
}
/// A name not taken yet: 「Notion」, then 「Notion 2」…
pub fn free_name(want: &str, servers: &[Server]) -> String {
let want = want.trim();
let taken = |n: &str| servers.iter().any(|s| s.name == n);
if !taken(want) {
return want.to_string();
}
(2..).map(|i| format!("{want} {i}")).find(|n| !taken(n)).unwrap_or_default()
}
/// A 公用市集 row as the 新增連接器 form: (name not taken yet, address, header line, what the
/// person still has to fill in).
pub fn registry_form(e: &Value, servers: &[Server]) -> (String, String, String, String) {
let name = free_name(e["title"].as_str().unwrap_or("連接器"), servers);
let url = e["url"].as_str().unwrap_or("").to_string();
let mut hint = vec![];
let header = match e["header"].as_object() {
Some(h) => {
let about = h.get("description").and_then(Value::as_str).unwrap_or("").trim();
hint.push(if about.is_empty() { "把標頭裡的「{…}」換成你的金鑰。".to_string() } else { format!("把標頭裡的「{{…}}」換成你的金鑰({about})。") });
format!("{}: {}", h.get("name").and_then(Value::as_str).unwrap_or(""), h.get("value").and_then(Value::as_str).unwrap_or(""))
}
None => String::new(),
};
for v in e["variables"].as_array().into_iter().flatten() {
let choices: Vec<&str> = v["choices"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let mut line = format!("把網址裡的「{{{}}}」換成{}", v["name"].as_str().unwrap_or(""), v["description"].as_str().map(|d| format!(":{d}")).unwrap_or_default());
if !choices.is_empty() {
line.push_str(&format!("(可填 {})", choices.join("、")));
}
hint.push(line);
}
hint.push("按「新增」就會連線;要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時會說。".into());
(name, url, header, hint.join(" "))
}
/// A server reached by address, with its one header ("Authorization: Bearer …") if any.
pub fn remote_server(name: &str, url: &str, header: &str) -> Server {
let headers = header.split_once(':').map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).filter(|(k, _)| !k.is_empty()).into_iter().collect();
Server { name: name.trim().to_string(), command: String::new(), args: vec![], env: BTreeMap::new(), url: url.trim().to_string(), headers, enabled: true, instructions: String::new() }
}
/// 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();
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
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() }
}
#[cfg(test)]
mod tests {
use super::*;
const FAKE_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": "fake"}}
elif m["method"] == "tools/list":
r = {"tools": [{"name": "add", "description": "Add two numbers", "inputSchema": {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}}]}
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()
"#;
#[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 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("用來算數學"));
sync(&[]);
assert!(tools().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone - 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API): servers reached by address only (a package would have to run on the brain, which may have no Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name that only says "mcp" (com.notion/mcp) reads as whose it is (notion). - 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown unmasked with what to put there (the key's description, an address variable's choices). 新增 stays off while a 「{…}」 is left. - The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key or the address part and the brain adds it (the 「mcp」 action's new `add`). - A server that answers 401 (or a 403 asking for a login) with no key given now says it signs people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old. - mcpservers.org and the like are pages for people behind a browser check, with no list a program may read, so the market uses the registry. - Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`. - Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:12:12 +00:00
/// 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"));
}
/// 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 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();
}
}