From d203b6ede86de442ea90a26498926ed15bd1e554 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Wed, 28 Oct 2026 13:49:22 +0100 Subject: [PATCH] feat(pool): a pool names MCP upstreams for its members (ADR-0069 option B) A pool's coordinator keeps a list of MCP upstreams (name, https URL, prefix, allowlist, how it logs in; never a secret, never a command) in upstreams.json. Admins change it with `devstack pool upstreams add|remove` or in the pool area of the dashboard, each change audited; members read it with GET /v1/upstreams (404 from an earlier coordinator reads as none). Each member's hub asks its pools every minute, off the requests, and offers the entries on the MCP upstreams page. One is used, as `:`, only once the user accepted it at the URL the pool names; a new URL asks again and forgets the old login. The user's own upstreams go first, a declined entry stays declined, two pools' entries with one prefix wait for the user to give one another, and an entry the pool drops or of a pool left goes with its login. The Windows Credential Manager lost writes and deletes made side by side (seen in the hub's tests, which also shared the user's keychain service): the hub now makes one keychain call at a time, and its tests use a keychain service each. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + crates/devstack-hub/src/lib.rs | 58 ++ crates/devstack-hub/src/pool.rs | 50 ++ crates/devstack-hub/src/secrets.rs | 31 +- crates/devstack-hub/src/upstreams.rs | 605 ++++++++++++++++-- crates/devstack-node/src/coordinator.rs | 64 ++ crates/devstack-node/src/lib.rs | 1 + crates/devstack-node/src/member.rs | 22 + crates/devstack-node/src/store.rs | 2 +- crates/devstack-node/src/upstreams.rs | 228 +++++++ crates/devstack-node/tests/upstreams.rs | 107 ++++ crates/devstack/src/dispatch/pool.rs | 5 + crates/devstack/src/main.rs | 47 ++ crates/devstack/src/poolcmd.rs | 78 +++ crates/devstack/src/upstream.rs | 7 +- ...carry-the-tools-of-upstream-mcp-servers.md | 53 +- docs/adr/README.md | 2 +- docs/dashboard-api.md | 7 +- docs/pool.md | 35 +- skills/devstack/SKILL.md | 7 +- ui/src/api/mock/index.ts | 35 +- ui/src/api/transport.ts | 4 + ui/src/api/types.ts | 22 + ui/src/components/PoolUpstreams.vue | 203 ++++++ ui/src/views/PoolView.vue | 7 +- ui/src/views/UpstreamsView.vue | 66 +- 26 files changed, 1695 insertions(+), 63 deletions(-) create mode 100644 crates/devstack-node/src/upstreams.rs create mode 100644 crates/devstack-node/tests/upstreams.rs create mode 100644 ui/src/components/PoolUpstreams.vue diff --git a/CHANGELOG.md b/CHANGELOG.md index 81e6c8b1..e3216aaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,14 @@ and listed with their assets on the worktree… in its menu; the same menu opens from a lane's "…" button or a right click on its row in the branch picker. The separate "Stop worktree" and "Discard data" buttons are gone. +- **A pool names MCP upstreams for its members** (ADR-0069 option B): + `devstack pool upstreams add|remove` (admins) or the pool area of the + dashboard keep a list of URLs on the coordinator, never a secret or a + command, each change in the audit log. Each member's hub offers them on + its *MCP upstreams* page, from which pool, and uses one only once its + user accepted it, with that user's own login; a new URL is accepted + again, the user's own upstreams go first, and an entry the pool drops + goes with its login. ### Changed @@ -71,6 +79,10 @@ and listed with their assets on the - **The dashboard's MCP upstreams page** has the spacing of the other cards: a header with the Add button, the text and the form inside the card's padding instead of on its border. +- **Logins in the Windows Credential Manager** can no longer be lost when + two are written or removed at once (seen in the tests; parallel tool + calls refreshing tokens could do it): the hub makes one keychain call at + a time. ## [0.27.1] - 2026-10-28 diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index d255ff90..2dd1835b 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -443,6 +443,14 @@ pub fn serve() -> Result<(), String> { ) .map_err(|e| e.to_string())?; notify::start(state.clone()); + // The pools' MCP upstreams (ADR-0069 option B), off the requests. + let ups = state.upstreams.clone(); + std::thread::spawn(move || { + loop { + ups.refresh_pools(); + std::thread::sleep(upstreams::POOLS_EVERY); + } + }); tray::start_quietly(); let app = router(state); if let Some(v6) = v6 { @@ -493,6 +501,14 @@ fn router(state: AppState) -> axum::Router { .route("/hub/upstreams/{name}/login", post(upstream_login)) .route("/hub/upstreams/{name}/token", post(upstream_token)) .route("/hub/upstreams/{name}/logout", post(upstream_logout)) + .route( + "/hub/upstreams/pool/{pool}/{name}/accept", + post(upstream_accept), + ) + .route( + "/hub/upstreams/pool/{pool}/{name}/decline", + post(upstream_decline), + ) .route("/hub/pair", post(pair)) .route("/hub/shutdown", post(shutdown)) .route("/hub/session", get(session)) @@ -567,6 +583,11 @@ fn router(state: AppState) -> axum::Router { get(pool::telemetry).put(pool::set_telemetry), ) .route("/hub/pool/nodes/{id}/policy", post(pool::policy)) + .route( + "/hub/pool/upstreams", + get(pool::upstreams).post(pool::upstream_put), + ) + .route("/hub/pool/upstreams/{name}", delete(pool::upstream_remove)) .route("/hub/pool/join", post(pool::join)) .fallback(get(asset)) .layer(middleware::from_fn_with_state(state.clone(), guard)) @@ -2513,6 +2534,43 @@ async fn upstream_remove(State(s): State, Path(name): Path) -> .await } +#[derive(Deserialize, Default)] +struct AcceptBody { + /// A prefix of the user's instead of the pool's. + #[serde(default)] + prefix: Option, +} + +/// `POST /hub/upstreams/pool/{pool}/{name}/accept {prefix?}`: use an +/// upstream a pool names, at the URL it names now (ADR-0069 option B). +async fn upstream_accept( + State(s): State, + Path((pool, name)): Path<(String, String)>, + body: Option>, +) -> Response { + let b = body.map(|Json(b)| b).unwrap_or_default(); + let what = serde_json::json!({ "pool": pool, "upstream": name }); + let r = on_upstreams(&s, move |ups| ups.accept(&pool, &name, b.prefix)).await; + if r.status().is_success() { + diag::info("upstream_accept", what); + } + r +} + +/// `POST /hub/upstreams/pool/{pool}/{name}/decline`: do not use it; its +/// login goes. +async fn upstream_decline( + State(s): State, + Path((pool, name)): Path<(String, String)>, +) -> Response { + let what = serde_json::json!({ "pool": pool, "upstream": name }); + let r = on_upstreams(&s, move |ups| ups.decline(&pool, &name)).await; + if r.status().is_success() { + diag::info("upstream_decline", what); + } + r +} + #[derive(Deserialize)] struct TokenBody { token: String, diff --git a/crates/devstack-hub/src/pool.rs b/crates/devstack-hub/src/pool.rs index efbb524f..2a558926 100644 --- a/crates/devstack-hub/src/pool.rs +++ b/crates/devstack-hub/src/pool.rs @@ -18,6 +18,9 @@ //! - `POST /hub/pool/join` `{coordinator, fingerprint, name?}`: ask to join a //! pool (`devstack join` without waiting) //! - `GET /hub/pools`: the pools this machine belongs to (ADR-0034) +//! - `GET /hub/pool/upstreams`: the MCP upstreams the pool names for its +//! members; `POST /hub/pool/upstreams` (one), `DELETE +//! /hub/pool/upstreams/{name}`: an admin's changes (ADR-0069 option B) //! //! Each takes `?pool=`; without it, the default pool. @@ -557,6 +560,53 @@ pub async fn role( } } +/// `GET /hub/pool/upstreams`: the MCP upstreams the pool names for its +/// members (ADR-0069 option B). +pub async fn upstreams(Query(q): Query) -> Response { + match blocking(&q, |l| l.upstreams()).await { + Ok(v) => Json(v).into_response(), + Err(e) => error(&e), + } +} + +/// This hub asks its pools again now: an admin changed a list. +fn refresh(s: &crate::AppState) { + let ups = s.upstreams.clone(); + tokio::task::spawn_blocking(move || ups.refresh_pools()); +} + +/// `POST /hub/pool/upstreams`: add an upstream to the pool's list, or +/// change the one of its name (admins). +pub async fn upstream_put( + axum::extract::State(s): axum::extract::State, + Query(q): Query, + Json(u): Json, +) -> Response { + match blocking(&q, move |l| l.admin_upstream_put(&u)).await { + Ok(v) => { + refresh(&s); + Json(v).into_response() + } + Err(e) => error(&e), + } +} + +/// `DELETE /hub/pool/upstreams/{name}`: take an upstream off the pool's +/// list (admins). +pub async fn upstream_remove( + axum::extract::State(s): axum::extract::State, + Path(name): Path, + Query(q): Query, +) -> Response { + match blocking(&q, move |l| l.admin_upstream_remove(&name)).await { + Ok(()) => { + refresh(&s); + StatusCode::NO_CONTENT.into_response() + } + Err(e) => error(&e), + } +} + #[cfg(test)] mod tests { #[test] diff --git a/crates/devstack-hub/src/secrets.rs b/crates/devstack-hub/src/secrets.rs index 5d9e4e7e..4c37bc63 100644 --- a/crates/devstack-hub/src/secrets.rs +++ b/crates/devstack-hub/src/secrets.rs @@ -48,7 +48,9 @@ impl Secrets { Self::open_as(SERVICE, dir) } - fn open_as(service: &str, dir: PathBuf) -> Self { + /// [`Self::open`] under another service (tests: one each, so tests + /// running side by side, and the user's own entries, stay apart). + pub(crate) fn open_as(service: &str, dir: PathBuf) -> Self { if probe(service) { return Self { store: Store::Keychain { @@ -81,7 +83,10 @@ impl Secrets { /// The secret of `upstream`; `None` when there is none. pub fn get(&self, upstream: &str) -> Result, String> { match &self.store { - Store::Keychain { service } => match entry(service, upstream)?.get_password() { + Store::Keychain { service } => match entry(service, upstream).map(|e| { + let _one = keychain(); + e.get_password() + })? { Ok(s) => Ok(Some(s)), Err(keyring::Error::NoEntry) => Ok(None), Err(e) => Err(e.to_string()), @@ -96,9 +101,11 @@ impl Secrets { pub fn set(&self, upstream: &str, secret: &str) -> Result<(), String> { match &self.store { - Store::Keychain { service } => entry(service, upstream)? - .set_password(secret) - .map_err(|e| e.to_string()), + Store::Keychain { service } => { + let e = entry(service, upstream)?; + let _one = keychain(); + e.set_password(secret).map_err(|e| e.to_string()) + } Store::File { path, lock } => { let _held = lock.lock().unwrap(); let mut all = read_file(path)?; @@ -112,7 +119,10 @@ impl Secrets { /// Forget the secret of `upstream`; none there is no error. pub fn delete(&self, upstream: &str) -> Result<(), String> { match &self.store { - Store::Keychain { service } => match entry(service, upstream)?.delete_credential() { + Store::Keychain { service } => match entry(service, upstream).map(|e| { + let _one = keychain(); + e.delete_credential() + })? { Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), Err(e) => Err(e.to_string()), }, @@ -129,6 +139,15 @@ impl Secrets { } } +/// Held for each call into the keychain: the Windows Credential Manager +/// loses writes and deletes made side by side from several threads (seen in +/// the tests; the hub refreshes logins of parallel tool calls). +fn keychain() -> std::sync::MutexGuard<'static, ()> { + static ONE: Mutex<()> = Mutex::new(()); + ONE.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + fn entry(service: &str, upstream: &str) -> Result { keyring::Entry::new(service, &format!("upstream:{upstream}")).map_err(|e| e.to_string()) } diff --git a/crates/devstack-hub/src/upstreams.rs b/crates/devstack-hub/src/upstreams.rs index 7dc032d8..e1f8e53b 100644 --- a/crates/devstack-hub/src/upstreams.rs +++ b/crates/devstack-hub/src/upstreams.rs @@ -14,6 +14,15 @@ //! upstream as `resource` (RFC 8707). The browser comes back to the hub's //! own loopback port; a callback is taken only for a flow the hub started, //! by its one-time `state`, within ten minutes. No route hands a token out. +//! - **A pool's upstreams** (ADR-0069 option B; review card approved +//! 2026-10-28): each pool this machine is an approved member of may name +//! upstreams (URL only, never a secret). The hub keeps the last list it got +//! in `pool-upstreams.json` and offers them in the dashboard; one is used, +//! as `:`, only once the user accepted it at its URL. The +//! user's own configuration goes first: an entry with the name or prefix +//! of one of theirs is not taken, nor two entries of different pools with +//! one prefix until the user gives one another. An entry the pool drops, +//! or of a pool the machine left, goes with its login. use std::collections::HashMap; use std::path::PathBuf; @@ -175,6 +184,54 @@ impl Upstream { struct File { #[serde(default, rename = "upstream")] upstreams: Vec, + /// What the user decided about a pool's upstreams. + #[serde(default, rename = "pool", skip_serializing_if = "Vec::is_empty")] + decisions: Vec, +} + +/// The user's answer to an upstream a pool names. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +struct Decision { + pool: String, + name: String, + /// Accepted (at `url`), or declined. + accepted: bool, + /// The URL it was answered at: a pool that changes it asks again. + url: String, + /// The prefix the user gave it instead of the pool's. + #[serde(default, skip_serializing_if = "Option::is_none")] + prefix: Option, +} + +/// The pools' lists as the hub got them last, by pool. +type PoolLists = std::collections::BTreeMap>; + +/// What asking the pools found: each pool this machine is an approved +/// member of, with its list, or `None` when it could not be asked. A pool +/// not in it is one the machine is no longer in. +pub type Fetched = Vec<(String, Option>)>; + +type Fetch = Box Fetched + Send + Sync>; + +/// How often the hub asks its pools for their upstreams. +pub const POOLS_EVERY: Duration = Duration::from_secs(60); + +pub use devstack_node::upstreams::{PoolAuth, PoolUpstream}; + +/// Where an upstream the dashboard lists comes from, when it is a pool's. +#[derive(Debug, Clone, Serialize)] +pub struct FromPool { + pub pool: String, + /// Its name in the pool's list. + pub name: String, + /// `offered` (not answered yet), `accepted` (in use), `declined`, + /// `changed` (the pool changed its URL since it was accepted), or + /// `conflict` (`why` says with what). + pub status: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub why: Option, + /// The prefix the pool gives it. + pub pool_prefix: String, } /// What the hub keeps of an upstream's login in the secrets store. @@ -230,6 +287,11 @@ pub struct Upstreams { logs: PathBuf, /// When each upstream was asked last, and what it answered then. listed: Mutex>, + /// The pools' lists as last got (`pool-upstreams.json`). + pool_lists: PathBuf, + /// How the pools are asked; `None`: they are not (`devstack mcp` + /// without a hub uses what the hub got last). + fetch: Option, } /// An upstream as the dashboard lists it: never a secret. @@ -241,11 +303,33 @@ pub struct View { /// It has a credential (a token, or tokens of a login); with `Auth::None` /// always. pub logged_in: bool, + /// It is a pool's, and what the user made of it. + #[serde(skip_serializing_if = "Option::is_none")] + pub pool: Option, } impl Upstreams { pub fn open(dir: PathBuf) -> Self { - Self::with(dir.clone(), Secrets::open(dir)) + let state = dir.parent().map(PathBuf::from).unwrap_or_default(); + let mut u = Self::with(dir.clone(), Secrets::open(dir)); + u.fetch = Some(Box::new(move || ask_pools(&state))); + u + } + + /// A hub's upstreams for a test: secrets under a keychain service of its + /// own (tests run side by side, and must not touch the user's), the + /// pools asked with `fetch`. + #[cfg(test)] + fn for_test(dir: PathBuf, fetch: impl Fn() -> Fetched + Send + Sync + 'static) -> Self { + static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let service = format!( + "devstack-test-{}-{}", + std::process::id(), + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + ); + let mut u = Self::with(dir.clone(), Secrets::open_as(&service, dir)); + u.fetch = Some(Box::new(fetch)); + u } /// Its configuration without any secret: what `devstack mcp` uses without @@ -268,6 +352,8 @@ impl Upstreams { procs: Mutex::new(HashMap::new()), logs: dir.join("upstreams"), listed: Mutex::new(HashMap::new()), + pool_lists: dir.join("pool-upstreams.json"), + fetch: None, } } @@ -279,41 +365,17 @@ impl Upstreams { } } - pub fn list(&self) -> Result, String> { + fn read(&self) -> Result { let text = match std::fs::read_to_string(&self.file) { Ok(t) => t, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(File::default()), Err(e) => return Err(format!("{}: {e}", self.file.display())), }; - toml::from_str::(&text) - .map(|f| f.upstreams) - .map_err(|e| format!("{}: {e}", self.file.display())) - } - - pub fn views(&self) -> Result, String> { - Ok(self - .list()? - .into_iter() - .map(|u| { - let logged_in = match &u.auth { - Auth::None => true, - Auth::Token { env: Some(e) } => std::env::var_os(e).is_some(), - _ => self.secrets.get(&u.name).ok().flatten().is_some(), - }; - View { - prefix: u.prefix(), - upstream: u, - logged_in, - } - }) - .collect()) + toml::from_str::(&text).map_err(|e| format!("{}: {e}", self.file.display())) } - fn save(&self, all: &[Upstream]) -> Result<(), String> { - let text = toml::to_string_pretty(&File { - upstreams: all.to_vec(), - }) - .map_err(|e| e.to_string())?; + fn write(&self, f: &File) -> Result<(), String> { + let text = toml::to_string_pretty(f).map_err(|e| e.to_string())?; if let Some(d) = self.file.parent() { std::fs::create_dir_all(d).map_err(|e| e.to_string())?; } @@ -322,13 +384,301 @@ impl Upstreams { std::fs::rename(&tmp, &self.file).map_err(|e| e.to_string()) } + /// The user's own upstreams. + fn own(&self) -> Result, String> { + self.read().map(|f| f.upstreams) + } + + /// Every upstream in use: the user's own, and the pools' they accepted + /// that nothing else stands in the way of. + pub fn list(&self) -> Result, String> { + let f = self.read()?; + let pooled = self + .pooled(&f) + .into_iter() + .filter(|(_, p)| p.status == "accepted") + .map(|(u, _)| u); + Ok(f.upstreams.clone().into_iter().chain(pooled).collect()) + } + + /// The user configured an upstream, or accepted one of a pool: what makes + /// `devstack mcp` ask the hub at all. + pub fn configured(dir: &std::path::Path) -> bool { + std::fs::read_to_string(dir.join("upstreams.toml")) + .ok() + .and_then(|t| toml::from_str::(&t).ok()) + .is_some_and(|f| !f.upstreams.is_empty() || f.decisions.iter().any(|d| d.accepted)) + } + + pub fn views(&self) -> Result, String> { + let f = self.read()?; + let logged_in = |u: &Upstream| match &u.auth { + Auth::None => true, + Auth::Token { env: Some(e) } => std::env::var_os(e).is_some(), + _ => self.secrets.get(&u.name).ok().flatten().is_some(), + }; + let own = f.upstreams.iter().cloned().map(|u| View { + prefix: u.prefix(), + logged_in: logged_in(&u), + upstream: u, + pool: None, + }); + let pooled = self.pooled(&f).into_iter().map(|(u, p)| View { + prefix: u.prefix(), + logged_in: p.status == "accepted" && logged_in(&u), + upstream: u, + pool: Some(p), + }); + Ok(own.chain(pooled).collect()) + } + + /// Keep `all` as the user's own upstreams. + fn save(&self, all: &[Upstream]) -> Result<(), String> { + let mut f = self.read()?; + f.upstreams = all.to_vec(); + self.write(&f) + } + + fn pool_lists(&self) -> PoolLists { + std::fs::read(&self.pool_lists) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() + } + + /// Every upstream the pools name, as the hub would use it + /// (`:`, the user's prefix if they gave one), and what the + /// user made of it. + fn pooled(&self, f: &File) -> Vec<(Upstream, FromPool)> { + let mut out: Vec<(Upstream, FromPool)> = Vec::new(); + for (pool, entries) in self.pool_lists() { + for e in entries { + // A list on disk is checked again: it came from elsewhere. + if e.check().is_err() { + continue; + } + let d = f + .decisions + .iter() + .find(|d| d.pool == pool && d.name == e.name); + let prefix = d + .and_then(|d| d.prefix.clone()) + .unwrap_or_else(|| e.prefix()); + let mine = f + .upstreams + .iter() + .find(|o| o.name == e.name || o.prefix() == prefix); + let (status, why) = match (mine, d) { + (Some(o), _) => ( + "conflict", + Some(format!( + "your upstream `{}` has this name or the prefix `{prefix}`", + o.name + )), + ), + (None, None) => ("offered", None), + (None, Some(d)) if !d.accepted => ("declined", None), + (None, Some(d)) if d.url != e.url => ( + "changed", + Some(format!("the pool changed its URL from {}", d.url)), + ), + (None, Some(_)) => ("accepted", None), + }; + let auth = match &e.auth { + PoolAuth::None => Auth::None, + PoolAuth::Token => Auth::Token { env: None }, + PoolAuth::Oauth { client_id, scopes } => Auth::Oauth { + client_id: client_id.clone(), + scopes: scopes.clone(), + }, + }; + out.push(( + Upstream { + name: format!("{pool}:{}", e.name), + url: e.url.clone(), + prefix: Some(prefix), + allow: e.allow.clone(), + auth, + ..Default::default() + }, + FromPool { + pool: pool.clone(), + name: e.name.clone(), + status, + why, + pool_prefix: e.prefix(), + }, + )); + } + } + // Two pools' accepted entries with one prefix: neither, until the + // user gives one of them another. + let clash: Vec = (0..out.len()) + .filter(|&i| { + out[i].1.status == "accepted" + && out.iter().any(|o| { + o.1.status == "accepted" + && o.1.pool != out[i].1.pool + && o.0.prefix() == out[i].0.prefix() + }) + }) + .collect(); + for i in clash { + let p = out[i].0.prefix(); + out[i].1.status = "conflict"; + out[i].1.why = Some(format!( + "another pool's upstream has the prefix `{p}`: give one of them another" + )); + } + out + } + + /// Ask the pools for their upstreams (the hub does every + /// [`POOLS_EVERY`], off the requests: a coordinator that does not + /// answer takes seconds); keep what they name, and forget the decisions + /// and logins of entries a pool dropped or of pools this machine left. + /// A pool that cannot be asked keeps what it named last. + pub fn refresh_pools(&self) { + let Some(fetch) = &self.fetch else { + return; + }; + let got = fetch(); + let _one = self.write.lock().unwrap(); + let mut lists = self.pool_lists(); + lists.retain(|p, _| got.iter().any(|(g, _)| g == p)); + for (pool, list) in got { + if let Some(l) = list { + lists.insert(pool, l); + } + } + if let Ok(text) = serde_json::to_vec_pretty(&lists) { + if let Some(d) = self.pool_lists.parent() { + let _ = std::fs::create_dir_all(d); + } + let _ = std::fs::write(&self.pool_lists, text); + } + let Ok(mut f) = self.read() else { + return; + }; + let mut gone = Vec::new(); + f.decisions.retain(|d| { + let named = lists + .get(&d.pool) + .is_some_and(|l| l.iter().any(|e| e.name == d.name)); + if !named { + gone.push(format!("{}:{}", d.pool, d.name)); + } + named + }); + for key in &gone { + let _ = self.secrets.delete(key); + self.sessions.lock().unwrap().remove(key); + } + if !gone.is_empty() { + let _ = self.write(&f); + } + } + + /// The entry `name` of `pool`, as the hub got it last. + fn entry(&self, pool: &str, name: &str) -> Result { + self.pool_lists() + .remove(pool) + .and_then(|l| l.into_iter().find(|e| e.name == name)) + .ok_or_else(|| format!("the pool `{pool}` names no upstream `{name}`")) + } + + /// Use the upstream `name` of `pool` at the URL the pool names now, + /// with `prefix` instead of the pool's if given. A login for another + /// URL is forgotten. + pub fn accept(&self, pool: &str, name: &str, prefix: Option) -> Result<(), String> { + let _one = self.write.lock().unwrap(); + let mut f = self.read()?; + let entry = self.entry(pool, name)?; + let prefix = prefix + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty() && *p != entry.prefix()); + let mut probe = entry.clone(); + if prefix.is_some() { + probe.prefix = prefix.clone(); + } + probe.check()?; + let p = probe.prefix(); + let key = format!("{pool}:{name}"); + if let Some(o) = f + .upstreams + .iter() + .find(|o| o.name == name || o.prefix() == p) + { + return Err(format!( + "your upstream `{}` has the name `{name}` or the prefix `{p}`", + o.name + )); + } + if let Some((o, _)) = self + .pooled(&f) + .into_iter() + .find(|(o, s)| o.name != key && s.status == "accepted" && o.prefix() == p) + { + return Err(format!("the prefix `{p}` is `{}`'s", o.name)); + } + let d = Decision { + pool: pool.into(), + name: name.into(), + accepted: true, + url: entry.url.clone(), + prefix, + }; + match f + .decisions + .iter_mut() + .find(|d| d.pool == pool && d.name == name) + { + Some(old) => { + if old.url != entry.url { + self.secrets.delete(&key)?; + } + *old = d; + } + None => f.decisions.push(d), + } + self.sessions.lock().unwrap().remove(&key); + self.listed.lock().unwrap().remove(&key); + self.write(&f) + } + + /// Do not use the upstream `name` of `pool`; its login goes. + pub fn decline(&self, pool: &str, name: &str) -> Result<(), String> { + let _one = self.write.lock().unwrap(); + let mut f = self.read()?; + let entry = self.entry(pool, name)?; + let key = format!("{pool}:{name}"); + let d = Decision { + pool: pool.into(), + name: name.into(), + accepted: false, + url: entry.url, + prefix: None, + }; + match f + .decisions + .iter_mut() + .find(|d| d.pool == pool && d.name == name) + { + Some(old) => *old = d, + None => f.decisions.push(d), + } + self.secrets.delete(&key)?; + self.sessions.lock().unwrap().remove(&key); + self.write(&f) + } + /// Add `u`, or replace the one of its name. A change of its URL or of how /// it logs in forgets its credential: it was for the other. pub fn put(&self, u: Upstream) -> Result<(), String> { u.check()?; let name = u.name.clone(); let _one = self.write.lock().unwrap(); - let mut all = self.list()?; + let mut all = self.own()?; if all .iter() .any(|o| o.name != u.name && o.prefix() == u.prefix()) @@ -354,7 +704,7 @@ impl Upstreams { pub fn remove(&self, name: &str) -> Result { let _one = self.write.lock().unwrap(); - let mut all = self.list()?; + let mut all = self.own()?; let before = all.len(); all.retain(|u| u.name != name); if all.len() == before { @@ -1022,6 +1372,19 @@ pub fn dir() -> PathBuf { crate::state_dir() } +/// Each pool the machine whose state is `state` is an approved member of, +/// with the upstreams it names (`None`: it could not be asked). +fn ask_pools(state: &std::path::Path) -> Fetched { + devstack_node::member::pools(state) + .into_iter() + .filter_map(|(name, dir)| { + let l = devstack_node::member::Local::new(&dir); + let m = l.membership().ok().flatten()?; + (m.state == devstack_node::store::State::Approved).then(|| (name, l.upstreams().ok())) + }) + .collect() +} + /// The agent the hub talks to upstreams and their servers with: errors as /// answers, a time limit. pub fn http() -> ureq::Agent { @@ -1066,7 +1429,7 @@ mod tests { #[test] fn the_configuration_keeps_no_secret_and_forgets_one_on_a_new_url() { let d = tempfile::tempdir().unwrap(); - let ups = Upstreams::open(d.path().to_path_buf()); + let ups = Upstreams::for_test(d.path().to_path_buf(), Vec::new); let tracker = Upstream { name: "tracker".into(), url: "https://mcp.example.com/mcp".into(), @@ -1183,7 +1546,7 @@ mod tests { fn a_login_runs_once_with_pkce_and_refreshes() { let (base, seen) = fake_server(); let d = tempfile::tempdir().unwrap(); - let ups = Upstreams::open(d.path().to_path_buf()); + let ups = Upstreams::for_test(d.path().to_path_buf(), Vec::new); let name = format!("t{}", std::process::id()); ups.put(Upstream { name: name.clone(), @@ -1336,7 +1699,7 @@ mod tests { 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 ups = Upstreams::for_test(d.path().to_path_buf(), Vec::new); let name = format!("u{}", std::process::id()); ups.put(Upstream { name: name.clone(), @@ -1415,7 +1778,7 @@ mod tests { #[test] fn a_command_gets_the_token_the_hub_keeps_in_its_variable_and_nothing_else() { let d = tempfile::tempdir().unwrap(); - let ups = Upstreams::open(d.path().to_path_buf()); + let ups = Upstreams::for_test(d.path().to_path_buf(), Vec::new); let name = format!("c{}", std::process::id()); let cmd = Upstream { name: name.clone(), @@ -1458,4 +1821,174 @@ mod tests { ups.remove(&name).unwrap(); assert!(ups.procs.lock().unwrap().is_empty()); } + + /// A pool's list for the fetch of a test. + fn entry(name: &str, url: &str, prefix: Option<&str>) -> PoolUpstream { + PoolUpstream { + name: name.into(), + url: url.into(), + prefix: prefix.map(str::to_string), + auth: PoolAuth::Token, + ..Default::default() + } + } + + type Pools = std::sync::Arc>; + + fn pooled_hub(d: &std::path::Path, pools: &Pools) -> Upstreams { + let p = pools.clone(); + Upstreams::for_test(d.to_path_buf(), move || p.lock().unwrap().clone()) + } + + fn status(ups: &Upstreams, key: &str) -> Option<&'static str> { + ups.views() + .unwrap() + .into_iter() + .find(|v| v.upstream.name == key) + .and_then(|v| v.pool.map(|p| p.status)) + } + + fn used(ups: &Upstreams) -> Vec { + ups.list().unwrap().into_iter().map(|u| u.name).collect() + } + + #[test] + fn a_pools_upstream_is_used_once_accepted_and_asks_again_at_a_new_url() { + let d = tempfile::tempdir().unwrap(); + let pool = format!("t{}a", std::process::id()); + let key = format!("{pool}:wiki"); + let pools: Pools = std::sync::Arc::new(Mutex::new(vec![( + pool.clone(), + Some(vec![entry("wiki", "https://wiki.example.com/mcp", None)]), + )])); + let ups = pooled_hub(d.path(), &pools); + ups.refresh_pools(); + assert_eq!(status(&ups, &key), Some("offered")); + assert!(used(&ups).is_empty(), "offered is not used"); + assert!(!Upstreams::configured(d.path())); + + ups.accept(&pool, "wiki", None).unwrap(); + assert_eq!(status(&ups, &key), Some("accepted")); + assert_eq!(used(&ups), [key.as_str()]); + assert!(Upstreams::configured(d.path())); + ups.set_token(&key, "t-1").unwrap(); + + // The pool moves it: not used, and its login is not sent there. + *pools.lock().unwrap() = vec![( + pool.clone(), + Some(vec![entry("wiki", "https://evil.example.com/mcp", None)]), + )]; + ups.refresh_pools(); + assert_eq!(status(&ups, &key), Some("changed")); + assert!(used(&ups).is_empty()); + ups.accept(&pool, "wiki", None).unwrap(); + assert_eq!(used(&ups), [key.as_str()]); + assert_eq!( + ups.secrets.get(&key).unwrap(), + None, + "the old login is gone" + ); + + // A pool that does not answer keeps what it named. + *pools.lock().unwrap() = vec![(pool.clone(), None)]; + ups.refresh_pools(); + assert_eq!(used(&ups), [key.as_str()]); + + // Declined stays declined; its login goes. + ups.set_token(&key, "t-2").unwrap(); + ups.decline(&pool, "wiki").unwrap(); + assert_eq!(status(&ups, &key), Some("declined")); + assert!(used(&ups).is_empty()); + assert_eq!(ups.secrets.get(&key).unwrap(), None); + } + + #[test] + fn the_users_own_upstreams_go_first_and_two_pools_never_share_a_prefix() { + let d = tempfile::tempdir().unwrap(); + let (a, b) = ( + format!("t{}b", std::process::id()), + format!("t{}c", std::process::id()), + ); + let pools: Pools = std::sync::Arc::new(Mutex::new(vec![ + ( + a.clone(), + Some(vec![ + entry("wiki", "https://wiki.example.com/mcp", None), + entry("tracker", "https://tracker.example.com/mcp", None), + ]), + ), + ( + b.clone(), + Some(vec![entry("docs", "https://docs.example.com/mcp", None)]), + ), + ])); + let ups = pooled_hub(d.path(), &pools); + ups.refresh_pools(); + ups.put(Upstream { + name: "my-tracker".into(), + url: "https://mine.example.com/mcp".into(), + prefix: Some("tracker".into()), + ..Default::default() + }) + .unwrap(); + // The user's own prefix: the pool's is not taken. + assert_eq!(status(&ups, &format!("{a}:tracker")), Some("conflict")); + assert!(ups.accept(&a, "tracker", None).is_err()); + // Unless the user gives it a prefix of its own. + ups.accept(&a, "tracker", Some("team_tracker".into())) + .unwrap(); + assert_eq!(status(&ups, &format!("{a}:tracker")), Some("accepted")); + + ups.accept(&a, "wiki", None).unwrap(); + ups.accept(&b, "docs", None).unwrap(); + // Pool b gives its entry pool a's prefix: neither is used. + pools.lock().unwrap()[1].1 = Some(vec![entry( + "docs", + "https://docs.example.com/mcp", + Some("wiki"), + )]); + ups.refresh_pools(); + assert_eq!(status(&ups, &format!("{a}:wiki")), Some("conflict")); + assert_eq!(status(&ups, &format!("{b}:docs")), Some("conflict")); + assert!( + !used(&ups) + .iter() + .any(|n| n.ends_with(":wiki") || n.ends_with(":docs")) + ); + // The user gives one of them another: both are used. + ups.accept(&b, "docs", Some("docs".into())).unwrap(); + assert_eq!(status(&ups, &format!("{a}:wiki")), Some("accepted")); + assert_eq!(status(&ups, &format!("{b}:docs")), Some("accepted")); + } + + #[test] + fn an_entry_the_pool_drops_or_of_a_pool_left_goes_with_its_login() { + let d = tempfile::tempdir().unwrap(); + let pool = format!("t{}d", std::process::id()); + let key = format!("{pool}:wiki"); + let pools: Pools = std::sync::Arc::new(Mutex::new(vec![( + pool.clone(), + Some(vec![ + entry("wiki", "https://wiki.example.com/mcp", None), + entry("docs", "https://docs.example.com/mcp", None), + ]), + )])); + let ups = pooled_hub(d.path(), &pools); + ups.refresh_pools(); + ups.accept(&pool, "wiki", None).unwrap(); + ups.accept(&pool, "docs", None).unwrap(); + ups.set_token(&key, "t").unwrap(); + pools.lock().unwrap()[0].1 = + Some(vec![entry("docs", "https://docs.example.com/mcp", None)]); + ups.refresh_pools(); + assert_eq!(used(&ups), [format!("{pool}:docs")]); + assert_eq!(ups.secrets.get(&key).unwrap(), None); + + // The machine left the pool: nothing of it stays. + pools.lock().unwrap().clear(); + ups.refresh_pools(); + assert!(used(&ups).is_empty()); + assert!(ups.views().unwrap().is_empty()); + assert!(!Upstreams::configured(d.path())); + } } diff --git a/crates/devstack-node/src/coordinator.rs b/crates/devstack-node/src/coordinator.rs index a5cc02a9..afe26e3d 100644 --- a/crates/devstack-node/src/coordinator.rs +++ b/crates/devstack-node/src/coordinator.rs @@ -1200,6 +1200,8 @@ struct Inner { /// CA's fingerprint: what an enrolment names. public_url: String, fingerprint: String, + /// One change of the pool's MCP upstreams at a time (ADR-0069 option B). + upstreams: Mutex<()>, } /// A lease that waits for a machine (ADR-0051 point 5). @@ -1295,6 +1297,12 @@ fn router(shared: Shared) -> Router { .route("/v1/shared", get(shared_list)) .route("/v1/history", get(history)) .route("/v1/telemetry", get(telemetry_info)) + .route("/v1/upstreams", get(upstreams_list)) + .route("/v1/admin/upstreams", post(admin_upstream_put)) + .route( + "/v1/admin/upstreams/{name}", + axum::routing::delete(admin_upstream_remove), + ) .route( "/v1/telemetry/{kind}", post(telemetry_post).layer(axum::extract::DefaultBodyLimit::max(4 << 20)), @@ -3206,6 +3214,61 @@ async fn admin_role( Ok(Json(MemberView::for_admin(&m))) } +/// `GET /v1/upstreams`: the MCP upstreams this pool names for its members +/// (ADR-0069 option B), never a secret. +async fn upstreams_list( + AxState(s): AxState, + Extension(peer): Extension, +) -> ApiResult>> { + member(&s, &peer)?; + Ok(Json(crate::upstreams::load(&s.dir))) +} + +/// `POST /v1/admin/upstreams`: add an upstream to the pool's list, or +/// change the one of its name (admins only; audited). +async fn admin_upstream_put( + AxState(s): AxState, + Extension(peer): Extension, + Json(u): Json, +) -> ApiResult>> { + let (me, by) = admin(&s, &peer)?; + let detail = format!("{} {}", u.name, u.url); + { + let _one = s.upstreams.lock().unwrap(); + crate::upstreams::put(&s.dir, u) + .map_err(|e| (StatusCode::BAD_REQUEST, e))? + .map_err(internal)?; + } + s.store + .record(&by, "upstream", &me.id, Some(detail)) + .map_err(store_err)?; + Ok(Json(crate::upstreams::load(&s.dir))) +} + +/// `DELETE /v1/admin/upstreams/{name}`: take an upstream off the pool's +/// list (admins only; audited). +async fn admin_upstream_remove( + AxState(s): AxState, + Extension(peer): Extension, + UrlPath(name): UrlPath, +) -> ApiResult>> { + let (me, by) = admin(&s, &peer)?; + let removed = { + let _one = s.upstreams.lock().unwrap(); + crate::upstreams::remove(&s.dir, &name).map_err(internal)? + }; + if !removed { + return Err(( + StatusCode::NOT_FOUND, + format!("the pool names no upstream `{name}`"), + )); + } + s.store + .record(&by, "upstream-remove", &me.id, Some(name)) + .map_err(store_err)?; + Ok(Json(crate::upstreams::load(&s.dir))) +} + async fn admin_audit( AxState(s): AxState, Extension(peer): Extension, @@ -3289,6 +3352,7 @@ pub async fn serve_with( public_url: format!("https://{host}:{port}"), fingerprint: pki::fingerprint(&ca_pem)?, provisioner: options.provisioner, + upstreams: Mutex::new(()), ca_pem, }); if shared.provisioner.is_some() { diff --git a/crates/devstack-node/src/lib.rs b/crates/devstack-node/src/lib.rs index 95735558..e586b260 100644 --- a/crates/devstack-node/src/lib.rs +++ b/crates/devstack-node/src/lib.rs @@ -19,4 +19,5 @@ pub mod share; pub mod store; pub mod telemetry; pub mod tls; +pub mod upstreams; pub mod version; diff --git a/crates/devstack-node/src/member.rs b/crates/devstack-node/src/member.rs index c5e28628..24710cb3 100644 --- a/crates/devstack-node/src/member.rs +++ b/crates/devstack-node/src/member.rs @@ -630,6 +630,28 @@ impl Local { } /// Whether the pool collects telemetry (ADR-0037). + /// The MCP upstreams the pool names for its members (ADR-0069 option + /// B); none from a coordinator that names none yet (`404`). + pub fn upstreams(&self) -> Result> { + match self.get("/v1/upstreams") { + Err(MemberError::Status(404, _)) => Ok(Vec::new()), + r => r, + } + } + + /// Add an upstream to the pool's list, or change it (admins only). + pub fn admin_upstream_put( + &self, + u: &crate::upstreams::PoolUpstream, + ) -> Result> { + self.post("/v1/admin/upstreams", u) + } + + /// Take an upstream off the pool's list (admins only). + pub fn admin_upstream_remove(&self, name: &str) -> Result<()> { + self.delete(&format!("/v1/admin/upstreams/{name}")) + } + pub fn telemetry_info(&self) -> Result { self.get("/v1/telemetry") } diff --git a/crates/devstack-node/src/store.rs b/crates/devstack-node/src/store.rs index 866ee6f3..fa323c58 100644 --- a/crates/devstack-node/src/store.rs +++ b/crates/devstack-node/src/store.rs @@ -151,7 +151,7 @@ pub struct AuditEntry { /// Who: a member (`id (name)`) or [`SHELL`]. pub by: String, /// `approve`, `reject`, `remove`, `role`, `pause`, `resume`, `end`, - /// `tags`, `policy`. + /// `tags`, `policy`, `provisioning`, `upstream`, `upstream-remove`. pub action: String, pub member: String, pub name: String, diff --git a/crates/devstack-node/src/upstreams.rs b/crates/devstack-node/src/upstreams.rs new file mode 100644 index 00000000..329b8fd8 --- /dev/null +++ b/crates/devstack-node/src/upstreams.rs @@ -0,0 +1,228 @@ +//! The MCP upstreams a pool names for its members (ADR-0069, option B; +//! review card approved 2026-10-28): what each member's hub may offer its +//! user, never a secret. The member's hub logs in itself and uses an entry +//! only once its user accepted it. +//! +//! - **URL only** (card point 2): an entry is never a command, so a pool's +//! admin cannot run anything on a member's machine. +//! - **No credential, no variable**: an entry says how its upstream logs in +//! (OAuth, a token the member gives its own hub, or none), not with what. +//! - Kept in `upstreams.json` in the coordinator's directory; every change +//! in the audit log (card point 5). + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +const FILE: &str = "upstreams.json"; + +/// At most this many entries in a pool's list. +pub const MAX: usize = 64; + +/// One MCP upstream as a pool names it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PoolUpstream { + /// `[a-z0-9-]`, 1 to 32. + pub name: String, + /// Its MCP endpoint (Streamable HTTP), `https://`. + pub url: String, + /// What its tools are prefixed with (`__`); the name with + /// `_` for `-` when not given. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prefix: Option, + /// The tools offered; empty: all of them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub allow: Vec, + #[serde(default)] + pub auth: PoolAuth, +} + +/// How a pool's upstream logs in. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum PoolAuth { + /// No credential. + #[default] + None, + /// A static bearer token each member gives their own hub. + Token, + /// The hub's OAuth login. `client_id` (public) where the authorization + /// server does not register clients itself. + Oauth { + #[serde(default, skip_serializing_if = "Option::is_none")] + client_id: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + scopes: Vec, + }, +} + +impl PoolUpstream { + pub fn prefix(&self) -> String { + self.prefix + .clone() + .unwrap_or_else(|| self.name.replace('-', "_")) + } + + /// What is wrong with it, if anything. + pub fn check(&self) -> Result<(), String> { + let n = &self.name; + if n.is_empty() + || n.len() > 32 + || !n + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + { + return Err(format!("`{n}`: a name is 1 to 32 of a-z, 0-9 and -")); + } + let p = self.prefix(); + if p.is_empty() + || p.len() > 32 + || !p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + { + return Err(format!("`{p}`: a prefix is 1 to 32 of a-z, 0-9 and _")); + } + // A pool's `localhost` would be each member's own machine. + let u = self.url.trim(); + if u != self.url || !u.starts_with("https://") || u.len() <= "https://".len() { + return Err(format!( + "`{u}`: a pool's upstream is a URL reached over https" + )); + } + if u.len() > 2048 { + return Err("the URL is too long".into()); + } + if self.allow.len() > 256 || self.allow.iter().any(|t| t.is_empty() || t.len() > 128) { + return Err( + "the tool allowlist names 1 to 128 characters per tool, 256 at most".into(), + ); + } + Ok(()) + } +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct File { + #[serde(default)] + upstreams: Vec, +} + +/// The list in the coordinator's `dir`; none without a file. +pub fn load(dir: &Path) -> Vec { + std::fs::read(dir.join(FILE)) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .map(|f| f.upstreams) + .unwrap_or_default() +} + +fn save(dir: &Path, all: &[PoolUpstream]) -> std::io::Result<()> { + let path = dir.join(FILE); + let tmp = path.with_extension(format!("{}.tmp", crate::coordinator::random_hex(4))); + let bytes = serde_json::to_vec_pretty(&File { + upstreams: all.to_vec(), + }) + .expect("the list serialises"); + std::fs::write(&tmp, bytes) + .and_then(|()| std::fs::rename(&tmp, &path)) + .inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) +} + +/// Add `u` to the list in `dir`, or replace the entry of its name. `Err` +/// with why not (the caller's mistake), or an I/O error as `Ok(Err)`. +pub fn put(dir: &Path, u: PoolUpstream) -> Result, String> { + u.check()?; + let mut all = load(dir); + if all + .iter() + .any(|o| o.name != u.name && o.prefix() == u.prefix()) + { + return Err(format!("the prefix `{}` is another upstream's", u.prefix())); + } + let full = all.len() >= MAX; + match all.iter_mut().find(|o| o.name == u.name) { + Some(o) => *o = u, + None if full => { + return Err(format!("a pool names {MAX} upstreams at most")); + } + None => all.push(u), + } + Ok(save(dir, &all)) +} + +/// Remove the entry `name` from the list in `dir`: whether there was one. +pub fn remove(dir: &Path, name: &str) -> std::io::Result { + let mut all = load(dir); + let before = all.len(); + all.retain(|u| u.name != name); + if all.len() == before { + return Ok(false); + } + save(dir, &all).map(|()| true) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn up(name: &str, url: &str) -> PoolUpstream { + PoolUpstream { + name: name.into(), + url: url.into(), + auth: PoolAuth::Oauth { + client_id: None, + scopes: Vec::new(), + }, + ..Default::default() + } + } + + #[test] + fn an_entry_is_reached_over_https_and_never_on_the_members_machine() { + assert!(up("wiki", "https://wiki.example.com/mcp").check().is_ok()); + for bad in [ + "http://wiki.example.com/mcp", + "http://127.0.0.1:9000/mcp", + "http://localhost/mcp", + "https://", + " https://wiki.example.com/mcp", + ] { + assert!(up("wiki", bad).check().is_err(), "{bad}"); + } + assert!(up("Wiki", "https://wiki.example.com/mcp").check().is_err()); + } + + #[test] + fn a_command_in_the_list_is_not_read_as_an_entry() { + // A coordinator's file is the pool's: whatever it says, an entry + // has no command to carry. + let v: PoolUpstream = serde_json::from_str( + r#"{"name":"x","url":"https://x.example.com","command":["calc"],"auth":{"kind":"token","env":"HOME"}}"#, + ) + .unwrap(); + assert_eq!(v.auth, PoolAuth::Token); + let back = serde_json::to_value(&v).unwrap(); + assert!(back.get("command").is_none()); + assert!(back["auth"].get("env").is_none()); + } + + #[test] + fn put_replaces_by_name_refuses_a_taken_prefix_and_remove_says_whether() { + let dir = tempfile::tempdir().unwrap(); + put(dir.path(), up("wiki", "https://a.example.com/mcp")) + .unwrap() + .unwrap(); + put(dir.path(), up("wiki", "https://b.example.com/mcp")) + .unwrap() + .unwrap(); + assert_eq!(load(dir.path()).len(), 1); + assert_eq!(load(dir.path())[0].url, "https://b.example.com/mcp"); + let mut other = up("tracker", "https://c.example.com/mcp"); + other.prefix = Some("wiki".into()); + assert!(put(dir.path(), other).unwrap_err().contains("prefix")); + assert!(remove(dir.path(), "wiki").unwrap()); + assert!(!remove(dir.path(), "wiki").unwrap()); + assert!(load(dir.path()).is_empty()); + } +} diff --git a/crates/devstack-node/tests/upstreams.rs b/crates/devstack-node/tests/upstreams.rs new file mode 100644 index 00000000..b8a83393 --- /dev/null +++ b/crates/devstack-node/tests/upstreams.rs @@ -0,0 +1,107 @@ +//! The MCP upstreams a pool names (ADR-0069 option B): any member reads the +//! list, only an admin changes it, every change is in the audit log, and an +//! entry is a URL over https, never a command. + +use devstack_node::coordinator; +use devstack_node::member::{Local, MemberError}; +use devstack_node::store::{Role, SHELL, Store}; +use devstack_node::upstreams::{PoolAuth, PoolUpstream}; +use std::path::Path; + +fn coordinator(dir: &Path) -> (String, String) { + let fp = coordinator::init(dir, &["127.0.0.1".into()]).unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + let listener = rt + .block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0))) + .unwrap(); + let url = format!( + "https://127.0.0.1:{}", + listener.local_addr().unwrap().port() + ); + let dir = dir.to_path_buf(); + std::thread::spawn(move || { + rt.block_on(coordinator::serve(&dir, listener, std::future::pending())) + .unwrap(); + }); + (url, fp) +} + +fn member(coord: &Path, url: &str, fp: &str, dir: &Path, name: &str, role: Role) -> Local { + let l = Local::new(dir); + let m = l.join(url, fp, name).unwrap(); + Store::new(coord) + .approve(&m.id, &coordinator::ca(coord).unwrap(), Some(role), SHELL) + .unwrap(); + l.refresh().unwrap(); + l +} + +fn wiki(url: &str) -> PoolUpstream { + PoolUpstream { + name: "wiki".into(), + url: url.into(), + auth: PoolAuth::Oauth { + client_id: None, + scopes: Vec::new(), + }, + ..Default::default() + } +} + +#[test] +fn members_read_the_pools_upstreams_and_only_an_admin_changes_them() { + let c = tempfile::tempdir().unwrap(); + let (url, fp) = coordinator(c.path()); + let ad = tempfile::tempdir().unwrap(); + let admin = member(c.path(), &url, &fp, ad.path(), "lead-pc", Role::Admin); + let md = tempfile::tempdir().unwrap(); + let dev = member(c.path(), &url, &fp, md.path(), "dev-pc", Role::Member); + + assert!(dev.upstreams().unwrap().is_empty()); + let refused = dev.admin_upstream_put(&wiki("https://wiki.example.com/mcp")); + assert!( + matches!(refused, Err(MemberError::Status(403, _))), + "{refused:?}" + ); + + admin + .admin_upstream_put(&wiki("https://wiki.example.com/mcp")) + .unwrap(); + assert_eq!( + dev.upstreams().unwrap(), + [wiki("https://wiki.example.com/mcp")] + ); + + // Never the member's own machine, never plain http. + let local = admin.admin_upstream_put(&wiki("http://127.0.0.1:9000/mcp")); + assert!( + matches!(local, Err(MemberError::Status(400, _))), + "{local:?}" + ); + + assert!(matches!( + dev.admin_upstream_remove("wiki"), + Err(MemberError::Status(403, _)) + )); + admin.admin_upstream_remove("wiki").unwrap(); + assert!(dev.upstreams().unwrap().is_empty()); + assert!(matches!( + admin.admin_upstream_remove("wiki"), + Err(MemberError::Status(404, _)) + )); + + let audit = Store::new(c.path()).audit(50).unwrap(); + let actions: Vec<&str> = audit + .iter() + .filter(|e| e.action.starts_with("upstream")) + .map(|e| e.action.as_str()) + .collect(); + assert_eq!(actions.len(), 2, "{actions:?}"); + assert!(actions.contains(&"upstream") && actions.contains(&"upstream-remove")); + assert!( + audit + .iter() + .filter(|e| e.action.starts_with("upstream")) + .all(|e| e.by.contains("lead-pc")) + ); +} diff --git a/crates/devstack/src/dispatch/pool.rs b/crates/devstack/src/dispatch/pool.rs index 4703e78c..4a537a64 100644 --- a/crates/devstack/src/dispatch/pool.rs +++ b/crates/devstack/src/dispatch/pool.rs @@ -43,6 +43,11 @@ pub(crate) fn run(file: &Path, cmd: Cmd) -> Result<()> { } Some(PoolAction::DefaultOn { on }) => poolcmd::default_on(on.as_deref()), Some(PoolAction::Placement { lane }) => crate::client::print_placement(file, &lane), + Some(PoolAction::Upstreams { action }) => poolcmd::upstreams( + pool.as_deref() + .unwrap_or(devstack_node::member::DEFAULT_POOL), + action, + ), Some(PoolAction::Telemetry { state }) => poolcmd::telemetry( pool.as_deref() .unwrap_or(devstack_node::member::DEFAULT_POOL), diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index 0e69ecd8..f4c9e187 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -366,6 +366,34 @@ enum Cmd { }, } +#[derive(Subcommand)] +enum PoolUpstreamsAction { + /// The pool's list (the default). + List, + /// Add an upstream to the pool's list, or change the one of its name. + Add { + /// `[a-z0-9-]`, 1 to 32. + name: String, + /// Its MCP endpoint (Streamable HTTP), `https://` only. + url: String, + /// What its tools are prefixed with; the name with `_` for `-` by default. + #[arg(long)] + prefix: Option, + /// The tools offered, comma-separated; all by default. + #[arg(long, value_delimiter = ',')] + allow: Vec, + /// How it logs in: `oauth` (each member's hub, in the browser), + /// `token` (each member gives their hub one) or `none`. + #[arg(long, default_value = "oauth")] + login: String, + /// The OAuth client id, where the server registers no clients itself. + #[arg(long)] + client_id: Option, + }, + /// Take an upstream off the pool's list. + Remove { name: String }, +} + #[derive(Subcommand)] enum PoolAction { /// Whether this machine's lanes may run on nodes the pool's provisioner @@ -374,6 +402,13 @@ enum PoolAction { /// Whether this machine sends the pool's collector telemetry (ADR-0037): /// `on`, `off`, or nothing to show it and what is sent. Telemetry { state: Option }, + /// The MCP upstreams the pool names for its members (ADR-0069): each + /// member's hub offers them in the dashboard, and uses one once its user + /// accepted it. Only an admin adds or removes one. + Upstreams { + #[command(subcommand)] + action: Option, + }, /// The lanes others share with this machine (ADR-0035). Shared, /// Connect to a lane someone shares with this machine (ADR-0053): each @@ -988,6 +1023,18 @@ mod tests { Cmd::Pool { pool: Some(p), action: Some(PoolAction::Telemetry { state: Some(s) }) } if p == "team" && s == "on" )); + assert!(matches!( + parse(&["pool", "upstreams", "add", "wiki", "https://wiki.example.com/mcp", "--allow", "search,get"]).cmd, + Cmd::Pool { action: Some(PoolAction::Upstreams { action: Some(PoolUpstreamsAction::Add { name, allow, login, .. }) }), .. } + if name == "wiki" && allow == ["search", "get"] && login == "oauth" + )); + assert!(matches!( + parse(&["pool", "upstreams"]).cmd, + Cmd::Pool { + action: Some(PoolAction::Upstreams { action: None }), + .. + } + )); assert!(matches!( parse(&["pool", "default-on", "pool"]).cmd, Cmd::Pool { action: Some(PoolAction::DefaultOn { on: Some(o) }), .. } if o == "pool" diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index c6f95a36..91e47d7c 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -1188,6 +1188,84 @@ pub fn run_lane(file: &Path, on: &str, lane: &str, keep: bool) -> Result<()> { result } +/// `devstack pool upstreams [list|add|remove]`: the MCP upstreams the pool +/// names for its members (ADR-0069 option B). +pub fn upstreams(pool: &str, action: Option) -> Result<()> { + use crate::PoolUpstreamsAction as A; + use devstack_node::upstreams::{PoolAuth, PoolUpstream}; + let local = Local::new(&member_dir(pool)?); + let list = match action.unwrap_or(A::List) { + A::List => local.upstreams()?, + A::Add { + name, + url, + prefix, + allow, + login, + client_id, + } => { + let auth = match login.as_str() { + "oauth" => PoolAuth::Oauth { + client_id, + scopes: Vec::new(), + }, + "token" | "none" if client_id.is_some() => { + bail!("`--client-id` is for `--login oauth`") + } + "token" => PoolAuth::Token, + "none" => PoolAuth::None, + o => bail!("`{o}`: `oauth`, `token` or `none`"), + }; + let u = PoolUpstream { + name, + url, + prefix, + allow: allow.into_iter().filter(|t| !t.trim().is_empty()).collect(), + auth, + }; + u.check().map_err(|e| anyhow!(e))?; + let list = local.admin_upstream_put(&u)?; + println!( + "pool `{pool}` names `{}`: each member's hub offers it in the dashboard, and uses it once its user accepts it", + u.name + ); + list + } + A::Remove { name } => { + local.admin_upstream_remove(&name)?; + println!("pool `{pool}` no longer names `{name}`: members' hubs drop it and its login"); + local.upstreams()? + } + }; + if list.is_empty() { + println!("pool `{pool}` names no MCP upstreams"); + return Ok(()); + } + println!("MCP upstreams of pool `{pool}`:"); + for u in &list { + let login = match &u.auth { + PoolAuth::None => "no login".to_string(), + PoolAuth::Token => "a token each member gives".to_string(), + PoolAuth::Oauth { + client_id: Some(c), .. + } => format!("OAuth (client id {c})"), + PoolAuth::Oauth { .. } => "OAuth".to_string(), + }; + let tools = if u.allow.is_empty() { + "all tools".to_string() + } else { + u.allow.join(", ") + }; + println!( + " {:<16} {} {}__… {login}; {tools}", + u.name, + u.url, + u.prefix() + ); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::systemd_word; diff --git a/crates/devstack/src/upstream.rs b/crates/devstack/src/upstream.rs index 0f286472..b7839db4 100644 --- a/crates/devstack/src/upstream.rs +++ b/crates/devstack/src/upstream.rs @@ -43,11 +43,10 @@ fn hub(path: &str, body: Option, within: Duration) -> Option { 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. +/// The user configured upstreams at all, or accepted one of a pool: 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]]")) + devstack_hub::upstreams::Upstreams::configured(&devstack_hub::upstreams::dir()) } fn direct() -> devstack_hub::upstreams::Upstreams { diff --git a/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md b/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md index 0d49e359..00d96b26 100644 --- a/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md +++ b/docs/adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md @@ -1,6 +1,6 @@ # ADR-0069: `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub -- **Status:** Accepted (2026-10-27, [card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)); amended 2026-10-27 (the keychain spike: `keyring`, a file on Linux without a Secret Service) +- **Status:** Accepted (2026-10-27, [card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)); amended 2026-10-27 (the keychain spike: `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, card approved 2026-10-28) - **Date:** 2026-10-27 - **Deciders:** project owner - **Related:** [#316](https://github.com/nuetzliches/devstack/issues/316), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0019](0019-control-api-security.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md), [ADR-0032](0032-the-pool-is-administered-in-the-dashboard.md), [ADR-0054](0054-macos-is-a-developer-platform-in-preview.md), [ADR-0060](0060-the-tray-is-a-client-of-the-hub.md), [ADR-0067](0067-a-change-at-runtime-says-who-made-it.md) @@ -152,6 +152,47 @@ of these? upstream offers it, or no upstreams there? +## Addendum 2026-10-28: a pool names upstreams (option B) + +Option B, left for later above, is built; its review card was approved by +the owner on 2026-10-28 (all five points) and is in the description of the +pull request that built it. + +1. **A pool names MCP upstreams for its members** (name, URL, prefix, + allowlist, how it logs in, a public client id), never a secret or a + token; logging in and the tokens stay in each member's hub (point 3 + above is unchanged). +2. **An entry is a URL, never a command.** If it could be one, whoever holds + the coordinator or an admin's machine would run code on every member's. + The URL is `https://` only: a pool's `localhost` is each member's own + machine. A token login names no variable either: a pool could otherwise + send a member's environment to its URL. +3. **An entry is used only once the member accepted it** in the dashboard, + at the URL the pool names then; a pool that changes the URL has it + accepted again, and the login for the old one goes. Without this, a + coordinator could point every member's agents, and what they send, at a + server of its choosing, and feed them tool descriptions. +4. **The member's own configuration goes first:** an entry with the name or + prefix of one of the member's upstreams is not used, a declined one stays + declined, and two pools' entries with one prefix are neither used until + the member gives one of them another. +5. **The list lives with the coordinator** (`upstreams.json` in its + directory); an admin changes it with `devstack pool upstreams` or in the + pool area of the dashboard, each change in the audit log. Members read it + with `GET /v1/upstreams`; a coordinator of an earlier release answers + `404`, read as an empty list. + +Decided while building: the hub asks its pools every minute, off the +requests, and at once after its own admin changed a list; it keeps the +lists in `pool-upstreams.json` and uses the last one of a pool that does not +answer. An accepted entry is `:` in the hub (its keychain entry, +its log, its tools' description). An entry the pool drops, or of a pool the +machine left, goes with its decision and login. A change of an entry's +prefix, allowlist or login kind by the pool needs no new acceptance; only +its URL does. A pool names at most 64. Building it showed that the Windows +Credential Manager loses writes and deletes made side by side from several +threads: the hub now makes one keychain call at a time. + ## Enforced by `crates/devstack-hub/src/secrets.rs` (the store, with its test against @@ -177,3 +218,13 @@ configured, and looks for a change of their tools once a minute); the page *MCP upstreams* (`ui/src/views/UpstreamsView.vue`). One user token for every agent, as the owner chose on 2026-10-27; a token per agent was not built. + +*Option B, noted 2026-10-28:* `crates/devstack-node/src/upstreams.rs` (the +entry and its check, `upstreams.json`), the coordinator's `/v1/upstreams` +and `/v1/admin/upstreams` (`coordinator.rs`), `member.rs`; +`crates/devstack-hub/src/upstreams.rs` (`refresh_pools`, `pooled`, +`accept`, `decline`; the answers as `[[pool]]` in `upstreams.toml`), +`pool.rs` and `lib.rs` (the routes); `crates/devstack/src/poolcmd.rs` +(`devstack pool upstreams`); `ui/src/views/UpstreamsView.vue` and +`ui/src/components/PoolUpstreams.vue`; tests in +`crates/devstack-node/tests/upstreams.rs` and the hub's `upstreams.rs`. diff --git a/docs/adr/README.md b/docs/adr/README.md index f7ee9355..895395c9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -151,7 +151,7 @@ stay. | [0066](0066-a-measured-cpu-need-is-capped-at-half-of-what-its-node-gives-lanes.md) | A measured CPU need is capped at half of what its node gives lanes | Accepted | | [0067](0067-a-change-at-runtime-says-who-made-it.md) | A change at runtime says where it came from, and a journal keeps the last ones | Accepted; built 2026-10-27 (point 2 for the main slot and services); addendum 2026-10-27: the dashboard shows the journal | | [0068](0068-a-stop-takes-the-containers-too.md) | A stop takes the stack's containers too, unless asked to keep them | Accepted | -| [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service) | +| [0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) | `devstack mcp` can carry the tools of upstream MCP servers, logged in once by the hub | Accepted ([card](https://github.com/nuetzliches/devstack/issues/316#issuecomment-6452598449)): a proxy in the hub, per user; amended 2026-10-27 (keychain via `keyring`, a file on Linux without a Secret Service); addendum 2026-10-28 (option B: a pool names upstreams, a member accepts each) | | [0070](0070-a-review-card-comes-before-the-code-an-adr-records-what-was-built.md) | A review card comes before the code; an ADR records what was built | Accepted (supersedes ADR-0001); point 1 amended 2026-10-28 (the card in the conversation and the pull request, no issue) | | [0071](0071-the-dashboard-writes-no-file-of-a-repository.md) | The dashboard writes no file of a repository; a change to one is a prompt for a coding agent | Accepted | | [0072](0072-a-restart-is-warm-a-rebuild-or-cold.md) | A restart is warm, a rebuild or cold; a group acts on its containers too | Accepted ([card](https://github.com/nuetzliches/devstack/pull/351)) | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index bc32c31c..4e23e004 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -81,14 +81,19 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `GET /hub/pool/history?node=&range=1h\|24h` | cookie | a node's capacity over time, or the pool's without `node` ([ADR-0036](adr/0036-the-pool-shows-its-capacity-over-time.md)): `[{at, total_cpus, total_memory, offered_cpus, offered_memory, used_cpus, used_memory, gpus, gpus_offered, gpu_load, gpu_memory, gpu_memory_used}]`; the last hour as reported (every 15 s), or with `range=24h` the last day by minute (any other `range` is the hour); kept by the coordinator in memory, since it started | | `GET /hub/pool/telemetry` | cookie | `{consent, collects, what}`: whether this machine agreed to send the pool telemetry, whether the pool collects it (its coordinator has a collector), and what is sent ([ADR-0037](adr/0037-telemetry-goes-to-the-pools-collector-with-consent.md)) | | `PUT /hub/pool/telemetry {"enabled"}` | cookie + Origin | agree to send it, or take it back; off until given, per pool | +| `GET /hub/pool/upstreams` | cookie | the MCP upstreams the pool names for its members: `[{name, url, prefix?, allow?, auth: {kind: "none"} \| {kind: "token"} \| {kind: "oauth", client_id?, scopes?}}]`, never a secret ([pool.md](pool.md#mcp-upstreams-for-the-members)) | +| `POST /hub/pool/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | admins only: add one, or change the one of that name; the list after it. `400` with why (a URL over `https://` only, a prefix another entry has, at most 64); the coordinator audits it | +| `DELETE /hub/pool/upstreams/{name}` | cookie + Origin | admins only: take one off the list: `204`, `404` when the pool names none such; audited | | `GET /hub/pool/shared` | cookie | the lanes others share with this machine ([ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md)): `[{lease, repo, lane, owner, owner_name, node: {id, name, api, devstack?}, services: [{name, port, scheme, here, forwarded?}], owner_devstack?}]`; `devstack`, `owner_devstack`: `PoolRelease` of the node and of the owner, absent when they do not say (older); `forwarded`: the port here the service is forwarded to while this machine is connected to the lane ([ADR-0053](adr/0053-whoever-a-lane-is-shared-with-connects-to-it.md)), absent when it is not. Listing closes the forwards of lanes and services no longer shared with this machine | | `GET /hub/pool/shared/{lease}/api/?pool=` | cookie | a lane shared with this machine, viewed ([ADR-0040](adr/0040-a-shared-lane-can-be-watched-like-ones-own.md)): the lane daemon's `` through its node, streams passed through (also over `/hub/ws`). Reads only: `/v1/stack`, `/v1/events`, `/v1/usage`, `/v1/logs`, `/v1/journal` (since 0.27.0), a service's `logs`, `logs/stream`, `logs/files`, `builds`, `build-log`, `/v1/commands//runs`, `/v1/runs/[/log[/stream]]`, and a container's `/v1/infra///logs[/stream]` (the node answers those itself); anything else `403`. Whoever a lane is shared with may view it (up to 0.11.1 only those it was shared with `view`) | | `POST /hub/pool/shared/{lease}/connect` | cookie + Origin | connect to the lane ([ADR-0053](adr/0053-whoever-a-lane-is-shared-with-connects-to-it.md)): a forward on this machine to each service it shares with `http` or `https` that has none yet, through its node (which checks the sharing at every connection), on the owner's port `here` if free, else another; `{services: [{name, port, url}], warning?}` (`warning` as for `open`). It stays connected until `disconnect`, the hub stops, or the lane is no longer shared with this machine | | `POST /hub/pool/shared/{lease}/disconnect` | cookie + Origin | its forwards close, the connections through them too, the ports are free again; `{closed}`: how many (`0`: it was not connected) | | `POST /hub/pool/shared/{lease}/open {"service"}` | cookie + Origin | connect the lane if it is not (as `connect` does; ADR-0053 point 2), and answer for that service: `{url, port, warning?}`. Up to 0.19 it forwarded that service only, until the hub stopped. `warning`: the node runs another devstack than this machine or does not say which, or the owner's and the node's pool protocols differ ([ADR-0031](adr/0031-a-coordinator-places-lanes.md) point 8) `502` for a service shared with a scheme other than `http` or `https` | -| `GET /hub/upstreams` | cookie | the user's MCP upstreams ([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md)): `{store, upstreams: [{name, url?, command?, env?, token_var?, prefix, allow?, auth: {kind: "none"} \| {kind: "token", env?} \| {kind: "oauth", client_id?, scopes?}, logged_in}]}`, kept in `upstreams.toml` in the hub's state directory, never a secret. `store`: `keychain`, or `file` on a Linux machine without a Secret Service | +| `GET /hub/upstreams` | cookie | the user's MCP upstreams ([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md)): `{store, upstreams: [{name, url?, command?, env?, token_var?, prefix, allow?, auth: {kind: "none"} \| {kind: "token", env?} \| {kind: "oauth", client_id?, scopes?}, logged_in, pool?}]}`, kept in `upstreams.toml` in the hub's state directory, never a secret. `store`: `keychain`, or `file` on a Linux machine without a Secret Service. The upstreams the machine's pools name follow the user's own, named `:`, with `pool: {pool, name, status, why?, pool_prefix}`: `status` `offered` (not answered), `accepted` (in use), `declined`, `changed` (the pool changed its URL since it was accepted) or `conflict` (`why`: one of the user's has its name or prefix, or another pool's accepted one its prefix); only `accepted` ones are used ([pool.md](pool.md#mcp-upstreams-for-the-members)) | | `POST /hub/upstreams {name, url, prefix?, allow?, auth}` | cookie + Origin | add an upstream or change the one of that name: `204`; `400` with why (a name of a-z, 0-9, -; https, plain http on this machine only; a prefix another upstream has). Instead of `url`, `command` (program and arguments) makes it a command the hub starts (stdio), with `env` (no secret) on top of a base environment; with `auth.kind = "token"` the kept token goes into the variable `token_var`; OAuth is not for a command. A change restarts it. A new URL or another kind of login forgets its credential | | `DELETE /hub/upstreams/{name}` | cookie + Origin | it and its credential go: `204` | +| `POST /hub/upstreams/pool/{pool}/{name}/accept {prefix?}` | cookie + Origin | use an upstream a pool names, at the URL it names now, with `prefix` instead of the pool's if given: `204`; `400` with why (the pool names none such; a prefix one of the user's or another accepted one has). A login for another URL goes | +| `POST /hub/upstreams/pool/{pool}/{name}/decline` | cookie + Origin | do not use it; its login goes: `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 | diff --git a/docs/pool.md b/docs/pool.md index cbaeca13..25736d87 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -591,6 +591,38 @@ see the alarm), can refuse (`--refuse `), fail deletions and deletion. The tests in `crates/devstack-node/tests/provision.rs` use the same mock (`devstack_node::provision::mock`). +## MCP upstreams for the members + +A pool can name the MCP servers its members work with +([ADR-0069](adr/0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md), +option B): name, URL, prefix, tool allowlist and how each logs in. Never a +secret, and never a command: an entry is a URL over `https://`, so an admin +cannot run anything on a member's machine. + +```sh +devstack pool upstreams add tracker https://mcp.example.com/mcp # OAuth by default +devstack pool upstreams add wiki https://wiki.example.com/mcp --login token --allow search,get_page +devstack pool upstreams remove wiki +devstack pool upstreams # the list, for any member +``` + +`--login` is `oauth` (each member's hub logs in, in the browser; `--client-id` +where the server registers no clients itself), `token` (each member gives +their hub one) or `none`. Only an admin changes the list; each change is in +the audit log. The pool area of the dashboard shows the list to every member +and lets an admin add, change and remove entries. + +Each member's hub asks its pools for the list every minute and offers the +entries on its *MCP upstreams* page, from which pool. One is used, as +`:`, only once its user accepts it, at the URL the pool names +then; a pool that changes the URL has it accepted again, and the login for +the old one goes. The member's own configuration goes first: an entry with +the name or prefix of one of the member's upstreams is not used, nor are two +entries of different pools with one prefix until the member gives one of them +another. A declined entry stays declined. An entry the pool drops, or every +entry of a pool the machine leaves, goes with its login. A pool that does not +answer keeps what it named last. + ## Several pools A machine can belong to several pools, a customer's beside the team's, each @@ -731,7 +763,8 @@ same arguments. "Prune" on a node removes the stopped lanes it keeps |---|---| | Membership (key, certificate, coordinator) | devstack's per-user state, `pool/`; other pools in `pools//`; `DEVSTACK_POOL_DIR` overrides the default pool's | | Share settings, telemetry consent | `share.json`, `telemetry.json` beside the membership | -| Coordinator | `DEVSTACK_COORDINATOR_DIR`; `members.json` (changed under `members.lock`), `audit.jsonl`, `telemetry.json`; with a provisioner `provisioning.json` (the settings), `machines.json` (the machines asked for, until deleted), `provisioner.token` | +| The pools' MCP upstreams on a member | in the hub's state: `pool-upstreams.json` (the lists as last got), the member's answers in `upstreams.toml` (`[[pool]]`) | +| Coordinator | `DEVSTACK_COORDINATOR_DIR`; `members.json` (changed under `members.lock`), `audit.jsonl`, `telemetry.json`, `upstreams.json` (the MCP upstreams it names); with a provisioner `provisioning.json` (the settings), `machines.json` (the machines asked for, until deleted), `provisioner.token` | | Node agent state (leases, mirrors, uploaded files per member, `policy.json`, `secret`) | `node/` beside its membership | | Ports | coordinator and node agent: as you choose (`--listen`); mutual TLS with the pool's CA | | Certificates | the pool's CA 20 years, the coordinator's server certificate 10, a member's 5; not renewed: when one expires, that member (for the CA, the pool) is set up again | diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index 9937a014..5334b036 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -153,9 +153,10 @@ takes `profile`, `run` and `yes` (as `--profile`, `--run`, `--yes`) and 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. +upstreams, which the hub logs in to (the dashboard's *MCP upstreams*), some +of them named by the user's pool and accepted there. 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/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index 3bbc5496..6b7e5c5e 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -12,7 +12,7 @@ // ?mock=nodocker the Docker engine is stopped; "Start Docker" brings it up after 4 s // ?mock=nopool this machine is in no pool; ?mock=poolmember: a member, not an admin // ?mock=hubdown the hub is unreachable (toggle at runtime: window.devstackMock.hubDown(false)) -import type { DockerEngine, Guest, HubEvent, LaneView, McpUpstream, NotifySettings, LogStreamEvent, RunLogEvent, StackEvent, StackEntry } from '../types'; +import type { DockerEngine, Guest, HubEvent, LaneView, McpUpstream, NotifySettings, PoolUpstream, LogStreamEvent, RunLogEvent, StackEvent, StackEntry } from '../types'; import type { Response, StreamHandlers, Subscription, Transport } from '../transport'; import { Unreachable } from '../transport'; import { persist } from '@/lib/persist'; @@ -70,6 +70,15 @@ const MOCK_VERSION = '0.2.0'; const mockUpstreams: McpUpstream[] = [ { name: 'tracker', url: 'https://mcp.tracker.example.com/mcp', prefix: 'tracker', allow: [], auth: { kind: 'oauth' }, logged_in: true }, { name: 'wiki', url: 'https://wiki.example.com/mcp', prefix: 'wiki', allow: ['search', 'get_page'], auth: { kind: 'token' }, logged_in: false }, + // Named by the pool (ADR-0069 option B): one accepted, one offered. + { name: 'default:docs', url: 'https://docs.example.com/mcp', prefix: 'docs', auth: { kind: 'oauth' }, logged_in: true, pool: { pool: 'default', name: 'docs', status: 'accepted', pool_prefix: 'docs' } }, + { name: 'default:crm', url: 'https://crm.example.com/mcp', prefix: 'crm', auth: { kind: 'oauth' }, logged_in: false, pool: { pool: 'default', name: 'crm', status: 'offered', pool_prefix: 'crm' } }, +]; + +/** The MCP upstreams the mock pool names. */ +const mockPoolUpstreams: PoolUpstream[] = [ + { name: 'docs', url: 'https://docs.example.com/mcp', auth: { kind: 'oauth' } }, + { name: 'crm', url: 'https://crm.example.com/mcp', allow: ['search'], auth: { kind: 'oauth' } }, ]; class MockHub { @@ -444,6 +453,30 @@ export class MockTransport implements Transport { else mockUpstreams.push(next); return empty(204); } + const ua = /^\/hub\/upstreams\/pool\/([^/]+)\/([^/]+)\/(accept|decline)$/.exec(p); + if (ua && method === 'POST') { + const u = mockUpstreams.find((o) => o.pool?.pool === decodeURIComponent(ua[1]) && o.pool.name === decodeURIComponent(ua[2])); + if (!u?.pool) return json(400, { error: 'the pool names no such upstream' }); + u.pool.status = ua[3] === 'accept' ? 'accepted' : 'declined'; + if (ua[3] === 'decline') u.logged_in = false; + return empty(204); + } + if (p === '/hub/pool/upstreams' && method === 'GET') return json(200, mockPoolUpstreams); + if (p === '/hub/pool/upstreams' && method === 'POST') { + const u = body as unknown as PoolUpstream; + if (!u.url.startsWith('https://')) return json(400, { error: `\`${u.url}\`: a pool's upstream is a URL reached over https` }); + const at = mockPoolUpstreams.findIndex((o) => o.name === u.name); + if (at >= 0) mockPoolUpstreams[at] = u; + else mockPoolUpstreams.push(u); + return json(200, mockPoolUpstreams); + } + const pu = /^\/hub\/pool\/upstreams\/([^/]+)$/.exec(p); + if (pu && method === 'DELETE') { + const at = mockPoolUpstreams.findIndex((o) => o.name === decodeURIComponent(pu[1])); + if (at < 0) return json(404, { error: 'the pool names no such upstream' }); + mockPoolUpstreams.splice(at, 1); + return empty(204); + } const up = /^\/hub\/upstreams\/([^/]+)(?:\/(login|token|logout))?$/.exec(p); if (up) { const u = mockUpstreams.find((o) => o.name === decodeURIComponent(up[1])); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 2c1914f4..b32cc736 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -79,6 +79,8 @@ export const paths = { upstreamLogin: (name: string) => `/hub/upstreams/${enc(name)}/login`, upstreamToken: (name: string) => `/hub/upstreams/${enc(name)}/token`, upstreamLogout: (name: string) => `/hub/upstreams/${enc(name)}/logout`, + upstreamAccept: (pool: string, name: string) => `/hub/upstreams/pool/${enc(pool)}/${enc(name)}/accept`, + upstreamDecline: (pool: string, name: string) => `/hub/upstreams/pool/${enc(pool)}/${enc(name)}/decline`, pools: '/hub/pools', poolShared: '/hub/pool/shared', poolTelemetry: '/hub/pool/telemetry', @@ -107,6 +109,8 @@ export const paths = { poolGiveBack: (id: string) => `/hub/pool/nodes/${enc(id)}/give-back`, poolProvisioning: '/hub/pool/provisioning', poolProvisioned: '/hub/pool/provisioned', + poolUpstreams: '/hub/pool/upstreams', + poolUpstream: (name: string) => `/hub/pool/upstreams/${enc(name)}`, /** * A daemon path of `stack`. With a `lane` (plan §3.5) it goes to that * lane's API, except the lane routes themselves, which the main tree's diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 33c63db6..98b0c0a3 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -759,6 +759,28 @@ export type McpUpstream = { allow?: string[]; auth: McpUpstreamAuth; logged_in: boolean; + /** It is one a pool names (ADR-0069 option B); `name` is then `:`. */ + pool?: McpUpstreamFromPool; +}; + +/** What the user made of an upstream a pool names: `offered` (not answered), `accepted` (in use), `declined`, `changed` (the pool changed its URL since), `conflict` (`why` says with what). */ +export type McpUpstreamFromPool = { + pool: string; + /** Its name in the pool's list. */ + name: string; + status: 'offered' | 'accepted' | 'declined' | 'changed' | 'conflict'; + why?: string; + /** The prefix the pool gives it. */ + pool_prefix: string; +}; + +/** An MCP upstream a pool names for its members (`GET /hub/pool/upstreams`): a URL, never a secret. */ +export type PoolUpstream = { + name: string; + url: string; + prefix?: string; + allow?: string[]; + auth: { kind: 'none' } | { kind: 'token' } | { kind: 'oauth'; client_id?: string; scopes?: string[] }; }; /** `GET /hub/upstreams`. `file`: no keychain on this machine (Linux without a Secret Service). */ diff --git a/ui/src/components/PoolUpstreams.vue b/ui/src/components/PoolUpstreams.vue new file mode 100644 index 00000000..a4bb0e2e --- /dev/null +++ b/ui/src/components/PoolUpstreams.vue @@ -0,0 +1,203 @@ + + + + + diff --git a/ui/src/views/PoolView.vue b/ui/src/views/PoolView.vue index 97e03b7e..af48d778 100644 --- a/ui/src/views/PoolView.vue +++ b/ui/src/views/PoolView.vue @@ -12,6 +12,7 @@ import { connectedTo, usePool } from '@/stores/pool'; import { sharedId } from '@/api'; import Icon from '@/components/icons/Icon.vue'; import CapacityChart from '@/components/CapacityChart.vue'; +import PoolUpstreams from '@/components/PoolUpstreams.vue'; import type { PoolLease, PoolMember, PoolNode, PoolRelease } from '@/api/types'; import { useUi } from '@/stores/ui'; import { useHub } from '@/stores/hub'; @@ -56,6 +57,8 @@ const actionText: Record = { provision: 'changed whether lanes cause provisioning for', confirm: 'confirmed the provisioned node', enrol: 'saw the provisioned node enrol:', + upstream: 'named an MCP upstream for the pool', + 'upstream-remove': "took an MCP upstream off the pool's list", }; // Provisioned nodes (ADR-0051): what the provisioner made, for admins the @@ -444,6 +447,8 @@ function policyText(id: string) { + +
@@ -921,7 +926,7 @@ function policyText(id: string) {
  • {{ ago(e.at * 1000, now) }} - {{ e.by }} {{ actionText[e.action] ?? e.action }} {{ e.name }} + {{ e.by }} {{ actionText[e.action] ?? e.action }} {{ e.name }}
diff --git a/ui/src/views/UpstreamsView.vue b/ui/src/views/UpstreamsView.vue index 594107cf..4e779117 100644 --- a/ui/src/views/UpstreamsView.vue +++ b/ui/src/views/UpstreamsView.vue @@ -3,7 +3,8 @@ // in once by the hub, whose tools `devstack mcp` offers in every coding // agent. Per user, nothing per stack. The page never sees a secret: a token // goes to the hub's keychain, an OAuth login runs in a browser tab and comes -// back to the hub. +// back to the hub. A pool may name upstreams too (option B): they are listed +// with their pool and used only once the user accepts them. import { computed, onMounted, ref } from 'vue'; import { api, paths } from '@/api'; import type { McpUpstream, McpUpstreamAuth, McpUpstreams } from '@/api/types'; @@ -159,6 +160,31 @@ async function logout(u: McpUpstream) { if (r.ok) await load(); } +/** A prefix of the user's for a pool's upstream whose own one is taken. */ +const prefixFor = ref>({}); + +async function accept(u: McpUpstream) { + const p = u.pool!; + const prefix = prefixFor.value[u.name]?.trim(); + busy.value[u.name] = 'accept'; + const r = await act({ label: `Use ${p.name} of pool ${p.pool}`, path: paths.upstreamAccept(p.pool, p.name), body: prefix ? { prefix } : {}, success: `${p.name} is used now` }); + delete busy.value[u.name]; + if (r.ok) await load(); +} + +async function decline(u: McpUpstream) { + const p = u.pool!; + const r = await act({ label: `Do not use ${p.name} of pool ${p.pool}`, path: paths.upstreamDecline(p.pool, p.name), success: `${p.name} is not used` }); + if (r.ok) await load(); +} + +const statusText: Record = { + offered: 'offered, not used yet', + declined: 'declined', + changed: 'its URL changed: not used until you accept it again', + conflict: 'not used', +}; + function how(u: McpUpstream): string { if (u.auth.kind === 'none') return 'no login'; if (u.auth.kind === 'token') return u.auth.env ? `token from $${u.auth.env}` : 'token'; @@ -176,7 +202,8 @@ function how(u: McpUpstream): string {

MCP servers you use in every coding agent. The hub logs in to each once and keeps the login in your keychain; devstack mcp offers their tools as - <prefix>__<tool> in every agent that has it. They are yours, not a stack's. + <prefix>__<tool> in every agent that has it. They are yours, not a stack's. A pool can name some for its + members: they are listed here and used once you accept them, with your own login.

This machine has no keychain (no Secret Service): logins are kept in a file only you can read, beside the hub's state. @@ -231,15 +258,34 @@ function how(u: McpUpstream): string {

  • - {{ u.name }} + {{ u.pool ? u.pool.name : u.name }} + from pool {{ u.pool.pool }} {{ u.command?.length ? line(u.command) : u.url }} {{ u.prefix }}__… · {{ how(u) }} · - {{ u.logged_in ? 'logged in' : 'logged out' }} + {{ u.logged_in ? 'logged in' : 'logged out' }} + {{ statusText[u.pool.status] }} + {{ u.pool.why }}
    -
    +
    + + + +
    +
    @@ -247,8 +293,11 @@ function how(u: McpUpstream): string { {{ u.logged_in ? 'New token' : 'Give token' }} - - + +
    @@ -319,6 +368,9 @@ function how(u: McpUpstream): string { .warn-text { color: var(--warn-text); } +.prefix { + width: 140px; +} .token { display: flex; gap: 8px;