diff --git a/src/app/channels_ui.rs b/src/app/channels_ui.rs index 7baafa4..28c1c3c 100644 --- a/src/app/channels_ui.rs +++ b/src/app/channels_ui.rs @@ -28,6 +28,9 @@ pub struct ChannelUi { /// Teams sign-in: the code to show, and the refresh token when done. ms_login: Arc)>>, mcp_sig: String, + /// Last connector sync: a server whose process died is restarted by the next one, so + /// nobody has to visit the page to bring it back. + mcp_last: std::time::Instant, pub(super) mcp_errors: Arc>>, mcp_busy: Arc, new_mcp: (String, String, String, String), @@ -58,7 +61,7 @@ impl Default for ChannelUi { fn default() -> Self { let (tx, rx) = channel(); let (trig_tx, trig_rx) = channel(); - ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), sub: 0, adding: false, focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), focus_form: false, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } + ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_last: std::time::Instant::now(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), sub: 0, adding: false, focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), focus_form: false, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() } } } @@ -407,13 +410,18 @@ impl App { // ---------- 連接器 (MCP) ---------- impl App { - /// Connect the configured MCP servers when they change (in the background). + /// Connect the configured MCP servers when they change (in the background), and re-sync + /// every half minute: sync keeps what is alive and starts again what died, so a server + /// that was killed, crashed, or lost its machine reconnects on its own. fn mcp_poll(&mut self, ctx: &egui::Context) { let sig = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default(); - if sig == self.ch.mcp_sig || self.ch.mcp_busy.load(Ordering::SeqCst) { + if (sig == self.ch.mcp_sig && self.ch.mcp_last.elapsed() < std::time::Duration::from_secs(30)) + || self.ch.mcp_busy.load(Ordering::SeqCst) + { return; } self.ch.mcp_sig = sig; + self.ch.mcp_last = std::time::Instant::now(); let servers = self.state.mcp_servers.clone(); let (errs, busy, c) = (self.ch.mcp_errors.clone(), self.ch.mcp_busy.clone(), ctx.clone()); busy.store(true, Ordering::SeqCst); diff --git a/src/mcp.rs b/src/mcp.rs index dc4028e..a434898 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -342,7 +342,16 @@ 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(); map.retain(|name, c| { - let keep = wanted.iter().any(|s| &s.name == name && **s == c.config); + 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 connection would only ever answer 「the server has ended」. + if keep { + if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { + if child.try_wait().ok().flatten().is_some() { + keep = false; + } + } + } if !keep { if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { let _ = child.kill(); @@ -405,8 +414,13 @@ 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})) { + // Release the link lock before evicting: evict reaches for the table's lock, and a link + // lock must never be held while taking it. + let result = { + let mut live = conn.live.lock().unwrap(); + live.request("tools/call", json!({"name": tool, "arguments": arguments})) + }; + match result { Ok(r) => { let mut text = String::new(); let mut image = None; @@ -430,7 +444,27 @@ pub fn call(name: &str, args: &str) -> (String, bool, Option) { let ok = r["isError"].as_bool() != Some(true); (crate::tools::head_tail(text.trim()), ok, image) } - Err(e) => (e, false, None), + Err(e) => { + if link_dead(&e) { + evict(&server); + } + (e, false, None) + } + } +} + +/// An error that means the link itself is dead (broken pipe, the server ended): only a +/// fresh connection can help, so the call evicts the server and the next sync rebuilds it. +fn link_dead(e: &str) -> bool { + e.starts_with("送不出去") || e.contains("已經結束") +} + +/// Forget a server's connection (killing its process); the next sync starts a new one. +fn evict(name: &str) { + if let Some(c) = conns().lock().unwrap().remove(name) { + if let Link::Stdio { child, .. } = &mut c.live.lock().unwrap().link { + let _ = child.kill(); + } } } @@ -673,6 +707,61 @@ for line in sys.stdin: 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 = SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + 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]