连接器: 服务器说「工具变了」就立刻重抓 — stdio 通知与 Streamable HTTP 的长驻 SSE 都会送到,无需重连
This commit is contained in:
parent
908433967a
commit
bb46dea125
219
src/mcp.rs
219
src/mcp.rs
|
|
@ -67,7 +67,8 @@ struct Live {
|
||||||
|
|
||||||
struct Conn {
|
struct Conn {
|
||||||
live: Mutex<Live>,
|
live: Mutex<Live>,
|
||||||
tools: Vec<ToolInfo>,
|
/// Refetched in place when the server sends `notifications/tools/list_changed`.
|
||||||
|
tools: Mutex<Vec<ToolInfo>>,
|
||||||
config: Server,
|
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}"))
|
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).
|
/// 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> {
|
fn wait_id(rx: &Receiver<Value>, id: u64, secs: u64) -> Result<Value, String> {
|
||||||
let deadline = std::time::Instant::now() + Duration::from_secs(secs);
|
let deadline = std::time::Instant::now() + Duration::from_secs(secs);
|
||||||
|
|
@ -235,9 +241,17 @@ fn connect(s: &Server) -> Result<Conn, String> {
|
||||||
let stdin = child.stdin.take().ok_or("沒有標準輸入")?;
|
let stdin = child.stdin.take().ok_or("沒有標準輸入")?;
|
||||||
let stdout = child.stdout.take().ok_or("沒有標準輸出")?;
|
let stdout = child.stdout.take().ok_or("沒有標準輸出")?;
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
|
let watcher = s.name.clone();
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||||
if let Ok(v) = serde_json::from_str::<Value>(&line) {
|
if let Ok(v) = serde_json::from_str::<Value>(&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() {
|
if tx.send(v).is_err() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -249,19 +263,73 @@ fn connect(s: &Server) -> Result<Conn, String> {
|
||||||
let mut live = Live { link, next_id: 1 };
|
let mut live = Live { link, next_id: 1 };
|
||||||
live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?;
|
live.request("initialize", json!({"protocolVersion": PROTOCOL, "capabilities": {}, "clientInfo": {"name": "AnyBot", "version": "1"}}))?;
|
||||||
live.notify("notifications/initialized");
|
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<Vec<ToolInfo>, String> {
|
||||||
let mut tools = vec![];
|
let mut tools = vec![];
|
||||||
let mut cursor: Option<String> = None;
|
let mut cursor: Option<String> = None;
|
||||||
for _ in 0..20 {
|
for _ in 0..20 {
|
||||||
let r = live.request("tools/list", match &cursor { Some(x) => json!({"cursor": x}), None => json!({}) })?;
|
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() {
|
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);
|
cursor = r["nextCursor"].as_str().map(String::from);
|
||||||
if cursor.is_none() {
|
if cursor.is_none() {
|
||||||
break;
|
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<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));
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start (or keep) the enabled servers; stop the rest. Returns errors per server.
|
/// 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.
|
/// The connected servers' tools.
|
||||||
pub fn tools() -> Vec<ToolInfo> {
|
pub fn tools() -> Vec<ToolInfo> {
|
||||||
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<String, usize> {
|
pub fn status() -> HashMap<String, usize> {
|
||||||
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.
|
/// Tool specs for the model.
|
||||||
|
|
@ -522,8 +590,37 @@ for line in sys.stdin:
|
||||||
sys.stdout.flush()
|
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]
|
#[test]
|
||||||
fn stdio_server_round_trip() {
|
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()));
|
let dir = std::env::temp_dir().join(format!("anybot-mcp-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
let script = dir.join("server.py");
|
let script = dir.join("server.py");
|
||||||
|
|
@ -543,6 +640,50 @@ for line in sys.stdin:
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
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
|
/// 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.
|
/// HTTP first), the key's placeholder kept, none taken down, packages left out, one row each.
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -595,6 +736,74 @@ for line in sys.stdin:
|
||||||
assert!(http_refusal(500, true, false, "boom").contains("HTTP 500"));
|
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<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 沒出現)");
|
||||||
|
}
|
||||||
|
|
||||||
/// Run by hand (it goes out to the internet): `cargo test registry_search_live -- --ignored`.
|
/// Run by hand (it goes out to the internet): `cargo test registry_search_live -- --ignored`.
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue