diff --git a/CHANGELOG.md b/CHANGELOG.md index a9861d56..daa1a95b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ and listed with their assets on the ### Added +- **devstack's MCP server for every folder.** The MCP upstreams page has a + setting per coding agent: devstack's MCP server per repository (as + before) or for you, in every folder. Then the hub writes one entry + `devstack` into the agent's own configuration (Claude Code, Codex, + Cursor), so its tools and the upstreams' are there in repositories + without a stack too, and takes it out when you switch back; the rest of + the file stays as it was (ADR-0100). A repository whose agent loads the + server twice, under two names, shows "MCP twice", and `devstack doctor` + says in any folder whether the server is registered there (#492). + - **The Skills page shows what happens for your agent.** A new tab, Flow, draws the hooks of the skills switched on by when they give their text: a session starts, a prompt matches, a lane stops, a session ends. Hovering a diff --git a/Cargo.lock b/Cargo.lock index bcc613ca..1f770110 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -931,6 +931,7 @@ dependencies = [ "tokio-rustls", "tokio-stream", "toml", + "toml_edit", "ureq", ] @@ -2875,6 +2876,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 8a9ca256..0e28a45e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -81,6 +81,7 @@ thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "net", "time", "signal", "io-util"] } tokio-stream = { version = "0.1", features = ["sync"] } toml = "1" +toml_edit = "0.25" # The platform verifier: TLS to GitHub (update, release check) trusts the # system's certificate store, so a TLS-inspecting proxy works as it does for # the installers. diff --git a/crates/devstack-hub/Cargo.toml b/crates/devstack-hub/Cargo.toml index 71ee63b8..4f74b7be 100644 --- a/crates/devstack-hub/Cargo.toml +++ b/crates/devstack-hub/Cargo.toml @@ -38,6 +38,7 @@ tokio.workspace = true tokio-rustls.workspace = true tokio-stream.workspace = true toml.workspace = true +toml_edit.workspace = true ureq.workspace = true [dev-dependencies] diff --git a/crates/devstack-hub/src/agentmcp.rs b/crates/devstack-hub/src/agentmcp.rs index d27406b0..2d713c80 100644 --- a/crates/devstack-hub/src/agentmcp.rs +++ b/crates/devstack-hub/src/agentmcp.rs @@ -243,11 +243,11 @@ pub fn codex(config: &Path) -> Vec { .collect() } -fn claude_file() -> Option { +pub(crate) fn claude_file() -> Option { devstack_skills::agents::resolve(CLAUDE_FILE) } -fn codex_file() -> Option { +pub(crate) fn codex_file() -> Option { devstack_skills::agents::resolve(CODEX_FILE) } diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 6c479f12..9a177eea 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -39,8 +39,9 @@ pub mod agenthooks; pub mod agentmcp; mod branches; mod guests; -mod mcp; +pub mod mcp; mod mcpclient; +pub mod mcpscope; mod notice; mod notify; mod open; @@ -665,6 +666,7 @@ fn router(state: AppState) -> axum::Router { .route("/hub/pool/skills/{name}", delete(pool::skill_remove)) .route("/hub/skills", get(poolskills::get)) .route("/hub/activity", get(activity_get)) + .route("/hub/mcp/scope", get(mcp_scope_get).put(mcp_scope_put)) .route("/hub/activity/timeline", get(timeline_get)) .route( "/hub/activity/transcripts", @@ -1920,16 +1922,64 @@ async fn stack_mcp(State(s): State, Path(id): Path) -> Respons let Some(e) = entry(&s, &id) else { return err(StatusCode::NOT_FOUND, "no such stack"); }; - match tokio::task::spawn_blocking(move || mcp::registered(&e.repo)).await { - Ok(files) => Json(serde_json::json!({ + match tokio::task::spawn_blocking(move || (mcp::registered(&e.repo), mcp::doubles(&e.repo))) + .await + { + Ok((files, doubles)) => Json(serde_json::json!({ "registered": !files.is_empty(), "files": files, + "doubles": doubles, })) .into_response(), Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), } } +/// `GET /hub/mcp/scope`: where devstack's MCP server is registered for +/// each coding agent: per repository, or for the user in every folder +/// (#492). +async fn mcp_scope_get() -> Response { + match tokio::task::spawn_blocking(|| mcpscope::view(&state_dir())).await { + Ok(v) => Json(v).into_response(), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +#[derive(Deserialize)] +struct McpScopeBody { + agents: std::collections::BTreeMap, +} + +/// `PUT /hub/mcp/scope {agents: {: "repository"|"user"}}`: write or +/// remove the user entry of those agents; the agents and why one failed. +async fn mcp_scope_put(Json(b): Json) -> Response { + match tokio::task::spawn_blocking(move || mcpscope::set(&state_dir(), &b.agents)).await { + Ok(Ok(v)) => { + devstack_daemon::diag::info( + "mcp_scope", + serde_json::json!({ "agents": scopes_of(&v) }), + ); + Json(v).into_response() + } + Ok(Err(e)) => err(StatusCode::BAD_REQUEST, e), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +/// The agents' scopes, for the diagnostic log. +fn scopes_of(v: &mcpscope::View) -> serde_json::Value { + v.agents + .iter() + .map(|a| { + ( + a.id.to_string(), + serde_json::to_value(a.scope).expect("serialises"), + ) + }) + .collect::>() + .into() +} + #[derive(Deserialize)] struct OpenQuery { stack: String, diff --git a/crates/devstack-hub/src/mcp.rs b/crates/devstack-hub/src/mcp.rs index bce77667..b36a07bc 100644 --- a/crates/devstack-hub/src/mcp.rs +++ b/crates/devstack-hub/src/mcp.rs @@ -1,7 +1,10 @@ //! Whether a coding agent finds devstack's MCP server (`devstack mcp`) for a //! repository: an entry in the project's agent configuration, or in the //! user's. Read only: the dashboard offers a prompt where none is found, and -//! the agent writes the entry (`Prompt::Mcp`). +//! the agent writes the entry (`Prompt::Mcp`); the user entry for every +//! folder is the hub's to write once the user chose so (`crate::mcpscope`). +//! Two entries that run `devstack mcp` under different names load it twice +//! ([`doubles`]). use std::path::{Path, PathBuf}; @@ -14,20 +17,20 @@ enum Format { CodexToml, } -/// The project's files, relative to the repository: Claude Code, VS Code, -/// Cursor, Codex. -const PROJECT: &[(&str, Format)] = &[ - (".mcp.json", Format::Json("mcpServers")), - (".vscode/mcp.json", Format::Json("servers")), - (".cursor/mcp.json", Format::Json("mcpServers")), - (".codex/config.toml", Format::CodexToml), +/// The project's files, relative to the repository, and the agent that +/// reads each: Claude Code, VS Code, Cursor, Codex. +const PROJECT: &[(&str, Format, &str)] = &[ + (".mcp.json", Format::Json("mcpServers"), "Claude Code"), + (".vscode/mcp.json", Format::Json("servers"), "VS Code"), + (".cursor/mcp.json", Format::Json("mcpServers"), "Cursor"), + (".codex/config.toml", Format::CodexToml, "Codex"), ]; /// The user's files, relative to the home folder. -const USER: &[(&str, Format)] = &[ - (".claude.json", Format::Json("mcpServers")), - (".cursor/mcp.json", Format::Json("mcpServers")), - (".codex/config.toml", Format::CodexToml), +const USER: &[(&str, Format, &str)] = &[ + (".claude.json", Format::Json("mcpServers"), "Claude Code"), + (".cursor/mcp.json", Format::Json("mcpServers"), "Cursor"), + (".codex/config.toml", Format::CodexToml, "Codex"), ]; /// The files that register `devstack mcp` for `repo`: the project's first, @@ -40,14 +43,14 @@ pub fn registered(repo: &Path) -> Vec { fn registered_with(repo: &Path, home: Option<&Path>) -> Vec { let mut found: Vec = PROJECT .iter() - .map(|(rel, f)| (repo.join(rel), *f)) + .map(|(rel, f, _)| (repo.join(rel), *f)) .filter(|(p, f)| in_file(p, *f, None)) .map(|(p, _)| p) .collect(); if let Some(home) = home { found.extend( USER.iter() - .map(|(rel, f)| (home.join(rel), *f)) + .map(|(rel, f, _)| (home.join(rel), *f)) .filter(|(p, f)| in_file(p, *f, Some(repo))) .map(|(p, _)| p), ); @@ -55,6 +58,72 @@ fn registered_with(repo: &Path, home: Option<&Path>) -> Vec { found } +/// The user's own files that register `devstack mcp` for every folder +/// (their top-level servers, not one project's). +#[cfg(test)] +fn for_every_folder_in(home: &Path) -> Vec { + USER.iter() + .map(|(rel, f, _)| (home.join(rel), *f)) + .filter(|(p, f)| !names_in(p, *f, None).is_empty()) + .map(|(p, _)| p) + .collect() +} + +#[cfg(test)] +pub(crate) fn registered_in_home(home: &Path) -> bool { + !for_every_folder_in(home).is_empty() +} + +/// An entry that runs `devstack mcp` beside another one for the same agent +/// under a different name: the agent loads the server twice, every tool +/// doubled. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Double { + pub agent: &'static str, + pub file: PathBuf, + pub name: String, +} + +/// The entries that double `devstack mcp` for an agent in `repo`: per agent, +/// when its files name it under more than one name, every one not named +/// `devstack` (the name the hub writes). +pub fn doubles(repo: &Path) -> Vec { + doubles_with(repo, home().as_deref()) +} + +fn doubles_with(repo: &Path, home: Option<&Path>) -> Vec { + let mut all: Vec = Vec::new(); + let mut add = |agent: &'static str, file: PathBuf, format: Format, repo: Option<&Path>| { + for name in names_in(&file, format, repo) { + all.push(Double { + agent, + file: file.clone(), + name, + }); + } + }; + for (rel, f, agent) in PROJECT { + add(agent, repo.join(rel), *f, None); + } + if let Some(home) = home { + for (rel, f, agent) in USER { + add(agent, home.join(rel), *f, Some(repo)); + } + } + let mut out = Vec::new(); + for d in &all { + let names: std::collections::BTreeSet<&str> = all + .iter() + .filter(|x| x.agent == d.agent) + .map(|x| x.name.as_str()) + .collect(); + if names.len() > 1 && d.name != crate::mcpscope::NAME && !out.contains(d) { + out.push(d.clone()); + } + } + out +} + fn home() -> Option { let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; std::env::var_os(var) @@ -70,46 +139,68 @@ fn in_file(file: &Path, format: Format, repo: Option<&Path>) -> bool { let Ok(text) = std::fs::read_to_string(file) else { return false; }; + let parses = match format { + Format::Json(_) => serde_json::from_str::(&text).is_ok(), + Format::CodexToml => text.parse::().is_ok(), + }; + if !parses { + return text.contains("devstack"); + } + !names_in(file, format, repo).is_empty() +} + +/// The names under which `file` runs `devstack mcp`: its servers, and with +/// `repo` Claude Code's entries for that project. A file that does not +/// parse names none. +fn names_in(file: &Path, format: Format, repo: Option<&Path>) -> Vec { + let Ok(text) = std::fs::read_to_string(file) else { + return Vec::new(); + }; match format { - Format::Json(key) => match serde_json::from_str::(&text) { - Ok(v) => { - let mut tables = vec![v.get(key)]; - if let (Some(repo), Some(projects)) = - (repo, v.get("projects").and_then(|p| p.as_object())) - { - tables.extend( - projects - .iter() - .filter(|(k, _)| same_path(k, repo)) - .map(|(_, p)| p.get(key)), - ); - } - tables - .into_iter() - .flatten() - .filter_map(|t| t.as_object()) - .flat_map(|t| t.values()) - .any(|s| runs_devstack_mcp(s.get("command"), s.get("args"))) + Format::Json(key) => { + let Ok(v) = serde_json::from_str::(&text) else { + return Vec::new(); + }; + let mut tables = vec![v.get(key)]; + if let (Some(repo), Some(projects)) = + (repo, v.get("projects").and_then(|p| p.as_object())) + { + tables.extend( + projects + .iter() + .filter(|(k, _)| same_path(k, repo)) + .map(|(_, p)| p.get(key)), + ); } - Err(_) => text.contains("devstack"), - }, - Format::CodexToml => match text.parse::() { - Ok(t) => t - .get("mcp_servers") + tables + .into_iter() + .flatten() + .filter_map(|t| t.as_object()) + .flat_map(|t| t.iter()) + .filter(|(_, s)| runs_devstack_mcp(s.get("command"), s.get("args"))) + .map(|(n, _)| n.clone()) + .collect() + } + Format::CodexToml => { + let Ok(t) = text.parse::() else { + return Vec::new(); + }; + t.get("mcp_servers") .and_then(|s| s.as_table()) - .is_some_and(|s| { - s.values().any(|v| { - let json = |k| v.get(k).and_then(|x| serde_json::to_value(x).ok()); - runs_devstack_mcp(json("command").as_ref(), json("args").as_ref()) - }) - }), - Err(_) => text.contains("devstack"), - }, + .into_iter() + .flat_map(|s| s.iter()) + .filter(|(_, v)| { + let json = |k| v.get(k).and_then(|x| serde_json::to_value(x).ok()); + runs_devstack_mcp(json("command").as_ref(), json("args").as_ref()) + }) + .map(|(n, _)| n.clone()) + .collect() + } } } /// `command` is devstack (a path to it, `.exe` or not), `args` start with `mcp`. -fn runs_devstack_mcp( +pub(crate) fn runs_devstack_mcp( command: Option<&serde_json::Value>, args: Option<&serde_json::Value>, ) -> bool { @@ -211,6 +302,37 @@ mod tests { assert_eq!(registered_with(repo.path(), Some(home.path())), [claude]); } + #[test] + fn two_names_for_one_agent_are_a_double() { + let repo = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + let entry = r#"{ "command": "devstack", "args": ["mcp"] }"#; + write( + &home.path().join(".claude.json"), + &format!(r#"{{ "mcpServers": {{ "devstack": {entry} }} }}"#), + ); + assert!(doubles_with(repo.path(), Some(home.path())).is_empty()); + // The same name in the project: one server. + write( + &repo.path().join(".mcp.json"), + &format!(r#"{{ "mcpServers": {{ "devstack": {entry} }} }}"#), + ); + assert!(doubles_with(repo.path(), Some(home.path())).is_empty()); + // Another name: loaded twice. Another agent's file is no double. + write( + &repo.path().join(".mcp.json"), + &format!(r#"{{ "mcpServers": {{ "ds": {entry} }} }}"#), + ); + write( + &repo.path().join(".vscode/mcp.json"), + &format!(r#"{{ "servers": {{ "ds2": {entry} }} }}"#), + ); + let d = doubles_with(repo.path(), Some(home.path())); + assert_eq!(d.len(), 1, "{d:?}"); + assert_eq!((d[0].agent, d[0].name.as_str()), ("Claude Code", "ds")); + assert_eq!(for_every_folder_in(home.path()).len(), 1); + } + #[test] fn a_file_that_does_not_parse_counts_when_it_names_devstack() { let repo = tempfile::tempdir().unwrap(); diff --git a/crates/devstack-hub/src/mcpscope.rs b/crates/devstack-hub/src/mcpscope.rs new file mode 100644 index 00000000..1f1a707c --- /dev/null +++ b/crates/devstack-hub/src/mcpscope.rs @@ -0,0 +1,556 @@ +//! Where devstack's MCP server is registered for the user's coding agents +//! (#492): per repository (the default: the dashboard offers a prompt for +//! a repository's own file), or for the user, in every folder: the hub +//! writes one entry `devstack` into the agent's own configuration, and +//! takes it out again when switched back. +//! +//! - **The user decides**, per agent, on this machine. Neither a pool nor a +//! stack file does. +//! - **Only its own entry.** The rest of the file stays as it is: its keys in +//! their order, untouched values as they were written (JSON), its comments +//! and layout (Codex's TOML). An entry `devstack` the hub did not write is +//! left alone; one that runs something else than `devstack mcp` is an +//! error, not overwritten. Switched back, the hub removes only the entry +//! it wrote (as for the hooks, ADR-0094). +//! - **One name.** The entry is always `devstack`: a repository's entry of +//! that name is the same server, and an agent loads one of the two. An +//! entry that runs `devstack mcp` under another name doubles every tool: +//! [`crate::mcp::doubles`] says so. + +use indexmap::IndexMap; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// The setting's file in the hub's state. +const SETTING: &str = "mcp-scope.json"; +/// The entry's name in every agent's configuration. +pub const NAME: &str = "devstack"; + +/// Where devstack's MCP server is registered for an agent. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Scope { + /// In each repository's own file (the dashboard's prompt). + #[default] + Repository, + /// In the agent's user configuration: every folder. + User, +} + +/// The setting, per agent id; what the hub wrote. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Setting { + #[serde(default)] + pub agents: BTreeMap, + /// The agents whose user entry the hub wrote: only these it removes. + #[serde(default)] + pub written: Vec, +} + +impl Setting { + pub fn load(state: &Path) -> Self { + std::fs::read_to_string(state.join(SETTING)) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() + } + + fn save(&self, state: &Path) -> Result<(), String> { + std::fs::create_dir_all(state).map_err(|e| e.to_string())?; + write( + &state.join(SETTING), + &serde_json::to_vec_pretty(self).expect("serialises"), + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Format { + /// JSON, the servers under `mcpServers`. + Json, + /// Codex's TOML, `[mcp_servers.]`. + Toml, +} + +/// An agent whose user configuration takes an MCP server. +struct Agent { + id: &'static str, + name: &'static str, + format: Format, + file: fn() -> Option, +} + +fn cursor_file() -> Option { + devstack_skills::agents::resolve("~/.cursor/mcp.json") +} + +const AGENTS: &[Agent] = &[ + Agent { + id: "claude-code", + name: "Claude Code", + format: Format::Json, + file: crate::agentmcp::claude_file, + }, + Agent { + id: "codex", + name: "Codex", + format: Format::Toml, + file: crate::agentmcp::codex_file, + }, + Agent { + id: "cursor", + name: "Cursor", + format: Format::Json, + file: cursor_file, + }, +]; + +/// An agent as the dashboard shows it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AgentView { + pub id: &'static str, + pub name: &'static str, + pub scope: Scope, + /// Its user configuration. + pub file: Option, + /// Its configuration's folder is there: the agent is installed. + pub installed: bool, + /// The user configuration registers `devstack mcp` (by the hub or not). + pub registered: bool, + /// Why the entry could not be written or removed. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// What `GET /hub/mcp/scope` answers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct View { + pub agents: Vec, +} + +/// The agents, their setting and their files as they are now. +pub fn view(state: &Path) -> View { + view_with(state, &|a| (a.file)(), &BTreeMap::new()) +} + +fn view_with( + state: &Path, + file: &dyn Fn(&Agent) -> Option, + errors: &BTreeMap, +) -> View { + let setting = Setting::load(state); + View { + agents: AGENTS + .iter() + .map(|a| { + let f = file(a); + AgentView { + id: a.id, + name: a.name, + scope: setting.agents.get(a.id).copied().unwrap_or_default(), + installed: f + .as_deref() + .and_then(Path::parent) + .is_some_and(Path::is_dir), + registered: f.as_deref().is_some_and(|f| entry(f, a.format).is_some()), + file: f, + error: errors.get(a.id).cloned(), + } + }) + .collect(), + } +} + +/// Set the scope of the agents in `wanted` (by id): write or remove their +/// user entry, and keep the setting. Unknown ids are refused. +pub fn set(state: &Path, wanted: &BTreeMap) -> Result { + set_with(state, wanted, &|a| (a.file)()) +} + +fn set_with( + state: &Path, + wanted: &BTreeMap, + file: &dyn Fn(&Agent) -> Option, +) -> Result { + if let Some(id) = wanted.keys().find(|id| !AGENTS.iter().any(|a| a.id == *id)) { + return Err(format!("no agent `{id}` takes devstack's MCP server here")); + } + let mut setting = Setting::load(state); + let mut errors = BTreeMap::new(); + for a in AGENTS { + let Some(&scope) = wanted.get(a.id) else { + continue; + }; + let Some(path) = file(a) else { + errors.insert( + a.id.to_string(), + "no home folder to find its configuration".into(), + ); + continue; + }; + let wrote = setting.written.iter().any(|w| w == a.id); + let result = match scope { + Scope::User => put(&path, a.format).map(|written| { + if written && !wrote { + setting.written.push(a.id.to_string()); + } + }), + // Only the entry the hub wrote goes. + Scope::Repository if wrote => remove(&path, a.format).map(|()| { + setting.written.retain(|w| w != a.id); + }), + Scope::Repository => Ok(()), + }; + match result { + Ok(()) => { + setting.agents.insert(a.id.to_string(), scope); + } + Err(e) => { + errors.insert(a.id.to_string(), e); + } + } + } + setting.agents.retain(|_, s| *s != Scope::Repository); + setting.save(state)?; + Ok(view_with(state, file, &errors)) +} + +/// The command line of the entry. +fn command() -> (&'static str, [&'static str; 1]) { + ("devstack", ["mcp"]) +} + +/// The entry `devstack` in `file`, as JSON (`None`: there is none, or the +/// file does not parse). +fn entry(file: &Path, format: Format) -> Option { + let text = std::fs::read_to_string(file).ok()?; + let text = text.trim_start_matches('\u{feff}'); + match format { + Format::Json => serde_json::from_str::(text) + .ok()? + .get("mcpServers")? + .get(NAME) + .cloned(), + Format::Toml => { + let t: toml::Table = text.parse().ok()?; + serde_json::to_value(t.get("mcp_servers")?.get(NAME)?).ok() + } + } +} + +/// An entry runs `devstack mcp`. +fn runs_devstack(v: &serde_json::Value) -> bool { + crate::mcp::runs_devstack_mcp(v.get("command"), v.get("args")) +} + +/// Write the entry into `file` (made if missing). `Ok(false)`: an entry +/// `devstack` that runs `devstack mcp` was there already (the user's own): +/// left as it is, and not the hub's to remove. +fn put(file: &Path, format: Format) -> Result { + if let Some(e) = entry(file, format) { + if runs_devstack(&e) { + return Ok(false); + } + return Err(format!( + "{}: an entry `{NAME}` that does not run `devstack mcp` is there: not changed", + file.display() + )); + } + let text = match std::fs::read_to_string(file) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(format!("{}: {e}", file.display())), + }; + let (cmd, args) = command(); + let out = match format { + Format::Json => edit_json(file, &text, |servers| { + let entry = serde_json::json!({ "type": "stdio", "command": cmd, "args": args }); + servers.insert( + NAME.to_string(), + RawValue::from_string(serde_json::to_string_pretty(&entry).expect("serialises")) + .expect("valid JSON"), + ); + })?, + Format::Toml => { + let mut doc: toml_edit::DocumentMut = text + .parse() + .map_err(|e| format!("{}: not TOML ({e}): not changed", file.display()))?; + let servers = doc + .entry("mcp_servers") + .or_insert_with(|| { + let mut t = toml_edit::Table::new(); + t.set_implicit(true); + toml_edit::Item::Table(t) + }) + .as_table_mut() + .ok_or_else(|| { + format!( + "{}: `mcp_servers` is not a table: not changed", + file.display() + ) + })?; + let mut t = toml_edit::Table::new(); + t.insert("command", toml_edit::value(cmd)); + t.insert( + "args", + toml_edit::value(toml_edit::Array::from_iter(args.iter().copied())), + ); + servers.insert(NAME, toml_edit::Item::Table(t)); + doc.to_string() + } + }; + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + write(file, out.as_bytes())?; + Ok(true) +} + +/// Take the entry out of `file`, if it still runs `devstack mcp`. +fn remove(file: &Path, format: Format) -> Result<(), String> { + match entry(file, format) { + Some(e) if runs_devstack(&e) => {} + // Gone, or changed by the user since: theirs now. + _ => return Ok(()), + } + let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + let out = match format { + Format::Json => edit_json(file, &text, |servers| { + servers.shift_remove(NAME); + })?, + Format::Toml => { + let mut doc: toml_edit::DocumentMut = text + .parse() + .map_err(|e| format!("{}: not TOML ({e}): not changed", file.display()))?; + if let Some(t) = doc + .get_mut("mcp_servers") + .and_then(|t| t.as_table_like_mut()) + { + t.remove(NAME); + if t.is_empty() { + doc.remove("mcp_servers"); + } + } + doc.to_string() + } + }; + write(file, out.as_bytes()) +} + +/// `text` (a JSON object, or empty) with its `mcpServers` changed by +/// `change`: the other keys stay in their order and as they were written. +fn edit_json( + file: &Path, + text: &str, + change: impl FnOnce(&mut IndexMap>), +) -> Result { + let src = text.trim_start_matches('\u{feff}'); + let mut doc: IndexMap> = if src.trim().is_empty() { + IndexMap::new() + } else { + serde_json::from_str(src) + .map_err(|e| format!("{}: not a JSON object ({e}): not changed", file.display()))? + }; + let mut servers: IndexMap> = match doc.get("mcpServers") { + Some(s) => serde_json::from_str(s.get()).map_err(|e| { + format!( + "{}: `mcpServers` is not an object ({e}): not changed", + file.display() + ) + })?, + None => IndexMap::new(), + }; + change(&mut servers); + if servers.is_empty() { + doc.shift_remove("mcpServers"); + } else { + doc.insert( + "mcpServers".into(), + RawValue::from_string(serde_json::to_string_pretty(&servers).expect("serialises")) + .expect("valid JSON"), + ); + } + let mut out = serde_json::to_string_pretty(&doc).expect("serialises"); + out.push('\n'); + Ok(out) +} + +/// Write `bytes` to `path` through a file beside it. +fn write(path: &Path, bytes: &[u8]) -> Result<(), String> { + let tmp = path.with_extension(format!("devstack-{:08x}.tmp", rand::random::())); + std::fs::write(&tmp, bytes) + .and_then(|()| std::fs::rename(&tmp, path)) + .map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("{}: {e}", path.display()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn files(dir: &Path) -> impl Fn(&Agent) -> Option + '_ { + move |a| { + Some(match a.id { + "claude-code" => dir.join(".claude.json"), + "codex" => dir.join(".codex").join("config.toml"), + _ => dir.join(".cursor").join("mcp.json"), + }) + } + } + + fn only(id: &str, scope: Scope) -> BTreeMap { + BTreeMap::from([(id.to_string(), scope)]) + } + + #[test] + fn the_users_entry_comes_and_goes_and_the_rest_of_the_file_stays() { + let home = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let claude = home.path().join(".claude.json"); + // Keys in an order serde would not keep, a value as written. + let before = "{\n \"zeta\": 1,\n \"numStartups\": 42,\n \"mcpServers\": {\n \"tt\": { \"type\": \"http\", \"url\": \"https://t.example/mcp\" }\n },\n \"alpha\": {\"a\":[1,2]}\n}\n"; + std::fs::write(&claude, before).unwrap(); + let v = set_with( + state.path(), + &only("claude-code", Scope::User), + &files(home.path()), + ) + .unwrap(); + let a = v.agents.iter().find(|a| a.id == "claude-code").unwrap(); + assert_eq!( + (a.scope, a.registered, a.error.as_deref()), + (Scope::User, true, None) + ); + let text = std::fs::read_to_string(&claude).unwrap(); + let keys: Vec<&str> = ["\"zeta\"", "\"numStartups\"", "\"mcpServers\"", "\"alpha\""] + .into_iter() + .filter(|k| text.contains(k)) + .collect(); + assert_eq!(keys.len(), 4, "{text}"); + assert!(text.find("\"zeta\"") < text.find("\"alpha\""), "{text}"); + assert!( + text.contains("{\"a\":[1,2]}"), + "untouched as written: {text}" + ); + assert!(text.contains("https://t.example/mcp"), "{text}"); + assert!(crate::mcp::registered_in_home(home.path())); + // Switched back: the entry goes, the file is as it was. + set_with( + state.path(), + &only("claude-code", Scope::Repository), + &files(home.path()), + ) + .unwrap(); + let after: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&claude).unwrap()).unwrap(); + let was: serde_json::Value = serde_json::from_str(before).unwrap(); + assert_eq!(after, was); + assert_eq!(Setting::load(state.path()), Setting::default()); + } + + #[test] + fn codex_keeps_its_comments_and_the_users_own_entry_stays() { + let home = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let codex = home.path().join(".codex").join("config.toml"); + std::fs::create_dir_all(codex.parent().unwrap()).unwrap(); + let before = "# my settings\nmodel = \"gpt-5\"\n\n[mcp_servers.tt]\nurl = \"https://t.example/mcp\" # tracker\n"; + std::fs::write(&codex, before).unwrap(); + set_with( + state.path(), + &only("codex", Scope::User), + &files(home.path()), + ) + .unwrap(); + let text = std::fs::read_to_string(&codex).unwrap(); + assert!( + text.starts_with("# my settings\nmodel = \"gpt-5\""), + "{text}" + ); + assert!(text.contains("# tracker"), "{text}"); + assert!(text.contains("[mcp_servers.devstack]"), "{text}"); + let t: toml::Table = text.parse().unwrap(); + assert_eq!( + t["mcp_servers"]["devstack"]["command"].as_str(), + Some("devstack") + ); + set_with( + state.path(), + &only("codex", Scope::Repository), + &files(home.path()), + ) + .unwrap(); + assert_eq!(std::fs::read_to_string(&codex).unwrap(), before); + + // An entry of the user's own: kept on, and kept when switched back. + let own = + "[mcp_servers.devstack]\ncommand = \"C:\\\\tools\\\\devstack.exe\"\nargs = [\"mcp\"]\n"; + std::fs::write(&codex, own).unwrap(); + set_with( + state.path(), + &only("codex", Scope::User), + &files(home.path()), + ) + .unwrap(); + set_with( + state.path(), + &only("codex", Scope::Repository), + &files(home.path()), + ) + .unwrap(); + assert_eq!(std::fs::read_to_string(&codex).unwrap(), own); + } + + #[test] + fn an_entry_of_that_name_for_something_else_is_not_overwritten() { + let home = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let cursor = home.path().join(".cursor").join("mcp.json"); + std::fs::create_dir_all(cursor.parent().unwrap()).unwrap(); + let before = r#"{"mcpServers":{"devstack":{"command":"node","args":["other.js"]}}}"#; + std::fs::write(&cursor, before).unwrap(); + let v = set_with( + state.path(), + &only("cursor", Scope::User), + &files(home.path()), + ) + .unwrap(); + let a = v.agents.iter().find(|a| a.id == "cursor").unwrap(); + assert!( + a.error + .as_deref() + .is_some_and(|e| e.contains("does not run")), + "{a:?}" + ); + assert_eq!(a.scope, Scope::Repository); + assert_eq!(std::fs::read_to_string(&cursor).unwrap(), before); + assert!(set_with(state.path(), &only("vim", Scope::User), &files(home.path())).is_err()); + } + + #[test] + fn a_missing_file_is_made_and_removed_to_nothing_but_braces() { + let home = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let cursor = home.path().join(".cursor").join("mcp.json"); + set_with( + state.path(), + &only("cursor", Scope::User), + &files(home.path()), + ) + .unwrap(); + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap(); + assert_eq!(v["mcpServers"]["devstack"]["args"][0], "mcp"); + set_with( + state.path(), + &only("cursor", Scope::Repository), + &files(home.path()), + ) + .unwrap(); + assert_eq!(std::fs::read_to_string(&cursor).unwrap().trim(), "{}"); + } +} diff --git a/crates/devstack/src/doctor.rs b/crates/devstack/src/doctor.rs index 7b4ab4fd..0b4aaaea 100644 --- a/crates/devstack/src/doctor.rs +++ b/crates/devstack/src/doctor.rs @@ -86,6 +86,7 @@ pub fn run(stack_file: &Path) -> Vec { out.extend(path_entry()); out.extend(agent_hooks()); out.extend(upstreams_direct()); + out.extend(mcp_registration(stack_file)); #[cfg(windows)] out.extend(dev_drive(stack_file)); out @@ -663,6 +664,51 @@ fn agent_hooks() -> Vec { out } +/// Whether coding agents find devstack's MCP server in this folder (the +/// stack's repository, or the folder `doctor` runs in without one, #492), +/// and an entry that doubles it under another name. +fn mcp_registration(stack_file: &Path) -> Vec { + let folder = stack_file + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .map(Path::to_path_buf) + .or_else(|| std::env::current_dir().ok()); + let Some(folder) = folder else { + return Vec::new(); + }; + let files = devstack_hub::mcp::registered(&folder); + let mut out = vec![if let Some(first) = files.first() { + f( + Level::Ok, + format!( + "devstack's MCP server is registered for {} ({})", + folder.display(), + first.display() + ), + ) + } else { + f( + Level::Info, + format!( + "devstack's MCP server is not registered for {}: agents here have no devstack tools (no pool upstreams, no hooks bound to them); register it for every folder in the dashboard (MCP upstreams), or add {{ \"devstack\": {{ \"command\": \"devstack\", \"args\": [\"mcp\"] }} }} to the repository's .mcp.json", + folder.display() + ), + ) + }]; + out.extend(devstack_hub::mcp::doubles(&folder).into_iter().map(|d| { + f( + Level::Warn, + format!( + "{} loads devstack's MCP server twice: the entry `{}` in {} runs it under another name than `devstack`; remove one, or name it `devstack`", + d.agent, + d.name, + d.file.display() + ), + ) + })); + out +} + /// A pool's upstream an agent also has as a server of its own, at the same /// URL (#473): its tools twice once accepted, and before that a hook bound /// to it looked silent. diff --git a/docs/adr/0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md b/docs/adr/0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md new file mode 100644 index 00000000..05039e79 --- /dev/null +++ b/docs/adr/0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md @@ -0,0 +1,89 @@ +# ADR-0100: The user can register devstack's MCP server for every folder; the hub writes only its own entry `devstack` + +- **Status:** Accepted (card in the pull request); built +- **Date:** 2026-11-09 +- **Deciders:** project owner +- **Related:** [ADR-0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) (`devstack mcp` carries the upstreams), [ADR-0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) (the hub writes the agents' hook entries, by the same rules), issue #492 + +## Context + +`devstack mcp` carries the pool's upstream tools and the hooks bound to +them, but an agent got it only where a repository's own file registered +it: the dashboard offered that entry in a stack's head, so a repository +without a stack file never had it. An agent session there had no devstack +tools, every accepted upstream was missing, hooks bound to them stayed +silent, and nothing said why. The server works in any folder; only the +registration was missing. The hub read the agents' MCP configuration and +never wrote it (card of 2026-11-06, point 4). + +## Decision + +The owner approved the review card in the conversation on **2026-11-09**, +all five points: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | trust | For the agents the user picks, the hub writes one entry `devstack` into the agent's user configuration (`~/.claude.json` `mcpServers`, `~/.codex/config.toml` `[mcp_servers.devstack]`, `~/.cursor/mcp.json`); only that entry, the rest of the file kept, removed again when switched off, by ADR-0094's rules for the hooks. | A hint the user follows by hand (`claude mcp add -s user …`) | Low: switching off removes it | +| 2 | term | A setting in the hub per machine and agent: devstack's MCP server **per repository** (today, the default) or **for me, in every folder**; the user decides, not a pool or a stack file. | A pool pushing the registration | Low | +| 3 | concept | The user entry is always named `devstack`: a project's entry of that name is the same server and loads once; an entry that runs `devstack mcp` under another name is reported as a double by `doctor` and the dashboard, not removed. | `devstack mcp` noticing a sibling at runtime (it cannot see the agent's configuration) | Medium | +| 4 | contract | `devstack doctor` (and the MCP tool `doctor`) says in a folder without a stack file too whether devstack's MCP server is registered there and how to do it; the dashboard's hint offers every folder. | `doctor` inside a stack only | Low | +| 5 | contract | `GET`/`PUT /hub/mcp/scope` with `{agents: {: "repository" \| "user"}}`. | — | Low: a new endpoint | + +As built (`crates/devstack-hub/src/mcpscope.rs`): + +1. **The entry.** `{"type": "stdio", "command": "devstack", "args": ["mcp"]}` + in JSON, `command`/`args` in Codex's table: the command line of the + repository entry. A file that is not there is made. +2. **Only its own.** JSON: the top-level keys stay in their order, every + value but `mcpServers` as it was written (the hooks' technique); Codex: + `toml_edit`, so comments and layout stay. An entry `devstack` that runs + `devstack mcp` and was there before is the user's own: left on, not + removed when switched back (the setting keeps which entries the hub + wrote, `written`). One that runs something else is an error, and the + file is not changed. Removing takes only an entry that still runs + `devstack mcp`; an emptied `mcpServers` goes. +3. **The setting.** `mcp-scope.json` in the hub's state: the agents set to + `user` and the ones whose entry the hub wrote. The page lists Claude + Code, Codex and Cursor with their file, whether the agent is installed + (its folder is there; not installed, "in every folder" is off), whether + its user configuration registers the server already, and an error. +4. **Doubles** (`mcp::doubles`): per agent (Claude Code: `.mcp.json`, + `~/.claude.json` and its project's entries; VS Code; Cursor; Codex), when + its files run `devstack mcp` under more than one name, every one not + named `devstack`. `GET /hub/stacks/{id}/mcp` carries them (`doubles`), + the stack's head shows "MCP twice", `doctor` warns. +5. **Where it shows.** A card on the MCP upstreams page; the stack's "no + MCP" hint links there; `doctor` reports for the stack's repository, or + for the folder it runs in without a stack file. + +Decided while building, not on the card: + +- VS Code has no user file the hub writes (its user MCP configuration + lives in its settings profile); it keeps the per-repository prompt. +- Whether Cursor merges a user and a project entry of the same name is not + checked: `doctor` and the dashboard report only different names. + +## Alternatives considered + +- **Writing the entry under the repository's own name** to avoid a double. + A name differs per repository; one fixed name lets the agents' own + precedence (local over project over user) pick one. +- **A pool policy that registers it for its members.** The registration is + the user's tooling, not the pool's; a pool cannot see what else the + user's agents run. + +## Consequences + +- Claude Code rewrites `~/.claude.json` often; the hub writes through a + file beside it and renames, so a write that crosses one of Claude Code's + can lose one of the two (switching again repairs ours). +- A repository's entry under another name than `devstack` now shows as + "MCP twice" where a user entry exists. + +## Enforced by + +`crates/devstack-hub/src/mcpscope.rs`, `crates/devstack-hub/src/mcp.rs` +(`doubles`), `crates/devstack-hub/src/lib.rs` +(`mcp_scope_get`, `mcp_scope_put`, `stack_mcp`), `crates/devstack/src/doctor.rs` +(`mcp_registration`), `ui/src/components/McpScope.vue`, +`ui/src/components/McpHint.vue`, `docs/dashboard-api.md`. diff --git a/docs/adr/README.md b/docs/adr/README.md index c9d06447..da60ffa2 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -182,3 +182,4 @@ stay. | [0097](0097-the-dashboards-mark-says-what-needs-attention.md) | The dashboard's mark and favicon carry a red or yellow dot for what needs attention, from an `attention` event of the hub; the mark flips to the nut | Accepted (card in the pull request); built | | [0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md) | The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week | Accepted (card in the pull request); built; its activity list moved to a lane's timeline (ADR-0099) | | [0099](0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md) | A lane shows its agents' sessions in time; the hub reads their transcripts when switched on, and takes only times, counts and names | Accepted (card in the pull request); built | +| [0100](0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md) | The user can register devstack's MCP server for every folder; the hub writes only its own entry `devstack` | Accepted (card in the pull request); built | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 20007753..4266f6b0 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -73,7 +73,9 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/stacks/{id}/fetch` | cookie + Origin | `git fetch --all --prune`, without a prompt (`GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`) and within 120 s: `{}`; `409 {"error"}` with what git said | | *(none)* | | No route writes a file of a repository ([ADR-0071](adr/0071-the-dashboard-writes-no-file-of-a-repository.md); the hub's skill folders that ignore themselves are no file of it, [ADR-0079](adr/0079-skills-local-to-a-working-tree.md)): a first stack file and a worktree's stack file are prompts for a coding agent (`GET /hub/prompt`, kinds `setup`, `lane-file`). `POST /hub/stacks/init`, `POST /hub/stacks/{id}/skills` and `POST /hub/stacks/{id}/worktrees/stack-file` are gone since 0.27.0 (`405`/`404`). `GET /hub/stacks/{id}/skills` and the prompt kind `skills` are gone too: the hub keeps the generated skills current itself ([ADR-0087](adr/0087-the-generated-skills-are-the-hubs-no-tool-reports-them-outdated.md)) | | `GET /hub/stacks/{id}/upgrade` | cookie | how far the stack file is behind this devstack, apart from the agent skills (the hub keeps those current): `{reviewed, from, current, behind, file, error}`. `reviewed`: `[stack] reviewed`, the devstack the file was last brought up to date with (`null` when not set); `from`: the devstack to read the changes after, `reviewed`, or for a file without it the agent skills' `from` when older than `current` (`null` when unknown); `behind`: `reviewed` is older than `current`, or not set. `behind` is `false` when the stack file does not load. `file`: `ok`, `missing` (a setup broken off after the stack was registered, or the file removed since: the dashboard offers the `setup` prompt) or `invalid` (it does not load; `error` says why, `null` otherwise). Read while the stack is stopped too | -| `GET /hub/stacks/{id}/mcp` | cookie | whether a coding agent finds devstack's MCP server for the repository: `{registered, files}`, `files` the agent configuration files with a server that runs `devstack mcp` (command `devstack`, a path to it or `devstack.exe`, first argument `mcp`). The project's first: `.mcp.json`, `.vscode/mcp.json` (`servers`), `.cursor/mcp.json`, `.codex/config.toml` (`[mcp_servers.*]`); then the user's: `~/.claude.json` (its `mcpServers`, and those of its entry for the repository under `projects`), `~/.cursor/mcp.json`, `~/.codex/config.toml`. A file that does not parse (JSON with comments) counts when it names devstack. Read only; the dashboard offers the prompt `mcp` where `registered` is `false` | +| `GET /hub/stacks/{id}/mcp` | cookie | whether a coding agent finds devstack's MCP server for the repository: `{registered, files, doubles}`, `files` the agent configuration files with a server that runs `devstack mcp` (command `devstack`, a path to it or `devstack.exe`, first argument `mcp`). The project's first: `.mcp.json`, `.vscode/mcp.json` (`servers`), `.cursor/mcp.json`, `.codex/config.toml` (`[mcp_servers.*]`); then the user's: `~/.claude.json` (its `mcpServers`, and those of its entry for the repository under `projects`), `~/.cursor/mcp.json`, `~/.codex/config.toml`. A file that does not parse (JSON with comments) counts when it names devstack. Read only; the dashboard offers the prompt `mcp` where `registered` is `false`; `doubles`: `[{agent, file, name}]`, an entry that runs `devstack mcp` under another name than `devstack` beside another one of the same agent, which then loads it twice ([ADR-0100](adr/0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md)) | +| `GET /hub/mcp/scope` | cookie | where devstack's MCP server is registered for each coding agent ([ADR-0100](adr/0100-the-user-chooses-devstacks-mcp-server-for-every-folder.md)): `{agents: [{id, name, scope: "repository"\|"user", file, installed, registered, error?}]}` (Claude Code, Codex, Cursor; `file` the agent's user configuration, `installed` its folder is there, `registered` that file runs `devstack mcp` already, by the hub or not) | +| `PUT /hub/mcp/scope` | cookie | `{agents: {: "repository"\|"user"}}`: `user` writes the entry `devstack` into the agent's user configuration (only that entry, the rest of the file kept), `repository` removes the entry the hub wrote (one the user had before stays); answers as `GET`, an agent's `error` saying why its file was not changed; 400 for an unknown agent | | `POST /hub/open {"stack", "path", "with"}` | cookie + Origin | open `path` with the program `with`: `204`. `path` must be the stack's repository or one of its worktrees (`git worktree list`), `with` an id `GET /hub/openers` lists now; `400` otherwise, `404` for an unknown stack, `502 {"error"}` when the program could not be started | | `GET /hub/prompt?kind=&stack=`, `?kind=&path=` or `?kind=&stack=&path=` | cookie | a prompt for a coding agent, written by the hub ([ADR-0046](adr/0046-the-hub-opens-a-worktree-in-the-users-programs.md), amendment 2026-10-22): `{text, path}`, `path` the folder it works in. `kind` with `path` (a folder, checked as for `/hub/inspect`): `setup` (a stack file to write; says whether a draft is there), `fix-file` (one that does not load: `409` when there is none or it loads). With `stack`: `upgrade` (from the devstack `/hub/stacks/{id}/upgrade` names to this one), `start-failed` (the end of the last failed start from the dashboard and its log; `409` when there is none), `mcp` (register `devstack mcp` in the project's agent configuration, next to the servers there). `setup` and `upgrade` offer the same registration, suggested yes. With `stack` and `path`: `lane-file` (a linked worktree of the stack without a stack file of its own: take the main tree's over and adapt it to the branch, [ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md); `path` in the answer is the worktree, `400` for anything else), `lane-image` (a worktree of the stack, the main one too, whose lane cannot go to a node because the stack file it runs with names no lane image: name one, [ADR-0028](adr/0028-lane-images.md) addendum 2026-10-29; `path` in the answer is the folder of that file, `409` when it names one). `400` for another kind or a missing target, `404` for an unknown stack. Below 5,000 characters: what is quoted is cut | | `POST /hub/agent {"kind", "stack" \| "path" \| both, "with"}` | cookie + Origin | start the agent `with` in the prompt's folder with the prompt `GET /hub/prompt` writes for the same `kind` and target: `204`. The page never sends text. `with` must be an id `GET /hub/openers` lists now with `prompt`; `400` otherwise, the refusals of `/hub/prompt`, `502 {"error"}` when the program could not be started | diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index fde19a89..0a6ddedd 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -165,7 +165,9 @@ devstack passes their instructions on in its own, within what the client keeps (4096 characters); one shortened or left out there says so, and the tool `instructions` with its `prefix` returns its full text. Register it once (project `.mcp.json` or user configuration; the dashboard -shows *no MCP* in the stack's head while neither has it): +shows *no MCP* in the stack's head while neither has it, and on *MCP +upstreams* the user can have the hub register it for every folder; `devstack +doctor` says whether it is registered where you are): ```json { "mcpServers": { "devstack": { "command": "devstack", "args": ["mcp"] } } } diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index 3b7765c9..a1db5860 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -22,6 +22,16 @@ import { Abort, MockStack, sleep, type Listener } from './stack'; import { MockPool } from './pool'; import { mockActivity, mockHookDetails } from './activity'; import { mockTimeline, mockTranscripts } from './timeline'; +import type { McpScope, McpScopeView } from '../types'; + +/** The agents and where devstack's MCP server is registered for them: Cursor is not installed here. */ +const mockMcpScope: McpScopeView = { + agents: [ + { id: 'claude-code', name: 'Claude Code', scope: 'repository', file: 'C:\\Users\\dev\\.claude.json', installed: true, registered: false }, + { id: 'codex', name: 'Codex', scope: 'repository', file: 'C:\\Users\\dev\\.codex\\config.toml', installed: true, registered: false }, + { id: 'cursor', name: 'Cursor', scope: 'repository', file: 'C:\\Users\\dev\\.cursor\\mcp.json', installed: false, registered: false }, + ], +}; import { autoShift, daemonPorts, hubPorts, refusal, type MockLane } from './ports'; import { runningHolders } from '@/lib/shift'; @@ -661,6 +671,16 @@ export class MockTransport implements Transport { // Skill sets (ADR-0074). if (p === '/hub/skills' && method === 'GET') return json(200, this.hub.poolSkillState); if (p === '/hub/activity' && method === 'GET') return json(200, mockActivity(url.searchParams.get('session') ?? undefined)); + if (p === '/hub/mcp/scope' && method === 'GET') return json(200, mockMcpScope); + if (p === '/hub/mcp/scope' && method === 'PUT') { + const asked = (body?.agents ?? {}) as Record; + for (const a of mockMcpScope.agents) { + if (!(a.id in asked)) continue; + a.scope = asked[a.id]; + a.registered = a.scope === 'user'; + } + return json(200, mockMcpScope); + } if (p === '/hub/activity/timeline' && method === 'GET') { const t = mockTimeline(url.searchParams.get('session') ?? ''); return t ? json(200, t) : json(404, { error: 'no such session' }); @@ -924,8 +944,10 @@ export class MockTransport implements Transport { } // The first stack registers devstack's MCP server, the others do not. if (rest === '/mcp' && method === 'GET') { - const registered = stack === hub.stacks[0]; - return json(200, { registered, files: registered ? [`${stack.entry.repo}\\.mcp.json`] : [] }); + const registered = stack === hub.stacks[0] || mockMcpScope.agents.some((a) => a.scope === 'user'); + // The first stack's agent has it a second time, under another name. + const doubles = stack === hub.stacks[0] ? [{ agent: 'Claude Code', file: `${stack.entry.repo}\\.mcp.json`, name: 'ds' }] : []; + return json(200, { registered, files: registered ? [`${stack.entry.repo}\\.mcp.json`] : [], doubles }); } if (rest === '/up' && method === 'POST') { if (stack.running) return empty(202); diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index 12e3a0fe..a2a6d999 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -74,6 +74,8 @@ export const paths = { fetch: (stack: string) => `/hub/stacks/${enc(stack)}/fetch`, upgrade: (stack: string) => `/hub/stacks/${enc(stack)}/upgrade`, mcp: (stack: string) => `/hub/stacks/${enc(stack)}/mcp`, + /** Where devstack's MCP server is registered for each coding agent. */ + mcpScope: '/hub/mcp/scope', pool: '/hub/pool', upstreams: '/hub/upstreams', upstream: (name: string) => `/hub/upstreams/${enc(name)}`, diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 697938f1..7bd10a1c 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -575,7 +575,29 @@ export type UpgradeState = { * `GET /hub/stacks/{id}/mcp`: the agent configuration files (the project's, * then the user's) that register `devstack mcp` for the repository. */ -export type McpState = { registered: boolean; files: string[] }; +/** An entry that runs `devstack mcp` beside another one of the same agent under another name: its tools load twice. */ +export type McpDouble = { agent: string; file: string; name: string }; + +export type McpState = { registered: boolean; files: string[]; doubles?: McpDouble[] }; + +/** Where devstack's MCP server is registered for a coding agent (`/hub/mcp/scope`). */ +export type McpScope = 'repository' | 'user'; + +export type McpScopeAgent = { + id: string; + name: string; + scope: McpScope; + /** Its user configuration. */ + file: string | null; + /** Its configuration's folder is there. */ + installed: boolean; + /** Its user configuration registers `devstack mcp`, by the hub or not. */ + registered: boolean; + /** Why the entry could not be written or removed. */ + error?: string; +}; + +export type McpScopeView = { agents: McpScopeAgent[] }; export type CommandView = { name: string; description: string; confirm: string | null; requires: string[] }; diff --git a/ui/src/components/McpHint.vue b/ui/src/components/McpHint.vue index cb5ad7da..5863d1c8 100644 --- a/ui/src/components/McpHint.vue +++ b/ui/src/components/McpHint.vue @@ -29,6 +29,11 @@ const hidden = computed(() => { }); // Without a stack file the setup comes first; its prompt asks about MCP too. const shown = computed(() => stack.mcp?.registered === false && !hidden.value && !stack.readOnly && !stack.sharedLane && !stack.fileProblem); +// An entry under another name than `devstack` beside it: every tool twice. +const doubles = computed(() => (stack.readOnly ? [] : (stack.mcp?.doubles ?? []))); +const doublesText = computed(() => + doubles.value.map((d) => `${d.agent} loads devstack's MCP server twice: the entry "${d.name}" in ${d.file} runs it under another name than "devstack". Remove one, or name it "devstack".`).join('\n'), +); const root = ref(null); const trigger = ref(null); @@ -48,6 +53,7 @@ function dismiss() {