From bb46dea125894e99d68508c9a93c34be8f629318 Mon Sep 17 00:00:00 2001 From: anybot Date: Thu, 12 Nov 2026 11:31:31 +0800 Subject: [PATCH] =?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]