diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index b610264..581f306 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -5,8 +5,8 @@ use super::*; use crate::channels::{self, Channel, Incoming, Kind, ReplyTo}; use std::collections::VecDeque; -/// How long a connector that is on but not connected waits before it is tried again. -const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(60); +/// How often the connectors are synced again: what failed or died is connected again. +const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(30); pub struct ChannelUi { pub tx: Sender, @@ -33,8 +33,7 @@ pub struct ChannelUi { pub(super) mcp_sig: String, pub(super) mcp_errors: Arc>>, pub(super) mcp_busy: Arc, - /// When the servers were last connected (one that is on but not connected is tried again - /// a minute later). + /// When the connectors were last synced (again every half minute). mcp_tried: Option, new_mcp: (String, String, String, String), /// What the form needs from the person, for a server picked from the 公用市集. @@ -413,19 +412,15 @@ impl App { // ---------- 連接器 (MCP) ---------- impl App { - /// Connect the configured MCP servers when they change (in the background), and once a - /// minute again the ones that are on but not connected: a server that wasn't up yet, or whose - /// link died, used to stay down until its settings were changed. + /// Connect the configured MCP servers when they change (in the background), and re-sync + /// every half minute: sync keeps what is alive and connects again what failed or died, so a + /// server that wasn't up yet, crashed, or lost its machine comes back on its own. fn mcp_poll(&mut self, ctx: &egui::Context) { if self.ch.mcp_busy.load(Ordering::SeqCst) { return; } let sig = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default(); - let retry = self.ch.mcp_tried.is_some_and(|t| t.elapsed() >= MCP_RETRY) && { - let up = crate::mcp::status(); - self.state.mcp_servers.iter().any(|s| s.enabled && !up.contains_key(&s.name)) - }; - if sig == self.ch.mcp_sig && !retry { + if sig == self.ch.mcp_sig && self.ch.mcp_tried.is_some_and(|t| t.elapsed() < MCP_RETRY) { return; } self.ch.mcp_sig = sig; diff --git a/src/mcp.rs b/src/mcp.rs index a004714..e4df37d 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -88,7 +88,8 @@ impl Live { struct Conn { live: Mutex, - tools: Vec, + /// Refetched in place when the server sends `notifications/tools/list_changed`. + tools: Mutex>, config: Server, } @@ -126,6 +127,11 @@ fn send_stdio(stdin: &mut ChildStdin, msg: &Value) -> Result<(), String> { stdin.write_all(line.as_bytes()).and_then(|_| stdin.flush()).map_err(|e| format!("送不出去:{e}")) } +/// The server's own "my tools changed" notification (no id, so answers never match it). +pub fn is_list_changed(v: &Value) -> bool { + v.get("method").and_then(|m| m.as_str()) == Some("notifications/tools/list_changed") +} + /// Read the answer with this id (skipping notifications and requests from the server). fn wait_id(rx: &Receiver, id: u64, secs: u64) -> Result { let deadline = std::time::Instant::now() + Duration::from_secs(secs); @@ -321,6 +327,7 @@ fn connect(s: &Server) -> Result { }); } let (tx, rx) = std::sync::mpsc::sync_channel(256); + let watcher = s.name.clone(); std::thread::spawn(move || { let mut reader = BufReader::new(stdout); loop { @@ -329,6 +336,13 @@ fn connect(s: &Server) -> Result { Ok(0) | Err(_) => break, Ok(_) => { if let Ok(v) = serde_json::from_str::(&line) { + if is_list_changed(&v) { + // Refresh off this thread: it is the only reader of rx, and a + // refresh needs the link lock a running call holds. + let n = watcher.clone(); + std::thread::spawn(move || refresh_tools(&n)); + continue; + } if tx.send(v).is_err() { break; } @@ -341,10 +355,16 @@ fn connect(s: &Server) -> Result { }; let mut live = Live { link, next_id: 1, expired: false }; match handshake(&mut live, &s.name) { - Ok(tools) => Ok(Conn { live: Mutex::new(live), tools, config: s.clone() }), + Ok(tools) => { + // Streamable HTTP pushes only on an open GET stream; keep one per connection. + if let Link::Http { url, headers, session: Some(session) } = &live.link { + spawn_http_listener(url.clone(), headers.clone(), session.clone(), s.name.clone()); + } + Ok(Conn { live: Mutex::new(live), tools: Mutex::new(tools), config: s.clone() }) + } Err(e) => { - // A server that didn't come up is ended (retried each minute, it used to be left - // running each time), and what it said on stderr goes with the error. + // A server that didn't come up is ended (it is tried again each half minute, and + // used to be left running each time), and what it said on stderr goes with the error. if let Link::Stdio { child, .. } = &mut live.link { let _ = child.kill(); let _ = child.wait(); @@ -356,10 +376,15 @@ fn connect(s: &Server) -> Result { } } -/// initialize, then the server's tools (all pages). +/// initialize, then the server's tools. fn handshake(live: &mut Live, server: &str) -> Result, String> { live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?; live.notify("notifications/initialized"); + fetch_tools(live, server) +} + +/// The server's whole tool list, following `nextCursor` (a server may page). +fn fetch_tools(live: &mut Live, server: &str) -> Result, String> { let mut tools = vec![]; let mut cursor: Option = None; for _ in 0..20 { @@ -375,6 +400,50 @@ fn handshake(live: &mut Live, server: &str) -> Result, String> { Ok(tools) } +/// The server said its tools changed: refetch on the spot. A failed refresh keeps the old list. +pub fn refresh_tools(name: &str) { + let conn = conns().lock().unwrap().get(name).cloned(); + let Some(conn) = conn else { return }; + let mut live = match conn.live.lock() { + Ok(l) => l, + Err(_) => return, + }; + if let Ok(tools) = fetch_tools(&mut live, name) { + *conn.tools.lock().unwrap() = tools; + } +} + +/// Streamable HTTP has no push channel of its own: a connection keeps one long-lived GET +/// (SSE) open so `notifications/tools/list_changed` reaches us. A dropped stream reconnects +/// every few seconds (the global timeout also bounds the wait, so a server taken out of the +/// table ends this thread within it); a server that answers the GET with an error has no +/// stream to offer, and the thread ends — reconnecting the connector is the manual way. +fn spawn_http_listener(url: String, headers: BTreeMap, 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 BufReader::new(resp.body_mut().as_reader()).lines().map_while(Result::ok) { + if line.contains("notifications/tools/list_changed") { + let n = name.clone(); + std::thread::spawn(move || refresh_tools(&n)); + } + } + std::thread::sleep(Duration::from_secs(5)); + } + }); +} + /// A stdio server that names this computer's own folders (its home): it means nothing on another /// computer, so moving to a brain leaves it here. pub fn names_this_computer(s: &Server) -> bool { @@ -392,16 +461,35 @@ pub fn sync(servers: &[Server]) -> Vec<(String, String)> { { let mut map = conns().lock().unwrap(); let wanted: Vec<&Server> = servers.iter().filter(|s| s.enabled).collect(); + let mut gone = vec![]; map.retain(|name, c| { - let 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(); - let _ = child.wait(); + let mut keep = wanted.iter().any(|s| &s.name == name && **s == c.config); + // A stdio server whose process died is dropped here and started again below: the + // old link would only ever answer 「the server has ended」. A link in use by a call + // (locked) is alive; it isn't waited for here, under the table's lock. + if keep { + if let Ok(mut live) = c.live.try_lock() { + if let Link::Stdio { child, .. } = &mut live.link { + keep = child.try_wait().ok().flatten().is_none(); + } } } + if !keep { + gone.push(c.clone()); + } keep }); + // Their processes end off this thread (a call in progress holds its link). + if !gone.is_empty() { + std::thread::spawn(move || { + for c in gone { + if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { + let _ = child.kill(); + let _ = child.wait(); + } + } + }); + } for s in wanted { if !map.contains_key(&s.name) { to_connect.push(s.clone()); @@ -436,11 +524,11 @@ pub fn forget(name: &str) { /// The connected servers' tools. pub fn tools() -> Vec { - conns().lock().unwrap().values().flat_map(|c| c.tools.clone()).collect() + conns().lock().unwrap().values().flat_map(|c| c.tools.lock().unwrap().clone()).collect() } pub fn status() -> HashMap { - conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.len())).collect() + conns().lock().unwrap().iter().map(|(k, c)| (k.clone(), c.tools.lock().unwrap().len())).collect() } /// One tool as the model sees it. @@ -571,8 +659,15 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { // 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})) { + // The link lock is let go before the table's is taken (forget): sync takes them the other + // way round, and a link lock must never be held while taking the table's. + let (result, dead) = { + let mut live = conn.live.lock().unwrap(); + let r = live.request("tools/call", json!({"name": tool, "arguments": arguments})); + let dead = r.is_err() && live.dead(); + (r, dead) + }; + match result { Ok(r) => { let mut text = String::new(); let mut image = None; @@ -598,9 +693,8 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { } Err(e) => { // A link that died (the server's process ended, or it forgot the session) used to - // stay "connected" and fail every call: drop it, and the app connects it again. - if live.dead() { - drop(live); + // stay "connected" and fail every call: drop it, and the next sync connects it again. + if dead { forget(&server); return (format!("{e}(連線已中斷,AnyBot 會自動重新連線,稍後再試)"), false, None); } @@ -791,6 +885,32 @@ mod tests { use super::*; + + /// Same, but a call to 「refresh」 makes the server announce list_changed and add a tool. + const CHANGING_SERVER: &str = r#" +import sys, json +mode = {"n": 1} +base = [{"name": "add", "description": "Add", "inputSchema": {"type": "object", "properties": {}}}] +extra = {"name": "extra", "description": "New tool", "inputSchema": {"type": "object", "properties": {}}} +for line in sys.stdin: + m = json.loads(line) + if "id" not in m: + continue + if m["method"] == "initialize": + r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": True}}, "serverInfo": {"name": "fake"}} + elif m["method"] == "tools/list": + r = {"tools": base + ([extra] if mode["n"] == 2 else [])} + elif m["method"] == "tools/call" and m["params"]["name"] == "refresh": + mode["n"] = 2 + sys.stdout.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}) + "\n") + sys.stdout.flush() + r = {"content": [{"type": "text", "text": "changed"}]} + else: + r = {} + sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n") + sys.stdout.flush() +"#; + #[test] fn stdio_server_round_trip() { let _one = test_lock(); @@ -887,6 +1007,105 @@ mod tests { assert!(!names_this_computer(&one("", &[], "http://10.0.0.1:3900/mcp"))); } + /// A server that says 「my tools changed」 is taken at its word: the reader thread hands + /// the refresh to its own thread and the new tool shows up without a reconnect. + #[test] + fn list_changed_refetches_the_tools() { + let _turn = test_lock(); + let dir = std::env::temp_dir().join(format!("anybot-mcp-changed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("server.py"); + std::fs::write(&script, CHANGING_SERVER).unwrap(); + let s = Server { name: "庫存".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env: BTreeMap::new(), url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new() }; + let errs = sync(std::slice::from_ref(&s)); + assert!(errs.is_empty(), "{errs:?}"); + assert!(!tools().iter().any(|t| t.name == "extra"), "starts without the extra tool"); + // Trigger the announcement: the fake server emits list_changed on a call named + // refresh — send it through the server's own handle, like AnyBot's call() does. + { + let conn = conns().lock().unwrap().get("庫存").cloned().unwrap(); + let mut live = conn.live.lock().unwrap(); + live.request("tools/call", json!({"name": "refresh", "arguments": {}})).unwrap(); + } + let mut got = false; + for _ in 0..60 { + if tools().iter().any(|t| t.server == "庫存" && t.name == "extra") { + got = true; + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + sync(&[]); + let _ = std::fs::remove_dir_all(&dir); + assert!(got, "the tool list did not refresh after list_changed"); + } + + /// A stdio server that answers once and then dies: the dying link is evicted by the + /// call that finds it, and the next sync starts a fresh one — no manual reconnect. + const DYING_SERVER: &str = r#" +import sys, json +for line in sys.stdin: + m = json.loads(line) + if "id" not in m: + continue + if m["method"] == "initialize": + r = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "dying"}} + elif m["method"] == "tools/list": + r = {"tools": [{"name": "bye", "description": "Answer once, then exit", "inputSchema": {"type": "object", "properties": {}}}]} + elif m["method"] == "tools/call": + sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": {"content": [{"type": "text", "text": "bye"}]}}) + "\n") + sys.stdout.flush() + sys.exit(0) + else: + r = {} + sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": m["id"], "result": r}) + "\n") + sys.stdout.flush() +"#; + + #[test] + fn a_dead_server_is_evicted_and_started_again() { + let _turn = test_lock(); + let dir = std::env::temp_dir().join(format!("anybot-mcp-dying-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("server.py"); + std::fs::write(&script, DYING_SERVER).unwrap(); + let s = Server { name: "短命".into(), command: "python3".into(), args: vec!["-I".into(), script.display().to_string()], env: BTreeMap::new(), url: String::new(), headers: BTreeMap::new(), enabled: true, instructions: String::new() }; + let errs = sync(std::slice::from_ref(&s)); + assert!(errs.is_empty(), "{errs:?}"); + let name = tool_name("短命", "bye"); + // The server exits right after answering this call. + let (out, ok, _) = call(&name, "{}"); + assert!(ok && out.contains("bye"), "{out}"); + // The next call finds the dead link: it fails, and the server is evicted. + let (out, ok, _) = call(&name, "{}"); + assert!(!ok, "{out}"); + assert!(!status().contains_key("短命"), "the dead server was not evicted"); + // And the next sync brings it back on its own. + let errs = sync(std::slice::from_ref(&s)); + assert!(errs.is_empty(), "{errs:?}"); + assert_eq!(status().get("短命").copied(), Some(1), "the server did not come back"); + // A sync also notices a child that died quietly between calls (try_wait). + let (out, ok, _) = call(&name, "{}"); + assert!(ok && out.contains("bye"), "{out}"); + std::thread::sleep(Duration::from_millis(300)); + let errs = sync(std::slice::from_ref(&s)); + assert!(errs.is_empty(), "{errs:?}"); + assert_eq!(status().get("短命").copied(), Some(1), "the dead child was not restarted"); + sync(&[]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// What counts as the change notice, and a notice riding an HTTP answer stream must not + /// be taken for the answer. + #[test] + fn the_change_notice_is_recognised() { + assert!(is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}))); + assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "id": 3, "result": {}}))); + assert!(!is_list_changed(&json!({"jsonrpc": "2.0", "method": "notifications/message"}))); + let sse = "data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\n\ndata: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"tools\":[]}}\n"; + assert!(parse_http_answer(sse, 9).unwrap()["tools"].is_array()); + } + /// The registry's answer as the 公用市集 lists it: servers reached by address (streamable /// HTTP first), the key's placeholder kept, none taken down, packages left out, one row each. #[test] @@ -939,6 +1158,74 @@ mod tests { assert!(http_refusal(500, true, false, "boom").contains("HTTP 500")); } + /// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and + /// shouts list_changed over the SSE stream. Setup: + /// 1. /tmp/openapimcp-live.yaml exists (port 3901, Spec.File /tmp/openapimcp-live.json, + /// ReloadSeconds 60 so only the management endpoint reloads — the openapimcp repo ships one), + /// 2. from the openapimcp repo: ./bin/srv -f /tmp/openapimcp-live.yaml + /// Then: cargo test openapimcp_live -- --ignored --nocapture + /// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE + /// stream and refresh the tools without a reconnect. + #[test] + #[ignore] + fn openapimcp_live() { + const LIVE_SPEC: &str = "/tmp/openapimcp-live.json"; + const MANAGE: &str = "http://localhost:3901"; + let mini = |extra: &str| { + r#"{"swagger":"2.0","basePath":"/","info":{"title":"Live"},"paths":{"/v1/ping":{"get":{"summary":"Ping","responses":{"200":{"description":"ok"}}}}@}}"# + .replace("@", extra) + }; + let post = |path: &str| { + let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(5))).http_status_as_error(false).build().into(); + agent.post(&format!("{MANAGE}{path}")).send(()).ok().and_then(|mut r| r.body_mut().read_to_string().ok()) + }; + let health_tools = || -> Option { + 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::(&b).ok()?.get("tools")?.as_u64()? as usize) + }; + let _turn = test_lock(); + // Settle the SERVER on the baseline before opening any MCP session, so no ticker + // notification can race with the listener's GET starting: write baseline, reload, wait + // for the health endpoint to report the baseline tool count (ping + api_search + api_call). + std::fs::write(LIVE_SPEC, mini("")).unwrap(); + post("/api/reload"); + let mut settled = false; + for _ in 0..50 { + if health_tools() == Some(3) { + settled = true; + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + let s = remote_server("openapi", "http://localhost:3901/mcp", ""); + let errs = sync(&[s]); + if !errs.is_empty() { + eprintln!("openapimcp 沒跑在 :3901 — 先照上方說明啟動:{errs:?}"); + sync(&[]); + return; + } + assert!(settled, "server did not settle on the baseline (3 tools)"); + assert!(tools().iter().any(|t| t.name == "v1_ping_get"), "tools: {:?}", tools().iter().map(|t| t.name.clone()).collect::>()); + assert!(!tools().iter().any(|t| t.name == "v1_echo_get")); + let (out, ok, _) = call(&tool_name("openapi", "api_search"), r#"{"keyword":"ping"}"#); + assert!(ok && out.contains("v1_ping_get"), "{out}"); + // The spec gains a path; ask the server to reload now. It shouts list_changed on the + // open SSE stream; the listener refreshes the tools in place, no reconnect. + std::fs::write(LIVE_SPEC, mini(r#","/v1/echo":{"get":{"summary":"Echo","responses":{"200":{"description":"ok"}}}}"#)).unwrap(); + post("/api/reload"); + let mut got = false; + for _ in 0..100 { + if tools().iter().any(|t| t.name == "v1_echo_get") { + got = true; + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + sync(&[]); + assert!(got, "SSE 監聽沒有刷新工具清單(v1_echo_get 沒出現)"); + } + /// Run by hand (it goes out to the internet): `cargo test registry_search_live -- --ignored`. #[test] #[ignore]