diff --git a/.claude/skills/devstack/SKILL.md b/.claude/skills/devstack/SKILL.md index 8392a3b5..cb74b970 100644 --- a/.claude/skills/devstack/SKILL.md +++ b/.claude/skills/devstack/SKILL.md @@ -152,6 +152,10 @@ takes `profile`, `run` and `yes` (as `--profile`, `--run`, `--yes`) and `lane_start` takes `profile`, `run` and `timeout_s` too; `logs` takes `file` (one kept log, from its list); `diagnostics` takes `source: "hub"` for the hub's log. Each tool describes its parameters. +Tools named `__` are not devstack's: they are the user's MCP +upstreams, which the hub logs in to (the dashboard's *MCP upstreams*). One +that answers it is not logged in needs the user, in the dashboard; tell them, +do not look for another way in. Register it once (project `.mcp.json` or user configuration; the dashboard shows *no MCP* in the stack's head while neither has it): diff --git a/CHANGELOG.md b/CHANGELOG.md index 0145ab02..77faa156 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,8 +17,14 @@ and listed with their assets on the itself, with OAuth (it finds the authorization server, registers where the server allows it, PKCE; the browser comes back to the hub) or a token the user gives it, and keeps the login in the keychain (a file on - a Linux machine without a Secret Service). Their tools in `devstack mcp` - follow. + a Linux machine without a Secret Service). `devstack mcp` offers their + tools in every coding agent as `__`, beside its own, and + calls them through the hub, which starts when it does not run; the token + never leaves the hub. One that is logged out or unreachable keeps the + tools it listed last and answers with the dashboard's page; a change of + the tools is announced (`notifications/tools/list_changed`). Without a + hub (`DEVSTACK_NO_HUB`), upstreams without a login or with a token from + the environment are asked directly. ### Changed diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index fe8d188a..74f52a03 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -37,6 +37,7 @@ static UI: Dir<'_> = include_dir!("$OUT_DIR/ui"); mod branches; mod guests; mod mcp; +mod mcpclient; mod notice; mod notify; mod open; @@ -48,7 +49,7 @@ mod share; mod shared; mod summary; pub mod tray; -mod upstreams; +pub mod upstreams; mod ws; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -485,6 +486,8 @@ fn router(state: AppState) -> axum::Router { .route("/auth", get(auth)) .route(upstreams::CALLBACK, get(upstream_callback)) .route("/hub/upstreams", get(upstreams_list).post(upstream_put)) + .route("/hub/upstreams/tools", get(upstream_tools)) + .route("/hub/upstreams/call", post(upstream_call)) .route("/hub/upstreams/{name}", delete(upstream_remove)) .route("/hub/upstreams/{name}/login", post(upstream_login)) .route("/hub/upstreams/{name}/token", post(upstream_token)) @@ -2457,6 +2460,43 @@ async fn upstream_put(State(s): State, Json(u): Json__`, allowlists applied); for `devstack mcp`, with +/// the user token (card point 2). +async fn upstream_tools(State(s): State) -> Response { + let ups = s.upstreams.clone(); + match tokio::task::spawn_blocking(move || ups.tools(&upstreams::http())).await { + Ok(tools) => Json(serde_json::json!({ "tools": tools })).into_response(), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Deserialize)] +struct CallBody { + name: String, + #[serde(default)] + arguments: serde_json::Value, +} + +/// `POST /hub/upstreams/call {name, arguments}`: the upstream's answer to a +/// tool call, a `CallToolResult`. The credential stays in the hub. +async fn upstream_call(State(s): State, Json(b): Json) -> Response { + let ups = s.upstreams.clone(); + let name = b.name.clone(); + match tokio::task::spawn_blocking(move || ups.call(&upstreams::calls(), &b.name, b.arguments)) + .await + { + Ok(r) => { + diag::info( + "upstream_call", + serde_json::json!({ "tool": name, "error": r["isError"] == true }), + ); + Json(r).into_response() + } + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + /// `DELETE /hub/upstreams/{name}`: it and its credential go. async fn upstream_remove(State(s): State, Path(name): Path) -> Response { on_upstreams(&s, move |ups| { diff --git a/crates/devstack-hub/src/mcpclient.rs b/crates/devstack-hub/src/mcpclient.rs new file mode 100644 index 00000000..d5b4123a --- /dev/null +++ b/crates/devstack-hub/src/mcpclient.rs @@ -0,0 +1,233 @@ +//! A client of an MCP server over Streamable HTTP, as far as the hub needs +//! one for its upstreams (ADR-0069): `initialize` once per session, then +//! `tools/list` and `tools/call`. A request is a JSON-RPC POST; the answer is +//! JSON, or a server-sent event stream whose event with the request's id is +//! the answer. The session id the server gives comes with every later +//! request; a server that forgot it (`404`) gets a new session once. + +use serde_json::{Value, json}; + +/// The protocol version asked for; the server's answer is used after. +const PROTOCOL: &str = "2025-06-18"; + +/// A session with one upstream. +#[derive(Debug, Clone, Default)] +pub struct Session { + id: Option, + version: Option, + ready: bool, +} + +#[derive(Debug)] +pub enum Error { + /// The upstream refused the credential (`401`, `403`). + Unauthorized, + /// Anything else: not reachable, an HTTP or a JSON-RPC error. + Other(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Unauthorized => write!(f, "the upstream refused the login"), + Error::Other(e) => write!(f, "{e}"), + } + } +} + +/// `method` with `params` on the upstream at `url`: its `result`. Starts the +/// session first when it has none. +pub fn request( + http: &ureq::Agent, + url: &str, + bearer: Option<&str>, + session: &mut Session, + method: &str, + params: Value, +) -> Result { + for attempt in 0..2 { + if !session.ready { + start(http, url, bearer, session)?; + } + match post(http, url, bearer, session, method, Some(params.clone()), 2) { + Err(Gone) if attempt == 0 => { + *session = Session::default(); + } + Err(Gone) => { + return Err(Error::Other( + "the upstream keeps forgetting its session".into(), + )); + } + Ok(r) => return r, + } + } + unreachable!("the loop returns") +} + +/// The server forgot the session (`404` with one). +struct Gone; + +fn start( + http: &ureq::Agent, + url: &str, + bearer: Option<&str>, + session: &mut Session, +) -> Result<(), Error> { + *session = Session::default(); + let params = json!({ + "protocolVersion": PROTOCOL, + "capabilities": {}, + "clientInfo": { "name": "devstack-hub", "version": env!("CARGO_PKG_VERSION") }, + }); + let result = match post(http, url, bearer, session, "initialize", Some(params), 1) { + Ok(r) => r?, + Err(Gone) => { + return Err(Error::Other( + "the upstream refused to start a session".into(), + )); + } + }; + session.version = result["protocolVersion"].as_str().map(str::to_string); + // The notification has no answer to wait for (`202`). + let _ = notify(http, url, bearer, session, "notifications/initialized"); + session.ready = true; + Ok(()) +} + +fn with_headers( + mut req: ureq::RequestBuilder, + bearer: Option<&str>, + session: &Session, +) -> ureq::RequestBuilder { + req = req + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream"); + if let Some(b) = bearer { + req = req.header("Authorization", &format!("Bearer {b}")); + } + if let Some(id) = &session.id { + req = req.header("Mcp-Session-Id", id); + } + if let Some(v) = &session.version { + req = req.header("MCP-Protocol-Version", v); + } + req +} + +fn notify( + http: &ureq::Agent, + url: &str, + bearer: Option<&str>, + session: &Session, + method: &str, +) -> Result<(), String> { + let body = json!({ "jsonrpc": "2.0", "method": method }); + with_headers(http.post(url), bearer, session) + .send(body.to_string()) + .map(|_| ()) + .map_err(|e| e.to_string()) +} + +/// One request: `Err(Gone)` when the server forgot the session; else its +/// result or why not. +fn post( + http: &ureq::Agent, + url: &str, + bearer: Option<&str>, + session: &mut Session, + method: &str, + params: Option, + id: u64, +) -> Result, Gone> { + let mut body = json!({ "jsonrpc": "2.0", "id": id, "method": method }); + if let Some(p) = params { + body["params"] = p; + } + let mut r = match with_headers(http.post(url), bearer, session).send(body.to_string()) { + Ok(r) => r, + Err(e) => return Ok(Err(Error::Other(format!("{url}: {e}")))), + }; + let status = r.status().as_u16(); + if status == 404 && session.id.is_some() { + return Err(Gone); + } + if status == 401 || status == 403 { + return Ok(Err(Error::Unauthorized)); + } + if let Some(s) = r + .headers() + .get("mcp-session-id") + .and_then(|v| v.to_str().ok()) + { + session.id = Some(s.to_string()); + } + let sse = r + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|c| c.starts_with("text/event-stream")); + let text = match r.body_mut().read_to_string() { + Ok(t) => t, + Err(e) => return Ok(Err(Error::Other(format!("{url}: {e}")))), + }; + if !(200..300).contains(&status) { + return Ok(Err(Error::Other(format!( + "{url} answered {status}: {}", + text.trim() + )))); + } + let answer = if sse { + from_events(&text, id) + } else { + serde_json::from_str(&text).ok() + }; + let Some(a) = answer else { + return Ok(Err(Error::Other(format!( + "{url} gave no answer to `{method}`" + )))); + }; + if let Some(e) = a.get("error") { + return Ok(Err(Error::Other(format!( + "`{method}`: {}", + e["message"].as_str().unwrap_or("an error") + )))); + } + Ok(Ok(a.get("result").cloned().unwrap_or(Value::Null))) +} + +/// The JSON-RPC answer with `id` in a server-sent event stream. +fn from_events(text: &str, id: u64) -> Option { + let mut data = String::new(); + let mut found = None; + for line in text.lines().chain(std::iter::once("")) { + if let Some(d) = line.strip_prefix("data:") { + if !data.is_empty() { + data.push('\n'); + } + data.push_str(d.strip_prefix(' ').unwrap_or(d)); + } else if line.is_empty() && !data.is_empty() { + if let Ok(v) = serde_json::from_str::(&data) + && v["id"] == json!(id) + { + found = Some(v); + } + data.clear(); + } + } + found +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_answer_is_found_among_events() { + let text = "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\n\n\ + data: {\"jsonrpc\":\"2.0\",\"id\":2,\n\ + data: \"result\":{\"tools\":[]}}\n\n"; + let v = from_events(text, 2).unwrap(); + assert_eq!(v["result"]["tools"], json!([])); + assert!(from_events(text, 3).is_none()); + } +} diff --git a/crates/devstack-hub/src/secrets.rs b/crates/devstack-hub/src/secrets.rs index 1c4dc3c9..5d9e4e7e 100644 --- a/crates/devstack-hub/src/secrets.rs +++ b/crates/devstack-hub/src/secrets.rs @@ -30,8 +30,15 @@ pub struct Secrets { } enum Store { - Keychain { service: String }, - File { path: PathBuf, lock: Mutex<()> }, + Keychain { + service: String, + }, + File { + path: PathBuf, + lock: Mutex<()>, + }, + /// None: `devstack mcp` without a hub reads no secret (ADR-0069 point 6). + Nothing, } impl Secrets { @@ -57,9 +64,16 @@ impl Secrets { } } + /// A store that holds nothing and takes nothing. + pub fn nothing() -> Self { + Self { + store: Store::Nothing, + } + } + pub fn kind(&self) -> Kind { match self.store { - Store::Keychain { .. } => Kind::Keychain, + Store::Keychain { .. } | Store::Nothing => Kind::Keychain, Store::File { .. } => Kind::File, } } @@ -76,6 +90,7 @@ impl Secrets { let _held = lock.lock().unwrap(); Ok(read_file(path)?.remove(upstream)) } + Store::Nothing => Ok(None), } } @@ -90,6 +105,7 @@ impl Secrets { all.insert(upstream.to_string(), secret.to_string()); write_file(path, &all) } + Store::Nothing => Err("no secret is kept here".into()), } } @@ -108,6 +124,7 @@ impl Secrets { } Ok(()) } + Store::Nothing => Ok(()), } } } diff --git a/crates/devstack-hub/src/upstreams.rs b/crates/devstack-hub/src/upstreams.rs index fd3ab84e..cd9fb44a 100644 --- a/crates/devstack-hub/src/upstreams.rs +++ b/crates/devstack-hub/src/upstreams.rs @@ -22,6 +22,7 @@ use std::time::{Duration, Instant}; use base64::Engine as _; use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use sha2::Digest as _; use crate::secrets::Secrets; @@ -145,6 +146,9 @@ enum Secret { }, } +/// When an upstream was asked for its tools, and what it answered. +type Listed = (Instant, Result, String>); + /// A login started and not come back yet. struct Flow { upstream: String, @@ -164,6 +168,13 @@ pub struct Upstreams { flows: Mutex>, /// One configuration change at a time. write: Mutex<()>, + /// The MCP session with each upstream. + sessions: Mutex>, + /// The tools each upstream listed last, kept across restarts: a + /// logged-out or unreachable upstream keeps them listed (card point 5). + seen: PathBuf, + /// When each upstream was asked last, and what it answered then. + listed: Mutex>, } /// An upstream as the dashboard lists it: never a secret. @@ -179,11 +190,27 @@ pub struct View { impl Upstreams { pub fn open(dir: PathBuf) -> Self { + Self::with(dir.clone(), Secrets::open(dir)) + } + + /// Its configuration without any secret: what `devstack mcp` uses without + /// a hub, where only upstreams without a login or with a token from the + /// environment work (ADR-0069 point 6). It keeps no tools of its own. + pub fn without_secrets(dir: PathBuf) -> Self { + let mut u = Self::with(dir, Secrets::nothing()); + u.seen = PathBuf::new(); + u + } + + fn with(dir: PathBuf, secrets: Secrets) -> Self { Self { file: dir.join("upstreams.toml"), - secrets: Secrets::open(dir), + seen: dir.join("upstream-tools.json"), + secrets, flows: Mutex::new(HashMap::new()), write: Mutex::new(()), + sessions: Mutex::new(HashMap::new()), + listed: Mutex::new(HashMap::new()), } } @@ -406,9 +433,7 @@ impl Upstreams { /// The bearer token for a call to `name` now: a static one, or the /// login's access token, refreshed when it is about to expire (or when /// `stale`, after the upstream refused it). `None`: it needs none, or it - /// is logged out. Used by the proxy for `devstack mcp`, which follows - /// (ADR-0069); tested here with the login it belongs to. - #[cfg_attr(not(test), allow(dead_code))] + /// is logged out. pub fn bearer( &self, http: &ureq::Agent, @@ -468,6 +493,215 @@ impl Upstreams { } } +/// How long a tool list is taken as current. +const LISTED_FOR: Duration = Duration::from_secs(60); + +/// The page of the dashboard where upstreams are logged in. +fn dashboard() -> String { + format!("http://127.0.0.1:{}/#/upstreams", crate::port()) +} + +impl Upstreams { + /// `method` on upstream `u` with its credential; a refused one is + /// refreshed once (`stale`) before it counts as logged out. + fn ask( + &self, + http: &ureq::Agent, + u: &Upstream, + method: &str, + params: Value, + ) -> Result { + for stale in [false, true] { + let bearer = self.bearer(http, &u.name, stale)?; + if bearer.is_none() && !matches!(u.auth, Auth::None) { + return Err(format!( + "devstack is not logged in to the MCP upstream `{}`: log in at {}", + u.name, + dashboard() + )); + } + let mut session = self + .sessions + .lock() + .unwrap() + .remove(&u.name) + .unwrap_or_default(); + let r = crate::mcpclient::request( + http, + &u.url, + bearer.as_deref(), + &mut session, + method, + params.clone(), + ); + self.sessions + .lock() + .unwrap() + .insert(u.name.clone(), session); + match r { + Ok(v) => return Ok(v), + Err(crate::mcpclient::Error::Unauthorized) if !stale => continue, + Err(crate::mcpclient::Error::Unauthorized) => { + return Err(format!( + "the MCP upstream `{}` refused devstack's login: log in again at {}", + u.name, + dashboard() + )); + } + Err(e) => return Err(format!("the MCP upstream `{}`: {e}", u.name)), + } + } + unreachable!("the loop returns") + } + + /// The tools `u` offers now, all pages, before its allowlist. + fn list_tools(&self, http: &ureq::Agent, u: &Upstream) -> Result, String> { + let mut tools = Vec::new(); + let mut cursor: Option = None; + for _ in 0..20 { + let params = cursor + .as_ref() + .map_or_else(|| json!({}), |c| json!({ "cursor": c })); + let r = self.ask(http, u, "tools/list", params)?; + tools.extend(r["tools"].as_array().cloned().unwrap_or_default()); + cursor = r["nextCursor"].as_str().map(str::to_string); + if cursor.is_none() { + break; + } + } + Ok(tools) + } + + fn seen_tools(&self) -> HashMap> { + std::fs::read(&self.seen) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() + } + + fn keep_seen(&self, name: &str, tools: &[Value]) { + if self.seen.as_os_str().is_empty() { + return; + } + let mut all = self.seen_tools(); + if all.get(name).is_some_and(|t| t == tools) { + return; + } + all.insert(name.to_string(), tools.to_vec()); + if let Ok(text) = serde_json::to_vec(&all) { + let _ = std::fs::write(&self.seen, text); + } + } + + /// What `u` lists now, at most a minute old; `Err` with why it could + /// not be asked. + fn current(&self, http: &ureq::Agent, u: &Upstream) -> Result, String> { + if let Some((at, r)) = self.listed.lock().unwrap().get(&u.name) + && at.elapsed() < LISTED_FOR + { + return r.clone(); + } + let r = self.list_tools(http, u); + if let Ok(t) = &r { + self.keep_seen(&u.name, t); + } + self.listed + .lock() + .unwrap() + .insert(u.name.clone(), (Instant::now(), r.clone())); + r + } + + /// The tools of every upstream, as an agent sees them through + /// `devstack mcp`: `__`, its allowlist applied. One that + /// cannot be asked keeps the tools it listed last, said in their + /// description; one never listed shows a single `__login` that + /// says how to get its tools (card point 5). + pub fn tools(&self, http: &ureq::Agent) -> Vec { + let Ok(all) = self.list() else { + return Vec::new(); + }; + let seen = self.seen_tools(); + let mut out = Vec::new(); + for u in &all { + let prefix = u.prefix(); + let (tools, why) = match self.current(http, u) { + Ok(t) => (t, None), + Err(e) => (seen.get(&u.name).cloned().unwrap_or_default(), Some(e)), + }; + if tools.is_empty() { + if let Some(why) = why { + out.push(json!({ + "name": format!("{prefix}__login"), + "description": format!("The tools of the MCP upstream `{}` are not here yet: {why}", u.name), + "inputSchema": { "type": "object", "properties": {} }, + })); + } + continue; + } + for t in tools { + let Some(name) = t["name"].as_str() else { + continue; + }; + if !u.allow.is_empty() && !u.allow.iter().any(|a| a == name) { + continue; + } + let mut t = t.clone(); + t["name"] = json!(format!("{prefix}__{name}")); + let what = t["description"].as_str().unwrap_or("").to_string(); + t["description"] = json!(match &why { + None => format!("[{} via devstack] {what}", u.name), + Some(w) => format!("[{} via devstack, not available now: {w}] {what}", u.name), + }); + out.push(t); + } + } + out + } + + /// Call `__` with `arguments`: the upstream's + /// `CallToolResult`, or one with `isError` that says why not. + pub fn call(&self, http: &ureq::Agent, name: &str, arguments: Value) -> Value { + let failed = |text: String| json!({ "content": [{ "type": "text", "text": text }], "isError": true }); + let Ok(all) = self.list() else { + return failed("the hub cannot read its upstreams".into()); + }; + let Some((u, tool)) = all.iter().find_map(|u| { + name.strip_prefix(&format!("{}__", u.prefix())) + .map(|t| (u, t)) + }) else { + return failed(format!("no MCP upstream has the tool `{name}`")); + }; + if tool == "login" + && !self + .seen_tools() + .get(&u.name) + .is_some_and(|t| t.iter().any(|x| x["name"] == "login")) + { + return failed(format!( + "log in to the MCP upstream `{}` at {}", + u.name, + dashboard() + )); + } + if !u.allow.is_empty() && !u.allow.iter().any(|a| a == tool) { + return failed(format!( + "`{tool}` of `{}` is not among the tools allowed in the dashboard", + u.name + )); + } + match self.ask( + http, + u, + "tools/call", + json!({ "name": tool, "arguments": arguments }), + ) { + Ok(r) => r, + Err(e) => failed(e), + } + } +} + fn now_s() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -655,6 +889,21 @@ fn token_request( serde_json::from_str(&text).map_err(|e| format!("{endpoint}: {e}")) } +/// The agent a tool call goes out with: a tool may work for minutes. +pub fn calls() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(600))) + .http_status_as_error(false) + .build() + .new_agent() +} + +/// The hub's state directory, where `upstreams.toml` is: for `devstack mcp` +/// without a hub. +pub fn dir() -> PathBuf { + crate::state_dir() +} + /// The agent the hub talks to upstreams and their servers with: errors as /// answers, a time limit. pub fn http() -> ureq::Agent { @@ -877,4 +1126,167 @@ mod tests { assert_eq!(ups.bearer(&http, &name, false).unwrap(), None); let _ = ups.remove(&name); } + + /// An MCP server over Streamable HTTP that wants `Bearer good`: a + /// session, `search` and `drop`, `tools/call` answered as an event + /// stream. What each request named as its method. + fn fake_mcp() -> (String, Seen) { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://127.0.0.1:{}", l.local_addr().unwrap().port()); + let seen: Seen = std::sync::Arc::new(Mutex::new(Vec::new())); + let s = seen.clone(); + std::thread::spawn(move || { + for mut c in l.incoming().flatten() { + let mut r = BufReader::new(c.try_clone().unwrap()); + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + let (mut len, mut auth, mut session) = (0, String::new(), String::new()); + loop { + let mut h = String::new(); + r.read_line(&mut h).unwrap(); + if h.trim().is_empty() { + break; + } + let lower = h.to_ascii_lowercase(); + if let Some(v) = lower.strip_prefix("content-length:") { + len = v.trim().parse().unwrap(); + } else if lower.starts_with("authorization:") { + auth = h[14..].trim().to_string(); + } else if lower.starts_with("mcp-session-id:") { + session = h[15..].trim().to_string(); + } + } + let mut body = vec![0; len]; + r.read_exact(&mut body).unwrap(); + let m: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let method = m["method"].as_str().unwrap_or("").to_string(); + s.lock().unwrap().push((method.clone(), session.clone())); + let reply = |c: &mut std::net::TcpStream, + status: u16, + ctype: &str, + extra: &str, + text: &str| { + let _ = write!( + c, + "HTTP/1.1 {status} X\r\nContent-Type: {ctype}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n{text}", + text.len() + ); + }; + if auth != "Bearer good" { + reply(&mut c, 401, "application/json", "", "{}"); + continue; + } + let id = m["id"].clone(); + match method.as_str() { + "initialize" => { + let text = serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": {} } } }).to_string(); + reply( + &mut c, + 200, + "application/json", + "Mcp-Session-Id: s-1\r\n", + &text, + ); + } + "notifications/initialized" => reply(&mut c, 202, "application/json", "", ""), + "tools/list" => { + let text = serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [ + { "name": "search", "description": "Find issues", "inputSchema": { "type": "object" } }, + { "name": "drop", "description": "Delete everything", "inputSchema": { "type": "object" } }, + ] } }).to_string(); + reply(&mut c, 200, "application/json", "", &text); + } + "tools/call" => { + let q = m["params"]["arguments"]["q"].as_str().unwrap_or(""); + let answer = serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": { "content": [{ "type": "text", "text": format!("found {q}") }] } }); + let text = format!( + "event: message\ndata: {{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}}\n\nevent: message\ndata: {answer}\n\n" + ); + reply(&mut c, 200, "text/event-stream", "", &text); + } + _ => reply(&mut c, 400, "application/json", "", "{}"), + } + } + }); + (base, seen) + } + + #[test] + fn an_upstreams_tools_are_offered_with_its_prefix_and_called_through_the_hub() { + let (base, seen) = fake_mcp(); + let d = tempfile::tempdir().unwrap(); + let ups = Upstreams::open(d.path().to_path_buf()); + let name = format!("u{}", std::process::id()); + ups.put(Upstream { + name: name.clone(), + url: format!("{base}/mcp"), + prefix: Some("tr".into()), + allow: vec!["search".into()], + auth: Auth::Token { env: None }, + }) + .unwrap(); + let http = http(); + // Logged out and never listed: one tool that says how to get them. + let tools = ups.tools(&http); + assert_eq!(tools.len(), 1, "{tools:?}"); + assert_eq!(tools[0]["name"], "tr__login"); + assert!(ups.call(&http, "tr__login", json!({}))["isError"] == true); + + ups.set_token(&name, "good").unwrap(); + ups.listed.lock().unwrap().clear(); + let tools = ups.tools(&http); + let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect(); + assert_eq!(names, ["tr__search"], "the allowlist keeps `drop` out"); + assert!( + tools[0]["description"] + .as_str() + .unwrap() + .contains("via devstack") + ); + + let r = ups.call(&http, "tr__search", json!({ "q": "login bug" })); + assert_eq!(r["content"][0]["text"], "found login bug", "{r}"); + assert!( + ups.call(&http, "tr__drop", json!({}))["isError"] == true, + "not allowed" + ); + assert!(ups.call(&http, "other__search", json!({}))["isError"] == true); + // One session for all of it. + let sent = seen.lock().unwrap().clone(); + assert_eq!( + sent.iter().filter(|(m, _)| m == "initialize").count(), + 1, + "{sent:?}" + ); + assert!( + sent.iter() + .filter(|(m, _)| m == "tools/call") + .all(|(_, s)| s == "s-1"), + "{sent:?}" + ); + + // A refused token: its tools stay listed, a call says to log in again. + ups.set_token(&name, "revoked").unwrap(); + ups.sessions.lock().unwrap().clear(); + ups.listed.lock().unwrap().clear(); + let tools = ups.tools(&http); + assert_eq!(tools.len(), 1); + assert!( + tools[0]["description"] + .as_str() + .unwrap() + .contains("not available now"), + "{tools:?}" + ); + let r = ups.call(&http, "tr__search", json!({ "q": "x" })); + assert!( + r["isError"] == true + && r["content"][0]["text"] + .as_str() + .unwrap() + .contains("log in again"), + "{r}" + ); + let _ = ups.remove(&name); + } } diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index 1dd276f7..1d427427 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -17,6 +17,7 @@ mod mcp; mod poolcmd; mod selfcmd; mod tray; +mod upstream; use devstack_skills as skills; mod topcmd; mod update; diff --git a/crates/devstack/src/mcp.rs b/crates/devstack/src/mcp.rs index a6cd23c2..c355a46f 100644 --- a/crates/devstack/src/mcp.rs +++ b/crates/devstack/src/mcp.rs @@ -37,9 +37,51 @@ const MAX_CALLS: usize = 16; static RUNNING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The upstream tools the client was last given (`tools/list`): a change +/// of them is announced (`notifications/tools/list_changed`, ADR-0069). +static LISTED: Mutex>> = Mutex::new(None); + +/// How often the upstreams' tools are looked at for a change. +const LOOK_EVERY: Duration = Duration::from_secs(60); + +fn names(tools: &[Value]) -> Vec { + let mut n: Vec = tools + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect(); + n.sort(); + n +} + +/// Every [`LOOK_EVERY`]: the upstreams' tools, and the notification when +/// they are not the ones the client was given. A client that ignores it +/// gets them at its next `tools/list`. +fn follow_upstreams(out: Out) { + let _ = std::thread::Builder::new() + .name("mcp-upstreams".into()) + .spawn(move || { + loop { + std::thread::sleep(LOOK_EVERY); + if LISTED.lock().unwrap().is_none() { + continue; + } + let now = names(&crate::upstream::tools()); + let mut listed = LISTED.lock().unwrap(); + if listed.as_ref() != Some(&now) { + *listed = Some(now); + send( + &out, + json!({ "jsonrpc": "2.0", "method": "notifications/tools/list_changed" }), + ); + } + } + }); +} + pub fn serve(stack_file: &Path) -> Result<()> { client::serve_as("mcp"); let out: Out = Arc::new(Mutex::new(std::io::stdout())); + follow_upstreams(out.clone()); let file = std::path::absolute(stack_file)?; let mut input = std::io::stdin().lock(); let mut buf = Vec::new(); @@ -159,16 +201,27 @@ fn respond(m: Value, file: &Path) -> Option { id, json!({ "protocolVersion": version, - "capabilities": { "tools": {} }, + "capabilities": { "tools": { "listChanged": true } }, "serverInfo": { "name": "devstack", "version": env!("CARGO_PKG_VERSION") }, "instructions": INSTRUCTIONS, }), ) } "ping" => reply(id, json!({})), - "tools/list" => reply(id, json!({ "tools": tools() })), + "tools/list" => { + // The user's MCP upstreams' tools beside devstack's own (ADR-0069). + let upstream = crate::upstream::tools(); + *LISTED.lock().unwrap() = Some(names(&upstream)); + let mut all = tools(); + all.extend(upstream); + reply(id, json!({ "tools": all })) + } "tools/call" => { let name = params["name"].as_str().unwrap_or("").to_string(); + if crate::upstream::is_upstream(&name) { + let args = params.get("arguments").cloned().unwrap_or(json!({})); + return Some(reply(id, crate::upstream::call(&name, args))); + } if !tools().iter().any(|t| t["name"] == name) { return Some(error(id, -32602, &format!("unknown tool `{name}`"))); } diff --git a/crates/devstack/src/upstream.rs b/crates/devstack/src/upstream.rs new file mode 100644 index 00000000..0f286472 --- /dev/null +++ b/crates/devstack/src/upstream.rs @@ -0,0 +1,106 @@ +//! The tools of the user's MCP upstreams in `devstack mcp` (ADR-0069; review +//! card on #316, points 2, 5, 6): listed beside devstack's own as +//! `__`, and called through the hub, which holds the logins. +//! The hub is started when it does not run. Without a hub +//! (`DEVSTACK_NO_HUB`), only upstreams without a login or with a token from +//! the environment are asked, from here. + +use serde_json::{Value, json}; +use std::time::Duration; + +/// The hub's answer, or `None` when there is none to ask. +fn hub(path: &str, body: Option, within: Duration) -> Option { + if std::env::var_os("DEVSTACK_NO_HUB").is_some() { + return None; + } + let port = devstack_hub::ensure_running().ok()?; + let token = devstack_daemon::token::load().filter(|t| !t.is_empty())?; + let agent = ureq::Agent::config_builder() + .timeout_global(Some(within)) + .http_status_as_error(false) + .build() + .new_agent(); + let url = format!("http://127.0.0.1:{port}{path}"); + let auth = format!("Bearer {token}"); + let mut r = match body { + Some(b) => agent + .post(&url) + .header("Authorization", &auth) + .header("X-Devstack-Client", "mcp") + .header("Content-Type", "application/json") + .send(b.to_string()) + .ok()?, + None => agent + .get(&url) + .header("Authorization", &auth) + .header("X-Devstack-Client", "mcp") + .call() + .ok()?, + }; + if r.status() != 200 { + return None; + } + serde_json::from_str(&r.body_mut().read_to_string().ok()?).ok() +} + +/// The user configured upstreams at all: else neither the hub is started +/// nor anything asked. +fn configured() -> bool { + std::fs::read_to_string(devstack_hub::upstreams::dir().join("upstreams.toml")) + .is_ok_and(|t| t.contains("[[upstream]]")) +} + +fn direct() -> devstack_hub::upstreams::Upstreams { + devstack_hub::upstreams::Upstreams::without_secrets(devstack_hub::upstreams::dir()) +} + +/// The upstreams' tools as an agent sees them. +pub fn tools() -> Vec { + if !configured() { + return Vec::new(); + } + if std::env::var_os("DEVSTACK_NO_HUB").is_some() { + return direct().tools(&devstack_hub::upstreams::http()); + } + hub("/hub/upstreams/tools", None, Duration::from_secs(60)) + .and_then(|v| v["tools"].as_array().cloned()) + .unwrap_or_default() +} + +/// Call the upstream tool `name`: its `CallToolResult`. +pub fn call(name: &str, arguments: Value) -> Value { + if std::env::var_os("DEVSTACK_NO_HUB").is_some() { + return direct().call(&devstack_hub::upstreams::calls(), name, arguments); + } + hub( + "/hub/upstreams/call", + Some(json!({ "name": name, "arguments": arguments })), + Duration::from_secs(600), + ) + .unwrap_or_else(|| { + json!({ + "content": [{ "type": "text", "text": format!( + "`{name}` goes through the devstack hub, which does not answer: `devstack hub start`, then try again" + ) }], + "isError": true, + }) + }) +} + +/// Whether `name` is an upstream's tool rather than devstack's own: its own +/// have no `__`. +pub fn is_upstream(name: &str) -> bool { + name.contains("__") +} + +#[cfg(test)] +mod tests { + #[test] + fn devstacks_own_tools_never_look_like_an_upstreams() { + for t in crate::mcp::tools() { + let name = t["name"].as_str().unwrap(); + assert!(!super::is_upstream(name), "{name}"); + } + assert!(super::is_upstream("tracker__search")); + } +} diff --git a/crates/devstack/tests/hub.rs b/crates/devstack/tests/hub.rs index 5140eb96..ae0919af 100644 --- a/crates/devstack/tests/hub.rs +++ b/crates/devstack/tests/hub.rs @@ -1369,3 +1369,132 @@ fn the_hub_writes_the_prompts_and_starts_only_agents_with_them() { assert_eq!(s, 400, "{opener}: {body}"); } } + +/// An MCP server over Streamable HTTP without a login: `echo`, and `hidden`, +/// which the allowlist keeps out. +fn fake_mcp() -> String { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://127.0.0.1:{}/mcp", l.local_addr().unwrap().port()); + std::thread::spawn(move || { + for mut c in l.incoming().flatten() { + let mut r = BufReader::new(c.try_clone().unwrap()); + let mut line = String::new(); + r.read_line(&mut line).unwrap(); + let mut len = 0; + loop { + let mut h = String::new(); + r.read_line(&mut h).unwrap(); + if h.trim().is_empty() { + break; + } + if let Some(v) = h.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap(); + } + } + let mut body = vec![0; len]; + r.read_exact(&mut body).unwrap(); + let m: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let id = m["id"].clone(); + let result = match m["method"].as_str().unwrap_or("") { + "initialize" => { + serde_json::json!({ "protocolVersion": "2025-06-18", "capabilities": {} }) + } + "tools/list" => serde_json::json!({ "tools": [ + { "name": "echo", "description": "Says it back", "inputSchema": { "type": "object" } }, + { "name": "hidden", "description": "Not offered", "inputSchema": { "type": "object" } }, + ] }), + "tools/call" => { + serde_json::json!({ "content": [{ "type": "text", "text": format!("echo: {}", m["params"]["arguments"]["say"].as_str().unwrap_or("")) }] }) + } + _ => { + let _ = write!( + c, + "HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ); + continue; + } + }; + let text = + serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(); + let _ = write!( + c, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}", + text.len() + ); + } + }); + url +} + +/// ADR-0069: `devstack mcp` offers an upstream's tools beside its own, with +/// its prefix and allowlist, and calls them through the hub. +#[test] +fn devstack_mcp_offers_and_calls_an_upstreams_tools_through_the_hub() { + let h = start(); + let url = fake_mcp(); + std::fs::write( + h.home.path().join("devstack/hub/upstreams.toml"), + format!( + "[[upstream]]\nname = \"fake\"\nurl = \"{url}\"\nprefix = \"fk\"\nallow = [\"echo\"]\n" + ), + ) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let mut mcp = Command::new(BIN) + .arg("mcp") + .current_dir(dir.path()) + .env("DEVSTACK_HUB_PORT", h.port.to_string()) + .env("LOCALAPPDATA", h.home.path()) + .env("XDG_STATE_HOME", h.home.path()) + .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = mcp.stdin.take().unwrap(); + let mut lines = BufReader::new(mcp.stdout.take().unwrap()).lines(); + let mut ask = |msg: serde_json::Value| -> serde_json::Value { + writeln!(stdin, "{msg}").unwrap(); + stdin.flush().unwrap(); + loop { + let line = lines.next().unwrap().unwrap(); + let v: serde_json::Value = serde_json::from_str(&line).unwrap(); + if v["id"] == msg["id"] { + return v; + } + } + }; + let init = ask( + serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "t", "version": "1" } } }), + ); + assert_eq!( + init["result"]["capabilities"]["tools"]["listChanged"], true, + "{init}" + ); + let list = ask(serde_json::json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list" })); + let names: Vec<&str> = list["result"]["tools"] + .as_array() + .unwrap() + .iter() + .filter_map(|t| t["name"].as_str()) + .collect(); + assert!( + names.contains(&"status") && names.contains(&"fk__echo"), + "{names:?}" + ); + assert!(!names.contains(&"fk__hidden"), "{names:?}"); + let call = ask( + serde_json::json!({ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "fk__echo", "arguments": { "say": "hello" } } }), + ); + assert_eq!( + call["result"]["content"][0]["text"], "echo: hello", + "{call}" + ); + let refused = ask( + serde_json::json!({ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "fk__hidden", "arguments": {} } }), + ); + assert_eq!(refused["result"]["isError"], true, "{refused}"); + drop(stdin); + let _ = mcp.wait(); +} diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index c2a51bb1..03b679fc 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -91,6 +91,8 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `DELETE /hub/upstreams/{name}` | cookie + Origin | it and its credential go: `204` | | `POST /hub/upstreams/{name}/token {token}` | cookie + Origin | the static token of an upstream with `auth.kind = "token"` and no `env`, into the keychain: `204` | | `POST /hub/upstreams/{name}/login` | cookie + Origin | start its OAuth login: the authorization server found from the upstream (RFC 9728, RFC 8414), the hub registered where the server allows it (RFC 7591), PKCE with S256, the upstream as `resource`: `{url}` to open in the browser; `502 {"error"}` when the server cannot be found or refuses | +| `GET /hub/upstreams/tools` | user token (or cookie) | the upstreams' tools as `devstack mcp` offers them: `{tools: [Tool]}`, each named `__`, the allowlist applied, the description saying which upstream. One that cannot be asked (logged out, refused, unreachable) keeps the tools it listed last (kept in `upstream-tools.json` beside `upstreams.toml`), its description saying why; one never listed shows `__login`. Asked at most once a minute per upstream | +| `POST /hub/upstreams/call {name, arguments}` | user token (or cookie + Origin) | call the tool `__` on its upstream with the hub's credential (refreshed once when refused): the upstream's `CallToolResult`, or one with `isError` and why (not logged in, with the dashboard's page; not allowed; unreachable). The credential never leaves the hub | | `POST /hub/upstreams/{name}/logout` | cookie + Origin | its credential goes: `204` | | `GET /oauth/upstream/callback?code&state` | none | where the authorization server sends the browser back: a navigation from another site, so without a session; the one-time `state` of a login the hub started (within ten minutes) admits it. Exchanges the code for tokens, kept in the keychain; a page that says whether it worked | | `GET /hub/pool` | cookie | `PoolOverview`: this machine's pool, read from the coordinator with its member certificate (ADR-0032); `{"joined":false}` in no pool; `502 {"error"}` when the coordinator does not answer | diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index 0909d72d..4524cd72 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -152,6 +152,10 @@ takes `profile`, `run` and `yes` (as `--profile`, `--run`, `--yes`) and `lane_start` takes `profile`, `run` and `timeout_s` too; `logs` takes `file` (one kept log, from its list); `diagnostics` takes `source: "hub"` for the hub's log. Each tool describes its parameters. +Tools named `__` are not devstack's: they are the user's MCP +upstreams, which the hub logs in to (the dashboard's *MCP upstreams*). One +that answers it is not logged in needs the user, in the dashboard; tell them, +do not look for another way in. Register it once (project `.mcp.json` or user configuration; the dashboard shows *no MCP* in the stack's head while neither has it):