//! Remote MCP servers the hub signs in to for the sessions: a service's own //! Streamable-HTTP MCP endpoint (cartopolis.org's `/mcp`, its content pages), //! whose tools every session gets through the midas MCP server it already has, //! while the token stays on the hub. //! //! `midas mcp` lists each remote's tools beside its own, renamed //! `__` (`session_tools`), from what the remote last announced to //! the hub; a call to one goes to the hub, which forwards it with the bearer it //! holds (`call_from_session` → `POST /v1/remotes/call`). So it reaches every //! session that has midas's MCP server — the runner's, Zed's, a terminal's — //! with no server of its own, and a session never sees the token: revoking it //! at the service is the one off switch, and a transcript cannot leak it. //! //! Kept in `remote-mcp.json` beside the state directory, private, as the //! OpenAI key is (`discuss.rs`); set on the hub's machine with //! `midas remote set ` and the token on stdin. use std::collections::BTreeMap; use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::Mutex; use std::time::{Duration, Instant}; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::store; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Remote { pub url: String, pub token: String, } fn path() -> PathBuf { let root = crate::registry::root(); root.parent().map(|p| p.join("remote-mcp.json")).unwrap_or_else(|| root.join("remote-mcp.json")) } fn read() -> BTreeMap { std::fs::read_to_string(path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default() } /// A name an MCP server may carry in a session's tool names: `mcp____tool`. fn valid_name(name: &str) -> bool { (1..=40).contains(&name.len()) && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } /// Add or replace a remote; an empty token removes it. The token is never said back. pub fn set(name: &str, url: &str, token: &str, by: &str) -> Result<()> { if !valid_name(name) { bail!("a remote's name is lower-case letters, digits and hyphens: it becomes the sessions' mcp__{name}__… tools"); } let token = token.trim(); let mut all = read(); if token.is_empty() { all.remove(name); } else { if !url.starts_with("https://") && !url.starts_with("http://127.0.0.1") && !url.starts_with("http://localhost") { bail!("the endpoint is https:// (plain http only on this machine): the token travels with every call"); } if !token.bytes().all(|b| b.is_ascii_graphic()) { bail!("that token has spaces or control characters in it"); } all.insert(name.to_string(), Remote { url: url.to_string(), token: token.to_string() }); } store::write_atomic(&path(), serde_json::to_string_pretty(&all)?.as_bytes(), store::PRIVATE)?; CACHE.lock().unwrap_or_else(|p| p.into_inner()).remove(name); crate::events::emit("settings_changed", json!({"actor": by, "what": format!("remote mcp {name}"), "set": !token.is_empty()})); Ok(()) } /// One JSON-RPC message to a remote, its answer back. The token and the body /// go to curl as a config on stdin (`mcp::curl_forgejo`), never in argv. fn rpc(remote: &Remote, message: &Value) -> Result { let quote = crate::util::curl_quote; let cfg = format!( "silent\nshow-error\nrequest = \"POST\"\nurl = {}\nheader = {}\nheader = \"Content-Type: application/json\"\n\ header = \"Accept: application/json, text/event-stream\"\nheader = {}\ndata-binary = {}\nwrite-out = \"\\n%{{http_code}}\"\n", quote(&remote.url), quote(&format!("Authorization: Bearer {}", remote.token)), quote(&format!("MCP-Protocol-Version: {}", crate::mcp::PROTOCOL)), quote(&message.to_string()), ); let mut child = Command::new("curl").args(["-K", "-", "--max-time", "90"]) .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()) .spawn().context("starting curl")?; child.stdin.take().context("curl's stdin")?.write_all(cfg.as_bytes())?; let out = child.wait_with_output()?; let text = String::from_utf8_lossy(&out.stdout).to_string(); let (body, code) = text.rsplit_once('\n').unwrap_or(("", text.as_str())); let code: u16 = code.trim().parse().unwrap_or(0); match code { 0 => bail!("could not reach {}: {}", remote.url, String::from_utf8_lossy(&out.stderr).trim()), 202 => Ok(Value::Null), 401 | 403 => bail!("{} refused the hub's token ({code}): {}", remote.url, error_text(body)), 200 => parse(body), _ => bail!("{} answered {code}: {}", remote.url, error_text(body)), } } fn error_text(body: &str) -> String { serde_json::from_str::(body).ok().and_then(|v| v["error"].as_str().map(str::to_string)).unwrap_or_else(|| body.chars().take(200).collect()) } /// A JSON answer, or the last `data:` event of a stream that carries one. fn parse(body: &str) -> Result { if let Ok(v) = serde_json::from_str::(body) { return Ok(v); } body.lines().rev().find_map(|l| l.strip_prefix("data:").and_then(|d| serde_json::from_str(d.trim()).ok())) .context("the remote's answer was neither JSON nor an event stream") } /// What a remote last announced, kept for a while: every session asks once at /// its start, and a remote's tools change with its deploys, not by the minute. struct Announced { at: Instant, tools: Value, instructions: Value, } static CACHE: Mutex> = Mutex::new(BTreeMap::new()); const FRESH: Duration = Duration::from_secs(600); fn announced(name: &str, remote: &Remote) -> Result<(Value, Value)> { if let Some(a) = CACHE.lock().unwrap_or_else(|p| p.into_inner()).get(name).filter(|a| a.at.elapsed() < FRESH) { return Ok((a.tools.clone(), a.instructions.clone())); } let init = rpc(remote, &json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": crate::mcp::PROTOCOL, "capabilities": {}, "clientInfo": {"name": "midas hub", "version": crate::VERSION}}}))?; let _ = rpc(remote, &json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); let list = rpc(remote, &json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}))?; if let Some(e) = list.get("error") { bail!("{name}: {}", e["message"].as_str().unwrap_or("tools/list failed")); } let tools = list["result"]["tools"].clone(); let instructions = init["result"]["instructions"].clone(); CACHE.lock().unwrap_or_else(|p| p.into_inner()) .insert(name.to_string(), Announced { at: Instant::now(), tools: tools.clone(), instructions: instructions.clone() }); Ok((tools, instructions)) } /// The endpoint of a remote the hub has, for a token given again (sessions.rs, `awaits`). pub fn url_of(name: &str) -> Option { read().remove(name).map(|r| r.url) } pub fn known(name: &str) -> bool { url_of(name).is_some() } /// `GET /v1/remotes`: each remote's name, address and tools — never its token. /// A remote that does not answer is listed with its error and no tools. pub fn list() -> Value { let remotes: Vec = read().iter().map(|(name, r)| match announced(name, r) { Ok((tools, instructions)) => json!({"name": name, "url": r.url, "tools": tools, "instructions": instructions}), Err(e) => json!({"name": name, "url": r.url, "tools": [], "error": format!("{e:#}")}), }).collect(); json!({"remotes": remotes}) } /// `POST /v1/remotes/call`: one `tools/call`, forwarded with the hub's token. pub fn call(name: &str, request: &Value, by: &str) -> Result { let Some(remote) = read().remove(name) else { bail!("no remote MCP server {name} on this hub") }; if request["method"] != "tools/call" { bail!("only tools/call is forwarded"); } let tool = request["params"]["name"].as_str().unwrap_or("").to_string(); let answer = rpc(&remote, request)?; crate::events::emit("remote_call", json!({"remote": name, "tool": tool, "by": by, "error": answer["result"]["isError"].as_bool().unwrap_or(answer.get("error").is_some())})); Ok(answer) } /// A remote's tool as `midas mcp` offers it: `__`, so a session /// sees `mcp__midas__cartopolis-pages__put_page` beside midas's own tools. const SEP: &str = "__"; /// The remotes' tools, for `midas mcp`'s `tools/list`: each renamed into the /// remote's namespace and told where it acts. None when the hub cannot say. pub fn session_tools() -> Vec { let Ok(v) = crate::client::get("/v1/remotes") else { return vec![] }; let mut out = Vec::new(); for r in v["remotes"].as_array().into_iter().flatten() { let (Some(name), Some(tools)) = (r["name"].as_str(), r["tools"].as_array()) else { continue }; let host = r["url"].as_str().unwrap_or(name).trim_start_matches("https://").split('/').next().unwrap_or(name).to_string(); for t in tools { let Some(tool) = t["name"].as_str() else { continue }; let full = format!("{name}{SEP}{tool}"); // A tool name is at most 64 characters (Claude's limit); a longer one is left out, not cut. if full.len() > 64 { continue; } let mut t = t.clone(); t["name"] = json!(full); t["description"] = json!(format!("{host}, as the Midas hub's account there: {}", t["description"].as_str().unwrap_or(""))); out.push(t); } } out } /// `midas mcp`'s `tools/call` for a remote's tool: `None` when `name` is not /// one, else the remote's result as it gave it (an `isError` result included). pub fn call_from_session(name: &str, args: &Value) -> Option> { let (remote, tool) = name.split_once(SEP)?; if !valid_name(remote) || tool.is_empty() { return None; } let session = std::env::var("MIDAS_OWNER").unwrap_or_default(); let request = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": args}}); Some((|| { let v = crate::client::post_long("/v1/remotes/call", &json!({"name": remote, "request": request, "session": session.strip_prefix("session-").unwrap_or(&session)}), Duration::from_secs(120))?; if v["response"]["result"].is_object() { return Ok(v["response"]["result"].clone()); } bail!("{}", v["response"]["error"]["message"].as_str().or(v["error"].as_str()).unwrap_or("the remote gave no result")) })()) } /// `midas remote list`. pub fn cli_list() -> Result { let v = crate::client::get("/v1/remotes")?; let remotes = v["remotes"].as_array().cloned().unwrap_or_default(); if remotes.is_empty() { println!("no remote MCP servers (midas remote set , the token on stdin, on the hub's machine)"); } for r in remotes { let tools: Vec<&str> = r["tools"].as_array().into_iter().flatten().filter_map(|t| t["name"].as_str()).collect(); match r["error"].as_str() { Some(e) => println!("{} {} — {e}", r["name"].as_str().unwrap_or(""), r["url"].as_str().unwrap_or("")), None => println!("{} {} — {} tools: {}", r["name"].as_str().unwrap_or(""), r["url"].as_str().unwrap_or(""), tools.len(), tools.join(", ")), } } Ok(0) } /// `midas remote set `, the token read from stdin (empty removes it). pub fn cli_set(name: &str, url: &str) -> Result { let mut token = String::new(); std::io::stdin().read_line(&mut token)?; set(name, url, &token, &std::env::var("USER").unwrap_or_else(|_| "cli".into()))?; println!("{}", if token.trim().is_empty() { format!("removed {name}") } else { format!("{name} set; sessions started from now get its tools") }); Ok(0) } #[cfg(test)] mod tests { use super::*; /// A stand-in remote: answers initialize, tools/list and tools/call, and only /// to the right bearer. fn stand_in() -> String { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap().to_string(); std::thread::spawn(move || { for c in listener.incoming().flatten() { std::thread::spawn(move || { use std::io::{BufRead, Read}; let mut c = c; let mut reader = std::io::BufReader::new(c.try_clone().unwrap()); let (mut len, mut auth) = (0usize, String::new()); loop { let mut line = String::new(); if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { break; } let lower = line.to_ascii_lowercase(); if let Some(v) = lower.strip_prefix("content-length:") { len = v.trim().parse().unwrap_or(0); } if lower.starts_with("authorization:") { auth = line["authorization:".len()..].trim().to_string(); } } let mut body = vec![0; len]; reader.read_exact(&mut body).unwrap(); let msg: Value = serde_json::from_slice(&body).unwrap(); let (status, answer) = if auth != "Bearer s3cret" { ("401 Unauthorized", json!({"error": "not signed in"})) } else { match msg["method"].as_str().unwrap_or("") { "initialize" => ("200 OK", json!({"jsonrpc": "2.0", "id": msg["id"], "result": {"instructions": "Pages."}})), "tools/list" => ("200 OK", json!({"jsonrpc": "2.0", "id": msg["id"], "result": {"tools": [{"name": "put_page"}]}})), "tools/call" => ("200 OK", json!({"jsonrpc": "2.0", "id": msg["id"], "result": { "content": [{"type": "text", "text": format!("called {}", msg["params"]["name"].as_str().unwrap())}], "isError": false}})), _ => ("202 Accepted", Value::Null), } }; let text = if answer.is_null() { String::new() } else { answer.to_string() }; let _ = write!(c, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}", text.len()); }); } }); format!("http://{addr}/mcp") } #[test] fn a_remotes_tools_are_listed_and_called_with_the_hubs_token_never_shown() { let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner()); crate::tests::scratch("remote-mcp"); let url = stand_in(); assert!(set("Pages!", &url, "s3cret", "t").is_err(), "a name is a tool-name prefix"); assert!(set("pages", "http://example.org/mcp", "s3cret", "t").is_err(), "the token travels only over https"); set("cartopolis-pages", &url, "s3cret", "t").unwrap(); let listed = list(); assert_eq!(listed["remotes"][0]["tools"][0]["name"], "put_page"); assert_eq!(listed["remotes"][0]["instructions"], "Pages."); assert!(!listed.to_string().contains("s3cret"), "the list never carries the token"); let mode = std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(path()).unwrap().permissions()); assert_eq!(mode & 0o777, 0o600); let request = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "put_page", "arguments": {}}}); let answer = call("cartopolis-pages", &request, "s1").unwrap(); assert_eq!(answer["result"]["content"][0]["text"], "called put_page"); assert!(call("cartopolis-pages", &json!({"method": "tools/list"}), "s1").is_err(), "only calls are forwarded"); assert!(call("nope", &request, "s1").is_err()); // A wrong token is the remote's refusal, said plainly. set("cartopolis-pages", &url, "wrong", "t").unwrap(); let err = call("cartopolis-pages", &request, "s1").unwrap_err(); assert!(format!("{err:#}").contains("refused the hub's token"), "{err:#}"); assert!(list()["remotes"][0]["error"].as_str().unwrap().contains("refused")); // midas's own tools are never taken for a remote's. assert!(call_from_session("nodes_status", &json!({})).is_none()); assert!(call_from_session("Bad Name__x", &json!({})).is_none()); assert!(call_from_session("cartopolis-pages__", &json!({})).is_none()); set("cartopolis-pages", &url, "", "t").unwrap(); assert_eq!(list()["remotes"], json!([])); } }