SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Control channel and MCP on by default, with a setting to turn it off (#5561)
bherbruck98c4f335e8ee
diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rsindex 312e1fce70..f724d2901c 100644--- a/apps/solidcraft-cli/src/main.rs+++ b/apps/solidcraft-cli/src/main.rs@@ -15,7 +15,7 @@//! solidcraft-cli commands the command registry as JSON//! solidcraft-cli recipe <recipe.json> translate an oracle recipe to a script//! solidcraft-cli oracle <case-dir>... replay recipes and compare with expected.json-//! solidcraft-cli mcp [--in design|script] [--connect HOST:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]+//! 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 licences SolidCraft's licence and the third-party licences@@ -81,7 +81,7 @@ const USAGE: &str = "usage:solidcraft-cli recipe <recipe.json>solidcraft-cli oracle <case-dir>... [--json]solidcraft-cli fuzz [--from N] [--count N] [--jobs J] [--timeout S] [--steps N] [--minimise] [--out DIR] [--report FILE]- solidcraft-cli mcp [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path]+ solidcraft-cli mcp [--headless] [--in design.solidcraft|script.json] [--connect 127.0.0.1:PORT [--token T]] [--allow-path DIR]... [--allow-any-path][--param-check off|warn|strict]solidcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]solidcraft-cli licences@@ -600,17 +600,37 @@ fn cmd_mcp(args: &[String]) -> Result<(), String> {Box::new(remote)}(None, Some(path)) => Box::new(solidcraft_mcp::Headless::new(load_checked(path, param_check)?)),+ // No arguments: the running desktop app, found through the discovery file it wrote+ // (docs/control-protocol.md); none running (or `--headless`): a session of its own.(None, None) => {+ if !args.iter().any(|a| a == "--headless")+ && 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);+ }let mut headless = solidcraft_mcp::Headless::default();headless.session.param_check = param_check;Box::new(headless)}};+ serve_mcp(backend, scope)+}++fn serve_mcp(backend: Box<dyn solidcraft_mcp::Backend>, scope: Option<solidcraft_engine::io::vfs::PathScope>) -> Result<(), String> {let stdin = std::io::stdin();let stdout = std::io::stdout();solidcraft_mcp::Server::new(backend).with_path_scope(scope).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())}+/// The port of the running desktop app: the one its discovery file names, if something listens+/// there (a file left by an app that crashed names a closed port).+fn discover_app() -> Option<u16> {+ let port = solidcraft_engine::control_auth::read_current_port()?;+ let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));+ std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).ok().map(|_| port)+}+/// `save-stress <path> <rounds>`: save a design of a few hundred kilobytes `rounds` times, its/// parameter `save_round` set to the round number each time.fn cmd_save_stress(args: &[String]) -> Result<(), String> {diff --git a/apps/solidcraft-cli/tests/mcp_connect.rs b/apps/solidcraft-cli/tests/mcp_connect.rsindex e96ebd7d2b..1697152b8e 100644--- a/apps/solidcraft-cli/tests/mcp_connect.rs+++ b/apps/solidcraft-cli/tests/mcp_connect.rs@@ -89,3 +89,65 @@ fn mcp_connect_without_a_port_is_refused_at_start() {assert!(stderr.contains("HOST:PORT"), "{addr}: {stderr}");}}++/// `mcp` with no arguments finds the running app through the discovery file and uses that+/// launch's token; with no app behind the file it stays a headless session.+#[test]+fn mcp_without_arguments_finds_the_running_app() {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let control_dir = std::env::temp_dir().join(format!("solidcraft-mcp-discover-{}-{port}", std::process::id()));+ std::fs::create_dir_all(&control_dir).unwrap();+ let token = "fedcba9876543210".repeat(4);+ std::fs::write(control_dir.join(format!("{port}.token")), &token).unwrap();+ std::fs::write(control_dir.join("current.port"), format!("{port}\n")).unwrap();+ let app = std::thread::spawn(move || {+ // The discovery probe connects and leaves without a request; the tool call follows.+ let (stream, line) = loop {+ let (stream, _) = listener.accept().unwrap();+ let mut line = String::new();+ BufReader::new(stream.try_clone().unwrap()).read_line(&mut line).unwrap();+ if !line.is_empty() {+ break (stream, line);+ }+ };+ let req: Value = serde_json::from_str(&line).unwrap();+ let ok = req["token"] == json!(token);+ let reply = json!({"id": req["id"], "ok": ok, "result": {"bodies": [], "method": req["method"]}, "error": "unauthorized"});+ writeln!(&stream, "{reply}").unwrap();+ });+ let mut child = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))+ .args(["mcp", "--allow-any-path"])+ .env("SOLIDCRAFT_CONTROL_DIR", &control_dir)+ .env_remove("SOLIDCRAFT_CONTROL_TOKEN")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = BufReader::new(child.stdout.take().unwrap());+ writeln!(stdin, "{}", json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "measure", "arguments": {}}})).unwrap();+ let mut line = String::new();+ stdout.read_line(&mut line).unwrap();+ let r: Value = serde_json::from_str(&line).unwrap_or_else(|e| panic!("{e}: {line:?}"));+ assert_ne!(r["result"]["isError"], true, "{r}");+ assert!(r["result"]["content"][0]["text"].as_str().unwrap_or_default().contains("engine.execute"), "{r}");+ app.join().unwrap();+ drop(stdin);+ assert!(child.wait().unwrap().success());++ // The file names a port nothing listens on (the app crashed): a headless session instead.+ let closed = TcpListener::bind("127.0.0.1:0").unwrap();+ let dead = closed.local_addr().unwrap().port();+ drop(closed);+ std::fs::write(control_dir.join("current.port"), format!("{dead}\n")).unwrap();+ let out = Command::new(env!("CARGO_BIN_EXE_solidcraft-cli"))+ .args(["mcp", "--allow-any-path"])+ .env("SOLIDCRAFT_CONTROL_DIR", &control_dir)+ .stdin(Stdio::null())+ .output()+ .unwrap();+ 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();+}diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rsindex 5466f0b4e9..c64f210795 100644--- a/apps/solidcraft/src/control_server.rs+++ b/apps/solidcraft/src/control_server.rs@@ -19,7 +19,7 @@ const MAX_CONNECTIONS: usize = 16;const MAX_BAD_LINES: usize = 8;static OPEN: AtomicUsize = AtomicUsize::new(0);-/// The token files this launch wrote (its `--control` port, the agent chat's endpoint), removed+/// The token files this launch wrote (its control port, the agent chat's endpoint), removed/// when the app ends.static TOKEN_FILES: std::sync::Mutex<Vec<std::path::PathBuf>> = std::sync::Mutex::new(Vec::new());@@ -37,14 +37,42 @@ pub fn remove_token_file() {let _ = std::fs::remove_file(p);}}+ if let Some(port) = APP_PORT.lock().ok().and_then(|p| *p) {+ control_auth::remove_current_port(port);+ }}-pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {+/// The port the app's own channel listens on, for removing the discovery file at exit.+static APP_PORT: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);++pub fn start(listen_on: control_auth::Listen, ctx: egui::Context) -> Receiver<ControlRequest> {let (tx, rx) = channel::<ControlRequest>();// Every connection must show the token before anything runs (docs/control-protocol.md).match control_auth::env_token().or_else(new_token) {Some(token) => {- listen(port, token, tx, ctx, false);+ let listener = match listen_on {+ control_auth::Listen::Exact(port) => TcpListener::bind(("127.0.0.1", port)),+ control_auth::Listen::Default => control_auth::bind_with_fallback(control_auth::DEFAULT_PORT, control_auth::PORT_TRIES),+ };+ match listener {+ Ok(l) => {+ if let Some(port) = listen_on_listener(l, token, tx, ctx, false) {+ if matches!(listen_on, control_auth::Listen::Default) {+ eprintln!("solidcraft: control channel on the default port 127.0.0.1:{port} (Preferences > Assistant turns it off)");+ }+ // The discovery file: where `solidcraft-cli mcp` finds this app with no arguments.+ match control_auth::write_current_port(port) {+ Ok(_) => {+ if let Ok(mut p) = APP_PORT.lock() {+ *p = Some(port);+ }+ }+ Err(e) => eprintln!("solidcraft: could not write the control discovery file ({e})"),+ }+ }+ }+ Err(e) => eprintln!("solidcraft: control server failed to bind 127.0.0.1: {e}"),+ }}None => eprintln!("solidcraft: control server not started: no random token available"),}@@ -60,20 +88,20 @@ pub fn listen_agent(tx: Sender<ControlRequest>, ctx: egui::Context) -> Option<u1eprintln!("solidcraft: agent chat endpoint not started: no random token available");return None;};- listen(0, token, tx, ctx, true)-}--/// Listen on `port` (0: a free port the system picks) with `token`; the port it listens on.-/// `patient`: every request may wait as long as a batch (a person decides on it).-fn listen(port: u16, token: String, tx: Sender<ControlRequest>, ctx: egui::Context, patient: bool) -> Option<u16> {- let listener = match TcpListener::bind(("127.0.0.1", port)) {+ let listener = match TcpListener::bind(("127.0.0.1", 0)) {Ok(l) => l,Err(e) => {- eprintln!("solidcraft: control server failed to bind 127.0.0.1:{port}: {e}");+ eprintln!("solidcraft: control server failed to bind 127.0.0.1: {e}");return None;}};- let port = listener.local_addr().map(|a| a.port()).unwrap_or(port);+ listen_on_listener(listener, token, tx, ctx, true)+}++/// Serve `listener` (loopback) with `token`; the port it listens on.+/// `patient`: every request may wait as long as a batch (a person decides on it).+fn listen_on_listener(listener: TcpListener, token: String, tx: Sender<ControlRequest>, ctx: egui::Context, patient: bool) -> Option<u16> {+ let port = listener.local_addr().ok()?.port();match control_auth::token_path(port) {Some(path) => match control_auth::write_token_file(&path, &token) {Ok(()) => {diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rsindex f5eac643e5..3d587f7a94 100644--- a/apps/solidcraft/src/main.rs+++ b/apps/solidcraft/src/main.rs@@ -10,6 +10,7 @@//!//! `--control <port>` (or `SOLIDCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control//! server: `{"id":1,"method":"engine.execute","params":{"command":"solid.box","params":{…}}}`.+//! Without them the channel still opens, on the default port, unless Preferences turns it off.//! See `solidcraft_ui_egui::control` and docs/control-protocol.md.#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]@@ -741,8 +742,10 @@ fn main() -> eframe::Result {));}mark("viewport pipelines");- if let Some(port) = control_port {- let rx = control_server::start(port, cc.egui_ctx.clone());+ // `--control`/the environment name a port; otherwise the preference (on by default)+ // opens the default one (docs/control-protocol.md).+ if let Some(listen_on) = solidcraft_engine::control_auth::plan(control_port, app.preferences.agent_control) {+ let rx = control_server::start(listen_on, cc.egui_ctx.clone());app = app.with_control(rx);}// The agent chat's MCP bridge reaches the app through an endpoint of its own, starteddiff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 9145cbbb3a..795c41511c 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -568,6 +568,8 @@"Z angle": "Z angle","Z distance": "Z distance","Zebra": "Zebra",+ "ai.prefs.allow_control": "Let AI agents connect (control channel / MCP)",+ "ai.prefs.allow_control_note": "Opens a control channel on this computer only (127.0.0.1, port 27878 or the next free one). A program that connects must also show a secret token that only your user account can read, made fresh at every start. Takes effect the next time SolidCraft starts. Off: nothing listens unless you start SolidCraft with --control.","ai.prefs.availability": "Assistant controls","ai.prefs.background_commands": "Run agent commands in the background","ai.prefs.follow_camera": "Turn the camera to sketches",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 0105067e37..6fc0cba32f 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -568,6 +568,8 @@"Z angle": "Z角度","Z distance": "Z距離","Zebra": "ゼブラ",+ "ai.prefs.allow_control": "AI エージェントの接続を許可(コントロールチャンネル / MCP)",+ "ai.prefs.allow_control_note": "このコンピューター内だけのコントロールチャンネル(127.0.0.1、ポート 27878 または次に空いているポート)を開きます。接続するプログラムは、起動のたびに作られ、あなたのユーザーアカウントだけが読める秘密のトークンも提示する必要があります。次に SolidCraft を起動したときから有効です。オフ:--control を付けて起動しない限り、何も待ち受けません。","ai.prefs.availability": "アシスタントの操作","ai.prefs.background_commands": "エージェントのコマンドをバックグラウンドで実行","ai.prefs.follow_camera": "カメラをスケッチに向ける",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex b542c05e30..0c63042a18 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -568,6 +568,8 @@"Z angle": "Z 角度","Z distance": "Z 距离","Zebra": "斑马纹",+ "ai.prefs.allow_control": "允许 AI 代理连接(控制通道 / MCP)",+ "ai.prefs.allow_control_note": "仅在本机开放控制通道(127.0.0.1,端口 27878 或下一个空闲端口)。连接的程序还必须出示一个每次启动时新生成、只有你的用户账户能读取的秘密令牌。下次启动 SolidCraft 时生效。关闭:除非用 --control 启动,否则不监听任何端口。","ai.prefs.availability": "助手控制","ai.prefs.background_commands": "在后台执行代理命令","ai.prefs.follow_camera": "将相机转向草图",diff --git a/crates/engine/src/control_auth.rs b/crates/engine/src/control_auth.rsindex 0f0af31421..b6162e9059 100644--- a/crates/engine/src/control_auth.rs+++ b/crates/engine/src/control_auth.rs@@ -10,14 +10,92 @@ use std::path::{Path, PathBuf};/// Shortest token accepted from `SOLIDCRAFT_CONTROL_TOKEN` (hex characters).pub const MIN_TOKEN_LEN: usize = 32;+/// The port the control channel tries first when `--control` and `SOLIDCRAFT_CONTROL_PORT` give none.+/// Below the ephemeral ranges of Linux (32768+) and Windows/macOS (49152+), so the system never+/// hands it to an outgoing connection.+pub const DEFAULT_PORT: u16 = 27878;++/// Ports tried from [`DEFAULT_PORT`] upward when it is taken (a second window, another program).+pub const PORT_TRIES: u16 = 16;++/// Where the control channel listens, from the launch's `--control`/environment port and the+/// "Let AI agents connect" preference.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Listen {+ /// Exactly this port (`--control PORT`, `SOLIDCRAFT_CONTROL_PORT`); no fallback.+ Exact(u16),+ /// [`DEFAULT_PORT`], or the next free one of [`PORT_TRIES`].+ Default,+}++/// What a launch listens on. An explicit port wins over the preference, so a scripted launch+/// works with the setting off; with the setting off and no port, nothing listens.+pub fn plan(explicit: Option<u16>, enabled: bool) -> Option<Listen> {+ match explicit {+ Some(port) => Some(Listen::Exact(port)),+ None if enabled => Some(Listen::Default),+ None => None,+ }+}++/// Bind a loopback-only listener on `first`, or on the next free port when it is taken, up to+/// `tries` ports in all.+pub fn bind_with_fallback(first: u16, tries: u16) -> Result<std::net::TcpListener> {+ let mut last = Error::new(ErrorKind::AddrInUse, "no port to try");+ for port in (first..=u16::MAX).take(usize::from(tries.max(1))) {+ match std::net::TcpListener::bind(("127.0.0.1", port)) {+ Ok(l) => return Ok(l),+ // In use; Windows reports a port another program holds exclusively as denied.+ Err(e) if matches!(e.kind(), ErrorKind::AddrInUse | ErrorKind::PermissionDenied) => last = e,+ Err(e) => return Err(e),+ }+ }+ Err(last)+}++/// The folder of the token files: `<data folder>/control` (`SOLIDCRAFT_CONTROL_DIR` replaces it).+fn control_dir() -> Option<PathBuf> {+ match solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) {+ Some(d) => Some(PathBuf::from(d)),+ None => Some(crate::recovery::data_dir()?.join("control")),+ }+}+/// The token file of the app listening on `port`: `<data folder>/control/<port>.token`/// (`SOLIDCRAFT_CONTROL_DIR` replaces the folder).pub fn token_path(port: u16) -> Option<PathBuf> {- let dir = match solidcraft_geom::env::var_os("CONTROL_DIR").filter(|d| !d.is_empty()) {- Some(d) => PathBuf::from(d),- None => crate::recovery::data_dir()?.join("control"),- };- Some(dir.join(format!("{port}.token")))+ Some(control_dir()?.join(format!("{port}.token")))+}++/// The discovery file: the port of the most recently started app, so a client with no port+/// (`solidcraft-cli mcp`) finds it. It holds only the port; the token stays in its own file.+pub fn current_port_path() -> Option<PathBuf> {+ Some(control_dir()?.join("current.port"))+}++/// Record `port` as the running app's, readable only by the user like the token files.+pub fn write_current_port(port: u16) -> Result<PathBuf> {+ let path = current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;+ write_token_file(&path, &port.to_string())?;+ Ok(path)+}++/// The port the discovery file names, if there is one.+pub fn read_current_port() -> Option<u16> {+ parse_port(&std::fs::read_to_string(current_port_path()?).ok().filter(|t| t.len() <= 64)?)+}++fn parse_port(text: &str) -> Option<u16> {+ text.trim().parse::<u16>().ok().filter(|p| *p != 0)+}++/// Remove the discovery file at exit, unless a later app has taken it over (it names another port).+pub fn remove_current_port(port: u16) {+ if read_current_port() == Some(port)+ && let Some(path) = current_port_path()+ {+ let _ = std::fs::remove_file(path);+ }}/// A token set on purpose with `SOLIDCRAFT_CONTROL_TOKEN` (test harnesses, sandboxed packages@@ -108,6 +186,41 @@ mod tests {assert!(!tokens_match("", "a"));}+ /// The preference starts the listener by default, off it doesn't, and a port given on the+ /// command line or in the environment wins over it either way.+ #[test]+ fn the_preference_decides_unless_a_port_is_given() {+ assert_eq!(plan(None, true), Some(Listen::Default));+ assert_eq!(plan(None, false), None);+ assert_eq!(plan(Some(7878), false), Some(Listen::Exact(7878)));+ assert_eq!(plan(Some(7878), true), Some(Listen::Exact(7878)));+ }++ /// A taken port falls through to the next free one, on loopback only; a run of taken ports+ /// is an error, not a hang.+ #[test]+ fn a_taken_port_falls_back_to_the_next_free_one() {+ let first = bind_with_fallback(DEFAULT_PORT, PORT_TRIES).unwrap();+ let a = first.local_addr().unwrap();+ assert!(a.ip().is_loopback() && (DEFAULT_PORT..DEFAULT_PORT + PORT_TRIES).contains(&a.port()), "{a}");+ let second = bind_with_fallback(a.port(), PORT_TRIES).unwrap();+ assert!(second.local_addr().unwrap().port() > a.port());+ assert!(bind_with_fallback(a.port(), 1).is_err());+ }++ #[test]+ fn the_discovery_file_holds_a_port() {+ assert_eq!(parse_port("27879\n"), Some(27879));+ assert_eq!(parse_port("0"), None);+ assert_eq!(parse_port("70000"), None);+ assert_eq!(parse_port("nope"), None);+ let dir = std::env::temp_dir().join(format!("solidcraft-current-port-{}", std::process::id()));+ let path = dir.join("current.port");+ write_token_file(&path, "27881").unwrap();+ assert_eq!(parse_port(&std::fs::read_to_string(&path).unwrap()), Some(27881));+ let _ = std::fs::remove_dir_all(&dir);+ }+/// The token file is the user's alone, and a client reads it back.#[cfg(unix)]#[test]diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rsindex 27cafaa0b8..853228b540 100644--- a/crates/ui-egui/src/agent_chat/settings.rs+++ b/crates/ui-egui/src/agent_chat/settings.rs@@ -140,6 +140,9 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {let response = ui_kit::checkbox(ui, tr("ai.prefs.background_commands"), &mut app.preferences.agent_off_thread).on_hover_text(tr("ui.agent_off_thread_note"));crate::scenario::publish_handle("prefs:agent_off_thread", response.rect.center());+ let response = ui_kit::checkbox(ui, tr("ai.prefs.allow_control"), &mut app.preferences.agent_control)+ .on_hover_text(tr("ai.prefs.allow_control_note"));+ crate::scenario::publish_handle("prefs:agent_control", response.rect.center());}if cfg!(target_arch = "wasm32") {ui_kit::text(ui, tr("ui.agent_chat_desktop_only"), ui_kit::Text::Hint("desktop"));diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 822a0c4ad1..fe5e16c188 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -564,6 +564,9 @@ preference_settings! {/// so the window stays live while they run (#1989, [`crate::control_job`]). Off: they run on/// the window thread, and the window waits for each, as before (the default).agent_off_thread: bool = false, PAGE_AI;+ /// Let AI agents connect: the localhost control channel (MCP) opens on the default port at+ /// start-up, unless `--control`/`SOLIDCRAFT_CONTROL_PORT` name one. Read at start-up.+ agent_control: bool = true, PAGE_AI;/// Agents the user added (the installed ones are found by themselves). API keys are never/// here: they live in the system keychain.agents: Vec<crate::agent_chat::agents::AgentConfig> = Vec::new();@@ -1929,6 +1932,19 @@ mod tests {assert_eq!(app.preferences.msaa, Prefs::default().msaa);}+ /// "Let AI agents connect" is on for a new install and for preferences saved before it existed;+ /// an explicit off stays off.+ #[test]+ fn agent_control_is_on_unless_saved_off() {+ assert!(Prefs::default().agent_control);+ let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());+ app.preferences.agent_control = false;+ app.load_prefs(&serde_json::json!({ "preferences": { "msaa": 4 } }).to_string());+ assert!(app.preferences.agent_control);+ app.load_prefs(&serde_json::json!({ "preferences": { "agent_control": false } }).to_string());+ assert!(!app.preferences.agent_control);+ }+#[test]fn length_fields_read_bare_numbers_in_design_units_and_honour_explicit_units() {let inch = unit_scale("in").0;diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 272b60f981..22bbc08461 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -1,7 +1,31 @@# Control protocol-`solidcraft --control PORT` (or `SOLIDCRAFT_CONTROL_PORT=PORT`) listens on `127.0.0.1:PORT` for-JSON lines. Each request is one line `{"id": …, "method": "…", "params": {…}}`; each reply is one+The control channel is **on by default**. SolidCraft listens on `127.0.0.1` only, for JSON lines,+so agents can drive the app without a launch flag. Every connection still needs this launch's+token (below); nothing else on the machine, and nothing off it, can send a command.++| Launch | What listens |+|---|---|+| `solidcraft --control PORT`, or `SOLIDCRAFT_CONTROL_PORT=PORT` | exactly `127.0.0.1:PORT` (the flag wins over the variable), whatever the setting |+| neither, and Preferences > Assistant > "Let AI agents connect (control channel / MCP)" on (the default) | the default port **27878**, or the next free one up to 27893 when it is taken (a second window, another program) |+| neither, and the setting off | nothing |++The setting is read at start-up. Old preference files, which don't have it, load with it on. A+launch with `--control` or the variable behaves as it always did (the start page stays hidden,+the window doesn't ask for the foreground), because a scripted launch expects that; the default+channel changes neither for a normal launch.++### Finding the port++Each app that opens its channel writes the port to a discovery file beside the token files,+`control/current.port` (same folders and permissions as below), and removes it at exit if no later+app has replaced it. It holds only the port, never the token. `solidcraft-cli mcp` with no+arguments reads it, checks that something listens there and bridges to that app; with no app+running, or with `--headless`, it runs a session of its own. `--connect HOST:PORT` and the+other arguments still decide first. With several windows open, the most recently started one is+the one found; use `--connect` for another.++Requests are one line `{"id": …, "method": "…", "params": {…}}`; replies are described below. Each request is one line `{"id": …, "method": "…", "params": {…}}`; each reply is oneline `{"id": …, "ok": true, "result": …}` or `{"id": …, "ok": false, "error": "…"}`. Requests arehandled on the UI thread between frames; pointer and keyboard input is injected as real eguievents, one pointer event per frame.diff --git a/docs/mcp.md b/docs/mcp.mdindex c4790c03af..0a95dca623 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -24,11 +24,27 @@ solidcraft-cli mcp# Headless, starting from a design file or a command script.solidcraft-cli mcp --in part.solidcraft-# Bridged to the running app, so you can watch the agent model:+# Bridged to the running app, so you can watch the agent model. The app's control channel is+# on by default (see below), so no flag is needed on either side:+solidcraft &+solidcraft-cli mcp # finds the running app; headless when none runs (--headless forces that)++# A fixed port, or a second app: name it.solidcraft --control 7878 &solidcraft-cli mcp --connect 127.0.0.1:7878```+### The app listens by default++The desktop app opens its control channel at start-up on `127.0.0.1:27878` (or the next free port+when that one is taken), unless Preferences > Assistant > "Let AI agents connect (control+channel / MCP)" is off; the setting takes effect at the next start. It is reachable from this+computer only, and every connection must show the token made fresh for that launch, readable only+by your user account ([control-protocol.md](control-protocol.md#token)). The app writes the port to+`control/current.port` in the same folder as its token file; `solidcraft-cli mcp` with no+arguments reads it. `--control PORT` and `SOLIDCRAFT_CONTROL_PORT` still choose the port and apply+even when the setting is off. With the setting off and no flag, the app listens on nothing.+Bridged, the server finds the app's control token in the token file the app wrote for that port([control-protocol.md](control-protocol.md#token)); `--token T` or `SOLIDCRAFT_CONTROL_TOKEN` giveit explicitly when the app runs in a sandbox whose data folder the server can't see (prefer the