AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
// MCP connectors: the bot can use the tools of Model Context Protocol servers (the original's
|
|
|
|
|
|
// local-exec-daemon has an MCP client with its own permission layer: shouldBlockMcp /
|
|
|
|
|
|
// isMcpFullyAllowlisted, and per-server custom instructions). Here: stdio servers (a command
|
|
|
|
|
|
// AnyBot starts) and HTTP servers (Streamable HTTP, JSON or SSE answers).
|
|
|
|
|
|
|
|
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
use serde_json::{json, Value};
|
|
|
|
|
|
use std::collections::{BTreeMap, HashMap};
|
|
|
|
|
|
use std::io::{BufRead, BufReader, Write};
|
|
|
|
|
|
use std::process::{Child, ChildStdin, Command, Stdio};
|
|
|
|
|
|
use std::sync::mpsc::{channel, Receiver};
|
2026-11-05 07:48:20 +00:00
|
|
|
|
use std::sync::{Arc, Mutex, OnceLock};
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
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> },
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-05 07:48:20 +00:00
|
|
|
|
/// 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 {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
link: Link,
|
|
|
|
|
|
next_id: u64,
|
2026-11-05 07:48:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
struct Conn {
|
|
|
|
|
|
live: Mutex<Live>,
|
2026-11-12 03:31:31 +00:00
|
|
|
|
/// Refetched in place when the server sends `notifications/tools/list_changed`.
|
|
|
|
|
|
tools: Mutex<Vec<ToolInfo>>,
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
config: Server,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-05 07:48:20 +00:00
|
|
|
|
/// 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();
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
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}"))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-12 03:31:31 +00:00
|
|
|
|
/// The server's own "my tools changed" notification (no id, so answers never match it).
|
|
|
|
|
|
pub fn is_list_changed(v: &Value) -> bool {
|
|
|
|
|
|
v.get("method").and_then(|m| m.as_str()) == Some("notifications/tools/list_changed")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
/// 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>())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
/// 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())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-05 07:48:20 +00:00
|
|
|
|
impl Live {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
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");
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
let body = resp.body_mut().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));
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
parse_http_answer(&body, id)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
fn notify(&mut self, method: &str) {
|
|
|
|
|
|
let msg = json!({"jsonrpc": "2.0", "method": method});
|
|
|
|
|
|
match &mut self.link {
|
|
|
|
|
|
Link::Stdio { stdin, .. } => {
|
|
|
|
|
|
let _ = send_stdio(stdin, &msg);
|
|
|
|
|
|
}
|
|
|
|
|
|
Link::Http { url, headers, session } => {
|
|
|
|
|
|
let mut r = ureq::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() {
|
|
|
|
|
|
Link::Http { url: s.url.trim().to_string(), headers: s.headers.clone(), session: None }
|
|
|
|
|
|
} else {
|
|
|
|
|
|
if s.command.trim().is_empty() {
|
|
|
|
|
|
return Err("請給指令或網址".into());
|
|
|
|
|
|
}
|
|
|
|
|
|
let mut child = Command::new(s.command.trim())
|
|
|
|
|
|
.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("沒有標準輸出")?;
|
|
|
|
|
|
let (tx, rx) = channel();
|
2026-11-12 03:31:31 +00:00
|
|
|
|
let watcher = s.name.clone();
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
std::thread::spawn(move || {
|
|
|
|
|
|
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
|
|
|
|
|
if let Ok(v) = serde_json::from_str::<Value>(&line) {
|
2026-11-12 03:31:31 +00:00
|
|
|
|
if is_list_changed(&v) {
|
|
|
|
|
|
// Refresh off this thread: it is the only reader of rx, and a refresh
|
|
|
|
|
|
// needs the link lock a running call holds. Refreshing is cheap.
|
|
|
|
|
|
let n = watcher.clone();
|
|
|
|
|
|
std::thread::spawn(move || refresh_tools(&n));
|
|
|
|
|
|
continue;
|
|
|
|
|
|
}
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
if tx.send(v).is_err() {
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
Link::Stdio { child, stdin, rx }
|
|
|
|
|
|
};
|
2026-11-05 07:48:20 +00:00
|
|
|
|
let mut live = Live { link, next_id: 1 };
|
|
|
|
|
|
live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?;
|
|
|
|
|
|
live.notify("notifications/initialized");
|
2026-11-12 03:31:31 +00:00
|
|
|
|
let tools = fetch_tools(&mut live, &s.name)?;
|
|
|
|
|
|
// Streamable HTTP pushes only on an open GET stream; keep one per connection.
|
|
|
|
|
|
if let Link::Http { url, headers, session: Some(session) } = &live.link {
|
|
|
|
|
|
spawn_http_listener(url.clone(), headers.clone(), session.clone(), s.name.clone());
|
|
|
|
|
|
}
|
|
|
|
|
|
Ok(Conn { live: Mutex::new(live), tools: Mutex::new(tools), config: s.clone() })
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// The server's whole tool list, following `nextCursor` (a server may page).
|
|
|
|
|
|
fn fetch_tools(live: &mut Live, server: &str) -> Result<Vec<ToolInfo>, String> {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
let mut tools = vec![];
|
|
|
|
|
|
let mut cursor: Option<String> = None;
|
|
|
|
|
|
for _ in 0..20 {
|
2026-11-05 07:48:20 +00:00
|
|
|
|
let r = live.request("tools/list", match &cursor { Some(x) => json!({"cursor": x}), None => json!({}) })?;
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
for t in r["tools"].as_array().into_iter().flatten() {
|
2026-11-12 03:31:31 +00:00
|
|
|
|
tools.push(ToolInfo { server: server.into(), name: t["name"].as_str().unwrap_or("").into(), description: t["description"].as_str().unwrap_or("").into(), schema: t["inputSchema"].clone() });
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
cursor = r["nextCursor"].as_str().map(String::from);
|
|
|
|
|
|
if cursor.is_none() {
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-11-12 03:31:31 +00:00
|
|
|
|
Ok(tools)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// The server said its tools changed: refetch on the spot. A failed refresh keeps the old list.
|
|
|
|
|
|
pub fn refresh_tools(name: &str) {
|
|
|
|
|
|
let conn = conns().lock().unwrap().get(name).cloned();
|
|
|
|
|
|
let Some(conn) = conn else { return };
|
|
|
|
|
|
let mut live = match conn.live.lock() {
|
|
|
|
|
|
Ok(l) => l,
|
|
|
|
|
|
Err(_) => return,
|
|
|
|
|
|
};
|
|
|
|
|
|
if let Ok(tools) = fetch_tools(&mut live, name) {
|
|
|
|
|
|
*conn.tools.lock().unwrap() = tools;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Streamable HTTP has no push channel of its own: a connection keeps one long-lived GET
|
|
|
|
|
|
/// (SSE) open so `notifications/tools/list_changed` reaches us. A dropped stream reconnects
|
|
|
|
|
|
/// every few seconds (the global timeout also bounds the wait, so a server taken out of the
|
|
|
|
|
|
/// table ends this thread within it); a server that answers the GET with an error has no
|
|
|
|
|
|
/// stream to offer, and the thread ends — reconnecting the connector is the manual way.
|
|
|
|
|
|
fn spawn_http_listener(url: String, headers: std::collections::BTreeMap<String, String>, session: String, name: String) {
|
|
|
|
|
|
std::thread::spawn(move || {
|
|
|
|
|
|
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(600))).http_status_as_error(false).build().into();
|
|
|
|
|
|
loop {
|
|
|
|
|
|
if !conns().lock().unwrap().contains_key(&name) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
let mut req = agent.get(url.as_str()).header("Accept", "text/event-stream").header("MCP-Protocol-Version", PROTOCOL).header("Mcp-Session-Id", session.as_str());
|
|
|
|
|
|
for (k, v) in headers.iter() {
|
|
|
|
|
|
req = req.header(k.as_str(), v.as_str());
|
|
|
|
|
|
}
|
|
|
|
|
|
let mut resp = match req.call() {
|
|
|
|
|
|
Ok(r) if (200..300).contains(&r.status().as_u16()) => r,
|
|
|
|
|
|
_ => return,
|
|
|
|
|
|
};
|
|
|
|
|
|
for line in std::io::BufReader::new(resp.body_mut().as_reader()).lines().map_while(Result::ok) {
|
|
|
|
|
|
if line.contains("notifications/tools/list_changed") {
|
|
|
|
|
|
let n = name.clone();
|
|
|
|
|
|
std::thread::spawn(move || refresh_tools(&n));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
std::thread::sleep(Duration::from_secs(5));
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Start (or keep) the enabled servers; stop the rest. Returns errors per server.
|
2026-11-05 07:48:20 +00:00
|
|
|
|
/// Connecting happens outside the table's lock (a slow server must not freeze the UI's
|
|
|
|
|
|
/// status line, which reads that lock every second).
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
pub fn sync(servers: &[Server]) -> Vec<(String, String)> {
|
|
|
|
|
|
let mut errs = vec![];
|
2026-11-05 07:48:20 +00:00
|
|
|
|
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();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
keep
|
|
|
|
|
|
});
|
|
|
|
|
|
for s in wanted {
|
|
|
|
|
|
if !map.contains_key(&s.name) {
|
|
|
|
|
|
to_connect.push(s.clone());
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-11-05 07:48:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
for s in to_connect {
|
|
|
|
|
|
match connect(&s) {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
Ok(c) => {
|
2026-11-05 07:48:20 +00:00
|
|
|
|
conns().lock().unwrap().insert(s.name.clone(), Arc::new(c));
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
Err(e) => errs.push((s.name.clone(), e)),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
errs
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// The connected servers' tools.
|
|
|
|
|
|
pub fn tools() -> Vec<ToolInfo> {
|
2026-11-12 03:31:31 +00:00
|
|
|
|
conns().lock().unwrap().values().flat_map(|c| c.tools.lock().unwrap().clone()).collect()
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pub fn status() -> HashMap<String, usize> {
|
2026-11-12 03:31:31 +00:00
|
|
|
|
conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.lock().unwrap().len())).collect()
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// 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!({}));
|
2026-11-05 07:48:20 +00:00
|
|
|
|
// 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})) {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
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() {
|
2026-11-05 07:48:20 +00:00
|
|
|
|
for c in conns().lock().unwrap().values() {
|
|
|
|
|
|
if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link {
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
let _ = child.kill();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// 連接器市集: (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() }
|
|
|
|
|
|
}
|
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
/// 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();
|
|
|
|
|
|
Server { name: name.to_string(), command: parts[0].clone(), args: parts[1..].to_vec(), ..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()
|
|
|
|
|
|
"#;
|
|
|
|
|
|
|
2026-11-12 03:31:31 +00:00
|
|
|
|
/// One connection table per process: tests that sync servers take turns with it.
|
|
|
|
|
|
static SYNC_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
|
|
|
|
|
|
|
|
|
|
|
/// Same, but a call to 「refresh」 makes the server announce list_changed and add a tool.
|
|
|
|
|
|
const CHANGING_SERVER: &str = r#"
|
|
|
|
|
|
import sys, json
|
|
|
|
|
|
mode = {"n": 1}
|
|
|
|
|
|
base = [{"name": "add", "description": "Add", "inputSchema": {"type": "object", "properties": {}}}]
|
|
|
|
|
|
extra = {"name": "extra", "description": "New tool", "inputSchema": {"type": "object", "properties": {}}}
|
|
|
|
|
|
for line in sys.stdin:
|
|
|
|
|
|
m = json.loads(line)
|
|
|
|
|
|
if "id" not in m:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if m["method"] == "initialize":
|
|
|
|
|
|
r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": True}}, "serverInfo": {"name": "fake"}}
|
|
|
|
|
|
elif m["method"] == "tools/list":
|
|
|
|
|
|
r = {"tools": base + ([extra] if mode["n"] == 2 else [])}
|
|
|
|
|
|
elif m["method"] == "tools/call" and m["params"]["name"] == "refresh":
|
|
|
|
|
|
mode["n"] = 2
|
|
|
|
|
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}) + "\n")
|
|
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
|
r = {"content": [{"type": "text", "text": "changed"}]}
|
|
|
|
|
|
else:
|
|
|
|
|
|
r = {}
|
|
|
|
|
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n")
|
|
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
|
"#;
|
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
#[test]
|
|
|
|
|
|
fn stdio_server_round_trip() {
|
2026-11-12 03:31:31 +00:00
|
|
|
|
let _turn = SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
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);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-12 03:31:31 +00:00
|
|
|
|
/// A server that says 「my tools changed」 is taken at its word: the reader thread hands
|
|
|
|
|
|
/// the refresh to its own thread and the new tool shows up without a reconnect.
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn list_changed_refetches_the_tools() {
|
|
|
|
|
|
let _turn = SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
|
|
|
|
let dir = std::env::temp_dir().join(format!("anybot-mcp-changed-{}", std::process::id()));
|
|
|
|
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
|
|
|
|
let script = dir.join("server.py");
|
|
|
|
|
|
std::fs::write(&script, CHANGING_SERVER).unwrap();
|
|
|
|
|
|
let s = Server { name: "庫存".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env: BTreeMap::new(), url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new() };
|
|
|
|
|
|
let errs = sync(std::slice::from_ref(&s));
|
|
|
|
|
|
assert!(errs.is_empty(), "{errs:?}");
|
|
|
|
|
|
assert!(!tools().iter().any(|t| t.name == "extra"), "starts without the extra tool");
|
|
|
|
|
|
// Trigger the announcement: the fake server emits list_changed on a call named
|
|
|
|
|
|
// refresh — send it through the server's own handle, like AnyBot's call() does.
|
|
|
|
|
|
{
|
|
|
|
|
|
let conn = conns().lock().unwrap().get("庫存").cloned().unwrap();
|
|
|
|
|
|
let mut live = conn.live.lock().unwrap();
|
|
|
|
|
|
live.request("tools/call", json!({"name": "refresh", "arguments": {}})).unwrap();
|
|
|
|
|
|
}
|
|
|
|
|
|
let mut got = false;
|
|
|
|
|
|
for _ in 0..60 {
|
|
|
|
|
|
if tools().iter().any(|t| t.server == "庫存" && t.name == "extra") {
|
|
|
|
|
|
got = true;
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
|
|
|
|
}
|
|
|
|
|
|
sync(&[]);
|
|
|
|
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
|
|
|
|
assert!(got, "the tool list did not refresh after list_changed");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// What counts as the change notice, and a notice riding an HTTP answer stream must not
|
|
|
|
|
|
/// be taken for the answer.
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
fn the_change_notice_is_recognised() {
|
|
|
|
|
|
assert!(is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"})));
|
|
|
|
|
|
assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "id": 3, "result": {}})));
|
|
|
|
|
|
assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/message"})));
|
|
|
|
|
|
let sse = "data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\n\ndata: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"tools\":[]}}\n";
|
|
|
|
|
|
assert!(parse_http_answer(sse, 9).unwrap()["tools"].is_array());
|
|
|
|
|
|
}
|
|
|
|
|
|
|
連接器: 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"));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-12 03:31:31 +00:00
|
|
|
|
/// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and
|
|
|
|
|
|
/// shouts list_changed over the SSE stream. Setup:
|
|
|
|
|
|
/// 1. /tmp/openapimcp-live.yaml exists (port 3901, Spec.File /tmp/openapimcp-live.json,
|
|
|
|
|
|
/// ReloadSeconds 60 so only the management endpoint reloads — the openapimcp repo ships one),
|
|
|
|
|
|
/// 2. from the openapimcp repo: ./bin/srv -f /tmp/openapimcp-live.yaml
|
|
|
|
|
|
/// Then: cargo test openapimcp_live -- --ignored --nocapture
|
|
|
|
|
|
/// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE
|
|
|
|
|
|
/// stream and refresh the tools without a reconnect.
|
|
|
|
|
|
#[test]
|
|
|
|
|
|
#[ignore]
|
|
|
|
|
|
fn openapimcp_live() {
|
|
|
|
|
|
const LIVE_SPEC: &str = "/tmp/openapimcp-live.json";
|
|
|
|
|
|
const MANAGE: &str = "http://localhost:3901";
|
|
|
|
|
|
let mini = |extra: &str| {
|
|
|
|
|
|
r#"{"swagger":"2.0","basePath":"/","info":{"title":"Live"},"paths":{"/v1/ping":{"get":{"summary":"Ping","responses":{"200":{"description":"ok"}}}}@}}"#
|
|
|
|
|
|
.replace("@", extra)
|
|
|
|
|
|
};
|
|
|
|
|
|
let post = |path: &str| {
|
|
|
|
|
|
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into();
|
|
|
|
|
|
agent.post(&format!("{MANAGE}{path}")).send(()).ok().and_then(|mut r| r.body_mut().read_to_string().ok())
|
|
|
|
|
|
};
|
|
|
|
|
|
let health_tools = || -> Option<usize> {
|
|
|
|
|
|
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into();
|
|
|
|
|
|
let b = agent.get(&format!("{MANAGE}/healthz")).call().ok()?.body_mut().read_to_string().ok()?;
|
|
|
|
|
|
Some(serde_json::from_str::<Value>(&b).ok()?.get("tools")?.as_u64()? as usize)
|
|
|
|
|
|
};
|
|
|
|
|
|
let _turn = SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
|
|
|
|
// Settle the SERVER on the baseline before opening any MCP session, so no ticker
|
|
|
|
|
|
// notification can race with the listener's GET starting: write baseline, reload, wait
|
|
|
|
|
|
// for the health endpoint to report the baseline tool count (ping + api_search + api_call).
|
|
|
|
|
|
std::fs::write(LIVE_SPEC, mini("")).unwrap();
|
|
|
|
|
|
post("/api/reload");
|
|
|
|
|
|
let mut settled = false;
|
|
|
|
|
|
for _ in 0..50 {
|
|
|
|
|
|
if health_tools() == Some(3) {
|
|
|
|
|
|
settled = true;
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
|
|
|
|
}
|
|
|
|
|
|
let s = remote_server("openapi", "http://localhost:3901/mcp", "");
|
|
|
|
|
|
let errs = sync(&[s]);
|
|
|
|
|
|
if !errs.is_empty() {
|
|
|
|
|
|
eprintln!("openapimcp 沒跑在 :3901 — 先照上方說明啟動:{errs:?}");
|
|
|
|
|
|
sync(&[]);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
assert!(settled, "server did not settle on the baseline (3 tools)");
|
|
|
|
|
|
assert!(tools().iter().any(|t| t.name == "v1_ping_get"), "tools: {:?}", tools().iter().map(|t| t.name.clone()).collect::<Vec<_>>());
|
|
|
|
|
|
assert!(!tools().iter().any(|t| t.name == "v1_echo_get"));
|
|
|
|
|
|
let (out, ok, _) = call(&tool_name("openapi", "api_search"), r#"{"keyword":"ping"}"#);
|
|
|
|
|
|
assert!(ok && out.contains("v1_ping_get"), "{out}");
|
|
|
|
|
|
// The spec gains a path; ask the server to reload now. It shouts list_changed on the
|
|
|
|
|
|
// open SSE stream; the listener refreshes the tools in place, no reconnect.
|
|
|
|
|
|
std::fs::write(LIVE_SPEC, mini(r#","/v1/echo":{"get":{"summary":"Echo","responses":{"200":{"description":"ok"}}}}"#)).unwrap();
|
|
|
|
|
|
post("/api/reload");
|
|
|
|
|
|
let mut got = false;
|
|
|
|
|
|
for _ in 0..100 {
|
|
|
|
|
|
if tools().iter().any(|t| t.name == "v1_echo_get") {
|
|
|
|
|
|
got = true;
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
|
|
|
|
}
|
|
|
|
|
|
sync(&[]);
|
|
|
|
|
|
assert!(got, "SSE 監聽沒有刷新工具清單(v1_echo_get 沒出現)");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
連接器: 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
|
|
|
|
/// 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(&[]);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
AnyBot: first commit of the working desktop app
Rust/egui rebuild of Grok Bot as of 2026-11-04: chat with streaming
providers (xAI, OpenAI, Claude, Gemini, OpenRouter, OpenCode Go, Ollama,
custom), tools and approvals, the bot's Docker computer, computer use on
macOS / Linux X11 / Wayland, AnyBot's browser with a full DevTools-based
toolset, the encrypted vault, pinned grid and sidebar sections, Markdown
with Mermaid diagrams, phone access through the relay, and the Linux
build and test scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha3oEtWeHh58zA7ErHa
2026-11-04 08:51:51 +00:00
|
|
|
|
#[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();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|