Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

mcp setup: add SolidCraft to the AI clients on this computer; plain mcp finds a late app (#6379)

bherbruckdfde1e032d93
diff --git a/Cargo.lock b/Cargo.lock
index 177801cf0c..20adf138dc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4296,6 +4296,7 @@ dependencies = [
"solidcraft-render",
"solidcraft-sketch",
"thiserror 2.0.21",
+ "toml_edit",
"web-time",
]
@@ -4699,6 +4700,7 @@ dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
+ "toml_writer",
"winnow",
]
diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs
index c6c9f45226..51ee2bb768 100644
--- a/apps/solidcraft-cli/src/main.rs
+++ b/apps/solidcraft-cli/src/main.rs
@@ -18,6 +18,7 @@
//! solidcraft-cli mcp [--headless] [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]
//! [--param-check off|warn|strict]
//! MCP server on stdio (docs/mcp.md)
+//! solidcraft-cli mcp setup [--dry-run] [--client NAME] [--live] (alias: mcp install) add it to OpenCode, Claude Desktop, Claude Code, Cursor
//! solidcraft-cli licences SolidCraft's licence and the third-party licences
//! solidcraft-cli icon --out F.png|F.ico [--size N] the app icon (packaging; drawn, not a file)
//!
@@ -82,7 +83,7 @@ const USAGE_ORACLE: &str = " solidcraft-cli oracle <case-dir>... [--json]\n";
const USAGE_FUZZ: &str =
" solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE]\n";
/// `mcp`'s lines in the usage.
-const USAGE_MCP: &str = " solidcraft-cli mcp [--headless] [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]\n [--param-check off|warn|strict] [--render-gpu]\n";
+const USAGE_MCP: &str = " solidcraft-cli mcp [--headless] [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]\n [--param-check off|warn|strict] [--render-gpu]\n solidcraft-cli mcp setup [--dry-run] [--client opencode|claude-desktop|claude-code|cursor] [--live]\n (adds a `solidcraft` server, with this program's path, to each installed AI client; --live adds `solidcraft-live` for the running app; alias: mcp install)\n";
/// `crashes`'s lines in the usage.
const USAGE_CRASHES: &str = " solidcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]\n";
/// `licences`'s lines in the usage.
@@ -625,10 +626,23 @@ fn cmd_exec(args: &[String]) -> Result<(), String> {
Ok(())
}
+/// `mcp setup`: add the server to each installed AI client, with this program's own path.
+fn cmd_mcp_setup(args: &[String]) -> Result<(), String> {
+ use solidcraft_engine::agent_setup as setup;
+ let (lines, ok) = setup::setup(args, &setup::Env::from_process(), &setup::current_exe()?)?;
+ for l in lines {
+ println!("{l}");
+ }
+ if ok { Ok(()) } else { Err("mcp setup: some clients could not be configured".into()) }
+}
+
/// MCP server on stdio: headless (optionally starting from a design or script) or bridged to
/// a running app's control port. stdout carries only protocol messages. Files the agent's tool
/// calls reach are confined to `solidcraft_mcp::agent_scope` unless `--allow-any-path` is given.
fn cmd_mcp(args: &[String]) -> Result<(), String> {
+ if matches!(args.first().map(String::as_str), Some("setup" | "install")) {
+ return cmd_mcp_setup(&args[1..]);
+ }
let render_gpu = args.iter().any(|arg| arg == "--render-gpu");
if render_gpu && flag(args, "--connect").is_some() {
return Err("mcp: --render-gpu installs a headless image host; a connected application owns its own device".into());
@@ -684,9 +698,8 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
Box::new(headless)
}
(None, None) => {
- if !args.iter().any(|a| a == "--headless")
- && let Some(port) = discover_app()
- {
+ let auto = !args.iter().any(|a| a == "--headless");
+ if auto && let Some(port) = discover_app() {
eprintln!("solidcraft mcp: bridged to the running app at 127.0.0.1:{port} (--headless starts a session of its own)");
return serve_mcp(Box::new(solidcraft_mcp::Remote::new(&format!("127.0.0.1:{port}"), flag(args, "--token"))), scope);
}
@@ -695,7 +708,12 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {
if render_gpu {
headless.session.register_render_job_host(solidcraft_gpu::path::host().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
}
- Box::new(headless)
+ if auto {
+ // The app may start after the agent: look for it again until there is work here.
+ Box::new(solidcraft_mcp::Auto::new(headless, Box::new(discover_app), flag(args, "--token")))
+ } else {
+ Box::new(headless)
+ }
}
};
serve_mcp(backend, scope)
diff --git a/apps/solidcraft-cli/tests/mcp_connect.rs b/apps/solidcraft-cli/tests/mcp_connect.rs
index 1697152b8e..1475f40d78 100644
--- a/apps/solidcraft-cli/tests/mcp_connect.rs
+++ b/apps/solidcraft-cli/tests/mcp_connect.rs
@@ -151,3 +151,115 @@ fn mcp_without_arguments_finds_the_running_app() {
assert!(!String::from_utf8_lossy(&out.stderr).contains("bridged to the running app"), "{}", String::from_utf8_lossy(&out.stderr));
std::fs::remove_dir_all(&control_dir).ok();
}
+
+/// `mcp setup` against a temporary home: the client folders it finds are the only ones it writes.
+mod setup {
+ use serde_json::{Value, json};
+ use std::path::{Path, PathBuf};
+ use std::process::Command;
+
+ fn home(name: &str) -> PathBuf {
+ let h = std::env::temp_dir().join(format!("solidcraft-mcp-setup-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&h);
+ std::fs::create_dir_all(&h).unwrap();
+ h
+ }
+
+ fn run(home: &Path, args: &[&str]) -> std::process::Output {
+ Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))
+ .args(["mcp", "setup"])
+ .args(args)
+ .env_clear()
+ .env("HOME", home)
+ .env("USERPROFILE", home)
+ .env("APPDATA", home.join("AppData/Roaming"))
+ .env("LOCALAPPDATA", home.join("AppData/Local"))
+ .env("XDG_CONFIG_HOME", home.join(".config"))
+ .env("PATH", "")
+ .output()
+ .unwrap()
+ }
+
+ fn json_of(p: &Path) -> Value {
+ serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap()
+ }
+
+ fn exe() -> String {
+ let p = Path::new(env!("CARGO_BIN_EXE_solidcraft-cli")).canonicalize().unwrap();
+ p.to_string_lossy().trim_start_matches(r"\\?\").to_owned()
+ }
+
+ #[test]
+ fn merges_into_opencode_and_cursor_keeping_other_servers() {
+ let h = home("merge");
+ let oc = h.join(".config/opencode");
+ std::fs::create_dir_all(&oc).unwrap();
+ let old = json!({"$schema": "https://opencode.ai/config.json", "theme": "x", "mcp": {"other": {"type": "local", "command": ["o"]}}});
+ std::fs::write(oc.join("opencode.json"), old.to_string()).unwrap();
+ std::fs::create_dir_all(h.join(".cursor")).unwrap();
+ std::fs::write(h.join(".cursor/mcp.json"), r#"{"mcpServers": {"other": {"command": "o"}}}"#).unwrap();
+
+ let out = run(&h, &["--live"]);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let v = json_of(&oc.join("opencode.json"));
+ assert_eq!(v["theme"], "x");
+ assert_eq!(v["mcp"]["other"], old["mcp"]["other"]);
+ assert_eq!(v["mcp"]["solidcraft"], json!({"type": "local", "command": [exe(), "mcp"], "enabled": true}));
+ assert_eq!(v["mcp"]["solidcraft-live"]["command"], json!([exe(), "mcp", "--connect", "127.0.0.1:7878"]));
+ assert_eq!(json_of(&oc.join("opencode.json.bak")), old);
+ let c = json_of(&h.join(".cursor/mcp.json"));
+ assert_eq!(c["mcpServers"]["other"], json!({"command": "o"}));
+ assert_eq!(c["mcpServers"]["solidcraft"], json!({"command": exe(), "args": ["mcp"]}));
+
+ // Codex (TOML) and Claude Code (a big file the CLI owns) are edited in place too.
+ std::fs::create_dir_all(h.join(".codex")).unwrap();
+ std::fs::write(h.join(".codex/config.toml"), "# mine\nmodel = \"x\"\n").unwrap();
+ let cc = "{\n \"numStartups\": 3,\n \"projects\": {}\n}\n";
+ std::fs::write(h.join(".claude.json"), cc).unwrap();
+ assert!(run(&h, &[]).status.success());
+ let toml = std::fs::read_to_string(h.join(".codex/config.toml")).unwrap();
+ assert!(toml.starts_with("# mine\nmodel = \"x\"\n") && toml.contains("[mcp_servers.solidcraft]"), "{toml}");
+ let c = json_of(&h.join(".claude.json"));
+ assert_eq!(c["numStartups"], 3);
+ assert_eq!(c["mcpServers"]["solidcraft"], json!({"type": "stdio", "command": exe(), "args": ["mcp"]}));
+ assert_eq!(std::fs::read_to_string(h.join(".claude.json.bak")).unwrap(), cc);
+
+ // Running again updates the same entries and leaves one of each.
+ assert!(run(&h, &[]).status.success());
+ assert_eq!(json_of(&h.join(".cursor/mcp.json"))["mcpServers"].as_object().unwrap().len(), 3);
+ }
+
+ #[test]
+ fn dry_run_writes_nothing_and_missing_clients_are_skipped() {
+ let h = home("dry");
+ std::fs::create_dir_all(h.join(".cursor")).unwrap();
+ let out = run(&h, &["--dry-run"]);
+ assert!(out.status.success());
+ let text = String::from_utf8_lossy(&out.stdout);
+ assert!(text.contains("would write") && text.contains("solidcraft"), "{text}");
+ assert!(!h.join(".cursor/mcp.json").exists());
+ assert!(!h.join(".config/opencode").exists(), "OpenCode was not installed, so nothing is created for it");
+ let out = run(&h, &["--client", "claude-desktop"]);
+ assert!(String::from_utf8_lossy(&out.stdout).contains("not found"));
+ }
+
+ #[test]
+ fn a_file_that_is_not_json_is_left_alone() {
+ let h = home("bad");
+ std::fs::create_dir_all(h.join(".cursor")).unwrap();
+ std::fs::write(h.join(".cursor/mcp.json"), "{ // comment").unwrap();
+ let out = run(&h, &[]);
+ assert!(!out.status.success());
+ assert_eq!(std::fs::read_to_string(h.join(".cursor/mcp.json")).unwrap(), "{ // comment");
+ }
+
+ #[test]
+ fn claude_desktop_msix_folder_is_found() {
+ let h = home("msix");
+ let pkg = h.join("AppData/Local/Packages/Claude_abc/LocalCache/Roaming/Claude");
+ std::fs::create_dir_all(&pkg).unwrap();
+ // The MSIX folder is only read through LOCALAPPDATA, set for every platform here.
+ assert!(run(&h, &["--client", "claude-desktop"]).status.success());
+ assert!(json_of(&pkg.join("claude_desktop_config.json"))["mcpServers"]["solidcraft"].is_object());
+ }
+}
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 2ac7e49c75..fbe714e087 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -1140,6 +1140,8 @@
"help.apache": "Apache licence 2.0",
"help.attributions": "Attributions (ATTRIBUTION.md)",
"help.build": "Version {version} · commit {commit} · built {date}",
+ "help.connect_note": "Restart each assistant to load the SolidCraft server. Each file was backed up as .bak before it changed.",
+ "help.connect_title": "Connect AI assistants",
"help.font_details": "The interface uses egui's built-in fonts (Ubuntu Light and Hack, under the Ubuntu Font Licence and the MIT/Bitstream Vera licence; Noto Emoji and the emoji icon font, under the OFL and MIT). Sketch text uses Liberation Sans (SIL OFL 1.1). The Crafting Apps' optional font pack, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), is not bundled in SolidCraft builds.",
"help.fonts": "Fonts",
"help.licences": "Licences",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 0db7168a84..93a3993b7e 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -1140,6 +1140,8 @@
"help.apache": "Apacheライセンス2.0",
"help.attributions": "帰属表示 (ATTRIBUTION.md)",
"help.build": "バージョン {version} · コミット {commit} · ビルド日 {date}",
+ "help.connect_note": "各アシスタントを再起動すると SolidCraft サーバーが読み込まれます。変更したファイルは .bak としてバックアップされています。",
+ "help.connect_title": "AI アシスタントを接続",
"help.font_details": "インターフェースにはegui組み込みのフォントを使用しています(Ubuntu Font LicenceおよびMIT/Bitstream VeraライセンスのUbuntu LightとHack、OFLおよびMITのNoto Emojiと絵文字アイコンフォント)。スケッチのテキストにはLiberation Sans(SIL OFL 1.1)を使用しています。The Crafting Appsのオプションフォントパックcraft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic、SIL OFL 1.1)はSolidCraftのビルドに同梱されていません。",
"help.fonts": "フォント",
"help.licences": "ライセンス",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index b15576361b..af7c4aca4a 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -1140,6 +1140,8 @@
"help.apache": "Apache 许可证 2.0",
"help.attributions": "署名信息 (ATTRIBUTION.md)",
"help.build": "版本 {version} · 提交 {commit} · 构建日期 {date}",
+ "help.connect_note": "请重启各个助手以加载 SolidCraft 服务器。每个被修改的文件都已备份为 .bak。",
+ "help.connect_title": "连接 AI 助手",
"help.font_details": "界面使用 egui 的内置字体(Ubuntu Light 和 Hack,采用 Ubuntu Font Licence 和 MIT/Bitstream Vera 许可证;Noto Emoji 和表情图标字体,采用 OFL 和 MIT 许可证)。草图文本使用 Liberation Sans(SIL OFL 1.1)。The Crafting Apps 的可选字体包 craft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic;SIL OFL 1.1)未随 SolidCraft 构建版本捆绑提供。",
"help.fonts": "字体",
"help.licences": "许可证",
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 1c3babcc6c..ba5e1c4b7d 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -39,6 +39,7 @@ solidcraft-io = { workspace = true }
solidcraft-render = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+toml_edit = "0.25"
schemars = { workspace = true }
serde_path_to_error = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/agent_setup.rs b/crates/engine/src/agent_setup.rs
new file mode 100644
index 0000000000..49f04eec8f
--- /dev/null
+++ b/crates/engine/src/agent_setup.rs
@@ -0,0 +1,749 @@
+//! `solidcraft-cli mcp setup` and Help > Connect AI assistants: add a `solidcraft` MCP server entry
+//! to the AI clients installed on this machine, using the `solidcraft-cli` path given.
+//!
+//! The clients' own files are edited in place, not rewritten: only the `solidcraft` entries change,
+//! every other byte (other servers, other settings, comments, key order) stays as it was. The file
+//! is copied to `<name>.bak` first. A file that cannot be read as JSON (with comments) or TOML is
+//! left alone, and so is an entry the user changed (its command is not a SolidCraft CLI, or its
+//! arguments differ); an entry that only has an old path to the CLI is updated.
+//! A client counts as installed when its configuration folder exists; no client program is run.
+
+use serde_json::{Value, json};
+use std::path::{Path, PathBuf};
+
+/// The address `--live` bridges to, the one docs/mcp.md starts the app on.
+const LIVE_ADDR: &str = "127.0.0.1:7878";
+
+/// Where the clients keep their configuration, read from the environment so tests can point it at a
+/// temporary folder.
+pub struct Env {
+ pub home: Option<PathBuf>,
+ pub appdata: Option<PathBuf>,
+ pub local_appdata: Option<PathBuf>,
+ pub xdg_config: Option<PathBuf>,
+ pub codex_home: Option<PathBuf>,
+}
+
+impl Env {
+ pub fn from_process() -> Env {
+ let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
+ let home = var("HOME").or_else(|| var("USERPROFILE"));
+ Env { home, appdata: var("APPDATA"), local_appdata: var("LOCALAPPDATA"), xdg_config: var("XDG_CONFIG_HOME"), codex_home: var("CODEX_HOME") }
+ }
+
+ /// `$XDG_CONFIG_HOME`, else `~/.config`.
+ fn config_home(&self) -> Option<PathBuf> {
+ self.xdg_config.clone().or_else(|| self.home.as_ref().map(|h| h.join(".config")))
+ }
+
+ fn in_home(&self, rel: &str) -> Option<PathBuf> {
+ self.home.as_ref().map(|h| h.join(rel))
+ }
+}
+
+/// How a client spells a server entry and where its list is.
+#[derive(Clone, Copy, PartialEq)]
+enum Shape {
+ /// `"mcpServers": {name: {"command": exe, "args": [...]}}` (Claude Desktop, Cursor, Gemini CLI, Windsurf)
+ McpServers,
+ /// Claude Code's `~/.claude.json`: the same with `"type": "stdio"`.
+ ClaudeCode,
+ /// GitHub Copilot CLI: the same with `"type": "local"` and `"tools": ["*"]`.
+ Copilot,
+ /// VS Code's user `mcp.json`: `"servers": {name: {"type": "stdio", ...}}`.
+ VsCode,
+ /// Zed's `settings.json`: `"context_servers": {name: {"command": exe, "args": [...]}}`.
+ Zed,
+ /// OpenCode: `"mcp": {name: {"type": "local", "command": [exe, ...], "enabled": true}}`.
+ OpenCode,
+ /// Codex: `[mcp_servers.name]` with `command` and `args`, in `config.toml`.
+ Codex,
+}
+
+impl Shape {
+ fn list_key(self) -> &'static str {
+ match self {
+ Shape::McpServers | Shape::ClaudeCode | Shape::Copilot => "mcpServers",
+ Shape::VsCode => "servers",
+ Shape::Zed => "context_servers",
+ Shape::OpenCode => "mcp",
+ Shape::Codex => "mcp_servers",
+ }
+ }
+
+ fn entry(self, exe: &str, args: &[&str]) -> Value {
+ match self {
+ Shape::McpServers | Shape::Zed | Shape::Codex => json!({"command": exe, "args": args}),
+ Shape::ClaudeCode | Shape::VsCode => json!({"type": "stdio", "command": exe, "args": args}),
+ Shape::Copilot => json!({"type": "local", "command": exe, "args": args, "tools": ["*"]}),
+ Shape::OpenCode => {
+ let mut cmd = vec![exe];
+ cmd.extend_from_slice(args);
+ json!({"type": "local", "command": cmd, "enabled": true})
+ }
+ }
+ }
+}
+
+struct Target {
+ client: &'static str,
+ file: PathBuf,
+ shape: Shape,
+}
+
+/// The names `--client` takes.
+pub const CLIENTS: &[&str] = &["opencode", "claude-desktop", "claude-code", "cursor", "codex", "gemini", "copilot", "windsurf", "zed", "vscode"];
+
+/// The server entries to write: `solidcraft`, and `solidcraft-live` with `--live`.
+fn servers(live: bool) -> Vec<(&'static str, Vec<&'static str>)> {
+ let mut v = vec![("solidcraft", vec!["mcp"])];
+ if live {
+ v.push(("solidcraft-live", vec!["mcp", "--connect", LIVE_ADDR]));
+ }
+ v
+}
+
+/// The running executable's absolute path, without the `\\?\` prefix `canonicalize` adds on
+/// Windows (some clients mishandle it).
+pub fn current_exe() -> Result<String, String> {
+ let exe = std::env::current_exe().map_err(|e| format!("cannot find this executable: {e}"))?;
+ Ok(plain_path(&exe.canonicalize().unwrap_or(exe)))
+}
+
+/// A path as text, without the `\\?\` prefix of a canonicalized Windows path.
+pub fn plain_path(p: &Path) -> String {
+ let s = p.to_string_lossy().into_owned();
+ match s.strip_prefix(r"\\?\") {
+ Some(rest) if !rest.starts_with("UNC\\") => rest.to_owned(),
+ _ => s,
+ }
+}
+
+/// Claude Desktop's configuration folders: the regular one, and the Microsoft Store (MSIX)
+/// package's redirected copy on Windows.
+fn claude_desktop_dirs(env: &Env) -> Vec<PathBuf> {
+ let mut dirs = Vec::new();
+ if let Some(a) = &env.appdata {
+ dirs.push(a.join("Claude"));
+ }
+ if cfg!(target_os = "macos")
+ && let Some(d) = env.in_home("Library/Application Support/Claude")
+ {
+ dirs.push(d);
+ }
+ if cfg!(target_os = "linux")
+ && let Some(c) = env.config_home()
+ {
+ dirs.push(c.join("Claude"));
+ }
+ if let Some(l) = &env.local_appdata
+ && let Ok(rd) = std::fs::read_dir(l.join("Packages"))
+ {
+ let mut pk: Vec<PathBuf> = rd
+ .flatten()
+ .filter(|e| e.file_name().to_string_lossy().starts_with("Claude_"))
+ .map(|e| e.path().join("LocalCache/Roaming/Claude"))
+ .collect();
+ pk.sort();
+ dirs.extend(pk);
+ }
+ dirs
+}
+
+/// The folder VS Code keeps its user settings in.
+fn vscode_dir(env: &Env) -> Option<PathBuf> {
+ if cfg!(windows) {
+ env.appdata.as_ref().map(|a| a.join("Code/User"))
+ } else if cfg!(target_os = "macos") {
+ env.in_home("Library/Application Support/Code/User")
+ } else {
+ env.config_home().map(|c| c.join("Code/User"))
+ }
+}
+
+/// The clients found on this machine: those whose configuration folder exists.
+fn detect(env: &Env, only: Option<&str>) -> Vec<Target> {
+ let want = |c: &str| only.is_none_or(|o| o == c);
+ let mut v = Vec::new();
+ fn add(v: &mut Vec<Target>, client: &'static str, dir: Option<PathBuf>, file: &str, shape: Shape) {
+ if let Some(dir) = dir.filter(|d| d.is_dir()) {
+ v.push(Target { client, file: dir.join(file), shape });
+ }
+ }
+ if want("opencode") {
+ let dir = env.config_home().map(|c| c.join("opencode"));
+ // opencode.jsonc is read too (comments allowed); keep to the one the user has.
+ let file = if dir.as_ref().is_some_and(|d| !d.join("opencode.json").exists() && d.join("opencode.jsonc").exists()) {
+ "opencode.jsonc"
+ } else {
+ "opencode.json"
+ };
+ add(&mut v, "opencode", dir, file, Shape::OpenCode);
+ }
+ if want("claude-desktop") {
+ for dir in claude_desktop_dirs(env) {
+ add(&mut v, "claude-desktop", Some(dir), "claude_desktop_config.json", Shape::McpServers);
+ }
+ }
+ if want("claude-code")
+ && let Some(h) = &env.home
+ && (h.join(".claude.json").is_file() || h.join(".claude").is_dir())
+ {
+ v.push(Target { client: "claude-code", file: h.join(".claude.json"), shape: Shape::ClaudeCode });
+ }
+ if want("cursor") {
+ add(&mut v, "cursor", env.in_home(".cursor"), "mcp.json", Shape::McpServers);
+ }
+ if want("codex") {
+ add(&mut v, "codex", env.codex_home.clone().or_else(|| env.in_home(".codex")), "config.toml", Shape::Codex);
+ }
+ if want("gemini") {
+ add(&mut v, "gemini", env.in_home(".gemini"), "settings.json", Shape::McpServers);
+ }
+ if want("copilot") {
+ add(&mut v, "copilot", env.in_home(".copilot"), "mcp-config.json", Shape::Copilot);
+ }
+ if want("windsurf") {
+ add(&mut v, "windsurf", env.in_home(".codeium/windsurf"), "mcp_config.json", Shape::McpServers);
+ }
+ if want("zed") {
+ let dir = if cfg!(windows) { env.appdata.as_ref().map(|a| a.join("Zed")) } else { env.config_home().map(|c| c.join("zed")) };
+ add(&mut v, "zed", dir, "settings.json", Shape::Zed);
+ }
+ if want("vscode") {
+ add(&mut v, "vscode", vscode_dir(env), "mcp.json", Shape::VsCode);
+ }
+ v
+}
+
+// ---------------------------------------------------------------------------------------------
+// What an existing entry is.
+
+/// What setup does about one server entry.
+#[derive(Debug, PartialEq)]
+enum Verdict {
+ /// No entry: add it.
+ Add,
+ /// The entry is what setup would write.
+ Same,
+ /// The entry is ours with an older path to the CLI: update it.
+ Stale,
+ /// Something the user wrote or changed: leave it.
+ Custom,
+}
+
+/// Whether `command` runs a SolidCraft CLI (under this name or the pre-rename one).
+fn is_solidcraft_cli(command: &str) -> bool {
+ let name = command.rsplit(['/', '\\']).next().unwrap_or(command).to_ascii_lowercase();
+ let stem = name.strip_suffix(".exe").unwrap_or(&name);
+ stem == "solidcraft-cli" || stem == "solvecraft-cli"
+}
+
+/// The command and arguments of an entry, whether it spells them as `command` + `args` or as
+/// OpenCode's one `command` array.
+fn command_and_args(entry: &Value) -> Option<(String, Vec<String>)> {
+ let strings = |v: &Value| v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect::<Vec<_>>());
+ match entry.get("command")? {
+ Value::String(c) => Some((c.clone(), entry.get("args").and_then(strings).unwrap_or_default())),
+ Value::Array(_) => {
+ let mut all = strings(entry.get("command")?)?;
+ (!all.is_empty()).then(|| (all.remove(0), all))
+ }
+ _ => None,
+ }
+}
+
+fn judge(existing: Option<&Value>, exe: &str, args: &[&str]) -> Verdict {
+ let Some(existing) = existing else { return Verdict::Add };
+ let Some((cmd, got)) = command_and_args(existing) else { return Verdict::Custom };
+ if got != args {
+ return Verdict::Custom;
+ }
+ if cmd == exe {
+ Verdict::Same
+ } else if is_solidcraft_cli(&cmd) {
+ Verdict::Stale
+ } else {
+ Verdict::Custom
+ }
+}
+
+/// `existing` with its command replaced by `exe`, every other field kept.
+fn with_command(existing: &Value, exe: &str) -> Value {
+ let mut v = existing.clone();
+ match v.get_mut("command") {
+ Some(Value::Array(a)) if !a.is_empty() => a[0] = json!(exe),
+ Some(c) => *c = json!(exe),
+ None => {}
+ }
+ v
+}
+
+// ---------------------------------------------------------------------------------------------
+// Editing JSON (with comments and trailing commas, as VS Code, Zed and OpenCode accept) in place.
+
+/// One member of an object in the text: its key and the byte range of its value.
+struct Member {
+ key: String,
+ key_at: usize,
+ val: (usize, usize),
+}
+
+/// An object in the text: the offsets of its braces and its members.
+struct Obj {
+ open: usize,
+ close: usize,
+ members: Vec<Member>,
+}
+
+fn skip_ws(b: &[u8], mut i: usize) -> Result<usize, String> {
+ loop {
+ match b.get(i) {
+ Some(c) if c.is_ascii_whitespace() => i += 1,
+ Some(b'/') if b.get(i + 1) == Some(&b'/') => {
+ while b.get(i).is_some_and(|&c| c != b'\n') {
+ i += 1;
+ }
+ }
+ Some(b'/') if b.get(i + 1) == Some(&b'*') => {
+ i += 2;
+ while !(b.get(i) == Some(&b'*') && b.get(i + 1) == Some(&b'/')) {
+ if i >= b.len() {
+ return Err("an unterminated comment".into());
+ }
+ i += 1;
+ }
+ i += 2;
+ }
+ _ => return Ok(i),
+ }
+ }
+}
+
+fn scan_string(b: &[u8], mut i: usize) -> Result<usize, String> {
+ i += 1;
+ while let Some(&c) = b.get(i) {
+ match c {
+ b'\\' => i += 2,
+ b'"' => return Ok(i + 1),
+ _ => i += 1,
+ }
+ }
+ Err("an unterminated string".into())
+}
+
+/// The end of the value starting at `i`.
+fn scan_value(b: &[u8], i: usize, depth: usize) -> Result<usize, String> {
+ if depth > 64 {
+ return Err("nesting too deep".into());
+ }
+ match b.get(i) {
+ Some(b'"') => scan_string(b, i),
+ Some(b'{') => Ok(scan_object(b, i, depth)?.close + 1),
+ Some(b'[') => {
+ let mut j = skip_ws(b, i + 1)?;
+ loop {
+ match b.get(j) {
+ Some(b']') => return Ok(j + 1),
+ Some(b',') => j = skip_ws(b, j + 1)?,
+ Some(_) => j = skip_ws(b, scan_value(b, j, depth + 1)?)?,
+ None => return Err("an unterminated array".into()),
+ }
+ }
+ }
+ Some(c) if !matches!(c, b',' | b'}' | b']' | b':') => {
+ let mut j = i;
+ while b.get(j).is_some_and(|c| !c.is_ascii_whitespace() && !matches!(c, b',' | b'}' | b']' | b'/')) {
+ j += 1;
+ }
+ Ok(j)
+ }
+ _ => Err(format!("a value was expected at byte {i}")),
+ }
+}
+
+fn scan_object(b: &[u8], open: usize, depth: usize) -> Result<Obj, String> {
+ let mut members = Vec::new();
+ let mut i = skip_ws(b, open + 1)?;
+ loop {
+ match b.get(i) {
+ Some(b'}') => return Ok(Obj { open, close: i, members }),
+ Some(b',') => i = skip_ws(b, i + 1)?,
+ Some(b'"') => {
+ let end = scan_string(b, i)?;
+ let key: String = serde_json::from_slice(b.get(i..end).unwrap_or_default()).map_err(|e| e.to_string())?;
+ let colon = skip_ws(b, end)?;
+ if b.get(colon) != Some(&b':') {
+ return Err(format!("a `:` was expected at byte {colon}"));
+ }
+ let vs = skip_ws(b, colon + 1)?;
+ let ve = scan_value(b, vs, depth + 1)?;
+ members.push(Member { key, key_at: i, val: (vs, ve) });
+ i = skip_ws(b, ve)?;
+ }
+ _ => return Err(format!("a key or `}}` was expected at byte {i}")),
+ }
+ }
+}
+
+/// The top-level object of a JSON document, with the byte after it checked to hold nothing else.
+fn root_object(text: &str) -> Result<Obj, String> {
+ let b = text.as_bytes();
+ let i = skip_ws(b, 0)?;
+ if b.get(i) != Some(&b'{') {
+ return Err("the top level is not a JSON object".into());
+ }
+ let obj = scan_object(b, i, 0)?;
+ if skip_ws(b, obj.close + 1)? != b.len() {
+ return Err("text after the top-level object".into());
+ }
+ Ok(obj)
+}
+
+/// The indentation of the line holding byte `at`.
+fn line_indent(text: &str, at: usize) -> String {
+ let start = text.get(..at).and_then(|t| t.rfind('\n')).map_or(0, |n| n + 1);
+ text.get(start..).unwrap_or_default().chars().take_while(|c| *c == ' ' || *c == '\t').collect()
+}
+
+/// `value` pretty-printed, its lines after the first indented by `indent`.
+fn pretty_at(value: &Value, indent: &str) -> String {
+ serde_json::to_string_pretty(value).unwrap_or_default().replace('\n', &format!("\n{indent}"))
+}
+
+/// Insert `"key": value` as the last member of `obj`.
+fn insert_member(text: &mut String, obj: &Obj, key: &str, value: &Value) {
+ let closing_indent = line_indent(text, obj.open);
+ let member_indent = match obj.members.first() {
+ Some(m) => line_indent(text, m.key_at),
+ None => format!("{closing_indent} "),
+ };
+ let k = serde_json::to_string(key).unwrap_or_default();
+ let member = format!("{k}: {}", pretty_at(value, &member_indent));
+ match obj.members.last() {
+ Some(last) => text.insert_str(last.val.1, &format!(",\n{member_indent}{member}")),
+ None => {
+ let inner = format!("\n{member_indent}{member}\n{closing_indent}");
+ text.replace_range(obj.open + 1..obj.close, &inner);
+ }
+ }
+}
+
+/// What happened to one server entry.
+#[derive(Debug, PartialEq)]
+enum Change {
+ Added,
+ Updated,
+ Unchanged,
+ /// Not touched, because the user's own entry is there.
+ Custom,
+}
+
+/// Set the entries in the JSON text, in the object under the top-level `list_key`.
+fn edit_json(text: &mut String, shape: Shape, exe: &str, live: bool) -> Result<Vec<(&'static str, Change)>, String> {
+ let mut out = Vec::new();
+ let key = shape.list_key();
+ if text.trim().is_empty() {
+ *text = "{}\n".into();
+ }
+ let root = root_object(text)?;
+ // The list object: found, or created holding nothing yet.
+ let list_open = match root.members.iter().find(|m| m.key == key) {
+ Some(m) if text.as_bytes().get(m.val.0) == Some(&b'{') => m.val.0,
+ Some(_) => return Err(format!("`{key}` is not a JSON object")),
+ None => {
+ insert_member(text, &root, key, &json!({}));
+ let root = root_object(text)?;
+ root.members.iter().find(|m| m.key == key).map_or(0, |m| m.val.0)
+ }
+ };
+ for (name, args) in servers(live) {
+ let new = shape.entry(exe, &args);
+ let obj = scan_object(text.as_bytes(), list_open, 0)?;
+ let existing = obj.members.iter().find(|m| m.key == name);
+ let parsed = existing.and_then(|m| serde_json::from_str::<Value>(text.get(m.val.0..m.val.1).unwrap_or_default()).ok());
+ // An entry that is not even valid JSON (a comment inside it) is the user's.
+ let verdict = match (existing, &parsed) {
+ (Some(_), None) => Verdict::Custom,
+ _ => judge(parsed.as_ref(), exe, &args),
+ };
+ let change = match (verdict, existing) {
+ (Verdict::Add, _) => {
+ insert_member(text, &obj, name, &new);
+ Change::Added
+ }
+ (Verdict::Stale, Some(m)) => {
+ let updated = with_command(parsed.as_ref().unwrap_or(&new), exe);
+ let indent = line_indent(text, m.val.0);
+ text.replace_range(m.val.0..m.val.1, &pretty_at(&updated, &indent));
+ Change::Updated
+ }
+ (Verdict::Same, _) => Change::Unchanged,
+ _ => Change::Custom,
+ };
+ out.push((name, change));
+ }
+ if !text.ends_with('\n') {
+ text.push('\n');
+ }
+ Ok(out)
+}
+
+// ---------------------------------------------------------------------------------------------
+// Editing Codex's TOML in place.
+
+fn edit_toml(text: &mut String, exe: &str, live: bool) -> Result<Vec<(&'static str, Change)>, String> {
+ use toml_edit::{Array, DocumentMut, Item, Table, value};
+ let mut doc: DocumentMut = text.parse().map_err(|e: toml_edit::TomlError| e.to_string())?;
+ let mut out = Vec::new();
+ if doc.get("mcp_servers").is_some_and(|i| !i.is_table()) {
+ return Err("`mcp_servers` is not a table".into());
+ }
+ for (name, args) in servers(live) {
+ let existing = doc
+ .get("mcp_servers")
+ .and_then(|t| t.get(name))
+ .map(|i| i.as_table().map(toml_to_json).or_else(|| i.as_inline_table().map(|t| toml_to_json(&t.clone().into_table()))));
+ let existing = match existing {
+ Some(Some(v)) => Some(v),
+ Some(None) => {
+ out.push((name, Change::Custom));
+ continue;
+ }
+ None => None,
+ };
+ let change = match judge(existing.as_ref(), exe, &args) {
+ Verdict::Add => {
+ let mut t = Table::new();
+ t["command"] = value(exe);
+ let mut a = Array::new();
+ for x in &args {
+ a.push(*x);
+ }
+ t["args"] = value(a);
+ let servers = doc.entry("mcp_servers").or_insert_with(|| {
+ let mut t = Table::new();
+ t.set_implicit(true);
+ Item::Table(t)
+ });
+ if let Some(s) = servers.as_table_mut() {
+ s.insert(name, Item::Table(t));
+ }
+ Change::Added
+ }
+ Verdict::Stale => {
+ if let Some(entry) = doc.get_mut("mcp_servers").and_then(|t| t.get_mut(name)) {
+ entry["command"] = value(exe);
+ }
+ Change::Updated
+ }
+ Verdict::Same => Change::Unchanged,
+ Verdict::Custom => Change::Custom,
+ };
+ out.push((name, change));
+ }
+ *text = doc.to_string();
+ if !text.ends_with('\n') {
+ text.push('\n');
+ }
+ Ok(out)
+}
+
+/// The `command` and `args` of a TOML table, as JSON for `judge`.
+fn toml_to_json(t: &toml_edit::Table) -> Value {
+ let command = t.get("command").and_then(|c| c.as_str()).map(|c| json!(c));
+ let args = t.get("args").and_then(|a| a.as_array()).map(|a| Value::Array(a.iter().filter_map(|x| x.as_str().map(|s| json!(s))).collect()));
+ let mut m = serde_json::Map::new();
+ if let Some(c) = command {
+ m.insert("command".into(), c);
+ }
+ if let Some(a) = args {
+ m.insert("args".into(), a);
+ }
+ Value::Object(m)
+}
+
+// ---------------------------------------------------------------------------------------------
+
+/// One client's outcome, a line of the report.
+fn configure_file(t: &Target, exe: &str, live: bool, dry_run: bool) -> Result<String, String> {
+ let fail = |e: String| format!("{}: {e}; left unchanged", t.file.display());
+ let existing = match std::fs::read_to_string(&t.file) {
+ Ok(s) => Some(s),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
+ Err(e) => return Err(format!("{}: {e}", t.file.display())),
+ };
+ let mut text = existing.clone().unwrap_or_default();
+ let changes = if t.shape == Shape::Codex { edit_toml(&mut text, exe, live) } else { edit_json(&mut text, t.shape, exe, live) }.map_err(fail)?;
+ let said: Vec<String> = changes
+ .iter()
+ .map(|(name, c)| match c {
+ Change::Added => format!("added {name}"),
+ Change::Updated => format!("updated the path of {name}"),
+ Change::Unchanged => format!("{name} already set up"),
+ Change::Custom => format!("{name} left as you have it (it is not a plain SolidCraft entry)"),
+ })
+ .collect();
+ let said = said.join(", ");
+ let changed = existing.as_deref() != Some(text.as_str());
+ if dry_run {
+ return Ok(if changed { format!("would write {} ({said}):\n{text}", t.file.display()) } else { format!("no change needed ({said})") });
+ }
+ if !changed {
+ return Ok(said);
+ }
+ if existing.is_some() {
+ let mut bak = t.file.clone().into_os_string();
+ bak.push(".bak");
+ std::fs::copy(&t.file, &bak).map_err(|e| format!("{}: cannot back up: {e}", t.file.display()))?;
+ } else if let Some(dir) = t.file.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ }
+ std::fs::write(&t.file, text).map_err(|e| format!("{}: {e}", t.file.display()))?;
+ Ok(format!("{said} ({})", t.file.display()))
+}
+
+/// Set up every detected client (or `--client NAME`; flags `--dry-run`, `--live`) for the
+/// `solidcraft-cli` at `exe`. Returns the result lines, one per client file, and whether every
+/// client succeeded.
+pub fn setup(args: &[String], env: &Env, exe: &str) -> Result<(Vec<String>, bool), String> {
+ let dry_run = args.iter().any(|a| a == "--dry-run");
+ let live = args.iter().any(|a| a == "--live");
+ let mut only = None;
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ match a.as_str() {
+ "--dry-run" | "--live" => {}
+ "--client" => {
+ let c = it.next().ok_or("mcp setup: --client wants a name")?;
+ if !CLIENTS.contains(&c.as_str()) {
+ return Err(format!("mcp setup: unknown client `{c}`; one of {}", CLIENTS.join(", ")));
+ }
+ only = Some(c.as_str());
+ }
+ other => return Err(format!("mcp setup: unknown option `{other}`")),
+ }
+ }
+ let mut lines = Vec::new();
+ let mut ok = true;
+ for t in detect(env, only) {
+ match configure_file(&t, exe, live, dry_run) {
+ Ok(m) => lines.push(format!("{}: {m}", t.client)),
+ Err(e) => {
+ ok = false;
+ lines.push(format!("{}: failed: {e}", t.client));
+ }
+ }
+ }
+ if lines.is_empty() {
+ lines.push(match only {
+ Some(c) => format!("{c}: not found on this machine"),
+ None => format!("no supported client found ({}); see docs/mcp.md for manual setup", CLIENTS.join(", ")),
+ });
+ }
+ Ok((lines, ok))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const EXE: &str = "/opt/solidcraft/solidcraft-cli";
+
+ fn edit(text: &str, shape: Shape) -> (String, Vec<(&'static str, Change)>) {
+ let mut t = text.to_owned();
+ let c = edit_json(&mut t, shape, EXE, false).unwrap();
+ (t, c)
+ }
+
+ #[test]
+ fn adds_to_an_empty_file_and_keeps_everything_else_byte_for_byte() {
+ let (t, c) = edit("", Shape::McpServers);
+ assert_eq!(c, [("solidcraft", Change::Added)]);
+ let v: Value = serde_json::from_str(&t).unwrap();
+ assert_eq!(v["mcpServers"]["solidcraft"], json!({"command": EXE, "args": ["mcp"]}));
+
+ let src = "{\n \"zeta\": 1, // keep\n \"mcpServers\": {\n \"other\": {\"command\": \"o\"}\n },\n \"alpha\": [1,2]\n}\n";
+ let (t, _) = edit(src, Shape::McpServers);
+ // Only the new member was inserted: the original text is intact around it.
+ assert!(
+ t.starts_with("{\n \"zeta\": 1, // keep\n \"mcpServers\": {\n \"other\": {\"command\": \"o\"},\n \"solidcraft\": {"),
+ "{t}"
+ );
+ assert!(t.ends_with(" },\n \"alpha\": [1,2]\n}\n"), "{t}");
+ let v: Value = serde_json::from_str(t.replace("// keep", "").as_str()).unwrap();
+ assert_eq!(v["mcpServers"]["other"], json!({"command": "o"}));
+ }
+
+ #[test]
+ fn a_file_with_comments_and_a_missing_list_gets_the_list() {
+ let (t, _) = edit("// my settings\n{\n \"theme\": \"x\", /* c */\n}\n", Shape::Zed);
+ assert!(t.contains("// my settings") && t.contains("/* c */"), "{t}");
+ assert!(t.contains("\"context_servers\""), "{t}");
+ }
+
+ #[test]
+ fn stale_path_is_updated_and_custom_entries_are_not() {
+ let old = r#"{"mcpServers": {"solidcraft": {"command": "C:\\Old\\solidcraft-cli.exe", "args": ["mcp"], "env": {"A": "1"}}}}"#;
+ let (t, c) = edit(old, Shape::McpServers);
+ assert_eq!(c, [("solidcraft", Change::Updated)]);
+ let v: Value = serde_json::from_str(&t).unwrap();
+ assert_eq!(v["mcpServers"]["solidcraft"]["command"], EXE);
+ assert_eq!(v["mcpServers"]["solidcraft"]["env"], json!({"A": "1"}), "other fields stay");
+
+ // The user added an argument: theirs.
+ let custom = r#"{"mcpServers": {"solidcraft": {"command": "/x/solidcraft-cli", "args": ["mcp", "--allow-any-path"]}}}"#;
+ let (t, c) = edit(custom, Shape::McpServers);
+ assert_eq!(c, [("solidcraft", Change::Custom)]);
+ assert_eq!(t.trim_end(), custom);
+ // Another program under that name: theirs.
+ let other = r#"{"mcpServers": {"solidcraft": {"command": "node", "args": ["mcp"]}}}"#;
+ assert_eq!(edit(other, Shape::McpServers).1, [("solidcraft", Change::Custom)]);
+ // Already right: the text is untouched.
+ let same = format!(r#"{{"mcpServers": {{"solidcraft": {{"command": "{EXE}", "args": ["mcp"]}}}}}}"#);
+ let (t, c) = edit(&same, Shape::McpServers);
+ assert_eq!((t.trim_end(), c), (same.as_str(), vec![("solidcraft", Change::Unchanged)]));
+ }
+
+ #[test]
+ fn opencode_entries_use_one_command_array() {
+ let (t, _) = edit("{\"mcp\": {}}", Shape::OpenCode);
+ let v: Value = serde_json::from_str(&t).unwrap();
+ assert_eq!(v["mcp"]["solidcraft"], json!({"type": "local", "command": [EXE, "mcp"], "enabled": true}));
+ let stale = r#"{"mcp": {"solidcraft": {"type": "local", "command": ["/old/solidcraft-cli", "mcp"], "enabled": false}}}"#;
+ let (t, c) = edit(stale, Shape::OpenCode);
+ assert_eq!(c, [("solidcraft", Change::Updated)]);
+ let v: Value = serde_json::from_str(&t).unwrap();
+ assert_eq!(v["mcp"]["solidcraft"]["command"], json!([EXE, "mcp"]));
+ assert_eq!(v["mcp"]["solidcraft"]["enabled"], false);
+ }
+
+ #[test]
+ fn broken_json_is_an_error() {
+ for bad in ["[1]", "{\"a\": ", "{\"a\": 1} x", "{\"mcpServers\": 3}"] {
+ assert!(edit_json(&mut bad.to_owned(), Shape::McpServers, EXE, false).is_err(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn codex_toml_keeps_comments_and_other_tables() {
+ let src = "# my codex\nmodel = \"x\"\n\n[mcp_servers.other]\ncommand = \"o\" # mine\n";
+ let mut t = src.to_owned();
+ let c = edit_toml(&mut t, EXE, true).unwrap();
+ assert_eq!(c, [("solidcraft", Change::Added), ("solidcraft-live", Change::Added)]);
+ assert!(t.starts_with(src), "{t}");
+ assert!(t.contains("[mcp_servers.solidcraft]") && t.contains(&format!("command = \"{EXE}\"")), "{t}");
+ // Stale path, then a user-changed entry.
+ let mut stale = "[mcp_servers.solidcraft]\ncommand = \"/old/solidcraft-cli\"\nargs = [\"mcp\"]\nstartup_timeout_sec = 30\n".to_owned();
+ assert_eq!(edit_toml(&mut stale, EXE, false).unwrap(), [("solidcraft", Change::Updated)]);
+ assert!(stale.contains("startup_timeout_sec = 30") && stale.contains(EXE), "{stale}");
+ let mut custom = "[mcp_servers.solidcraft]\ncommand = \"/x/solidcraft-cli\"\nargs = [\"mcp\", \"--headless\"]\n".to_owned();
+ let before = custom.clone();
+ assert_eq!(edit_toml(&mut custom, EXE, false).unwrap(), [("solidcraft", Change::Custom)]);
+ assert_eq!(custom, before);
+ // An empty file works too.
+ let mut empty = String::new();
+ edit_toml(&mut empty, EXE, false).unwrap();
+ assert!(empty.contains("[mcp_servers.solidcraft]"), "{empty}");
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 34280646d6..05c91f9ffb 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,6 +7,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
+pub mod agent_setup;
pub mod batch_params;
pub mod capture;
pub mod cmd;
diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs
index e2e71cf0f6..f6b30ef4d9 100644
--- a/crates/mcp/src/backend.rs
+++ b/crates/mcp/src/backend.rs
@@ -29,6 +29,10 @@ pub trait Backend {
fn in_process(&self) -> bool {
false
}
+ /// A line every tool result carries (a session that is not what the user expects).
+ fn notice(&self) -> Option<String> {
+ None
+ }
}
/// Longest reply line accepted from the app.
@@ -564,3 +568,74 @@ impl Backend for Headless {
true
}
}
+
+/// `solidcraft-cli mcp` with no `--connect`: a headless session while no app runs, which gives
+/// way to the app the moment one is found, as long as the session has no work of its own yet.
+/// Once it has, it stays headless (the work is not carried over) and every tool result says so.
+pub struct Auto {
+ headless: Option<Headless>,
+ remote: Option<Remote>,
+ /// The port of the running app, when there is one.
+ discover: Box<dyn FnMut() -> Option<u16>>,
+ token: Option<String>,
+}
+
+impl Auto {
+ pub fn new(headless: Headless, discover: Box<dyn FnMut() -> Option<u16>>, token: Option<&str>) -> Self {
+ Auto { headless: Some(headless), remote: None, discover, token: token.map(str::to_owned) }
+ }
+
+ /// Switch to the app when the session is still empty and one is running.
+ fn look_for_app(&mut self) {
+ let empty = self.headless.as_ref().is_some_and(|h| h.session.doc.features.is_empty());
+ if !empty {
+ return;
+ }
+ if let Some(port) = (self.discover)() {
+ eprintln!("solidcraft mcp: the SolidCraft app is running now; bridged to 127.0.0.1:{port}");
+ self.remote = Some(Remote::new(&format!("127.0.0.1:{port}"), self.token.as_deref()));
+ self.headless = None;
+ }
+ }
+}
+
+impl Backend for Auto {
+ fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
+ if self.remote.is_none() {
+ self.look_for_app();
+ }
+ match (&mut self.remote, &mut self.headless) {
+ (Some(r), _) => r.call(method, params),
+ (None, Some(h)) => h.call(method, params),
+ (None, None) => Err("no session".into()),
+ }
+ }
+ fn has_ui(&self) -> bool {
+ self.remote.is_some()
+ }
+ fn describe(&self) -> String {
+ match (&self.remote, &self.headless) {
+ (Some(r), _) => r.describe(),
+ (None, Some(h)) => format!(
+ "{}, because the SolidCraft app was not running when this server started; if it starts before any design work \
+ is done here, the next call is bridged to it",
+ h.describe()
+ ),
+ (None, None) => String::new(),
+ }
+ }
+ fn design_path(&self) -> Option<String> {
+ self.headless.as_ref().and_then(Headless::design_path)
+ }
+ fn in_process(&self) -> bool {
+ self.remote.is_none()
+ }
+ fn notice(&self) -> Option<String> {
+ self.headless.as_ref().map(|_| {
+ "Note: this is a headless session because the SolidCraft app was not found; the user cannot see this work. \
+ Ask them to start SolidCraft. While this session has no features, the next call connects to the app; once it \
+ has work, it stays here."
+ .to_owned()
+ })
+ }
+}
diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs
index 758884f30d..36391eac0b 100644
--- a/crates/mcp/src/lib.rs
+++ b/crates/mcp/src/lib.rs
@@ -14,7 +14,7 @@ mod server;
mod skill_reference;
mod tools;
-pub use backend::{Backend, Headless, Remote};
+pub use backend::{Auto, Backend, Headless, Remote};
pub use server::{PROTOCOL_VERSION, SUPPORTED_VERSIONS, Server};
pub use tools::{call_tool, tool_definitions};
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index a40c00f72f..2a897c0d85 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -25,7 +25,9 @@ const RESOURCE_NOT_FOUND: i64 = -32002;
/// Most messages in one JSON-RPC batch.
const MAX_BATCH: usize = 1000;
-const INSTRUCTIONS: &str = "SolidCraft is an independent parametric 3D CAD app. Units are millimetres \
+const INSTRUCTIONS: &str = "SolidCraft is an independent parametric 3D CAD app, and these tools drive it: when its window is \
+open the user watches the model appear, otherwise a headless session builds it. When asked to design or build a part \
+(a bracket, an enclosure, a gear) do it with these tools straight away; nothing needs explaining first. Units are millimetres \
and degrees in expressions (internally radians), Z is up. Model like this: `sketch.create {plane: XY}`, draw \
(`sketch.rectangle.two_point {p0, p1}`, `sketch.circle.center {center, radius}`, `sketch.line {points, closed}`), constrain \
and dimension (`sketch.dimension {entities, value}`; values may name parameters), `sketch.finish`, then features \
@@ -186,7 +188,13 @@ impl Server {
// The open design's folder counts as it is now (a save-as or open moves it).
let scope = self.scope.clone().map(|s| s.with_design(self.backend.design_path().as_deref()));
let backend = self.backend.as_mut();
- Ok(vfs::scoped(scope, || call_tool(backend, name, &args)))
+ let mut result = vfs::scoped(scope, || call_tool(backend, name, &args));
+ if let Some(note) = backend.notice()
+ && let Some(content) = result.get_mut("content").and_then(Value::as_array_mut)
+ {
+ content.push(json!({"type": "text", "text": note}));
+ }
+ Ok(result)
}
"resources/list" => Ok(json!({"resources": [
{"uri": "solidcraft://design", "name": "Active design", "description": "document.inspect with measurements", "mimeType": "application/json"},
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index b391ae4ec5..47b8e45815 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -2178,3 +2178,53 @@ fn describe_command_and_strict_parameter_checking() {
let m = tool(&mut s, "measure", json!({}));
assert_eq!(m["body_count"], json!(0), "{m}");
}
+
+/// Plain `mcp` with no app running: the session is headless, says so on every result, and bridges
+/// to the app once one runs, but only while it holds no work of its own.
+#[test]
+fn auto_session_bridges_to_a_late_app_only_while_empty() {
+ use std::cell::Cell;
+ use std::rc::Rc;
+ // A port nothing listens on: the bridge exists, its calls say the app is not running.
+ let port = Rc::new(Cell::new(None::<u16>));
+ let seen = port.clone();
+ let mut s = Server::new(Box::new(crate::Auto::new(Headless::default(), Box::new(move || seen.get()), None)));
+ let text = |r: &Value| r["result"]["content"].as_array().unwrap().iter().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>().join("\n");
+
+ let r = raw_tool(&mut s, "list_commands", json!({}));
+ assert!(text(&r).contains("headless session because the SolidCraft app was not found"), "{r}");
+ let init = call(&mut s, 1, "initialize", json!({}));
+ assert!(init["result"]["instructions"].as_str().unwrap().contains("was not running when this server started"));
+
+ // The app appears while the session is empty: the next call goes to it.
+ port.set(Some(1));
+ let r = raw_tool(&mut s, "inspect_design", json!({}));
+ assert!(!text(&r).contains("headless session because"), "{r}");
+ assert!(s.backend().has_ui());
+ assert!(s.backend().describe().contains("connected to the SolidCraft app"));
+
+ // With work in the headless session, the app showing up changes nothing.
+ port.set(None);
+ let mut s = Server::new(Box::new(crate::Auto::new(
+ Headless::default(),
+ Box::new({
+ let p = port.clone();
+ move || p.get()
+ }),
+ None,
+ )));
+ let r = raw_tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}));
+ assert_ne!(r["result"]["isError"], json!(true), "{r}");
+ port.set(Some(1));
+ let r = raw_tool(&mut s, "inspect_design", json!({}));
+ assert!(text(&r).contains("headless session because the SolidCraft app was not found"), "{r}");
+ assert!(!s.backend().has_ui());
+}
+
+/// A server with no `Auto` backend (`--headless`, `--in`) adds no notice.
+#[test]
+fn plain_headless_adds_no_notice() {
+ let mut s = server();
+ let r = raw_tool(&mut s, "list_commands", json!({}));
+ assert_eq!(r["result"]["content"].as_array().unwrap().len(), 1);
+}
diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs
index 8332ac0c96..144ffbf004 100644
--- a/crates/ui-egui/src/agent_chat/mod.rs
+++ b/crates/ui-egui/src/agent_chat/mod.rs
@@ -753,7 +753,7 @@ fn solidcraft_tool(title: &str) -> bool {
/// `solidcraft-cli` next to this program, else on the search path.
#[cfg(not(target_arch = "wasm32"))]
-fn find_cli() -> Option<std::path::PathBuf> {
+pub(crate) fn find_cli() -> Option<std::path::PathBuf> {
let name = if cfg!(windows) { "solidcraft-cli.exe" } else { "solidcraft-cli" };
if let Some(p) = solidcraft_engine::geom::env::var("CLI").map(std::path::PathBuf::from).filter(|p| p.is_file()) {
return Some(p);
diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rs
index 2b687eb95e..90132c8a36 100644
--- a/crates/ui-egui/src/help.rs
+++ b/crates/ui-egui/src/help.rs
@@ -19,6 +19,8 @@ use solidcraft_engine::licences::{LICENSE_APACHE, LICENSE_MIT, NOTICE, THIRD_PAR
pub struct HelpState {
pub menu: bool,
pub about: bool,
+ /// The result of Connect AI assistants, one line per client, while its window is open.
+ pub connect: Option<Vec<String>>,
/// The GPU the window renders with (set by the host).
pub gpu: Option<String>,
}
@@ -38,7 +40,7 @@ pub fn diagnostics(app: &SolveApp) -> String {
)
}
-/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`, `install_cli` (macOS).
+/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`, `connect`, `install_cli` (macOS).
pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {
app.help.menu = false;
match item {
@@ -49,6 +51,7 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {
app.keymap.read_only = true;
}
"crashes" => crate::crash_ui::open(app),
+ "connect" => app.help.connect = Some(connect_assistants()),
"install_cli" => {
let (msg, error) = crate::cli_link::install_from_menu();
app.set_status(msg, error);
@@ -63,6 +66,47 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {
}
}
+/// Add SolidCraft's MCP server to the AI assistants installed here (`solidcraft-cli mcp setup`),
+/// with the `solidcraft-cli` beside this program. One line per client.
+#[cfg(not(target_arch = "wasm32"))]
+fn connect_assistants() -> Vec<String> {
+ use solidcraft_engine::agent_setup as setup;
+ let Some(cli) = crate::agent_chat::find_cli() else {
+ return vec!["solidcraft-cli was not found next to SolidCraft; run `solidcraft-cli mcp setup` from a terminal.".into()];
+ };
+ let cli = cli.canonicalize().unwrap_or(cli).to_string_lossy().trim_start_matches(r"\\?\").to_owned();
+ match setup::setup(&[], &setup::Env::from_process(), &cli) {
+ Ok((lines, _)) => lines,
+ Err(e) => vec![e],
+ }
+}
+
+#[cfg(target_arch = "wasm32")]
+fn connect_assistants() -> Vec<String> {
+ vec!["Connecting AI assistants needs the desktop app.".into()]
+}
+
+/// The Connect AI assistants result window.
+fn connect(app: &mut SolveApp, ctx: &egui::Context) {
+ let Some(lines) = app.help.connect.clone() else {
+ return;
+ };
+ let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_connect_assistants"), "help", crate::i18n::tr_label("Connect AI assistants"))
+ .cards(2.0)
+ .actions("", "Close", None)
+ .show(ctx, true, |ui| {
+ ui_kit::text(
+ ui,
+ crate::i18n::tr_label("Restart each assistant to load the SolidCraft server. Each file was backed up as .bak before it changed."),
+ ui_kit::Text::Note("connect_note"),
+ );
+ ui_kit::text(ui, &lines.join("\n"), ui_kit::Text::Report("connect", false));
+ });
+ if closed || action == ui_kit::Action::Cancel {
+ app.help.connect = None;
+ }
+}
+
/// The Help menu under the ? button, and the About window.
pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {
if app.help.menu {
@@ -81,6 +125,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {
("messages", "Messages…", "list"),
("report", "Report an Issue…", "bug_report"),
("crashes", "Crash Reports…", "status_error"),
+ ("connect", "Connect AI assistants…", "settings"),
("install_cli", "Install solidcraft-cli command", "settings"),
]
.into_iter()
@@ -103,6 +148,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {
ctx.data_mut(|d| d.insert_temp(egui::Id::new("sc_help_opened"), false));
}
about(app, ctx);
+ connect(app, ctx);
crate::crash_ui::show(app, ctx);
crate::messages::show(app, ctx);
}
diff --git a/docs/mcp.md b/docs/mcp.md
index 3796fc6c1a..cc1957ee17 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -135,6 +135,48 @@ not read-only, `destructiveHint` and `openWorldHint` are true.
`solidcraft-cli` is on `PATH` after every package install: the Windows installer adds its folder, the deb, rpm and FreeBSD packages install it in `/usr/bin`, the Homebrew cask links it, the AppImage writes a small `solidcraft-cli` launcher into `~/.local/bin` on its first run, and the macOS app links it into `/opt/homebrew/bin` or `/usr/local/bin` when it starts (Help > Install solidcraft-cli command does it with an administrator prompt when those are not writable). Two packages keep it out of `PATH` by design: Snap exposes it as `solidcraft.cli`, and Flatpak runs it as `flatpak run --command=solidcraft-cli ai.storyteller.solidcraft`; use those as the client's `command` (with `mcp` as the arguments).
+The quickest way: **Help > Connect AI assistants…** in the app, or
+
+```sh
+solidcraft-cli mcp setup # every client found on this computer
+solidcraft-cli mcp setup --dry-run # show what it would write, change nothing
+solidcraft-cli mcp setup --client opencode --live
+```
+
+(`mcp install` is the same.) It adds a `solidcraft` server, using the full path of the
+`solidcraft-cli` that runs it, so nothing has to be on `PATH`. A client counts as installed when its
+configuration folder exists, and no client program is started. Supported:
+
+| `--client` | Configuration file |
+| --- | --- |
+| `opencode` | `~/.config/opencode/opencode.json` (or `.jsonc`) |
+| `claude-desktop` | `%APPDATA%\Claude\claude_desktop_config.json`, `~/Library/Application Support/Claude/`, `~/.config/Claude/`, and the Microsoft Store package's folder |
+| `claude-code` | `~/.claude.json` (user scope `mcpServers`) |
+| `cursor` | `~/.cursor/mcp.json` |
+| `codex` | `$CODEX_HOME` or `~/.codex`, `config.toml` (CLI, IDE extension and desktop app) |
+| `gemini` | `~/.gemini/settings.json` |
+| `copilot` | `~/.copilot/mcp-config.json` (GitHub Copilot CLI) |
+| `windsurf` | `~/.codeium/windsurf/mcp_config.json` |
+| `zed` | Zed's `settings.json` (`context_servers`) |
+| `vscode` | VS Code's user `mcp.json` |
+
+The files are edited in place: only the `solidcraft` entries change, everything else in the file
+(other servers, comments, order) stays as it was, and the file is copied to `<name>.bak` first. A
+file that does not parse is left alone. Running it again after an update moves the program only
+refreshes the path of an entry it wrote; an entry you changed (extra arguments, another program)
+is left as you have it. `--live` also adds `solidcraft-live`, which bridges to the open app (port
+7878, see below). Restart the client afterwards.
+
+To configure a client by hand instead, these are the entries. OpenCode (`opencode.json`):
+
+```json
+{
+ "mcp": {
+ "solidcraft": { "type": "local", "command": ["/path/to/solidcraft-cli", "mcp"], "enabled": true }
+ }
+}
+```
+
Claude Code (project `.mcp.json`, or `claude mcp add solidcraft -- solidcraft-cli mcp`; a setup
added under the previous name keeps working, see the [compatibility notes](https://github.com/bherbruck/solidcraft/blob/main/docs/compatibility.md#mcp)):