From bb46dea125894e99d68508c9a93c34be8f629318 Mon Sep 17 00:00:00 2001 From: anybot Date: Thu, 12 Nov 2026 11:31:31 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E5=99=A8:=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E8=AF=B4=E3=80=8C=E5=B7=A5=E5=85=B7=E5=8F=98?= =?UTF-8?q?=E4=BA=86=E3=80=8D=E5=B0=B1=E7=AB=8B=E5=88=BB=E9=87=8D=E6=8A=93?= =?UTF-8?q?=20=E2=80=94=20stdio=20=E9=80=9A=E7=9F=A5=E4=B8=8E=20Streamable?= =?UTF-8?q?=20HTTP=20=E7=9A=84=E9=95=BF=E9=A9=BB=20SSE=20=E9=83=BD?= =?UTF-8?q?=E4=BC=9A=E9=80=81=E5=88=B0=EF=BC=8C=E6=97=A0=E9=9C=80=E9=87=8D?= =?UTF-8?q?=E8=BF=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mcp.rs | 219 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 214 insertions(+), 5 deletions(-) diff --git a/src/mcp.rs b/src/mcp.rs index c72f2fd..dc4028e 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -67,7 +67,8 @@ struct Live { struct Conn { live: Mutex, - tools: Vec, + /// Refetched in place when the server sends `notifications/tools/list_changed`. + tools: Mutex>, config: Server, } @@ -105,6 +106,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); @@ -235,9 +241,17 @@ fn connect(s: &Server) -> Result { let stdin = child.stdin.take().ok_or("沒有標準輸入")?; let stdout = child.stdout.take().ok_or("沒有標準輸出")?; let (tx, rx) = channel(); + let watcher = s.name.clone(); std::thread::spawn(move || { for line in BufReader::new(stdout).lines().map_while(Result::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. Refreshing is cheap. + let n = watcher.clone(); + std::thread::spawn(move || refresh_tools(&n)); + continue; + } if tx.send(v).is_err() { break; } @@ -249,19 +263,73 @@ fn connect(s: &Server) -> Result { let mut live = Live { link, next_id: 1 }; live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?; live.notify("notifications/initialized"); + let 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, String> { let mut tools = vec![]; let mut cursor: Option = None; for _ in 0..20 { let r = live.request("tools/list", match &cursor { Some(x) => json!({"cursor": x}), None => json!({}) })?; for t in r["tools"].as_array().into_iter().flatten() { - tools.push(ToolInfo { server: s.name.clone(), name: t["name"].as_str().unwrap_or("").into(), description: t["description"].as_str().unwrap_or("").into(), schema: t["inputSchema"].clone() }); + 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() }); } cursor = r["nextCursor"].as_str().map(String::from); if cursor.is_none() { break; } } - Ok(Conn { live: Mutex::new(live), tools, config: s.clone() }) + Ok(tools) +} + +/// 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, 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)); + } + }); } /// Start (or keep) the enabled servers; stop the rest. Returns errors per server. @@ -301,11 +369,11 @@ pub fn sync(servers: &[Server]) -> Vec<(String, String)> { /// 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() } /// Tool specs for the model. @@ -522,8 +590,37 @@ for line in sys.stdin: sys.stdout.flush() "#; + /// 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() +"#; + #[test] fn stdio_server_round_trip() { + let _turn = SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner()); 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"); @@ -543,6 +640,50 @@ for line in sys.stdin: let _ = std::fs::remove_dir_all(&dir); } + /// 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()); + } + /// 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] @@ -595,6 +736,74 @@ for line in sys.stdin: 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 = 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::>()); + 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] From 41aca0a7096ac2ccba9d22ce2173a26ea49c20d5 Mon Sep 17 00:00:00 2001 From: daniel wang Date: Thu, 12 Nov 2026 15:04:05 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E9=80=A3=E6=8E=A5=E5=99=A8:=20=E6=8E=9B?= =?UTF-8?q?=E6=8E=89=E7=9A=84=E4=BC=BA=E6=9C=8D=E5=99=A8=E6=9C=83=E8=87=AA?= =?UTF-8?q?=E5=B7=B1=E6=B4=BB=E9=81=8E=E4=BE=86=20=E2=80=94=20=E5=91=BC?= =?UTF-8?q?=E5=8F=AB=E7=99=BC=E7=8F=BE=E6=96=B7=E7=B7=9A=E5=B0=B1=E8=B8=A2?= =?UTF-8?q?=E6=8E=89=E9=80=A3=E7=B7=9A=E3=80=81sync=20=E5=81=B5=E6=B8=AC?= =?UTF-8?q?=E5=88=B0=E8=A1=8C=E7=A8=8B=E5=B7=B2=E6=AD=BB=E5=B0=B1=E9=87=8D?= =?UTF-8?q?=E5=95=9F=E3=80=81=E6=AF=8F=E5=8D=8A=E5=88=86=E9=90=98=E8=87=AA?= =?UTF-8?q?=E5=8B=95=E9=87=8D=E6=8E=83=E4=B8=80=E6=AC=A1,=E4=B8=8D?= =?UTF-8?q?=E7=94=A8=E6=89=8B=E5=8B=95=E9=87=8D=E9=80=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/channels_ui.rs | 14 ++++-- src/mcp.rs | 97 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 104 insertions(+), 7 deletions(-) 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]