From d4f69b23e0454435c6295c569227c7074b937089 Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:00:49 -0800 Subject: [PATCH 01/27] feat(local-mcp): detect installed Craft Apps and manage LM Studio MCP entries Adds a native module that reuses the existing app detection to find every Craft App on this machine (reading each MSI InstallLocation, never a hardcoded folder), derives each app's stdio CLI path, and writes stdio server entries into LM Studio/Bionic's ng-mcp.json. Config path is derived from the user profile and overridable via ARTCRAFT_LAUNCHER_MCP_CONFIG for tests. Entries are added/disabled/removed atomically, preserving other top- level keys. Unit tests cover CLI derivation, round-trip, and toggle behavior; a gated Windows test verifies real detection on a machine with the suite installed. --- crates/native/src/lib.rs | 1 + crates/native/src/local_mcp.rs | 433 +++++++++++++++++++++++++++++++++ 2 files changed, 434 insertions(+) create mode 100644 crates/native/src/local_mcp.rs diff --git a/crates/native/src/lib.rs b/crates/native/src/lib.rs index 0bf0b570..24209104 100644 --- a/crates/native/src/lib.rs +++ b/crates/native/src/lib.rs @@ -13,6 +13,7 @@ pub mod detect; pub mod feed_throttle; pub mod http; pub mod install; +pub mod local_mcp; pub mod login; pub mod manifest; #[cfg(any(windows, test))] diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs new file mode 100644 index 00000000..2c8b52e9 --- /dev/null +++ b/crates/native/src/local_mcp.rs @@ -0,0 +1,433 @@ +//! Exposes installed Craft Apps as stdio MCP servers in LM Studio's Bionic config. +//! +//! The launcher already knows which Craft Apps are on this machine (see [`detect`](crate::detect)). +//! This module turns that into `ng-mcp.json` entries so LM Studio / Bionic can drive each app's +//! built-in tools over MCP stdio. Every path comes from detection, which reads the user's own +//! install location (`InstallLocation` on Windows, the App bundle or package dir elsewhere). Nothing +//! here hardcodes a folder; [`mcp_config_path`] derives LM Studio's config file from the user +//! profile and is overridable via `ARTCRAFT_LAUNCHER_MCP_CONFIG` for tests. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use artcraft_launcher_core::CraftApp; +use serde::{Deserialize, Serialize}; + +use crate::detect; +use crate::manifest::Manifest; + +/// A Craft App that has a usable CLI on this machine and can be exposed as an MCP server. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LocalService { + /// The app id (`wordcraft`), stable across versions. + pub id: String, + /// Display name (`WordCraft`). + pub name: String, + /// The detected main executable path; the CLI lives beside it. + pub location: String, + /// The `-cli` binary that speaks MCP stdio. `None` when detection found the app but no CLI + /// sits next to it. + #[serde(default)] + pub cli_path: Option, +} + +/// One entry in LM Studio's `ng-mcp.json` `servers` array, matching the file's shape exactly. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServerEntry { + /// Stable id for this server; reused across toggles so Bionic keeps its own state keyed to it. + pub id: String, + pub name: String, + pub description: String, + pub enabled: bool, + pub connection: Connection, +} + +/// The transport a host uses to reach the server. Mirrors `ng-mcp.json`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Connection { + /// A local process the host spawns. `command` is the CLI path; `args` are its arguments. + #[serde(rename = "stdio")] + Stdio { + command: String, + args: Vec, + env: HashMap, + }, + /// A network endpoint the host connects to (reserved for HTTP-based services like the bridge). + #[serde(rename = "streamableHttp")] + StreamableHttp { + url: String, + headers: HashMap, + auth: Option, + }, +} + +/// Credentials a streamable-HTTP host sends. `None` means no auth; Bionic writes this field only +/// when present. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Auth { + #[serde(rename = "none")] + None, + #[serde(rename = "bearerToken")] + BearerToken { token: String }, +} + +/// The path to LM Studio / Bionic's MCP server config on this machine. +/// +/// Derived from the user profile, never hardcoded. Overridable via `ARTCRAFT_LAUNCHER_MCP_CONFIG` +/// (tests point it at a temp file). Returns `None` when the home directory can't be resolved. +pub fn mcp_config_path() -> Option { + if let Ok(p) = std::env::var("ARTCRAFT_LAUNCHER_MCP_CONFIG") { + return Some(PathBuf::from(&p)); + } + Some( + dirs::home_dir()? + .join(".lmstudio") + .join("apps") + .join("bionic") + .join(".internal") + .join("ng-mcp.json"), + ) +} + +/// Load the `servers` array from a config file. A missing, unreadable, or malformed file yields an +/// empty list rather than an error, so a fresh install starts with no servers and never crashes. +pub fn load_servers(path: &Path) -> Vec { + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(_) => return vec![], + }; + let value = match serde_json::from_slice::(&bytes) { + Ok(v) => v, + Err(_) => return vec![], + }; + match value.get("servers").and_then(|s| s.as_array()) { + Some(arr) => arr + .iter() + .filter_map(|e| serde_json::from_value(e.clone()).ok()) + .collect(), + None => vec![], + } +} + +/// Save `servers` back to the config file, preserving any top-level keys other than `servers`. +/// Writes atomically (temp file + rename) so a crash never leaves a half-written config. +pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> { + let existing: Option = std::fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + let array = match servers.iter().map(serde_json::to_value).collect::, _>>() { + Ok(a) => a, + Err(e) => return Err(e.to_string()), + }; + // Preserve any top-level keys other than `servers`; replace the array. If the file was not + // a JSON object, it is not an `ng-mcp.json` shape and starts fresh. + let mut map = serde_json::Map::new(); + if let Some(existing_value) = existing { + if let Some(obj) = existing_value.as_object() { + for (k, v) in obj { + if k != "servers" { + map.insert(k.clone(), v.clone()); + } + } + } + } + map.insert("servers".to_string(), serde_json::json!(array)); + let out = serde_json::to_string_pretty(&serde_json::Value::Object(map)) + .map_err(|e| e.to_string())?; + crate::paths::write_atomic(path, out.as_bytes()) +} + +/// Every Craft App that has a usable CLI on this machine, in suite order. Detection is the single +/// source of truth for "installed"; this just adds the CLI path each app would expose to MCP. +pub fn installed_services(manifest: &Manifest, snapshot: &detect::Snapshot) -> Vec { + artcraft_launcher_core::SUITE + .iter() + .filter_map(|app| { + let installed = detect::detect(app, manifest, snapshot)?; + Some(LocalService { + id: app.id.to_string(), + name: app.name.to_string(), + location: installed.location.clone(), + cli_path: cli_path_for(&installed.location, app), + }) + }) + .collect() +} + +/// The `-cli` binary beside a detected main executable. Tries every stem the app has shipped as, +/// current first, and both the bare name (Unix) and `.exe` (Windows). `None` when no CLI exists +/// next to it. +fn cli_path_for(location: &str, app: &CraftApp) -> Option { + let dir = Path::new(location).parent()?; + for stem in app.stems() { + for ext in ["", ".exe"] { + let candidate = dir.join(format!("{stem}-cli{ext}")); + if candidate.is_file() { + return Some(candidate); + } + } + } + None +} + +/// The stable id this module uses for a given app, so enable/disable/remove agree. +pub fn entry_id(service_id: &str) -> String { + format!("craft-ai-mcp-{}", service_id) +} + +/// The stdio `ServerEntry` for a service, ready to drop into `ng-mcp.json`. Returns `None` when +/// the service has no usable CLI. +pub fn entry_for(service: &LocalService) -> Option { + let cli = service.cli_path.clone()?; + Some(ServerEntry { + id: entry_id(&service.id), + name: service.name.clone(), + description: format!("{} built-in tools over MCP.", service.name), + enabled: true, + connection: Connection::Stdio { + command: cli.display().to_string(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }) +} + +/// Add or update the entry for `service`, enabling it. Returns false when there was no usable CLI. +pub fn enable_service(servers: &mut Vec, service: &LocalService) -> bool { + let Some(entry) = entry_for(service) else { return false }; + match servers.iter_mut().find(|e| e.id == entry.id) { + Some(existing) => { + *existing = entry; + existing.enabled = true; + } + None => servers.push(entry), + } + true +} + +/// Disable the entry for `service_id`, leaving it in the list (Bionic keeps a disabled row). +/// Returns false when there was nothing to disable. +pub fn disable_service(servers: &mut Vec, service_id: &str) -> bool { + let id = entry_id(service_id); + match servers.iter_mut().find(|e| e.id == id) { + Some(e) => { + if e.enabled { + e.enabled = false; + true + } else { + false + } + } + None => false, + } +} + +/// Remove the entry for `service_id` entirely. Returns false when there was nothing to remove. +pub fn remove_service(servers: &mut Vec, service_id: &str) -> bool { + let id = entry_id(service_id); + let before = servers.len(); + servers.retain(|e| e.id != id); + servers.len() != before +} + +#[cfg(test)] +mod tests { + use super::*; + use artcraft_launcher_core::catalog::AppKind; + + /// A minimal Craft App for CLI-path tests. Only `id` and `former_ids` matter (they feed + /// [`CraftApp::stems`]); the rest are inert literals. String literals carry `'static`, which + /// every field here requires. + fn fake_app(id: &'static str, former_ids: &'static [&'static str]) -> CraftApp { + CraftApp { + id, + name: "TestCraft", + tagline: "A test app.", + color: [0; 3], + ink_light: [0; 3], + ink_dark: [0; 3], + repo: "storyteller/example", + former_ids, + former_names: &[], + kind: AppKind::Official, + publisher: "ArtCraft", + msi_publisher: None, + bundle: None, + former_bundles: &[], + site: None, + mac_team: None, + } + } + + #[test] + fn cli_path_prefers_the_current_stem_and_windows_extension() { + let dir = tempfile::tempdir().unwrap(); + // Main exe (what detection returns) plus a CLI under the current stem. + std::fs::write(dir.path().join("wordcraft.exe"), b"").unwrap(); + std::fs::write(dir.path().join("wordcraft-cli.exe"), b"cli").unwrap(); + let app = fake_app("wordcraft", &[]); + assert_eq!( + cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), + Some(dir.path().join("wordcraft-cli.exe")) + ); + } + + #[test] + fn cli_path_falls_back_to_a_former_stem() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("pdfcraft.exe"), b"").unwrap(); + // Only the former stem's CLI exists (e.g. an older install renamed to printcraft). + std::fs::write(dir.path().join("printcraft-cli.exe"), b"cli").unwrap(); + let app = fake_app("pdfcraft", &["printcraft"]); + assert_eq!( + cli_path_for(&dir.path().join("pdfcraft.exe").display().to_string(), &app), + Some(dir.path().join("printcraft-cli.exe")) + ); + } + + #[test] + fn cli_path_is_none_when_no_cli_sits_beside_the_exe() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("wordcraft.exe"), b"").unwrap(); + let app = fake_app("wordcraft", &[]); + assert_eq!(cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), None); + } + + #[test] + fn cli_path_is_none_when_the_location_has_no_parent() { + // A bare file name with no directory component has no parent to look in. + let app = fake_app("wordcraft", &[]); + assert_eq!(cli_path_for("wordcraft.exe", &app), None); + } + + #[test] + fn save_then_load_round_trips_and_preserves_other_top_level_keys() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ng-mcp.json"); + // Seed a top-level key that is not `servers` to prove it survives. + std::fs::write(&path, r#"{"meta":{"note":"keep me"},"servers":[]}"#).unwrap(); + + let servers = vec![ + ServerEntry { + id: entry_id("wordcraft"), + name: "WordCraft".into(), + description: "WordCraft built-in tools over MCP.".into(), + enabled: true, + connection: Connection::Stdio { + command: dir.path().join("wordcraft-cli.exe").display().to_string(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }, + ]; + assert!(save_servers(&path, &servers).is_ok()); + + let loaded = load_servers(&path); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].id, entry_id("wordcraft")); + assert!(loaded[0].enabled); + match &loaded[0].connection { + Connection::Stdio { args, .. } => { + assert_eq!(args.len(), 1); + assert_eq!(args[0], "mcp"); + } + _ => panic!("expected a stdio connection"), + }; + + // The non-`servers` top-level key must survive the round trip. + let raw: serde_json::Value = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(raw["meta"]["note"], serde_json::json!("keep me")); + } + + #[test] + fn load_returns_empty_for_missing_malformed_and_serverless_files() { + let dir = tempfile::tempdir().unwrap(); + + // Missing file. + assert_eq!(load_servers(&dir.path().join("nope.json")), vec![]); + + // Malformed JSON. + std::fs::write(dir.path().join("bad.json"), b"{ not json").unwrap(); + assert_eq!(load_servers(&dir.path().join("bad.json")), vec![]); + + // Valid JSON with no `servers` key. + std::fs::write(dir.path().join("plain.json"), r#"{"other": 1}"#).unwrap(); + assert_eq!(load_servers(&dir.path().join("plain.json")), vec![]); + } + + #[test] + fn save_creates_the_file_when_it_is_missing() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ng-mcp.json"); + assert!(save_servers(&path, &[]).is_ok()); + assert_eq!(load_servers(&path), vec![]); + } + + #[test] + fn enable_disable_remove_manage_the_server_list() { + let mut servers: Vec = Vec::new(); + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: Some("/x/wordcraft-cli.exe".into()), + }; + + // Enable adds it. + assert!(enable_service(&mut servers, &service)); + assert_eq!(servers.len(), 1); + assert!(servers[0].enabled); + assert_eq!(servers[0].id, entry_id("wordcraft")); + + // Enabling again is idempotent (no duplicate row). + assert!(enable_service(&mut servers, &service)); + assert_eq!(servers.len(), 1); + + // Disable keeps the row but turns it off. + assert!(disable_service(&mut servers, "wordcraft")); + assert!(!servers[0].enabled); + assert_eq!(servers.len(), 1); + + // Disabling again is a no-op that reports false. + assert!(!disable_service(&mut servers, "wordcraft")); + assert!(!servers[0].enabled); + + // Remove takes the row out. + assert!(remove_service(&mut servers, "wordcraft")); + assert_eq!(servers.len(), 0); + assert!(!remove_service(&mut servers, "wordcraft")); + } + + #[test] + fn entry_for_is_none_without_a_cli() { + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: None, + }; + assert!(entry_for(&service).is_none()); + } + + #[cfg(windows)] + #[test] + fn detects_the_apps_installed_on_this_machine_when_requested() { + // Gated on an env var so it only runs where the suite is actually installed (a dev box), + // never in CI. Set ARTCRAFT_LAUNCHER_VERIFY_INSTALLED=1 to run it. + if std::env::var("ARTCRAFT_LAUNCHER_VERIFY_INSTALLED").is_err() { + return; + } + let paths = crate::paths::Paths::new().unwrap(); + let manifest = Manifest::load(&paths.manifest()); + let services = installed_services(&manifest, &detect::Snapshot::take()); + for s in &services { + assert!(s.cli_path.is_some(), "service {} has no CLI path: {:?}", s.id, s.location); + } + // WordCraft and PdfCraft are installed on the machine this test runs against. + assert!(services.iter().any(|s| s.id == "wordcraft"), "expected wordcraft to be detected"); + assert!(services.iter().any(|s| s.id == "pdfcraft"), "expected pdfcraft to be detected"); + } +} From 0ff0063b5852d8faaeeb89772051a2ee699953b0 Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:17:06 -0800 Subject: [PATCH 02/27] feat(local-mcp): add unified-bridge mode that ties in craft-ai-mcp Locate the unified craft-ai-mcp bridge binary (via ARTCRAFT_LAUNCHER_BRIDGE_PATH override or derived install locations), version-check it, and register a single streamableHttp entry at http://127.0.0.1:12345/mcp in ng-mcp.json. This links the launcher (Branch B) to the unified HTTP bridge crate (Branch A / PR #154): one 'Enable Local Services' toggle can expose all Craft AI tools over a single endpoint instead of per-app stdio rows, with per-app stdio as fallback. - locate_bridge/first_existing/candidate_bridge_paths: pure, testable path lookup (no unsafe env mutation in tests) - bridge_version: delegates to the launcher's existing PE-version reader on Windows - bridge_entry/enable_bridge/disable_bridge/remove_bridge: manage the single entry - tests cover shape, port, enable/disable/remove lifecycle, and first_existing --- crates/native/src/local_mcp.rs | 180 +++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index 2c8b52e9..d8c5a98a 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -232,6 +232,110 @@ pub fn remove_service(servers: &mut Vec, service_id: &str) -> bool servers.len() != before } +/// Port the unified `craft-ai-mcp` bridge listens on by default. +pub const BRIDGE_PORT: u16 = 12345; + +/// Stable id for the single unified-bridge entry in `ng-mcp.json`. +const BRIDGE_ID: &str = "craft-ai-mcp"; + +/// Locate the unified `craft-ai-mcp` bridge binary, if present. +/// +/// Checks, in order: +/// - `ARTCRAFT_LAUNCHER_BRIDGE_PATH` (dev/test override); +/// - a small set of derived install locations. +/// Returns `None` when no bridge is found so callers can fall back to per-app stdio entries. +pub fn locate_bridge() -> Option { + let override_path = std::env::var("ARTCRAFT_LAUNCHER_BRIDGE_PATH").ok().map(PathBuf::from); + first_existing(override_path.as_deref(), &candidate_bridge_paths()) +} + +/// First existing path among `override` (checked first) then `candidates`. +fn first_existing(override_path: Option<&Path>, candidates: &[PathBuf]) -> Option { + if let Some(p) = override_path { + return p.is_file().then_some(PathBuf::from(p)); + } + candidates.iter().find(|p| p.is_file()).cloned() +} + +/// Candidate locations for the bridge binary. Derived from this launcher's own install, not +/// hardcoded to one machine's layout; extend as the ship story settles. +fn candidate_bridge_paths() -> Vec { + let mut out = Vec::new(); + if let Some(exe) = std::env::current_exe().ok() { + if let Some(dir) = exe.parent() { + for name in ["craft-ai-mcp.exe", "craft-ai-mcp"] { + out.push(dir.join(name)); + } + } + } + out +} + +/// The bridge binary's version, when readable. Reuses the launcher's existing PE-version reader so +/// the two branches agree on how a version is read; `None` off-Windows or without version info. +#[cfg(windows)] +pub fn bridge_version(path: &Path) -> Option { + crate::detect::windows::executable_version(path) +} + +#[cfg(not(windows))] +pub fn bridge_version(_path: &Path) -> Option { + None +} + +/// The single `streamableHttp` entry for the unified bridge at `port`. +pub fn bridge_entry(port: u16) -> ServerEntry { + ServerEntry { + id: BRIDGE_ID.to_string(), + name: "Craft AI (unified)".to_string(), + description: "All Craft AI tools over one MCP endpoint.".to_string(), + enabled: true, + connection: Connection::StreamableHttp { + url: format!("http://127.0.0.1:{port}/mcp"), + headers: HashMap::new(), + auth: Some(Auth::None), + }, + } +} + +/// Add or update the unified-bridge entry, enabling it. Returns false for a zero port. +pub fn enable_bridge(servers: &mut Vec, port: u16) -> bool { + if port == 0 { + return false; + } + let entry = bridge_entry(port); + match servers.iter_mut().find(|e| e.id == BRIDGE_ID) { + Some(existing) => { + *existing = entry; + existing.enabled = true; + } + None => servers.push(entry), + } + true +} + +/// Disable the unified-bridge entry (leaving it in the list). Returns false when absent or already off. +pub fn disable_bridge(servers: &mut Vec) -> bool { + match servers.iter_mut().find(|e| e.id == BRIDGE_ID) { + Some(e) => { + if e.enabled { + e.enabled = false; + true + } else { + false + } + } + None => false, + } +} + +/// Remove the unified-bridge entry entirely. Returns false when absent. +pub fn remove_bridge(servers: &mut Vec) -> bool { + let before = servers.len(); + servers.retain(|e| e.id != BRIDGE_ID); + servers.len() != before +} + #[cfg(test)] mod tests { use super::*; @@ -430,4 +534,80 @@ mod tests { assert!(services.iter().any(|s| s.id == "wordcraft"), "expected wordcraft to be detected"); assert!(services.iter().any(|s| s.id == "pdfcraft"), "expected pdfcraft to be detected"); } + + #[test] + fn bridge_entry_matches_the_streamable_http_shape() { + let entry = bridge_entry(BRIDGE_PORT); + assert_eq!(entry.id, BRIDGE_ID); + assert_eq!(entry.name, "Craft AI (unified)"); + assert!(entry.enabled); + match &entry.connection { + Connection::StreamableHttp { url, auth, .. } => { + assert_eq!(url, "http://127.0.0.1:12345/mcp"); + assert_eq!(*auth, Some(Auth::None)); + } + _ => panic!("expected a streamableHttp connection"), + }; + } + + #[test] + fn bridge_entry_uses_the_requested_port() { + let entry = bridge_entry(9000); + match &entry.connection { + Connection::StreamableHttp { url, .. } => assert_eq!(url, "http://127.0.0.1:9000/mcp"), + _ => panic!("expected a streamableHttp connection"), + }; + } + + #[test] + fn enable_disable_remove_bridge_manage_the_entry() { + let mut servers: Vec = Vec::new(); + assert!(!enable_bridge(&mut servers, 0)); // zero port is refused + assert_eq!(servers.len(), 0); + + assert!(enable_bridge(&mut servers, BRIDGE_PORT)); + assert_eq!(servers.len(), 1); + assert!(servers[0].enabled); + assert_eq!(servers[0].id, BRIDGE_ID); + + // Enabling again is idempotent (no duplicate row). + assert!(enable_bridge(&mut servers, BRIDGE_PORT)); + assert_eq!(servers.len(), 1); + + // Disabling turns it off. + assert!(disable_bridge(&mut servers)); + assert!(!servers[0].enabled); + // Disabling again is a no-op that reports false. + assert!(!disable_bridge(&mut servers)); + + // Remove takes the row out. + assert!(remove_bridge(&mut servers)); + assert_eq!(servers.len(), 0); + assert!(!remove_bridge(&mut servers)); + } + + #[test] + fn first_existing_prefers_the_override() { + let dir = tempfile::tempdir().unwrap(); + let present = dir.path().join("craft-ai-mcp.exe"); + std::fs::write(&present, b"").unwrap(); + let missing = dir.path().join("nope.exe"); + // Override wins even when a candidate also exists. + assert_eq!( + first_existing(Some(present.as_ref()), &[missing.clone(), present.clone()]), + Some(present), + ); + } + + #[test] + fn first_existing_falls_back_to_candidates_and_reports_none_when_missing() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("nope.exe"); + let present = dir.path().join("craft-ai-mcp.exe"); + std::fs::write(&present, b"").unwrap(); + // No override: the first existing candidate wins. + assert_eq!(first_existing(None, &[missing.clone(), present.clone()]), Some(present)); + // Nothing exists -> None. + assert_eq!(first_existing(None, &[missing]), None); + } } From 2b8204aad6bda59fbef6adfd04d468d635344188 Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:00:14 -0800 Subject: [PATCH 03/27] feat(local-mcp): Local Services panel in Settings (POC) Detect installed Craft apps and the unified craft-ai-mcp bridge, and let the user toggle each on/off as an MCP server in LM Studio / Bionic's ng-mcp.json. Plumbing: - core/protocol: Command::McpState | McpSetService { service_id, enabled } | McpSetBridge { port, enabled }; Event::Mcp { services, bridge } plus the McpService / McpBridge types (Default-derived). - native/backend: mcp_state(&Shared) reads the manifest + a fresh detection snapshot and ng-mcp.json to report which apps have usable CLIs (with their current on/off state) and whether the bridge binary is present (found? version?). Emits Event::Mcp after every detection pass and after each change. - native/local_mcp: BRIDGE_ID now public; candidate_bridge_paths collapsed to a let-chain (clippy). UI (egui): - app.rs: LauncherUi holds mcp_services / mcp_bridge / bridge_port (+ the once- synced flag) and handles Event::Mcp. - dialogs.rs: opening Settings requests Command::McpState once; the request is reset when no dialog is on screen so reopening re-fetches fresh state. - settings_dialog.rs: new "Local services" panel (only where manage_apps). A collapsible "Craft apps" section lists each installed app as a toggle with its CLI path shown in muted text; the unified bridge row has an editable, accessible-labelled port field and a toggle that applies the current port. i18n: translations for every new literal across all complete catalogs (ru, zh-CN, zh-TW, de, fr, pt-BR, es, cs, pl, hu, ja, ka). All tests pass; clippy clean of denied lints. --- crates/core/src/protocol.rs | 40 ++++++++++++++ crates/native/src/backend.rs | 73 ++++++++++++++++++++++++- crates/native/src/local_mcp.rs | 11 ++-- crates/ui-egui/src/app.rs | 27 +++++++++- crates/ui-egui/src/dialogs.rs | 7 +++ crates/ui-egui/src/i18n/cs.tsv | 16 ++++++ crates/ui-egui/src/i18n/de.tsv | 16 ++++++ crates/ui-egui/src/i18n/es.tsv | 16 ++++++ crates/ui-egui/src/i18n/fr.tsv | 16 ++++++ crates/ui-egui/src/i18n/hu.tsv | 16 ++++++ crates/ui-egui/src/i18n/ja.tsv | 16 ++++++ crates/ui-egui/src/i18n/ka.tsv | 16 ++++++ crates/ui-egui/src/i18n/pl.tsv | 16 ++++++ crates/ui-egui/src/i18n/pt-BR.tsv | 16 ++++++ crates/ui-egui/src/i18n/ru.tsv | 16 ++++++ crates/ui-egui/src/i18n/zh-CN.tsv | 16 ++++++ crates/ui-egui/src/i18n/zh-TW.tsv | 16 ++++++ crates/ui-egui/src/settings_dialog.rs | 77 +++++++++++++++++++++++++++ 18 files changed, 419 insertions(+), 8 deletions(-) diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index d699f24c..7614156b 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -72,6 +72,19 @@ pub enum Command { }, /// Change how the backend behaves. Configure(BackendOptions), + + /// Ask for the current state of the local MCP services (installed apps + unified bridge). + McpState, + /// Turn an installed app's stdio MCP entry on or off in LM Studio's config. + McpSetService { + service_id: String, + enabled: bool, + }, + /// Turn the unified-bridge HTTP MCP entry on or off at `port`. + McpSetBridge { + port: u16, + enabled: bool, + }, } /// Parent folders for new installs. Existing installations keep their recorded location. @@ -283,6 +296,33 @@ pub enum Event { /// GitHub refused more API calls until this time (Unix seconds). rate_limited_until: Option, }, + + /// The local MCP services: which installed apps can be exposed as stdio servers, their current + /// on/off state in LM Studio's config, plus the unified HTTP bridge (found? version? port? + /// enabled?). Sent after detection and after any change, so the settings panel is always in sync. + Mcp { + services: Vec, + bridge: McpBridge, + }, +} + +/// One installed app that can be exposed as a stdio MCP server. `command` is the CLI path the +/// host would spawn; `enabled` is its current state in LM Studio's config. +#[derive(Clone, Debug, PartialEq)] +pub struct McpService { + pub id: String, + pub name: String, + pub command: String, + pub enabled: bool, +} + +/// The unified HTTP bridge. `found` when its binary exists on this machine; `version` when readable. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct McpBridge { + pub found: bool, + pub version: Option, + pub port: u16, + pub enabled: bool, } /// What a backend can do on this platform. diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 5da76788..9dc4f362 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -9,7 +9,7 @@ use artcraft_launcher_core::catalog::{LAUNCHER, LAUNCHER_ID}; use artcraft_launcher_core::feed::{Feed, FeedAnswer}; use artcraft_launcher_core::platform::{Arch, Os, Platform, pick_asset}; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, Origin, PAUSED, PausedDownload, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, Origin, PAUSED, PausedDownload, Source, VersionTrack, }; use artcraft_launcher_core::release::{Asset, Release}; @@ -18,6 +18,7 @@ use artcraft_launcher_core::{CraftApp, Installed, PackageKind, SUITE, version}; use crate::feed_throttle::{self, FeedThrottle, Outcome}; use crate::http::{self, Http, Stop}; use crate::install::{self, Job}; +use crate::local_mcp; use crate::manifest::Manifest; use crate::paths::Paths; use crate::process; @@ -357,6 +358,8 @@ impl NativeBackend { for app in SUITE.iter().filter(|a| platform.is_none_or(|p| a.runs_on(p.os))) { report_partial(app, &shared, &paths, platform); } + // Local MCP state: which installed apps can be exposed + the unified bridge. + shared.emit(mcp_state(&shared)); drop(busy); }); } @@ -1591,6 +1594,39 @@ impl Backend for NativeBackend { self.check(true); } } + Command::McpState => { + self.shared.emit(mcp_state(&self.shared)); + } + Command::McpSetService { service_id, enabled } => { + let manifest = self.shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let snapshot = crate::detect::Snapshot::take(); + if let Some(p) = local_mcp::mcp_config_path() { + let mut servers = local_mcp::load_servers(&p); + // Rebuild from detection so the command path is current, then flip the flag. + let service = local_mcp::installed_services(&manifest, &snapshot).into_iter().find(|s| s.id == service_id); + if enabled { + if let Some(s) = service { + local_mcp::enable_service(&mut servers, &s); + } + } else { + local_mcp::disable_service(&mut servers, &service_id); + } + let _ = local_mcp::save_servers(&p, &servers); + } + self.shared.emit(mcp_state(&self.shared)); + } + Command::McpSetBridge { port, enabled } => { + if let Some(p) = local_mcp::mcp_config_path() { + let mut servers = local_mcp::load_servers(&p); + if enabled { + local_mcp::enable_bridge(&mut servers, port); + } else { + local_mcp::disable_bridge(&mut servers); + } + let _ = local_mcp::save_servers(&p, &servers); + } + self.shared.emit(mcp_state(&self.shared)); + } } } @@ -1625,6 +1661,41 @@ impl Backend for NativeBackend { } } +/// The current local MCP state: installed apps with usable CLIs (with their on/off state in +/// LM Studio's config) plus the unified HTTP bridge. Reads the manifest and ng-mcp.json, and takes +/// a fresh detection snapshot so it reflects what's on disk now. +fn mcp_state(shared: &Shared) -> Event { + let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let snapshot = crate::detect::Snapshot::take(); + let detected = local_mcp::installed_services(&manifest, &snapshot); + + let existing: Vec = match local_mcp::mcp_config_path() { + Some(p) => local_mcp::load_servers(&p), + None => vec![], + }; + + let services = detected.into_iter().map(|s| { + let id = local_mcp::entry_id(&s.id); + McpService { + id: s.id, + name: s.name, + command: s.cli_path.map(|c| c.display().to_string()).unwrap_or_default(), + enabled: existing.iter().any(|e| e.id == id && e.enabled), + } + }).collect(); + + let bridge_path = local_mcp::locate_bridge(); + Event::Mcp { + services, + bridge: McpBridge { + found: bridge_path.is_some(), + version: bridge_path.as_deref().and_then(local_mcp::bridge_version).map(|v| v.to_string()), + port: local_mcp::BRIDGE_PORT, + enabled: existing.iter().any(|e| e.id == local_mcp::BRIDGE_ID && e.enabled), + }, + } +} + #[cfg(test)] mod tests { use std::sync::atomic::AtomicUsize; diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index d8c5a98a..d11d2211 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -236,7 +236,7 @@ pub fn remove_service(servers: &mut Vec, service_id: &str) -> bool pub const BRIDGE_PORT: u16 = 12345; /// Stable id for the single unified-bridge entry in `ng-mcp.json`. -const BRIDGE_ID: &str = "craft-ai-mcp"; +pub const BRIDGE_ID: &str = "craft-ai-mcp"; /// Locate the unified `craft-ai-mcp` bridge binary, if present. /// @@ -261,11 +261,10 @@ fn first_existing(override_path: Option<&Path>, candidates: &[PathBuf]) -> Optio /// hardcoded to one machine's layout; extend as the ship story settles. fn candidate_bridge_paths() -> Vec { let mut out = Vec::new(); - if let Some(exe) = std::env::current_exe().ok() { - if let Some(dir) = exe.parent() { - for name in ["craft-ai-mcp.exe", "craft-ai-mcp"] { - out.push(dir.join(name)); - } + if let Some(exe) = std::env::current_exe().ok() + && let Some(dir) = exe.parent() { + for name in ["craft-ai-mcp.exe", "craft-ai-mcp"] { + out.push(dir.join(name)); } } out diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5a99b68e..3679eab5 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,7 +3,7 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, PAUSED, Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, PAUSED, Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; @@ -140,6 +140,15 @@ pub struct LauncherUi { pub(crate) backend: Box, pub settings: Settings, pub(crate) entries: Vec, + /// Local MCP services from the backend: installed apps exposed as stdio servers, plus the + /// unified HTTP bridge. Empty until the first [`Event::Mcp`]. + pub(crate) mcp_services: Vec, + pub(crate) mcp_bridge: McpBridge, + /// Editable port text for the unified bridge; synced from events only once so user edits stick. + pub(crate) bridge_port: String, + pub(crate) bridge_port_initialized: bool, + /// Whether we've asked for MCP state since the settings dialog last opened (reset when it closes). + pub(crate) mcp_requested: bool, pub(crate) caps: Capabilities, pub(crate) platform: Option, pub(crate) checking: bool, @@ -261,6 +270,11 @@ impl LauncherUi { backend, settings, entries: SUITE.iter().filter(|a| platform.is_none_or(|p| a.runs_on(p.os))).map(AppEntry::new).collect(), + mcp_services: Vec::new(), + mcp_bridge: McpBridge::default(), + bridge_port: String::new(), + bridge_port_initialized: false, + mcp_requested: false, caps, platform, checking: false, @@ -626,6 +640,17 @@ impl LauncherUi { self.rate_limited_until = rate_limited_until; true } + Event::Mcp { services, bridge } => { + let port = bridge.port; + self.mcp_services = services; + self.mcp_bridge = bridge; + // Sync the editable port only once so a user's typed value isn't clobbered by later events. + if !self.bridge_port_initialized && port != 0 { + self.bridge_port = port.to_string(); + self.bridge_port_initialized = true; + } + false + } } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ba404275..dc0422de 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -16,9 +16,16 @@ impl LauncherUi { /// a click outside) discards the dialog. pub(crate) fn dialogs(&mut self, ctx: &egui::Context, host: &mut dyn Host) { let Some(mut dialog) = self.dialog.clone() else { + // No dialog on screen: next time settings opens we want fresh MCP state. + self.mcp_requested = false; self.alert_popup(ctx); return; }; + // Opening the settings dialog (fresh): ask for current local-service state. + if matches!(dialog, Dialog::Settings) && !self.mcp_requested { + self.act_command(Command::McpState); + self.mcp_requested = true; + } let t = Tokens::get(ctx); // An area is laid out in the size it had last frame, so dialogs can't share one id: the // uninstall prompt would open as tall as Settings and never shrink (#88). diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5f1b1b43..47f5bb49 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -412,3 +412,19 @@ anicraft Familiar by design Navrženo tak, jak jste zvyklí anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Scéna, nástroje, časová osa, vrstvy, klíčové snímky, Vlastnosti i Knihovna jsou tam, kde je animátoři čekají, včetně cibulového pauzáku. anicraft Tweens that ease Plynulé mezilehlé pohyby (tweens) anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Klasické mezilehlé pohyby s osmi předvolbami zpomalení a vlastními křivkami, plus tvarové mezilehlé pohyby pro morphing. + + Local services Lokální služby + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Zveřejněte aplikace Craft AI jako MCP servery, aby LM Studio / Bionic mohlo ovládat jejich nástroje. + + Craft apps Aplikace Craft + + No installed Craft app has a usable CLI yet. Žádná nainstalovaná aplikace Craft zatím nemá dostupné CLI. + + Unified bridge Jednotný most + + Not found on this machine Není nalezeno na tomto počítači + + Found Nalezeno + + Port Port diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 07d16406..336533fc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -444,3 +444,19 @@ anicraft Familiar by design Gewohnt aufgebaut anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Bühne, Werkzeuge, Zeitleiste, Ebenen, Keyframes, Eigenschaften und Bibliothek genau dort, wo Animatoren sie erwarten, inklusive Zwiebelhaut. anicraft Tweens that ease Fließende Tweens anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Klassische Tweens mit acht Easing-Voreinstellungen und Kurven sowie Form-Tweens für Vektor-Morphing. + + Local services Lokale Dienste + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft-AI-Apps als MCP-Server bereitstellen, damit LM Studio / Bionic ihre Tools steuern kann. + + Craft apps Craft-Apps + + No installed Craft app has a usable CLI yet. Ein installiertes Craft-App hat noch kein nutzbares CLI. + + Unified bridge Einheitliche Brücke + + Not found on this machine Auf diesem Rechner nicht gefunden + + Found Gefunden + + Port Port diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4d843290..c9d77558 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -425,3 +425,19 @@ anicraft Familiar by design Diseño familiar anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Escenario, herramientas, línea de tiempo, capas, fotogramas clave, Propiedades y Biblioteca donde los animadores esperan, con papel cebolla. anicraft Tweens that ease Interpolaciones suaves anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Interpolaciones clásicas con ocho preajustes de aceleración y curvas personalizadas, además de interpolación de forma. + + Local services Servicios locales + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exponga las aplicaciones de Craft AI como servidores MCP para que LM Studio / Bionic pueda controlar sus herramientas. + + Craft apps Aplicaciones Craft + + No installed Craft app has a usable CLI yet. Ninguna aplicación de Craft instalada tiene aún un CLI utilizável. + + Unified bridge Puente unificado + + Not found on this machine No encontrado en esta máquina + + Found Encontrado + + Port Puerto diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e1a0146f..4c4e5fe4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -442,3 +442,19 @@ anicraft Familiar by design Conception familière anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Scène, outils, chronologie, calques, images clés, Propriétés et Bibliothèque là où les animateurs les attendent, avec pelure d'oignon. anicraft Tweens that ease Interpolations fluides anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Interpolations classiques avec huit préréglages d'accélération et courbes personnalisées, plus interpolations de forme. + + Local services Services locaux + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exposer les applications Craft AI en tant que serveurs MCP afin que LM Studio / Bionic puisse piloter leurs outils. + + Craft apps Applications Craft + + No installed Craft app has a usable CLI yet. Aucune application Craft installée n'a encore de CLI utilisable. + + Unified bridge Pont unifié + + Not found on this machine Non trouvé sur cette machine + + Found Trouvé + + Port Port diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 178935f3..772d9611 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -445,3 +445,19 @@ anicraft Familiar by design Ismerős kialakítás anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Színpad, eszközök, idővonal, rétegek, kulcsképkockák, Tulajdonságok és Könyvtár a megszokott helyen, hagymabőr funkcióval. anicraft Tweens that ease Finom mozgásinterpolációk anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Klasszikus mozgásinterpolációk nyolc görbe-előbeállítással és egyéni görbékkel, valamint alakos interpolációk. + + Local services Helyi szolgáltatások + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Javítsd ki a Craft AI alkalmazásokat MCP szerverként, hogy az LM Studio / Bionic kezelje a eszközeiket. + + Craft apps Craft alkalmazások + + No installed Craft app has a usable CLI yet. Egy nincsen még használható CLI-vel rendelkező telepített Craft alkalmazás. + + Unified bridge Egységes híd + + Not found on this machine Nem található ezen a gépen + + Found Találva + + Port Port diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c661cb12..edf1d893 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -447,3 +447,19 @@ anicraft Familiar by design 直感的なデザイン anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. ステージ、ツール、タイムライン、レイヤー、キーフレーム、プロパティ、ライブラリが期待通りの場所に配置され、オニオンスキンも備えています。 anicraft Tweens that ease 滑らかなトゥイーン anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. 8つのイージングプリセットとカスタム曲線を持つクラシックトゥイーン、そしてシェイプトゥイーンに対応。 + + Local services ローカルサービス + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft AI アプリを MCP サーバーとして公開し、LM Studio / Bionic がそのツールを操作できるようにします。 + + Craft apps Craft アプリ + + No installed Craft app has a usable CLI yet. インストールされた Craft アプリにまだ利用可能な CLI がありません。 + + Unified bridge 統一ブリッジ + + Not found on this machine このマシンでは見つかりません + + Found 見つかりました + + Port ポート diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a66d0db8..f405e5a7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -443,3 +443,19 @@ anicraft Familiar by design ნაცნობი დიზაინი anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. სცენა, ხელსაწყოები, დროის ხაზი, ფენები, საკვანძო კადრები, თვისებები და ბიბლიოთეკა იქ, სადაც ანიმატორები ელიან. anicraft Tweens that ease გლუვი ანიმაცია anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. კლასიკური ანიმაციური გადასვლები რვა წინასწარ დაყენებული პარამეტრით და ფორმის გარდაქმნით. + + Local services ლოკალური სერვისები + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft AI აპლიკაციები MCP სერვერად გამოქეცეთ, რომ LM Studio / Bionic მათის ინსტРУმენტებს... + + Craft apps Craft აპლიკაციები + + No installed Craft app has a usable CLI yet. იnstallებული Craft აპლიკაცია ჯერ... CLI... + + Unified bridge ერთი ხიმის + + Not found on this machine ამ კომპიუტერში ვერა + + Found მოვიდა + + Port პორტი diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d0307707..47341bb5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -446,3 +446,19 @@ anicraft Familiar by design Znany i intuicyjny interfejs anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Scena, narzędzia, oś czasu, warstwy, klatki kluczowe, Właściwości i Biblioteka znajdują się tam, gdzie oczekują animatorzy, wraz z łuskami cebuli. anicraft Tweens that ease Płynne klatki pośrednie (tweens) anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Klasyczne animacje klatek pośrednich z ośmioma profilami dynamiki i własnymi krzywymi oraz przejścia kształtu. + + Local services Lokalne usługi + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Odsłaniaj aplikacje Craft AI jako serwery MCP, aby LM Studio / Bionic mogło sterować ich narzędziami. + + Craft apps Aplikacje Craft + + No installed Craft app has a usable CLI yet. Żadna zainstalowana aplikacja Craft nie ma jeszcze używalnego CLI. + + Unified bridge Zjednoczony most + + Not found on this machine Nie znaleziono na tym komputerze + + Found Znaleziono + + Port Port diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index d50365ba..f20718f4 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -432,3 +432,19 @@ anicraft Familiar by design Design familiar anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Palco, ferramentas, linha do tempo, camadas, quadros-chave, Propriedades e Biblioteca onde os animadores esperam, com papel vegetal. anicraft Tweens that ease Interpolações suaves anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Interpolações clássicas com oito predefinições de suavização e curvas personalizadas, além de interpolação de forma. + + Local services Serviços locais + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exponha os aplicativos do Craft AI como servidores MCP para que o LM Studio / Bionic possa controlar suas ferramentas. + + Craft apps Aplicativos Craft + + No installed Craft app has a usable CLI yet. Nenhum aplicativo Craft instalado ainda tem um CLI utilizável. + + Unified bridge Ponte unificada + + Not found on this machine Não encontrado neste computador + + Found Encontrado + + Port Porta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cb2c5c30..f55ff5d2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -440,3 +440,19 @@ anicraft Familiar by design Привычный интерфейс anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. Сцена, инструменты, шкала времени, слои, ключевые кадры, Свойства и Библиотека там, где их ждут аниматоры, со шлейфом калькирования. anicraft Tweens that ease Плавные твины anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. Классические твины с восемью пресетами замедления и кривыми, а также твины формы. + + Local services Локальные службы + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Предоставить приложения Craft AI в качестве MCP-серверов, чтобы LM Studio / Bionic могли управлять их инструментами. + + Craft apps Приложения Craft + + No installed Craft app has a usable CLI yet. Установленное приложение Craft пока не имеет доступного CLI. + + Unified bridge Единый мост + + Not found on this machine Не найдено на этом компьютере + + Found Найдено + + Port Порт diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 45587c51..f08e21c8 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -412,3 +412,19 @@ anicraft Familiar by design 布局熟悉自然 anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. 舞台、工具、时间线、图层、关键帧、“属性”和“库”均位于动画师熟悉的直观位置,并配有洋葱皮功能。 anicraft Tweens that ease 流畅补间缓动 anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. 经典补间具备八种缓动预设与自定义曲线,外加将一种矢量轮廓变换为另一种的形状补间。 + + Local services 本地服务 + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. 将 Craft AI 应用暴露为 MCP 服务器,以便 LM Studio / Bionic 可以驱动其工具。 + + Craft apps Craft 应用 + + No installed Craft app has a usable CLI yet. 已安装的 Craft 应用目前还没有可用的 CLI。 + + Unified bridge 统一桥接 + + Not found on this machine 本机未找到 + + Found 已找到 + + Port 端口 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index b62d689a..b037305a 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -403,3 +403,19 @@ anicraft Familiar by design 設計直觀熟悉 anicraft Stage, tools, timeline, layers, keyframes, Properties and Library sit where animators expect them, with onion skinning for in-betweening. 舞台、工具、時間軸、圖層、關鍵影格、「屬性」與「元件庫」皆位於動畫師熟悉的位置,並具備洋蔥皮功能。 anicraft Tweens that ease 平滑補間緩動 anicraft Classic tweens with eight easing presets and custom ease curves, plus shape tweens that morph one vector contour into another. 傳統補間具備八種緩動預設與自訂曲線,並支援變換向量外框的形狀補間。 + + Local services 本地服務 + + Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. 將 Craft AI 應用公開為 MCP 伺服器,以便 LM Studio / Bionic 可以驅動其工具。 + + Craft apps Craft 應用 + + No installed Craft app has a usable CLI yet. 已安裝的 Craft 應用目前還沒有可用的 CLI。 + + Unified bridge 統一橋接 + + Not found on this machine 本機未找到 + + Found 已找到 + + Port 埠口 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index a50c33a8..6344f29f 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -2,6 +2,7 @@ //! groups of settings in boxes, two columns once the window is wide enough. use artcraft_launcher_core::{Os, PackageKind}; +use artcraft_launcher_core::protocol::{Command, McpService}; use egui::{RichText, Ui, vec2}; use crate::app::{Host, LauncherUi}; @@ -116,6 +117,7 @@ impl LauncherUi { this.settings_language(ui); this.settings_updates(ui); this.settings_appearance(ui); + this.settings_local_mcp(ui); }, |ui| { let Ok(mut state) = state.try_borrow_mut() else { return }; @@ -368,4 +370,79 @@ impl LauncherUi { }); self.settings.theme = theme_choice; } + + /// Local MCP services: turn Craft AI apps on or off as MCP servers for LM Studio / Bionic, and + /// manage the unified HTTP bridge. Only shown where the backend can manage installs (desktop). + fn settings_local_mcp(&mut self, ui: &mut Ui) { + if !self.caps.manage_apps { + return; + } + let t = Tokens::get(ui.ctx()); + sheet::panel(ui, tl!("Local services"), |ui| { + note(ui, tl!("Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools.")); + ui.add_space(8.0); + + // Unified bridge (HTTP): editable port + toggle; status shown below the row. + self.draw_bridge_row(ui, &t); + ui.add_space(12.0); + + // Per-app stdio services in a collapsible section. + egui::CollapsingHeader::new(tl!("Craft apps")).id_salt("mcp-apps").default_open(true).show(ui, |ui| { + // Clone out of self so the per-row toggle (which needs &mut self) doesn't fight the list borrow. + let services = self.mcp_services.clone(); + if services.is_empty() { + note(ui, tl!("No installed Craft app has a usable CLI yet.")); + } else { + for (i, s) in services.iter().enumerate() { + if i > 0 { + ui.add_space(6.0); + } + self.draw_service_row(ui, &t, s); + } + } + }); + }); + } + + /// One row for the unified HTTP bridge: a toggle plus an editable port field; its status (found? + /// version?) is drawn beneath in muted text. + fn draw_bridge_row(&mut self, ui: &mut Ui, t: &Tokens) { + let mut enabled = self.mcp_bridge.enabled; + if ui.checkbox(&mut enabled, tl!("Unified bridge")).changed() && enabled != self.mcp_bridge.enabled { + // The port is applied when the toggle flips; a bad value falls back to the default. + let port: u16 = self.bridge_port.parse().unwrap_or(12345); + self.act_command(Command::McpSetBridge { port, enabled }); + } + ui.add_space(8.0); + // The port field needs an accessible name for screen readers (kittest). + let port_label = ui.label(tl!("Port")); + ui.add(egui::TextEdit::singleline(&mut self.bridge_port) + .id_salt("mcp-bridge-port") + .desired_width(72.0)) + .labelled_by(port_label.id); + ui.label(RichText::new(self.bridge_status()).size(12.0).color(t.muted)); + } + + /// The bridge's one-line status: whether its binary is present and, when readable, its version. + fn bridge_status(&self) -> String { + if !self.mcp_bridge.found { + return tl!("Not found on this machine").to_string(); + } + match &self.mcp_bridge.version { + Some(v) => format!("{} · v{}", tl!("Found"), v), + None => tl!("Found").to_string(), + } + } + + /// One installed app exposed as a stdio MCP server: a toggle named after the app, with its CLI + /// path shown beneath in muted text. + fn draw_service_row(&mut self, ui: &mut Ui, t: &Tokens, s: &McpService) { + let mut enabled = s.enabled; + if ui.checkbox(&mut enabled, &s.name).changed() && enabled != s.enabled { + self.act_command(Command::McpSetService { service_id: s.id.clone(), enabled }); + } + if !s.command.is_empty() { + ui.label(RichText::new(s.command.as_str()).size(12.0).color(t.muted)); + } + } } From cf6dabd9b6e48a023be4daf9c7199e32b54c72db Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:20:27 -0800 Subject: [PATCH 04/27] feat(local-mcp): manage existing entries by display name, not just id The user's ng-mcp.json already contains Craft app + bridge entries created under UUID ids (by an earlier launcher version). Matching only on the deterministic craft-ai-mcp-* ids would create duplicates instead of managing those working entries in place. Now every managed entry is matched by display name first, with the deterministic id as a creation-only fallback: - local_mcp: new find_by_name() helper; enable_service/disable_service/remove_service now take &LocalService and match by display name (disable/remove fall back to the deterministic id). Bridge functions use find_bridge(), which matches the deterministic bridge id or a streamableHttp entry named "Craft AI". bridge_entry is renamed to "Craft AI" so it lines up with existing entries. New public helpers service_enabled / bridge_port_current / bridge_enabled (with parse_port) let the backend report current state; enable_bridge refreshes the URL in place. - backend: mcp_state reports each app's on/off state via service_enabled(name) and the bridge's port/enabled via bridge_port_current/bridge_enabled, so UUID entries show as already present. McpSetService now passes the detected LocalService to both enable and disable. - tests: cover name-based management for apps and the bridge (id preserved, command/ URL refreshed, no duplicate created), plus port parsing and enabled reporting. --- crates/native/src/backend.rs | 22 +-- crates/native/src/local_mcp.rs | 298 +++++++++++++++++++++++++++++---- 2 files changed, 274 insertions(+), 46 deletions(-) diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 9dc4f362..5d12f303 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -1603,13 +1603,12 @@ impl Backend for NativeBackend { if let Some(p) = local_mcp::mcp_config_path() { let mut servers = local_mcp::load_servers(&p); // Rebuild from detection so the command path is current, then flip the flag. - let service = local_mcp::installed_services(&manifest, &snapshot).into_iter().find(|s| s.id == service_id); - if enabled { - if let Some(s) = service { + if let Some(s) = local_mcp::installed_services(&manifest, &snapshot).into_iter().find(|s| s.id == service_id) { + if enabled { local_mcp::enable_service(&mut servers, &s); + } else { + local_mcp::disable_service(&mut servers, &s); } - } else { - local_mcp::disable_service(&mut servers, &service_id); } let _ = local_mcp::save_servers(&p, &servers); } @@ -1663,7 +1662,9 @@ impl Backend for NativeBackend { /// The current local MCP state: installed apps with usable CLIs (with their on/off state in /// LM Studio's config) plus the unified HTTP bridge. Reads the manifest and ng-mcp.json, and takes -/// a fresh detection snapshot so it reflects what's on disk now. +/// a fresh detection snapshot so it reflects what's on disk now. Entries are matched by display +/// name so those created under a different id (e.g. a UUID by an earlier launcher version) are +/// recognized and reported as already present. fn mcp_state(shared: &Shared) -> Event { let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); let snapshot = crate::detect::Snapshot::take(); @@ -1675,12 +1676,13 @@ fn mcp_state(shared: &Shared) -> Event { }; let services = detected.into_iter().map(|s| { - let id = local_mcp::entry_id(&s.id); + // Read the current on/off state before moving `name` into the struct. + let enabled = local_mcp::service_enabled(&existing, &s.name); McpService { id: s.id, name: s.name, command: s.cli_path.map(|c| c.display().to_string()).unwrap_or_default(), - enabled: existing.iter().any(|e| e.id == id && e.enabled), + enabled, } }).collect(); @@ -1690,8 +1692,8 @@ fn mcp_state(shared: &Shared) -> Event { bridge: McpBridge { found: bridge_path.is_some(), version: bridge_path.as_deref().and_then(local_mcp::bridge_version).map(|v| v.to_string()), - port: local_mcp::BRIDGE_PORT, - enabled: existing.iter().any(|e| e.id == local_mcp::BRIDGE_ID && e.enabled), + port: local_mcp::bridge_port_current(&existing).unwrap_or(local_mcp::BRIDGE_PORT), + enabled: local_mcp::bridge_enabled(&existing), }, } } diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index d11d2211..b1ed9222 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -194,23 +194,51 @@ pub fn entry_for(service: &LocalService) -> Option { }) } -/// Add or update the entry for `service`, enabling it. Returns false when there was no usable CLI. +/// Index of an entry whose display name matches `name`, or None. Matching by name (rather than +/// id) lets us recognize and manage entries created with a different id, e.g. UUIDs from an +/// earlier launcher version. +fn find_by_name(servers: &[ServerEntry], name: &str) -> Option { + servers.iter().position(|e| e.name == name) +} + +/// Add or update the entry for `service`, enabling it. Manages any existing entry with the same +/// display name in place (keeping its id, refreshing the command); otherwise creates one under +/// the deterministic id. Returns false when there was no usable CLI. pub fn enable_service(servers: &mut Vec, service: &LocalService) -> bool { - let Some(entry) = entry_for(service) else { return false }; - match servers.iter_mut().find(|e| e.id == entry.id) { - Some(existing) => { - *existing = entry; - existing.enabled = true; + let Some(cli) = service.cli_path.as_deref() else { return false }; + match find_by_name(servers, &service.name) { + Some(i) => { + servers[i].enabled = true; + if let Connection::Stdio { command: c, .. } = &mut servers[i].connection { + *c = cli.display().to_string(); + } } - None => servers.push(entry), + None => servers.push(ServerEntry { + id: entry_id(&service.id), + name: service.name.clone(), + description: format!("{} built-in tools over MCP.", service.name), + enabled: true, + connection: Connection::Stdio { + command: cli.display().to_string(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }), } true } -/// Disable the entry for `service_id`, leaving it in the list (Bionic keeps a disabled row). -/// Returns false when there was nothing to disable. -pub fn disable_service(servers: &mut Vec, service_id: &str) -> bool { - let id = entry_id(service_id); +/// Disable the entry for `service`, leaving it in the list (Bionic keeps a disabled row). Matches +/// by display name first, then the deterministic id. Returns false when there was nothing to disable. +pub fn disable_service(servers: &mut Vec, service: &LocalService) -> bool { + if let Some(i) = find_by_name(servers, &service.name) { + if servers[i].enabled { + servers[i].enabled = false; + return true; + } + return false; + } + let id = entry_id(&service.id); match servers.iter_mut().find(|e| e.id == id) { Some(e) => { if e.enabled { @@ -224,14 +252,24 @@ pub fn disable_service(servers: &mut Vec, service_id: &str) -> bool } } -/// Remove the entry for `service_id` entirely. Returns false when there was nothing to remove. -pub fn remove_service(servers: &mut Vec, service_id: &str) -> bool { - let id = entry_id(service_id); +/// Remove the entry for `service`. Matches by display name first, then the deterministic id. +/// Returns false when there was nothing to remove. +pub fn remove_service(servers: &mut Vec, service: &LocalService) -> bool { + if let Some(i) = find_by_name(servers, &service.name) { + servers.remove(i); + return true; + } + let id = entry_id(&service.id); let before = servers.len(); servers.retain(|e| e.id != id); servers.len() != before } +/// Whether an entry with display name `name` is currently enabled. +pub fn service_enabled(servers: &[ServerEntry], name: &str) -> bool { + find_by_name(servers, name).map_or(false, |i| servers[i].enabled) +} + /// Port the unified `craft-ai-mcp` bridge listens on by default. pub const BRIDGE_PORT: u16 = 12345; @@ -282,11 +320,12 @@ pub fn bridge_version(_path: &Path) -> Option ServerEntry { ServerEntry { id: BRIDGE_ID.to_string(), - name: "Craft AI (unified)".to_string(), + name: "Craft AI".to_string(), description: "All Craft AI tools over one MCP endpoint.".to_string(), enabled: true, connection: Connection::StreamableHttp { @@ -297,28 +336,68 @@ pub fn bridge_entry(port: u16) -> ServerEntry { } } -/// Add or update the unified-bridge entry, enabling it. Returns false for a zero port. +/// Index of the unified-bridge entry, or None: one whose id is the deterministic bridge id, or a +/// `streamableHttp` entry named "Craft AI" (created by an earlier launcher version under a UUID). +fn find_bridge(servers: &[ServerEntry]) -> Option { + servers.iter().position(|e| e.id == BRIDGE_ID) + .or_else(|| { + servers.iter().position(|e| { + matches!(&e.connection, Connection::StreamableHttp { .. }) && e.name == "Craft AI" + }) + }) +} + +/// The current port of the unified-bridge entry (parsed from its `streamableHttp` URL), or None +/// when there is no bridge entry. +pub fn bridge_port_current(servers: &[ServerEntry]) -> Option { + find_bridge(servers).and_then(|i| match &servers[i].connection { + Connection::StreamableHttp { url, .. } => parse_port(url), + _ => None, + }) +} + +/// Whether the unified-bridge entry is currently present and enabled. +pub fn bridge_enabled(servers: &[ServerEntry]) -> bool { + find_bridge(servers).map_or(false, |i| servers[i].enabled) +} + +/// Port from a `streamableHttp` URL like `http://127.0.0.1:12345/mcp`, or None when absent. +fn parse_port(url: &str) -> Option { + let parts: Vec<&str> = url.split('/').collect(); + if parts.len() < 3 { + return None; + } + // parts[0] is the scheme, parts[2] is `host[:port]`. + let host_port = parts[2]; + let port_str = host_port.rsplit_once(':').map(|(_, p)| p)?; + port_str.parse::().ok() +} + +/// Add or update the unified-bridge entry, enabling it. Manages any existing bridge entry in place +/// (keeping its id, refreshing the URL); otherwise creates one under the deterministic id. Returns +/// false for a zero port. pub fn enable_bridge(servers: &mut Vec, port: u16) -> bool { if port == 0 { return false; } - let entry = bridge_entry(port); - match servers.iter_mut().find(|e| e.id == BRIDGE_ID) { - Some(existing) => { - *existing = entry; - existing.enabled = true; + match find_bridge(servers) { + Some(i) => { + servers[i].enabled = true; + if let Connection::StreamableHttp { url, .. } = &mut servers[i].connection { + *url = format!("http://127.0.0.1:{port}/mcp"); + } } - None => servers.push(entry), + None => servers.push(bridge_entry(port)), } true } /// Disable the unified-bridge entry (leaving it in the list). Returns false when absent or already off. pub fn disable_bridge(servers: &mut Vec) -> bool { - match servers.iter_mut().find(|e| e.id == BRIDGE_ID) { - Some(e) => { - if e.enabled { - e.enabled = false; + match find_bridge(servers) { + Some(i) => { + if servers[i].enabled { + servers[i].enabled = false; true } else { false @@ -330,9 +409,13 @@ pub fn disable_bridge(servers: &mut Vec) -> bool { /// Remove the unified-bridge entry entirely. Returns false when absent. pub fn remove_bridge(servers: &mut Vec) -> bool { - let before = servers.len(); - servers.retain(|e| e.id != BRIDGE_ID); - servers.len() != before + match find_bridge(servers) { + Some(i) => { + servers.remove(i); + true + } + None => false, + } } #[cfg(test)] @@ -489,19 +572,19 @@ mod tests { assert!(enable_service(&mut servers, &service)); assert_eq!(servers.len(), 1); - // Disable keeps the row but turns it off. - assert!(disable_service(&mut servers, "wordcraft")); + // Disable keeps the row but turns it off (matched by display name). + assert!(disable_service(&mut servers, &service)); assert!(!servers[0].enabled); assert_eq!(servers.len(), 1); // Disabling again is a no-op that reports false. - assert!(!disable_service(&mut servers, "wordcraft")); + assert!(!disable_service(&mut servers, &service)); assert!(!servers[0].enabled); // Remove takes the row out. - assert!(remove_service(&mut servers, "wordcraft")); + assert!(remove_service(&mut servers, &service)); assert_eq!(servers.len(), 0); - assert!(!remove_service(&mut servers, "wordcraft")); + assert!(!remove_service(&mut servers, &service)); } #[test] @@ -538,7 +621,7 @@ mod tests { fn bridge_entry_matches_the_streamable_http_shape() { let entry = bridge_entry(BRIDGE_PORT); assert_eq!(entry.id, BRIDGE_ID); - assert_eq!(entry.name, "Craft AI (unified)"); + assert_eq!(entry.name, "Craft AI"); assert!(entry.enabled); match &entry.connection { Connection::StreamableHttp { url, auth, .. } => { @@ -609,4 +692,147 @@ mod tests { // Nothing exists -> None. assert_eq!(first_existing(None, &[missing]), None); } + + /// Enabling a service manages an existing entry by display name (keeping its id) rather than + /// creating a duplicate under the deterministic id. + #[test] + fn enable_service_manages_an_existing_entry_by_name() { + let mut servers = vec![ServerEntry { + id: "uuid-1".into(), + name: "WordCraft".into(), + description: "old".into(), + enabled: false, + connection: Connection::Stdio { + command: "/old/wordcraft-cli.exe".into(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }]; + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: Some("/x/wordcraft-cli.exe".into()), + }; + assert!(enable_service(&mut servers, &service)); + // Same single entry, original id preserved, command refreshed. + assert_eq!(servers.len(), 1); + assert_eq!(servers[0].id, "uuid-1"); + assert!(servers[0].enabled); + match &servers[0].connection { + Connection::Stdio { command, .. } => assert_eq!(command, "/x/wordcraft-cli.exe"), + _ => panic!("expected stdio"), + } + } + + /// Disabling matches by display name first (a UUID entry is found via its name). + #[test] + fn disable_service_matches_by_name_first() { + let mut servers = vec![ServerEntry { + id: "uuid-1".into(), + name: "WordCraft".into(), + description: String::new(), + enabled: true, + connection: Connection::Stdio { + command: "/x/wordcraft-cli.exe".into(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }]; + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: Some("/x/wordcraft-cli.exe".into()), + }; + assert!(disable_service(&mut servers, &service)); + assert!(!servers[0].enabled); + // The deterministic-id entry is not created. + assert_eq!(servers.len(), 1); + } + + /// Removing matches by display name first. + #[test] + fn remove_service_matches_by_name_first() { + let mut servers = vec![ServerEntry { + id: "uuid-1".into(), + name: "WordCraft".into(), + description: String::new(), + enabled: true, + connection: Connection::Stdio { + command: "/x/wordcraft-cli.exe".into(), + args: vec!["mcp".into()], + env: HashMap::new(), + }, + }]; + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: Some("/x/wordcraft-cli.exe".into()), + }; + assert!(remove_service(&mut servers, &service)); + assert_eq!(servers.len(), 0); + } + + /// Enabling the bridge manages an existing "Craft AI" entry by name (keeping its id, refreshing + /// the URL) rather than creating a duplicate. + #[test] + fn enable_bridge_manages_an_existing_entry_by_name() { + let mut servers = vec![ServerEntry { + id: "uuid-bridge".into(), + name: "Craft AI".into(), + description: String::new(), + enabled: false, + connection: Connection::StreamableHttp { + url: "http://127.0.0.1:9999/mcp".into(), + headers: HashMap::new(), + auth: Some(Auth::None), + }, + }]; + assert!(enable_bridge(&mut servers, BRIDGE_PORT)); + assert_eq!(servers.len(), 1); + assert_eq!(servers[0].id, "uuid-bridge"); + assert!(servers[0].enabled); + match &servers[0].connection { + Connection::StreamableHttp { url, .. } => assert_eq!(url, "http://127.0.0.1:12345/mcp"), + _ => panic!("expected streamableHttp"), + } + } + + /// bridge_port_current parses the port from an existing entry's URL. + #[test] + fn bridge_port_current_parses_the_url() { + let servers = vec![ServerEntry { + id: "uuid-bridge".into(), + name: "Craft AI".into(), + description: String::new(), + enabled: true, + connection: Connection::StreamableHttp { + url: "http://127.0.0.1:9876/mcp".into(), + headers: HashMap::new(), + auth: Some(Auth::None), + }, + }]; + assert_eq!(bridge_port_current(&servers), Some(9876)); + } + + /// bridge_enabled reports whether the existing entry is on. + #[test] + fn bridge_enabled_reports_the_existing_entry() { + let mut servers = vec![ServerEntry { + id: "uuid-bridge".into(), + name: "Craft AI".into(), + description: String::new(), + enabled: true, + connection: Connection::StreamableHttp { + url: "http://127.0.0.1:12345/mcp".into(), + headers: HashMap::new(), + auth: Some(Auth::None), + }, + }]; + assert!(bridge_enabled(&servers)); + servers[0].enabled = false; + assert!(!bridge_enabled(&servers)); + } } From d9c933f6ffe054070007dee9b72b949d0bf5e796 Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:23:59 -0800 Subject: [PATCH 05/27] test(local-mcp): verify existing entries are recognized against the real config Gated on ARTCRAFT_LAUNCHER_VERIFY_MCP (dev-box only, never CI), this loads the real ng-mcp.json and asserts that WordCraft/PdfCraft stdio entries and the Craft AI bridge are recognized by display name and reported as enabled at port 12345. Guards against regressions to the name-based matching so existing UUID-id entries keep being managed in place rather than duplicated. --- crates/native/src/local_mcp.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index b1ed9222..b66fdde0 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -835,4 +835,25 @@ mod tests { servers[0].enabled = false; assert!(!bridge_enabled(&servers)); } + + /// Against the real `ng-mcp.json` on this machine: existing Craft app + bridge entries (created + /// under UUID ids by an earlier launcher version) must be recognized by display name and reported + /// as present. Gated on an env var so it only runs where the real config exists (a dev box), + /// never in CI. Set ARTCRAFT_LAUNCHER_VERIFY_MCP=1 to run it. + #[test] + fn mcp_state_recognizes_existing_entries_on_this_machine_when_requested() { + if std::env::var("ARTCRAFT_LAUNCHER_VERIFY_MCP").is_err() { + return; + } + let Some(path) = mcp_config_path() else { return }; + let servers = load_servers(&path); + // WordCraft and PdfCraft are installed here and already present as enabled stdio entries. + assert!(service_enabled(&servers, "WordCraft"), + "WordCraft entry not recognized (by name) or disabled"); + assert!(service_enabled(&servers, "PdfCraft"), + "PdfCraft entry not recognized (by name) or disabled"); + // The unified bridge is present at the default port and enabled. + assert_eq!(bridge_port_current(&servers), Some(BRIDGE_PORT)); + assert!(bridge_enabled(&servers), "bridge entry not recognized (by name) or disabled"); + } } From 71685ab8ec8fdfc3c62c84decf621744f4d7afba Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:04:11 -0800 Subject: [PATCH 06/27] fix(local-mcp): adapt to upstream CraftApp changes; apply rustfmt Upstream main added the mac_bundle_name field to the CraftApp struct; add it to the local_mcp test fixture so the crate compiles. Also apply rustfmt to files whose formatting drifted after rebasing onto main (use-statement wrapping, method-chain reflow, struct-variant collapse). No logic changes. --- crates/native/src/backend.rs | 22 ++-- crates/native/src/local_mcp.rs | 154 +++++++------------------- crates/ui-egui/src/app.rs | 3 +- crates/ui-egui/src/settings_dialog.rs | 7 +- 4 files changed, 53 insertions(+), 133 deletions(-) diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 5d12f303..71baf382 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -9,8 +9,8 @@ use artcraft_launcher_core::catalog::{LAUNCHER, LAUNCHER_ID}; use artcraft_launcher_core::feed::{Feed, FeedAnswer}; use artcraft_launcher_core::platform::{Arch, Os, Platform, pick_asset}; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, Origin, PAUSED, PausedDownload, - Source, VersionTrack, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, Origin, + PAUSED, PausedDownload, Source, VersionTrack, }; use artcraft_launcher_core::release::{Asset, Release}; use artcraft_launcher_core::{CraftApp, Installed, PackageKind, SUITE, version}; @@ -1675,16 +1675,14 @@ fn mcp_state(shared: &Shared) -> Event { None => vec![], }; - let services = detected.into_iter().map(|s| { - // Read the current on/off state before moving `name` into the struct. - let enabled = local_mcp::service_enabled(&existing, &s.name); - McpService { - id: s.id, - name: s.name, - command: s.cli_path.map(|c| c.display().to_string()).unwrap_or_default(), - enabled, - } - }).collect(); + let services = detected + .into_iter() + .map(|s| { + // Read the current on/off state before moving `name` into the struct. + let enabled = local_mcp::service_enabled(&existing, &s.name); + McpService { id: s.id, name: s.name, command: s.cli_path.map(|c| c.display().to_string()).unwrap_or_default(), enabled } + }) + .collect(); let bridge_path = local_mcp::locate_bridge(); Event::Mcp { diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index b66fdde0..5119e459 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -48,18 +48,10 @@ pub struct ServerEntry { pub enum Connection { /// A local process the host spawns. `command` is the CLI path; `args` are its arguments. #[serde(rename = "stdio")] - Stdio { - command: String, - args: Vec, - env: HashMap, - }, + Stdio { command: String, args: Vec, env: HashMap }, /// A network endpoint the host connects to (reserved for HTTP-based services like the bridge). #[serde(rename = "streamableHttp")] - StreamableHttp { - url: String, - headers: HashMap, - auth: Option, - }, + StreamableHttp { url: String, headers: HashMap, auth: Option }, } /// Credentials a streamable-HTTP host sends. `None` means no auth; Bionic writes this field only @@ -81,14 +73,7 @@ pub fn mcp_config_path() -> Option { if let Ok(p) = std::env::var("ARTCRAFT_LAUNCHER_MCP_CONFIG") { return Some(PathBuf::from(&p)); } - Some( - dirs::home_dir()? - .join(".lmstudio") - .join("apps") - .join("bionic") - .join(".internal") - .join("ng-mcp.json"), - ) + Some(dirs::home_dir()?.join(".lmstudio").join("apps").join("bionic").join(".internal").join("ng-mcp.json")) } /// Load the `servers` array from a config file. A missing, unreadable, or malformed file yields an @@ -103,10 +88,7 @@ pub fn load_servers(path: &Path) -> Vec { Err(_) => return vec![], }; match value.get("servers").and_then(|s| s.as_array()) { - Some(arr) => arr - .iter() - .filter_map(|e| serde_json::from_value(e.clone()).ok()) - .collect(), + Some(arr) => arr.iter().filter_map(|e| serde_json::from_value(e.clone()).ok()).collect(), None => vec![], } } @@ -114,9 +96,7 @@ pub fn load_servers(path: &Path) -> Vec { /// Save `servers` back to the config file, preserving any top-level keys other than `servers`. /// Writes atomically (temp file + rename) so a crash never leaves a half-written config. pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> { - let existing: Option = std::fs::read(path) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()); + let existing: Option = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()); let array = match servers.iter().map(serde_json::to_value).collect::, _>>() { Ok(a) => a, Err(e) => return Err(e.to_string()), @@ -134,8 +114,7 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> } } map.insert("servers".to_string(), serde_json::json!(array)); - let out = serde_json::to_string_pretty(&serde_json::Value::Object(map)) - .map_err(|e| e.to_string())?; + let out = serde_json::to_string_pretty(&serde_json::Value::Object(map)).map_err(|e| e.to_string())?; crate::paths::write_atomic(path, out.as_bytes()) } @@ -186,11 +165,7 @@ pub fn entry_for(service: &LocalService) -> Option { name: service.name.clone(), description: format!("{} built-in tools over MCP.", service.name), enabled: true, - connection: Connection::Stdio { - command: cli.display().to_string(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + connection: Connection::Stdio { command: cli.display().to_string(), args: vec!["mcp".into()], env: HashMap::new() }, }) } @@ -218,11 +193,7 @@ pub fn enable_service(servers: &mut Vec, service: &LocalService) -> name: service.name.clone(), description: format!("{} built-in tools over MCP.", service.name), enabled: true, - connection: Connection::Stdio { - command: cli.display().to_string(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + connection: Connection::Stdio { command: cli.display().to_string(), args: vec!["mcp".into()], env: HashMap::new() }, }), } true @@ -300,7 +271,8 @@ fn first_existing(override_path: Option<&Path>, candidates: &[PathBuf]) -> Optio fn candidate_bridge_paths() -> Vec { let mut out = Vec::new(); if let Some(exe) = std::env::current_exe().ok() - && let Some(dir) = exe.parent() { + && let Some(dir) = exe.parent() + { for name in ["craft-ai-mcp.exe", "craft-ai-mcp"] { out.push(dir.join(name)); } @@ -328,23 +300,17 @@ pub fn bridge_entry(port: u16) -> ServerEntry { name: "Craft AI".to_string(), description: "All Craft AI tools over one MCP endpoint.".to_string(), enabled: true, - connection: Connection::StreamableHttp { - url: format!("http://127.0.0.1:{port}/mcp"), - headers: HashMap::new(), - auth: Some(Auth::None), - }, + connection: Connection::StreamableHttp { url: format!("http://127.0.0.1:{port}/mcp"), headers: HashMap::new(), auth: Some(Auth::None) }, } } /// Index of the unified-bridge entry, or None: one whose id is the deterministic bridge id, or a /// `streamableHttp` entry named "Craft AI" (created by an earlier launcher version under a UUID). fn find_bridge(servers: &[ServerEntry]) -> Option { - servers.iter().position(|e| e.id == BRIDGE_ID) - .or_else(|| { - servers.iter().position(|e| { - matches!(&e.connection, Connection::StreamableHttp { .. }) && e.name == "Craft AI" - }) - }) + servers + .iter() + .position(|e| e.id == BRIDGE_ID) + .or_else(|| servers.iter().position(|e| matches!(&e.connection, Connection::StreamableHttp { .. }) && e.name == "Craft AI")) } /// The current port of the unified-bridge entry (parsed from its `streamableHttp` URL), or None @@ -437,6 +403,7 @@ mod tests { repo: "storyteller/example", former_ids, former_names: &[], + mac_bundle_name: None, kind: AppKind::Official, publisher: "ArtCraft", msi_publisher: None, @@ -454,10 +421,7 @@ mod tests { std::fs::write(dir.path().join("wordcraft.exe"), b"").unwrap(); std::fs::write(dir.path().join("wordcraft-cli.exe"), b"cli").unwrap(); let app = fake_app("wordcraft", &[]); - assert_eq!( - cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), - Some(dir.path().join("wordcraft-cli.exe")) - ); + assert_eq!(cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), Some(dir.path().join("wordcraft-cli.exe"))); } #[test] @@ -467,10 +431,7 @@ mod tests { // Only the former stem's CLI exists (e.g. an older install renamed to printcraft). std::fs::write(dir.path().join("printcraft-cli.exe"), b"cli").unwrap(); let app = fake_app("pdfcraft", &["printcraft"]); - assert_eq!( - cli_path_for(&dir.path().join("pdfcraft.exe").display().to_string(), &app), - Some(dir.path().join("printcraft-cli.exe")) - ); + assert_eq!(cli_path_for(&dir.path().join("pdfcraft.exe").display().to_string(), &app), Some(dir.path().join("printcraft-cli.exe"))); } #[test] @@ -495,19 +456,17 @@ mod tests { // Seed a top-level key that is not `servers` to prove it survives. std::fs::write(&path, r#"{"meta":{"note":"keep me"},"servers":[]}"#).unwrap(); - let servers = vec![ - ServerEntry { - id: entry_id("wordcraft"), - name: "WordCraft".into(), - description: "WordCraft built-in tools over MCP.".into(), - enabled: true, - connection: Connection::Stdio { - command: dir.path().join("wordcraft-cli.exe").display().to_string(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + let servers = vec![ServerEntry { + id: entry_id("wordcraft"), + name: "WordCraft".into(), + description: "WordCraft built-in tools over MCP.".into(), + enabled: true, + connection: Connection::Stdio { + command: dir.path().join("wordcraft-cli.exe").display().to_string(), + args: vec!["mcp".into()], + env: HashMap::new(), }, - ]; + }]; assert!(save_servers(&path, &servers).is_ok()); let loaded = load_servers(&path); @@ -523,8 +482,7 @@ mod tests { }; // The non-`servers` top-level key must survive the round trip. - let raw: serde_json::Value = - serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let raw: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); assert_eq!(raw["meta"]["note"], serde_json::json!("keep me")); } @@ -589,12 +547,7 @@ mod tests { #[test] fn entry_for_is_none_without_a_cli() { - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: None, - }; + let service = LocalService { id: "wordcraft".into(), name: "WordCraft".into(), location: "/x/wordcraft.exe".into(), cli_path: None }; assert!(entry_for(&service).is_none()); } @@ -675,10 +628,7 @@ mod tests { std::fs::write(&present, b"").unwrap(); let missing = dir.path().join("nope.exe"); // Override wins even when a candidate also exists. - assert_eq!( - first_existing(Some(present.as_ref()), &[missing.clone(), present.clone()]), - Some(present), - ); + assert_eq!(first_existing(Some(present.as_ref()), &[missing.clone(), present.clone()]), Some(present),); } #[test] @@ -702,11 +652,7 @@ mod tests { name: "WordCraft".into(), description: "old".into(), enabled: false, - connection: Connection::Stdio { - command: "/old/wordcraft-cli.exe".into(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + connection: Connection::Stdio { command: "/old/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, }]; let service = LocalService { id: "wordcraft".into(), @@ -733,11 +679,7 @@ mod tests { name: "WordCraft".into(), description: String::new(), enabled: true, - connection: Connection::Stdio { - command: "/x/wordcraft-cli.exe".into(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, }]; let service = LocalService { id: "wordcraft".into(), @@ -759,11 +701,7 @@ mod tests { name: "WordCraft".into(), description: String::new(), enabled: true, - connection: Connection::Stdio { - command: "/x/wordcraft-cli.exe".into(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, + connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, }]; let service = LocalService { id: "wordcraft".into(), @@ -784,11 +722,7 @@ mod tests { name: "Craft AI".into(), description: String::new(), enabled: false, - connection: Connection::StreamableHttp { - url: "http://127.0.0.1:9999/mcp".into(), - headers: HashMap::new(), - auth: Some(Auth::None), - }, + connection: Connection::StreamableHttp { url: "http://127.0.0.1:9999/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, }]; assert!(enable_bridge(&mut servers, BRIDGE_PORT)); assert_eq!(servers.len(), 1); @@ -808,11 +742,7 @@ mod tests { name: "Craft AI".into(), description: String::new(), enabled: true, - connection: Connection::StreamableHttp { - url: "http://127.0.0.1:9876/mcp".into(), - headers: HashMap::new(), - auth: Some(Auth::None), - }, + connection: Connection::StreamableHttp { url: "http://127.0.0.1:9876/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, }]; assert_eq!(bridge_port_current(&servers), Some(9876)); } @@ -825,11 +755,7 @@ mod tests { name: "Craft AI".into(), description: String::new(), enabled: true, - connection: Connection::StreamableHttp { - url: "http://127.0.0.1:12345/mcp".into(), - headers: HashMap::new(), - auth: Some(Auth::None), - }, + connection: Connection::StreamableHttp { url: "http://127.0.0.1:12345/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, }]; assert!(bridge_enabled(&servers)); servers[0].enabled = false; @@ -848,10 +774,8 @@ mod tests { let Some(path) = mcp_config_path() else { return }; let servers = load_servers(&path); // WordCraft and PdfCraft are installed here and already present as enabled stdio entries. - assert!(service_enabled(&servers, "WordCraft"), - "WordCraft entry not recognized (by name) or disabled"); - assert!(service_enabled(&servers, "PdfCraft"), - "PdfCraft entry not recognized (by name) or disabled"); + assert!(service_enabled(&servers, "WordCraft"), "WordCraft entry not recognized (by name) or disabled"); + assert!(service_enabled(&servers, "PdfCraft"), "PdfCraft entry not recognized (by name) or disabled"); // The unified bridge is present at the default port and enabled. assert_eq!(bridge_port_current(&servers), Some(BRIDGE_PORT)); assert!(bridge_enabled(&servers), "bridge entry not recognized (by name) or disabled"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 3679eab5..cf1e429b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,7 +3,8 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, PAUSED, Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, PAUSED, + Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 6344f29f..f271aab0 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -1,8 +1,8 @@ //! The Settings dialog: a large card in the shape of the app page (see `sheet.rs`), with the //! groups of settings in boxes, two columns once the window is wide enough. -use artcraft_launcher_core::{Os, PackageKind}; use artcraft_launcher_core::protocol::{Command, McpService}; +use artcraft_launcher_core::{Os, PackageKind}; use egui::{RichText, Ui, vec2}; use crate::app::{Host, LauncherUi}; @@ -416,10 +416,7 @@ impl LauncherUi { ui.add_space(8.0); // The port field needs an accessible name for screen readers (kittest). let port_label = ui.label(tl!("Port")); - ui.add(egui::TextEdit::singleline(&mut self.bridge_port) - .id_salt("mcp-bridge-port") - .desired_width(72.0)) - .labelled_by(port_label.id); + ui.add(egui::TextEdit::singleline(&mut self.bridge_port).id_salt("mcp-bridge-port").desired_width(72.0)).labelled_by(port_label.id); ui.label(RichText::new(self.bridge_status()).size(12.0).color(t.muted)); } From e38b02c6af5e367173043f2c351c9f25706a1682 Mon Sep 17 00:00:00 2001 From: Timothy Austin <121047756+tacitup@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:29:33 -0800 Subject: [PATCH 07/27] fix(local-mcp): address CodeRabbit review comments - save_servers now refuses to overwrite a present-but-malformed ng-mcp.json instead of clobbering it (prevents lossy writes). - enable/disable/remove_service only manage stdio entries; a same-named entry of another connection type is left alone and we fall back to the deterministic id. - Save failures are surfaced via a new Event::McpError shown as an error toast, so a failed toggle is never silent. - Settings now explain that the bridge port applies when the toggle flips. Adds tests for the malformed-config refusal and the non-stdio name guard. --- crates/core/src/protocol.rs | 5 ++ crates/native/src/backend.rs | 8 ++- crates/native/src/local_mcp.rs | 85 +++++++++++++++++++++++++-- crates/ui-egui/src/app.rs | 6 ++ crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-BR.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/zh-CN.tsv | 1 + crates/ui-egui/src/i18n/zh-TW.tsv | 1 + crates/ui-egui/src/settings_dialog.rs | 3 + 17 files changed, 113 insertions(+), 6 deletions(-) diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 7614156b..50792249 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -304,6 +304,11 @@ pub enum Event { services: Vec, bridge: McpBridge, }, + /// A local MCP operation failed (e.g. writing `ng-mcp.json`). Carries a short, user-facing + /// message; the UI shows it as an error toast so a failed toggle is never silent. + McpError { + message: String, + }, } /// One installed app that can be exposed as a stdio MCP server. `command` is the CLI path the diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 71baf382..9fdab39c 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -1610,7 +1610,9 @@ impl Backend for NativeBackend { local_mcp::disable_service(&mut servers, &s); } } - let _ = local_mcp::save_servers(&p, &servers); + if let Err(e) = local_mcp::save_servers(&p, &servers) { + self.shared.emit(Event::McpError { message: e }); + } } self.shared.emit(mcp_state(&self.shared)); } @@ -1622,7 +1624,9 @@ impl Backend for NativeBackend { } else { local_mcp::disable_bridge(&mut servers); } - let _ = local_mcp::save_servers(&p, &servers); + if let Err(e) = local_mcp::save_servers(&p, &servers) { + self.shared.emit(Event::McpError { message: e }); + } } self.shared.emit(mcp_state(&self.shared)); } diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index 5119e459..00ec9f6a 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -96,7 +96,16 @@ pub fn load_servers(path: &Path) -> Vec { /// Save `servers` back to the config file, preserving any top-level keys other than `servers`. /// Writes atomically (temp file + rename) so a crash never leaves a half-written config. pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> { - let existing: Option = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()); + // Distinguish "no config yet" (safe to create) from "a config exists but is not valid JSON" + // (refuse rather than clobber it). A file we cannot read as JSON may hold content the user + // cares about; overwriting it would be a lossy write. + let existing: Option = match std::fs::read(path) { + Ok(b) => match serde_json::from_slice(&b) { + Ok(v) => Some(v), + Err(e) => return Err(format!("existing MCP config at {} is not valid JSON; refusing to overwrite it: {}", path.display(), e,)), + }, + Err(_) => None, // missing (or unreadable): start fresh + }; let array = match servers.iter().map(serde_json::to_value).collect::, _>>() { Ok(a) => a, Err(e) => return Err(e.to_string()), @@ -176,12 +185,21 @@ fn find_by_name(servers: &[ServerEntry], name: &str) -> Option { servers.iter().position(|e| e.name == name) } +/// Whether an entry is one of ours — a stdio CLI server — as opposed to the streamableHttp bridge +/// or some other tool's entry that happens to share a display name. We only manage entries we +/// created; matching by name must never flip, drop or rewrite an unrelated entry. +fn is_stdio(entry: &ServerEntry) -> bool { + matches!(&entry.connection, Connection::Stdio { .. }) +} + /// Add or update the entry for `service`, enabling it. Manages any existing entry with the same /// display name in place (keeping its id, refreshing the command); otherwise creates one under /// the deterministic id. Returns false when there was no usable CLI. pub fn enable_service(servers: &mut Vec, service: &LocalService) -> bool { let Some(cli) = service.cli_path.as_deref() else { return false }; - match find_by_name(servers, &service.name) { + // Manage an existing same-named entry only when it is one of ours (stdio); a same-named + // entry of another connection type is left alone and we create our own under the deterministic id. + match find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { Some(i) => { servers[i].enabled = true; if let Connection::Stdio { command: c, .. } = &mut servers[i].connection { @@ -202,7 +220,9 @@ pub fn enable_service(servers: &mut Vec, service: &LocalService) -> /// Disable the entry for `service`, leaving it in the list (Bionic keeps a disabled row). Matches /// by display name first, then the deterministic id. Returns false when there was nothing to disable. pub fn disable_service(servers: &mut Vec, service: &LocalService) -> bool { - if let Some(i) = find_by_name(servers, &service.name) { + // Only disable an entry that is one of ours (stdio); a same-named entry of another connection + // type is left alone and we fall back to the deterministic id. + if let Some(i) = find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { if servers[i].enabled { servers[i].enabled = false; return true; @@ -226,7 +246,9 @@ pub fn disable_service(servers: &mut Vec, service: &LocalService) - /// Remove the entry for `service`. Matches by display name first, then the deterministic id. /// Returns false when there was nothing to remove. pub fn remove_service(servers: &mut Vec, service: &LocalService) -> bool { - if let Some(i) = find_by_name(servers, &service.name) { + // Only remove an entry that is one of ours (stdio); a same-named entry of another connection + // type is left alone and we fall back to the deterministic id. + if let Some(i) = find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { servers.remove(i); return true; } @@ -510,6 +532,61 @@ mod tests { assert_eq!(load_servers(&path), vec![]); } + #[test] + fn save_refuses_to_overwrite_a_malformed_config() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ng-mcp.json"); + // A present but malformed file must not be clobbered. + std::fs::write(&path, b"{ this is not json").unwrap(); + + let servers = vec![ServerEntry { + id: entry_id("wordcraft"), + name: "WordCraft".into(), + description: "WordCraft built-in tools over MCP.".into(), + enabled: true, + connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, + }]; + let err = save_servers(&path, &servers).unwrap_err(); + assert!(err.contains("not valid JSON"), "{err}"); + + // The original bytes are still on disk. + assert_eq!(std::fs::read(&path).unwrap(), b"{ this is not json"); + } + + #[test] + fn enable_service_leaves_a_same_named_non_stdio_entry_alone() { + // A same-named streamableHttp entry (e.g. the bridge or another tool) must not be flipped + // or rewritten; we create our own stdio entry instead. + let mut servers = vec![ServerEntry { + id: "some-uuid".into(), + name: "WordCraft".into(), + description: "unrelated".into(), + enabled: false, + connection: Connection::StreamableHttp { url: "http://127.0.0.1:9999/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, + }]; + + let service = LocalService { + id: "wordcraft".into(), + name: "WordCraft".into(), + location: "/x/wordcraft.exe".into(), + cli_path: Some("/x/wordcraft-cli.exe".into()), + }; + assert!(enable_service(&mut servers, &service)); + + // The unrelated entry is untouched (still disabled, still streamableHttp). + let first = &servers[0]; + assert_eq!(first.id, "some-uuid"); + assert!(!first.enabled); + assert!(matches!(&first.connection, Connection::StreamableHttp { .. })); + + // Our stdio entry was added under the deterministic id. + assert_eq!(servers.len(), 2); + let ours = &servers[1]; + assert_eq!(ours.id, entry_id("wordcraft")); + assert!(ours.enabled); + assert!(matches!(&ours.connection, Connection::Stdio { .. })); + } + #[test] fn enable_disable_remove_manage_the_server_list() { let mut servers: Vec = Vec::new(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index cf1e429b..2a93def3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -652,6 +652,12 @@ impl LauncherUi { } false } + Event::McpError { message } => { + // A failed MCP write (e.g. a full disk or an unreadable config) is surfaced so the + // user knows their toggle did not take effect. + self.toast(message, true); + false + } } } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 47f5bb49..1eee9594 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -428,3 +428,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Nalezeno Port Port + Port applies when you toggle the bridge. Port se uplatní, když přepněte most. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 336533fc..7a8c7946 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -460,3 +460,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Gefunden Port Port + Port applies when you toggle the bridge. Der Port wird angewendet, wenn Sie die Brücke umschalten. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c9d77558..2a97faca 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -441,3 +441,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Encontrado Port Puerto + Port applies when you toggle the bridge. El puerto se aplica cuando cambias el puente. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4c4e5fe4..f748f2c5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -458,3 +458,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Trouvé Port Port + Port applies when you toggle the bridge. Le port est appliqué lorsque vous basculez le pont. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 772d9611..1d505058 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -461,3 +461,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Találva Port Port + Port applies when you toggle the bridge. A port akkor lép hatályba, ha kikapcsolod a hidrat. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index edf1d893..077974b7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -463,3 +463,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found 見つかりました Port ポート + Port applies when you toggle the bridge. ポートはブリッジを切り替えたときに適用されます。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f405e5a7..6df29444 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -459,3 +459,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found მოვიდა Port პორტი + Port applies when you toggle the bridge. პორტის ცვლილება მხოლოდ გათიშვისას მოქმედება. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 47341bb5..4a1f81c1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -462,3 +462,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Znaleziono Port Port + Port applies when you toggle the bridge. Port jest stosowany, gdy przełączysz most. diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index f20718f4..e13b4486 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -448,3 +448,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Encontrado Port Porta + Port applies when you toggle the bridge. A porta é aplicada quando você alterna a ponte. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f55ff5d2..8849c77c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -456,3 +456,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found Найдено Port Порт + Port applies when you toggle the bridge. Порт применяется при переключении моста. diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index f08e21c8..7a833ba0 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -428,3 +428,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found 已找到 Port 端口 + Port applies when you toggle the bridge. 端口在切换桥接时生效。 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index b037305a..e8155af7 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -419,3 +419,4 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Found 已找到 Port 埠口 + Port applies when you toggle the bridge. 埠口在切換橋接時生效。 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index f271aab0..007e5e06 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -417,6 +417,9 @@ impl LauncherUi { // The port field needs an accessible name for screen readers (kittest). let port_label = ui.label(tl!("Port")); ui.add(egui::TextEdit::singleline(&mut self.bridge_port).id_salt("mcp-bridge-port").desired_width(72.0)).labelled_by(port_label.id); + // The port is only written when the toggle flips, so say so plainly rather than + // implying a live edit. + ui.label(RichText::new(tl!("Port applies when you toggle the bridge.")).size(12.0).color(t.muted)); ui.label(RichText::new(self.bridge_status()).size(12.0).color(t.muted)); } From a5ce794a0a416efef6ab77ffe7fe9236c2618ff4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 13:48:45 +0100 Subject: [PATCH 08/27] fix(local-mcp): clear the clippy findings (collapsible ifs, slices, is_some_and, doc list) --- crates/native/src/local_mcp.rs | 43 ++++++++++++++-------------------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index 00ec9f6a..355f445b 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -113,12 +113,10 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> // Preserve any top-level keys other than `servers`; replace the array. If the file was not // a JSON object, it is not an `ng-mcp.json` shape and starts fresh. let mut map = serde_json::Map::new(); - if let Some(existing_value) = existing { - if let Some(obj) = existing_value.as_object() { - for (k, v) in obj { - if k != "servers" { - map.insert(k.clone(), v.clone()); - } + if let Some(obj) = existing.as_ref().and_then(serde_json::Value::as_object) { + for (k, v) in obj { + if k != "servers" { + map.insert(k.clone(), v.clone()); } } } @@ -219,7 +217,7 @@ pub fn enable_service(servers: &mut Vec, service: &LocalService) -> /// Disable the entry for `service`, leaving it in the list (Bionic keeps a disabled row). Matches /// by display name first, then the deterministic id. Returns false when there was nothing to disable. -pub fn disable_service(servers: &mut Vec, service: &LocalService) -> bool { +pub fn disable_service(servers: &mut [ServerEntry], service: &LocalService) -> bool { // Only disable an entry that is one of ours (stdio); a same-named entry of another connection // type is left alone and we fall back to the deterministic id. if let Some(i) = find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { @@ -231,15 +229,11 @@ pub fn disable_service(servers: &mut Vec, service: &LocalService) - } let id = entry_id(&service.id); match servers.iter_mut().find(|e| e.id == id) { - Some(e) => { - if e.enabled { - e.enabled = false; - true - } else { - false - } + Some(e) if e.enabled => { + e.enabled = false; + true } - None => false, + _ => false, } } @@ -260,7 +254,7 @@ pub fn remove_service(servers: &mut Vec, service: &LocalService) -> /// Whether an entry with display name `name` is currently enabled. pub fn service_enabled(servers: &[ServerEntry], name: &str) -> bool { - find_by_name(servers, name).map_or(false, |i| servers[i].enabled) + find_by_name(servers, name).is_some_and(|i| servers[i].enabled) } /// Port the unified `craft-ai-mcp` bridge listens on by default. @@ -274,6 +268,7 @@ pub const BRIDGE_ID: &str = "craft-ai-mcp"; /// Checks, in order: /// - `ARTCRAFT_LAUNCHER_BRIDGE_PATH` (dev/test override); /// - a small set of derived install locations. +/// /// Returns `None` when no bridge is found so callers can fall back to per-app stdio entries. pub fn locate_bridge() -> Option { let override_path = std::env::var("ARTCRAFT_LAUNCHER_BRIDGE_PATH").ok().map(PathBuf::from); @@ -346,7 +341,7 @@ pub fn bridge_port_current(servers: &[ServerEntry]) -> Option { /// Whether the unified-bridge entry is currently present and enabled. pub fn bridge_enabled(servers: &[ServerEntry]) -> bool { - find_bridge(servers).map_or(false, |i| servers[i].enabled) + find_bridge(servers).is_some_and(|i| servers[i].enabled) } /// Port from a `streamableHttp` URL like `http://127.0.0.1:12345/mcp`, or None when absent. @@ -381,17 +376,13 @@ pub fn enable_bridge(servers: &mut Vec, port: u16) -> bool { } /// Disable the unified-bridge entry (leaving it in the list). Returns false when absent or already off. -pub fn disable_bridge(servers: &mut Vec) -> bool { +pub fn disable_bridge(servers: &mut [ServerEntry]) -> bool { match find_bridge(servers) { - Some(i) => { - if servers[i].enabled { - servers[i].enabled = false; - true - } else { - false - } + Some(i) if servers[i].enabled => { + servers[i].enabled = false; + true } - None => false, + _ => false, } } From d8a424e30fd94e6d9be65b3f3b0d6995425ad2bf Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 13:48:45 +0100 Subject: [PATCH 09/27] feat(settings): AI agents reach every Craft app through one MCP entry Settings gets an "AI agents" box. "Let AI agents use Craft apps" writes the installed apps and their CLIs into ArtCraft/mcp/apps.json, the list the craft-ai-mcp gateway reads (storytold/craft-ai-integrations#197). Each MCP client found on this machine (Claude Desktop, Claude Code, Cursor, LM Studio) gets an Add / Remove button for one entry, `craft-apps` -> `craft-ai-mcp --stdio`, through which the agent reaches every app. Turning the switch off removes the list and every entry the launcher added. A client configuration that does not parse is never overwritten, and other servers and keys in it are kept. While agents are on, the app list is refreshed whenever Settings asks for the MCP state, so a newly installed app is reachable too. Without craft-ai-mcp beside the launcher, the box says so and offers no switch. Refs storytold/craft-ai-integrations#195 --- crates/core/src/protocol.rs | 40 +++++ crates/native/src/agents.rs | 224 ++++++++++++++++++++++++++ crates/native/src/agents_tests.rs | 120 ++++++++++++++ crates/native/src/backend.rs | 26 ++- crates/native/src/lib.rs | 1 + crates/ui-egui/src/app.rs | 10 +- crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-BR.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/zh-CN.tsv | 8 + crates/ui-egui/src/i18n/zh-TW.tsv | 8 + crates/ui-egui/src/settings_dialog.rs | 52 +++++- crates/ui-egui/tests/ui.rs | 60 +++++++ 20 files changed, 622 insertions(+), 7 deletions(-) create mode 100644 crates/native/src/agents.rs create mode 100644 crates/native/src/agents_tests.rs diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 6a6a12d1..14682ede 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -85,6 +85,16 @@ pub enum Command { port: u16, enabled: bool, }, + /// Let AI agents use the Craft apps (writes the gateway's app list), or stop them (removes the + /// list and the client entries the launcher added). + McpSetAgents { + enabled: bool, + }, + /// Add the one gateway entry to an MCP client's configuration, or remove it. + McpSetClient { + client: McpClient, + added: bool, + }, } /// Parent folders for new installs. Existing installations keep their recorded location. @@ -305,6 +315,7 @@ pub enum Event { Mcp { services: Vec, bridge: McpBridge, + agents: McpAgents, }, /// A local MCP operation failed (e.g. writing `ng-mcp.json`). Carries a short, user-facing /// message; the UI shows it as an error toast so a failed toggle is never silent. @@ -332,6 +343,35 @@ pub struct McpBridge { pub enabled: bool, } +/// An MCP client the launcher can add the gateway entry to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum McpClient { + ClaudeDesktop, + ClaudeCode, + Cursor, + LmStudio, +} + +/// One MCP client on this machine: whether it looks installed, and whether our entry is in it. +#[derive(Clone, Debug, PartialEq)] +pub struct McpClientState { + pub client: McpClient, + pub name: String, + pub installed: bool, + pub added: bool, +} + +/// AI agents and the Craft apps: the `craft-ai-mcp` gateway (found beside the launcher?), the +/// switch, and the MCP clients. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct McpAgents { + pub gateway_found: bool, + pub enabled: bool, + /// How many installed apps agents can reach (those with a CLI). + pub apps: usize, + pub clients: Vec, +} + /// What a backend can do on this platform. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Capabilities { diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs new file mode 100644 index 00000000..aa6c4513 --- /dev/null +++ b/crates/native/src/agents.rs @@ -0,0 +1,224 @@ +//! AI agents and the Craft apps: one switch in Settings, and one entry in each MCP client. +//! +//! With the switch on, the launcher writes the installed apps and their CLIs into +//! `ArtCraft/mcp/apps.json` (the list the `craft-ai-mcp` gateway reads, see +//! `docs/CRAFT-AI-MCP.md` in storytold/craft-ai-integrations), and can add one stdio entry, +//! `craft-apps` → `craft-ai-mcp --stdio`, to Claude Desktop, Claude Code, Cursor and LM Studio. +//! Through that one entry an agent reaches every installed app, without one entry per app. +//! +//! Turning the switch off removes the list and the entries this module added. A client +//! configuration that does not parse is never overwritten, and entries other than ours are kept. + +use std::path::{Path, PathBuf}; + +use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; +use serde_json::{Map, Value, json}; + +use crate::local_mcp::LocalService; + +/// The app list the gateway reads. +pub const APPS_FILE: &str = "apps.json"; +/// Same override the gateway honours (tests, portable installs). +pub const DIR_ENV: &str = "CRAFT_MCP_DIR"; +/// The key our entry has in a client's `mcpServers`. +pub const SERVER_KEY: &str = "craft-apps"; +/// Largest client configuration read; anything bigger is not a configuration file. +const MAX_CONFIG_BYTES: u64 = 64 << 20; + +/// The gateway's folder: [`DIR_ENV`], otherwise `ArtCraft/mcp` in the per-user local +/// configuration folder (beside the AI layer's `ArtCraft/ai`). +pub fn mcp_dir() -> Option { + match std::env::var_os(DIR_ENV) { + Some(d) if !d.is_empty() => Some(PathBuf::from(d)), + _ => dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), + } +} + +/// The app list for `services`: each app with a CLI, started as ` mcp`. Apps without a CLI +/// beside them are left out. +pub fn apps_json(services: &[LocalService]) -> Value { + let apps: Vec = services + .iter() + .filter_map(|s| { + let cli = s.cli_path.as_ref().filter(|p| p.is_absolute())?; + Some(json!({"id": s.id, "name": s.name, "command": cli, "args": ["mcp"]})) + }) + .collect(); + json!({"version": 1, "apps": apps}) +} + +/// Whether agents are on: the app list exists in `dir`. +pub fn enabled(dir: &Path) -> bool { + dir.join(APPS_FILE).is_file() +} + +/// Write (or refresh) the app list in `dir`. +pub fn write_apps(dir: &Path, services: &[LocalService]) -> Result<(), String> { + let text = serde_json::to_string_pretty(&apps_json(services)).map_err(|e| e.to_string())?; + crate::paths::write_atomic(&dir.join(APPS_FILE), text.as_bytes()) +} + +/// Remove the app list in `dir`. A missing list is fine. +pub fn remove_apps(dir: &Path) -> Result<(), String> { + match std::fs::remove_file(dir.join(APPS_FILE)) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(format!("couldn't remove {} ({e})", dir.join(APPS_FILE).display())), + } +} + +/// Every client the launcher can add the entry to. +pub const CLIENTS: [McpClient; 4] = [McpClient::ClaudeDesktop, McpClient::ClaudeCode, McpClient::Cursor, McpClient::LmStudio]; + +/// Where `client` keeps its MCP servers on this machine, and the folder whose presence shows the +/// client is installed. +pub fn client_paths(client: McpClient) -> Option<(PathBuf, PathBuf)> { + let home = dirs::home_dir()?; + Some(match client { + McpClient::ClaudeDesktop => { + let dir = dirs::config_dir()?.join("Claude"); + (dir.join("claude_desktop_config.json"), dir) + } + McpClient::ClaudeCode => (home.join(".claude.json"), home.join(".claude")), + McpClient::Cursor => (home.join(".cursor").join("mcp.json"), home.join(".cursor")), + McpClient::LmStudio => (home.join(".lmstudio").join("mcp.json"), home.join(".lmstudio")), + }) +} + +/// A client's display name. +pub fn client_name(client: McpClient) -> &'static str { + match client { + McpClient::ClaudeDesktop => "Claude Desktop", + McpClient::ClaudeCode => "Claude Code", + McpClient::Cursor => "Cursor", + McpClient::LmStudio => "LM Studio", + } +} + +/// Read a client configuration: `Ok(None)` when it does not exist yet. A file that is not a JSON +/// object is an error, so it is never replaced. +fn read_config(path: &Path) -> Result>, String> { + let meta = match std::fs::metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("couldn't read {} ({e})", path.display())), + }; + if !meta.is_file() || meta.len() > MAX_CONFIG_BYTES { + return Err(format!("{} is not a configuration file the launcher can change", path.display())); + } + let bytes = std::fs::read(path).map_err(|e| format!("couldn't read {} ({e})", path.display()))?; + // An empty file is a fresh configuration. + if bytes.iter().all(u8::is_ascii_whitespace) { + return Ok(Some(Map::new())); + } + match serde_json::from_slice::(&bytes) { + Ok(Value::Object(m)) => Ok(Some(m)), + Ok(_) | Err(_) => Err(format!("{} is not valid JSON; the launcher leaves it unchanged", path.display())), + } +} + +/// Whether `config` holds our entry. +pub fn registered(config: &Path) -> bool { + matches!(read_config(config), Ok(Some(m)) if m.get("mcpServers").and_then(|s| s.get(SERVER_KEY)).is_some()) +} + +/// Add (or update) our entry in the client configuration at `config`, starting `gateway`. +/// Everything else in the file is kept. +pub fn register(config: &Path, gateway: &Path) -> Result<(), String> { + let mut root = read_config(config)?.unwrap_or_default(); + let servers = root.entry("mcpServers").or_insert_with(|| Value::Object(Map::new())); + let Value::Object(servers) = servers else { + return Err(format!("`mcpServers` in {} is not an object; the launcher leaves it unchanged", config.display())); + }; + servers.insert(SERVER_KEY.to_string(), json!({"command": gateway.to_string_lossy(), "args": ["--stdio"]})); + let text = serde_json::to_string_pretty(&Value::Object(root)).map_err(|e| e.to_string())?; + crate::paths::write_atomic(config, text.as_bytes()) +} + +/// Remove our entry from the client configuration at `config`. Nothing to do when the file or +/// the entry is missing. +pub fn unregister(config: &Path) -> Result<(), String> { + let Some(mut root) = read_config(config)? else { + return Ok(()); + }; + let removed = match root.get_mut("mcpServers") { + Some(Value::Object(servers)) => servers.remove(SERVER_KEY).is_some(), + _ => false, + }; + if !removed { + return Ok(()); + } + let text = serde_json::to_string_pretty(&Value::Object(root)).map_err(|e| e.to_string())?; + crate::paths::write_atomic(config, text.as_bytes()) +} + +/// The `craft-ai-mcp` gateway binary: beside the launcher, or `ARTCRAFT_LAUNCHER_BRIDGE_PATH`. +pub fn locate_gateway() -> Option { + crate::local_mcp::locate_bridge() +} + +/// What Settings shows. While agents are on, the app list is refreshed first, so an app +/// installed since then is reachable too (a failed refresh keeps the previous list). +pub fn state(services: &[LocalService]) -> McpAgents { + let dir = mcp_dir(); + let on = dir.as_deref().is_some_and(enabled); + if on && let Some(d) = &dir { + let _ = write_apps(d, services); + } + let clients = CLIENTS + .iter() + .map(|c| { + let paths = client_paths(*c); + McpClientState { + client: *c, + name: client_name(*c).to_string(), + installed: paths.as_ref().is_some_and(|(config, folder)| folder.is_dir() || config.is_file()), + added: paths.as_ref().is_some_and(|(config, _)| registered(config)), + } + }) + .collect(); + McpAgents { + gateway_found: locate_gateway().is_some(), + enabled: on, + apps: services.iter().filter(|s| s.cli_path.as_ref().is_some_and(|p| p.is_absolute())).count(), + clients, + } +} + +/// Turn agents on (write the app list) or off (remove it and every client entry this module +/// added). All clients are tried; the first error is returned. +pub fn set_enabled(on: bool, services: &[LocalService]) -> Result<(), String> { + let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; + if on { + if locate_gateway().is_none() { + return Err("the Craft gateway (craft-ai-mcp) is not installed beside the launcher".into()); + } + return write_apps(&dir, services); + } + let mut first_error = remove_apps(&dir).err(); + for c in CLIENTS { + if let Some((config, _)) = client_paths(c) + && let Err(e) = unregister(&config) + { + first_error.get_or_insert(e); + } + } + first_error.map_or(Ok(()), Err) +} + +/// Add the gateway entry to `client`, or remove it. Adding needs agents on and the gateway found. +pub fn set_client(client: McpClient, added: bool) -> Result<(), String> { + let (config, _) = client_paths(client).ok_or("couldn't find the home folder")?; + if !added { + return unregister(&config); + } + if !mcp_dir().as_deref().is_some_and(enabled) { + return Err("turn on \"Let AI agents use Craft apps\" first".into()); + } + let gateway = locate_gateway().ok_or("the Craft gateway (craft-ai-mcp) is not installed beside the launcher")?; + register(&config, &gateway) +} + +#[cfg(test)] +#[path = "agents_tests.rs"] +mod tests; diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs new file mode 100644 index 00000000..d3926ef2 --- /dev/null +++ b/crates/native/src/agents_tests.rs @@ -0,0 +1,120 @@ +use std::path::PathBuf; + +use serde_json::{Value, json}; + +use super::*; + +fn service(id: &str, name: &str, cli: Option) -> LocalService { + LocalService { id: id.into(), name: name.into(), location: String::new(), cli_path: cli } +} + +fn read(p: &Path) -> Value { + serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap() +} + +#[test] +fn the_app_list_has_every_app_with_a_cli_in_the_gateways_format() { + let dir = tempfile::tempdir().unwrap(); + let cli = dir.path().join("photocraft-cli.exe"); + let list = apps_json(&[ + service("photocraft", "PhotoCraft", Some(cli.clone())), + service("wordcraft", "WordCraft", None), + service("relcraft", "RelCraft", Some(PathBuf::from("relative/cli"))), + ]); + assert_eq!(list["version"], 1); + let apps = list["apps"].as_array().unwrap(); + assert_eq!(apps.len(), 1, "apps without an absolute CLI are left out"); + assert_eq!(apps[0]["id"], "photocraft"); + assert_eq!(apps[0]["name"], "PhotoCraft"); + assert_eq!(apps[0]["command"], cli.to_string_lossy().as_ref()); + assert_eq!(apps[0]["args"], json!(["mcp"])); +} + +#[test] +fn switching_on_and_off() { + let dir = tempfile::tempdir().unwrap(); + assert!(!enabled(dir.path())); + write_apps(dir.path(), &[]).unwrap(); + assert!(enabled(dir.path())); + remove_apps(dir.path()).unwrap(); + assert!(!enabled(dir.path())); + remove_apps(dir.path()).unwrap(); +} + +#[test] +fn register_creates_a_config_and_keeps_other_servers_and_keys() { + let dir = tempfile::tempdir().unwrap(); + let fresh = dir.path().join("new").join("mcp.json"); + let gw = dir.path().join("craft-ai-mcp.exe"); + register(&fresh, &gw).unwrap(); + assert_eq!(read(&fresh)["mcpServers"][SERVER_KEY]["args"], json!(["--stdio"])); + assert!(registered(&fresh)); + + let existing = dir.path().join("claude.json"); + std::fs::write(&existing, r#"{"theme":"dark","mcpServers":{"other":{"command":"x"}}}"#).unwrap(); + register(&existing, &gw).unwrap(); + let v = read(&existing); + assert_eq!(v["theme"], "dark"); + assert_eq!(v["mcpServers"]["other"]["command"], "x"); + assert_eq!(v["mcpServers"][SERVER_KEY]["command"], gw.to_string_lossy().as_ref()); + + unregister(&existing).unwrap(); + let v = read(&existing); + assert!(v["mcpServers"].get(SERVER_KEY).is_none()); + assert_eq!(v["mcpServers"]["other"]["command"], "x"); + assert!(!registered(&existing)); +} + +#[test] +fn a_broken_config_is_never_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let gw = dir.path().join("craft-ai-mcp"); + for (name, text) in [("bad.json", "{ not json"), ("array.json", "[1,2]"), ("servers.json", r#"{"mcpServers":[1]}"#)] { + let p = dir.path().join(name); + std::fs::write(&p, text).unwrap(); + assert!(register(&p, &gw).is_err(), "{name}"); + assert_eq!(std::fs::read_to_string(&p).unwrap(), text, "{name} changed"); + } + let bad = dir.path().join("bad.json"); + assert!(unregister(&bad).is_err()); + assert!(!registered(&bad)); +} + +#[test] +fn an_empty_config_counts_as_fresh_and_a_missing_one_needs_no_unregister() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("empty.json"); + std::fs::write(&p, " \n").unwrap(); + register(&p, &dir.path().join("gw")).unwrap(); + assert!(registered(&p)); + unregister(&dir.path().join("missing.json")).unwrap(); + assert!(!dir.path().join("missing.json").exists()); +} + +#[test] +fn unregister_leaves_a_file_without_our_entry_untouched() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("c.json"); + let text = "{\"mcpServers\": {\"other\": {}}}"; + std::fs::write(&p, text).unwrap(); + unregister(&p).unwrap(); + assert_eq!(std::fs::read_to_string(&p).unwrap(), text); +} + +#[test] +fn a_folder_in_place_of_the_config_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("mcp.json"); + std::fs::create_dir(&p).unwrap(); + assert!(register(&p, &dir.path().join("gw")).is_err()); +} + +#[test] +fn every_client_has_a_name_and_paths() { + for c in CLIENTS { + assert!(!client_name(c).is_empty()); + if let Some((config, folder)) = client_paths(c) { + assert!(config.is_absolute() && folder.is_absolute()); + } + } +} diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index bd6edac7..6ae3cc67 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -1642,6 +1642,19 @@ impl Backend for NativeBackend { } self.shared.emit(mcp_state(&self.shared)); } + Command::McpSetAgents { enabled } => { + let services = detected_services(&self.shared); + if let Err(e) = crate::agents::set_enabled(enabled, &services) { + self.shared.emit(Event::McpError { message: e }); + } + self.shared.emit(mcp_state(&self.shared)); + } + Command::McpSetClient { client, added } => { + if let Err(e) = crate::agents::set_client(client, added) { + self.shared.emit(Event::McpError { message: e }); + } + self.shared.emit(mcp_state(&self.shared)); + } } } @@ -1682,9 +1695,8 @@ impl Backend for NativeBackend { /// name so those created under a different id (e.g. a UUID by an earlier launcher version) are /// recognized and reported as already present. fn mcp_state(shared: &Shared) -> Event { - let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); - let snapshot = crate::detect::Snapshot::take(); - let detected = local_mcp::installed_services(&manifest, &snapshot); + let detected = detected_services(shared); + let agents = crate::agents::state(&detected); let existing: Vec = match local_mcp::mcp_config_path() { Some(p) => local_mcp::load_servers(&p), @@ -1709,9 +1721,17 @@ fn mcp_state(shared: &Shared) -> Event { port: local_mcp::bridge_port_current(&existing).unwrap_or(local_mcp::BRIDGE_PORT), enabled: local_mcp::bridge_enabled(&existing), }, + agents, } } +/// The installed apps with their CLIs, from a fresh detection snapshot. +fn detected_services(shared: &Shared) -> Vec { + let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let snapshot = crate::detect::Snapshot::take(); + local_mcp::installed_services(&manifest, &snapshot) +} + #[cfg(test)] mod tests { use std::sync::atomic::AtomicUsize; diff --git a/crates/native/src/lib.rs b/crates/native/src/lib.rs index 8f123a1e..56929801 100644 --- a/crates/native/src/lib.rs +++ b/crates/native/src/lib.rs @@ -7,6 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod agents; pub mod backend; pub mod desktop_entry; pub mod detect; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a175f688..4474d72c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,8 +3,8 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, PAUSED, - Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, McpBridge, McpService, + PAUSED, Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; @@ -147,6 +147,8 @@ pub struct LauncherUi { /// unified HTTP bridge. Empty until the first [`Event::Mcp`]. pub(crate) mcp_services: Vec, pub(crate) mcp_bridge: McpBridge, + /// AI agents: the gateway switch and the MCP clients. + pub(crate) mcp_agents: McpAgents, /// Editable port text for the unified bridge; synced from events only once so user edits stick. pub(crate) bridge_port: String, pub(crate) bridge_port_initialized: bool, @@ -279,6 +281,7 @@ impl LauncherUi { .collect(), mcp_services: Vec::new(), mcp_bridge: McpBridge::default(), + mcp_agents: McpAgents::default(), bridge_port: String::new(), bridge_port_initialized: false, mcp_requested: false, @@ -659,7 +662,8 @@ impl LauncherUi { self.rate_limited_until = rate_limited_until; true } - Event::Mcp { services, bridge } => { + Event::Mcp { services, bridge, agents } => { + self.mcp_agents = agents; let port = bridge.port; self.mcp_services = services; self.mcp_bridge = bridge; diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0f0d355e..6e616066 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -434,3 +434,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Port Port applies when you toggle the bridge. Port se uplatní, když přepněte most. + AI agents AI agenti + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jedna položka v Claude, Cursoru nebo LM Studiu dosáhne na každou nainstalovanou aplikaci Craft. Po přidání klienta restartujte. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brána Craft (craft-ai-mcp) není nainstalována vedle spouštěče. + Let AI agents use Craft apps Povolit AI agentům používat aplikace Craft + Apps agents can reach: {count} Aplikace dostupné agentům: {count} + Added Přidáno + Remove Odebrat + Add Přidat diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 357d66ec..854adad8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -466,3 +466,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Port Port applies when you toggle the bridge. Der Port wird angewendet, wenn Sie die Brücke umschalten. + AI agents KI-Agenten + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Ein Eintrag in Claude, Cursor oder LM Studio erreicht jede installierte Craft-App. Starte den Client neu, nachdem du ihn hinzugefügt hast. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Das Craft-Gateway (craft-ai-mcp) ist nicht neben dem Launcher installiert. + Let AI agents use Craft apps KI-Agenten Craft-Apps nutzen lassen + Apps agents can reach: {count} Apps, die Agenten erreichen: {count} + Added Hinzugefügt + Remove Entfernen + Add Hinzufügen diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 595096f8..7e6140df 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -447,3 +447,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Puerto Port applies when you toggle the bridge. El puerto se aplica cuando cambias el puente. + AI agents Agentes de IA + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Una sola entrada en Claude, Cursor o LM Studio llega a todas las apps Craft instaladas. Reinicia el cliente después de añadirla. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La pasarela Craft (craft-ai-mcp) no está instalada junto al lanzador. + Let AI agents use Craft apps Permitir que los agentes de IA usen las apps Craft + Apps agents can reach: {count} Apps que los agentes pueden usar: {count} + Added Añadida + Remove Quitar + Add Añadir diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 47e0add2..8b095939 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -464,3 +464,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Port Port applies when you toggle the bridge. Le port est appliqué lorsque vous basculez le pont. + AI agents Agents IA + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Une seule entrée dans Claude, Cursor ou LM Studio atteint toutes les apps Craft installées. Redémarrez le client après l'avoir ajoutée. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La passerelle Craft (craft-ai-mcp) n'est pas installée à côté du lanceur. + Let AI agents use Craft apps Permettre aux agents IA d'utiliser les apps Craft + Apps agents can reach: {count} Apps accessibles aux agents : {count} + Added Ajoutée + Remove Retirer + Add Ajouter diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3551319d..989fded5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -467,3 +467,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Port Port applies when you toggle the bridge. A port akkor lép hatályba, ha kikapcsolod a hidrat. + AI agents AI-ügynökök + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Egyetlen bejegyzés a Claude-ban, a Cursorban vagy az LM Studióban eléri az összes telepített Craft alkalmazást. Hozzáadás után indítsa újra a klienst. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. A Craft átjáró (craft-ai-mcp) nincs telepítve az indító mellé. + Let AI agents use Craft apps AI-ügynökök használhatják a Craft alkalmazásokat + Apps agents can reach: {count} Ügynökök által elérhető alkalmazások: {count} + Added Hozzáadva + Remove Eltávolítás + Add Hozzáadás diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c45a5609..3fd76948 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -469,3 +469,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port ポート Port applies when you toggle the bridge. ポートはブリッジを切り替えたときに適用されます。 + AI agents AI エージェント + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Claude、Cursor、LM Studio に 1 つ登録するだけで、インストール済みのすべての Craft アプリを使えます。追加したらクライアントを再起動してください。 + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft ゲートウェイ (craft-ai-mcp) がランチャーと同じ場所にインストールされていません。 + Let AI agents use Craft apps AI エージェントに Craft アプリの使用を許可 + Apps agents can reach: {count} エージェントが使えるアプリ: {count} + Added 追加済み + Remove 削除 + Add 追加 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d72d591..fb031a1f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -465,3 +465,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port პორტი Port applies when you toggle the bridge. პორტის ცვლილება მხოლოდ გათიშვისას მოქმედება. + AI agents AI აგენტები + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. ერთი ჩანაწერი Claude-ში, Cursor-ში ან LM Studio-ში აღწევს ყველა დაინსტალირებულ Craft აპს. დამატების შემდეგ კლიენტი გადატვირთეთ. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft კარიბჭე (craft-ai-mcp) გამშვების გვერდით არ არის დაინსტალირებული. + Let AI agents use Craft apps AI აგენტებს Craft აპების გამოყენების ნება + Apps agents can reach: {count} აგენტებისთვის ხელმისაწვდომი აპები: {count} + Added დამატებულია + Remove წაშლა + Add დამატება diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f41e85e9..78d76751 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -468,3 +468,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Port Port applies when you toggle the bridge. Port jest stosowany, gdy przełączysz most. + AI agents Agenci AI + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jeden wpis w Claude, Cursorze lub LM Studio daje dostęp do każdej zainstalowanej aplikacji Craft. Po dodaniu uruchom klienta ponownie. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brama Craft (craft-ai-mcp) nie jest zainstalowana obok launchera. + Let AI agents use Craft apps Pozwól agentom AI używać aplikacji Craft + Apps agents can reach: {count} Aplikacje dostępne dla agentów: {count} + Added Dodano + Remove Usuń + Add Dodaj diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 7102d9db..8c0a48d4 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -454,3 +454,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Porta Port applies when you toggle the bridge. A porta é aplicada quando você alterna a ponte. + AI agents Agentes de IA + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Uma única entrada no Claude, no Cursor ou no LM Studio alcança todos os apps Craft instalados. Reinicie o cliente depois de adicioná-la. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. O gateway Craft (craft-ai-mcp) não está instalado ao lado do inicializador. + Let AI agents use Craft apps Permitir que agentes de IA usem os apps Craft + Apps agents can reach: {count} Apps que os agentes alcançam: {count} + Added Adicionado + Remove Remover + Add Adicionar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f9375258..f94e47ff 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -462,3 +462,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port Порт Port applies when you toggle the bridge. Порт применяется при переключении моста. + AI agents ИИ-агенты + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Одна запись в Claude, Cursor или LM Studio открывает доступ ко всем установленным приложениям Craft. После добавления перезапустите клиент. + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Шлюз Craft (craft-ai-mcp) не установлен рядом с лаунчером. + Let AI agents use Craft apps Разрешить ИИ-агентам использовать приложения Craft + Apps agents can reach: {count} Приложения, доступные агентам: {count} + Added Добавлено + Remove Удалить + Add Добавить diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 5dcd6bf3..07e74560 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -434,3 +434,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port 端口 Port applies when you toggle the bridge. 端口在切换桥接时生效。 + AI agents AI 智能体 + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中添加一个条目,即可使用所有已安装的 Craft 应用。添加后请重启客户端。 + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 启动器旁未安装 Craft 网关 (craft-ai-mcp)。 + Let AI agents use Craft apps 允许 AI 智能体使用 Craft 应用 + Apps agents can reach: {count} 智能体可用的应用:{count} + Added 已添加 + Remove 移除 + Add 添加 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index f1b71bb9..fb29726e 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -425,3 +425,11 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Port 埠口 Port applies when you toggle the bridge. 埠口在切換橋接時生效。 + AI agents AI 代理 + One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中加入一個項目,即可使用所有已安裝的 Craft 應用程式。加入後請重新啟動用戶端。 + The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 啟動器旁未安裝 Craft 閘道 (craft-ai-mcp)。 + Let AI agents use Craft apps 允許 AI 代理使用 Craft 應用程式 + Apps agents can reach: {count} 代理可使用的應用程式:{count} + Added 已加入 + Remove 移除 + Add 加入 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index b0515971..559f5493 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -1,7 +1,7 @@ //! The Settings dialog: a large card in the shape of the app page (see `sheet.rs`), with the //! groups of settings in boxes, two columns once the window is wide enough. -use artcraft_launcher_core::protocol::{Command, McpService}; +use artcraft_launcher_core::protocol::{Command, McpClientState, McpService}; use artcraft_launcher_core::{Os, PackageKind}; use egui::{RichText, Ui, vec2}; @@ -117,6 +117,7 @@ impl LauncherUi { this.settings_language(ui); this.settings_updates(ui); this.settings_appearance(ui); + this.settings_agents(ui); this.settings_local_mcp(ui); }, |ui| { @@ -372,6 +373,55 @@ impl LauncherUi { self.settings.theme = theme_choice; } + /// AI agents: one switch that lets MCP clients reach every installed Craft app through the + /// `craft-ai-mcp` gateway, and one Add/Remove button per MCP client found on this machine. + fn settings_agents(&mut self, ui: &mut Ui) { + if !self.caps.manage_apps { + return; + } + let t = Tokens::get(ui.ctx()); + sheet::panel(ui, tl!("AI agents"), |ui| { + note(ui, tl!("One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it.")); + ui.add_space(8.0); + let agents = self.mcp_agents.clone(); + if !agents.gateway_found { + ui.label(RichText::new(tl!("The Craft gateway (craft-ai-mcp) is not installed beside the launcher.")).size(12.0).color(t.muted)); + return; + } + let mut on = agents.enabled; + if ui.checkbox(&mut on, tl!("Let AI agents use Craft apps")).changed() && on != agents.enabled { + self.act_command(Command::McpSetAgents { enabled: on }); + } + if !agents.enabled { + return; + } + ui.label(RichText::new(tl!("Apps agents can reach: {count}").replace("{count}", &agents.apps.to_string())).size(12.0).color(t.muted)); + ui.add_space(8.0); + for c in &agents.clients { + self.draw_client_row(ui, &t, c); + } + }); + } + + /// One MCP client: its name, and Add or Remove (or "Not installed" when it isn't). + fn draw_client_row(&mut self, ui: &mut Ui, t: &Tokens, c: &McpClientState) { + ui.horizontal(|ui| { + ui.label(c.name.as_str()); + if c.added { + ui.label(RichText::new(tl!("Added")).size(12.0).color(t.muted)); + if ui.button(tl!("Remove")).clicked() { + self.act_command(Command::McpSetClient { client: c.client, added: false }); + } + } else if c.installed { + if ui.button(tl!("Add")).clicked() { + self.act_command(Command::McpSetClient { client: c.client, added: true }); + } + } else { + ui.label(RichText::new(tl!("Not installed")).size(12.0).color(t.muted)); + } + }); + } + /// Local MCP services: turn Craft AI apps on or off as MCP servers for LM Studio / Bionic, and /// manage the unified HTTP bridge. Only shown where the backend can manage installs (desktop). fn settings_local_mcp(&mut self, ui: &mut Ui) { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 7ee44022..0aa39458 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4411,3 +4411,63 @@ fn launcher_version_padlock_confirms_and_returns_to_settings() { h.get_by_label("Launcher version"); assert!(sent.borrow().iter().any(|c| matches!(c, Command::Configure(options) if options.launcher_version == VersionTrack::Stable))); } + +/// Settings › AI agents: the switch, and Add / Remove per MCP client, each sending one command. +#[test] +fn ai_agents_switch_and_client_buttons_send_their_commands() { + use artcraft_launcher_core::protocol::{McpAgents, McpBridge, McpClient, McpClientState}; + let client = |client, name: &str, installed, added| McpClientState { client, name: name.into(), installed, added }; + let mut evs = events(); + evs.push(Event::Mcp { + services: vec![], + bridge: McpBridge::default(), + agents: McpAgents { + gateway_found: true, + enabled: true, + apps: 3, + clients: vec![ + client(McpClient::ClaudeDesktop, "Claude Desktop", true, false), + client(McpClient::Cursor, "Cursor", true, true), + client(McpClient::LmStudio, "LM Studio", false, false), + ], + }, + }); + let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); + h.run_steps(6); + h.get_by_label("Settings").click(); + h.run_steps(4); + h.get_by_label("Apps agents can reach: 3").scroll_to_me(); + h.run_steps(6); + snapshot(&mut h, "settings-ai-agents"); + h.get_by_label("Add").click(); + h.run_steps(3); + h.get_by_label("Remove").click(); + h.run_steps(3); + h.get_by_label("Let AI agents use Craft apps").click(); + h.run_steps(2); + let sent = sent.borrow(); + assert!(sent.iter().any(|c| matches!(c, Command::McpSetClient { client: McpClient::ClaudeDesktop, added: true }))); + assert!(sent.iter().any(|c| matches!(c, Command::McpSetClient { client: McpClient::Cursor, added: false }))); + assert!(sent.iter().any(|c| matches!(c, Command::McpSetAgents { enabled: false }))); + assert!( + !sent.iter().any(|c| matches!(c, Command::McpSetClient { client: McpClient::LmStudio, .. })), + "a client that isn't installed has no button" + ); +} + +/// Without the gateway beside the launcher, Settings says so and offers no switch. +#[test] +fn ai_agents_without_the_gateway_offer_no_switch() { + let mut evs = events(); + evs.push(Event::Mcp { + services: vec![], + bridge: artcraft_launcher_core::protocol::McpBridge::default(), + agents: artcraft_launcher_core::protocol::McpAgents::default(), + }); + let (mut h, _sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); + h.run_steps(6); + h.get_by_label("Settings").click(); + h.run_steps(4); + h.get_by_label("The Craft gateway (craft-ai-mcp) is not installed beside the launcher."); + assert!(h.query_by_label("Let AI agents use Craft apps").is_none()); +} From f94bce3ca846b27dae701240dd0a71973adf6a47 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 14:12:55 +0100 Subject: [PATCH 10/27] fix(agents): the review findings on the AI agents box - Changes to the app list and the gateway copy run under one lock, and a refresh checks again that agents are on, so detection can't bring the list back after it was turned off. - Clients get a copy of craft-ai-mcp in ArtCraft/mcp/bin, refreshed when the shipped one changes, never a path inside an AppImage mount, a Flatpak sandbox or a folder an update replaces. - MCP commands run on a worker thread, one at a time, with one detection per command: detection can run flatpak queries for seconds on Linux. - Saving ng-mcp.json keeps entries it can't read where they were, and fields of managed entries it doesn't know; only entries removed on purpose go. - Without the gateway, agents that are on can still be turned off and their entries removed; only turning on and Add need it. --- crates/native/src/agents.rs | 99 ++++++++++++++++++---- crates/native/src/agents_tests.rs | 34 ++++++++ crates/native/src/backend.rs | 114 +++++++++++++------------- crates/native/src/local_mcp.rs | 85 ++++++++++++++++++- crates/ui-egui/src/settings_dialog.rs | 16 ++-- crates/ui-egui/tests/ui.rs | 33 ++++++++ 6 files changed, 301 insertions(+), 80 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index aa6c4513..c3d7669d 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -10,6 +10,7 @@ //! configuration that does not parse is never overwritten, and entries other than ours are kept. use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard, PoisonError}; use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; use serde_json::{Map, Value, json}; @@ -152,19 +153,75 @@ pub fn unregister(config: &Path) -> Result<(), String> { crate::paths::write_atomic(config, text.as_bytes()) } -/// The `craft-ai-mcp` gateway binary: beside the launcher, or `ARTCRAFT_LAUNCHER_BRIDGE_PATH`. +/// The `craft-ai-mcp` gateway binary as shipped: beside the launcher, or +/// `ARTCRAFT_LAUNCHER_BRIDGE_PATH`. pub fn locate_gateway() -> Option { crate::local_mcp::locate_bridge() } -/// What Settings shows. While agents are on, the app list is refreshed first, so an app -/// installed since then is reachable too (a failed refresh keeps the previous list). +/// The folder in [`mcp_dir`] that holds the gateway copy clients start. +pub const GATEWAY_DIR: &str = "bin"; + +/// Where the gateway copy lives in `dir`. +pub fn gateway_copy(dir: &Path) -> PathBuf { + dir.join(GATEWAY_DIR).join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX)) +} + +/// Copy the shipped gateway `src` into `dir`, so client configurations name a path that stays +/// valid: not one inside an AppImage mount that goes away when the launcher quits, a Flatpak +/// sandbox path host clients can't run, or a folder an update or a move replaces. An existing +/// copy of the same size that is not older than `src` is kept. A copy a client is running can't +/// be replaced on Windows; then the existing copy is used and refreshed later. +pub fn install_gateway(src: &Path, dir: &Path) -> Result { + let dest = gateway_copy(dir); + let current = match (std::fs::metadata(src), std::fs::metadata(&dest)) { + (Ok(a), Ok(b)) => a.len() == b.len() && matches!((a.modified(), b.modified()), (Ok(ma), Ok(mb)) if mb >= ma), + (Err(e), _) => return Err(format!("couldn't read the Craft gateway at {} ({e})", src.display())), + _ => false, + }; + if current { + return Ok(dest); + } + let bytes = std::fs::read(src).map_err(|e| format!("couldn't read the Craft gateway at {} ({e})", src.display()))?; + match crate::paths::write_atomic(&dest, &bytes) { + Ok(()) => {} + Err(_) if dest.is_file() => return Ok(dest), + Err(e) => return Err(e), + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| format!("couldn't make {} executable ({e})", dest.display()))?; + } + Ok(dest) +} + +/// Serialises every change to the app list and the gateway copy. Detection refreshes them on a +/// background thread while Settings may be turning agents off; without this, a refresh that +/// read "on" just before the switch could write the list back after it was removed. +static LOCK: Mutex<()> = Mutex::new(()); + +fn lock() -> MutexGuard<'static, ()> { + LOCK.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// What Settings shows. While agents are on, the app list and the gateway copy are refreshed +/// first, so an app installed (or a gateway updated) since then is used too; a failed refresh +/// keeps the previous ones. pub fn state(services: &[LocalService]) -> McpAgents { let dir = mcp_dir(); - let on = dir.as_deref().is_some_and(enabled); - if on && let Some(d) = &dir { - let _ = write_apps(d, services); - } + let on = { + let _guard = lock(); + let on = dir.as_deref().is_some_and(enabled); + if on && let Some(d) = &dir { + let _ = write_apps(d, services); + if let Some(src) = locate_gateway() { + let _ = install_gateway(&src, d); + } + } + on + }; let clients = CLIENTS .iter() .map(|c| { @@ -185,14 +242,16 @@ pub fn state(services: &[LocalService]) -> McpAgents { } } -/// Turn agents on (write the app list) or off (remove it and every client entry this module -/// added). All clients are tried; the first error is returned. +const NO_GATEWAY: &str = "the Craft gateway (craft-ai-mcp) is not installed beside the launcher"; + +/// Turn agents on (copy the gateway, write the app list) or off (remove the list, every client +/// entry this module added, and the copy). All clients are tried; the first error is returned. pub fn set_enabled(on: bool, services: &[LocalService]) -> Result<(), String> { let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; + let _guard = lock(); if on { - if locate_gateway().is_none() { - return Err("the Craft gateway (craft-ai-mcp) is not installed beside the launcher".into()); - } + let src = locate_gateway().ok_or(NO_GATEWAY)?; + install_gateway(&src, &dir)?; return write_apps(&dir, services); } let mut first_error = remove_apps(&dir).err(); @@ -203,19 +262,29 @@ pub fn set_enabled(on: bool, services: &[LocalService]) -> Result<(), String> { first_error.get_or_insert(e); } } + // A client still running the copy keeps it busy on Windows; it goes next time. + let _ = std::fs::remove_file(gateway_copy(&dir)); first_error.map_or(Ok(()), Err) } -/// Add the gateway entry to `client`, or remove it. Adding needs agents on and the gateway found. +/// Add the gateway entry to `client`, or remove it. Adding needs agents on; the entry names the +/// gateway copy in [`mcp_dir`]. pub fn set_client(client: McpClient, added: bool) -> Result<(), String> { let (config, _) = client_paths(client).ok_or("couldn't find the home folder")?; if !added { return unregister(&config); } - if !mcp_dir().as_deref().is_some_and(enabled) { + let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; + let _guard = lock(); + if !enabled(&dir) { return Err("turn on \"Let AI agents use Craft apps\" first".into()); } - let gateway = locate_gateway().ok_or("the Craft gateway (craft-ai-mcp) is not installed beside the launcher")?; + let copy = gateway_copy(&dir); + let gateway = match locate_gateway() { + Some(src) => install_gateway(&src, &dir)?, + None if copy.is_file() => copy, + None => return Err(NO_GATEWAY.into()), + }; register(&config, &gateway) } diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index d3926ef2..0bc2dc0e 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -118,3 +118,37 @@ fn every_client_has_a_name_and_paths() { } } } + +#[test] +fn the_gateway_is_copied_once_and_refreshed_when_it_changes() { + let src_dir = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let src = src_dir.path().join("craft-ai-mcp"); + std::fs::write(&src, b"v1").unwrap(); + let copy = install_gateway(&src, dir.path()).unwrap(); + assert_eq!(copy, gateway_copy(dir.path())); + assert!(copy.starts_with(dir.path()), "clients get a path in the launcher's folder, not the shipped one"); + assert_eq!(std::fs::read(©).unwrap(), b"v1"); + // Unchanged: kept as is. + let before = std::fs::metadata(©).unwrap().modified().unwrap(); + install_gateway(&src, dir.path()).unwrap(); + assert_eq!(std::fs::metadata(©).unwrap().modified().unwrap(), before); + // An update of another size replaces it. + std::fs::write(&src, b"version 2").unwrap(); + install_gateway(&src, dir.path()).unwrap(); + assert_eq!(std::fs::read(©).unwrap(), b"version 2"); + // No source: an error, not a panic. + assert!(install_gateway(&src_dir.path().join("missing"), dir.path()).is_err()); +} + +#[cfg(unix)] +#[test] +fn the_gateway_copy_is_executable() { + use std::os::unix::fs::PermissionsExt; + let src_dir = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let src = src_dir.path().join("craft-ai-mcp"); + std::fs::write(&src, b"#!/bin/sh\n").unwrap(); + let copy = install_gateway(&src, dir.path()).unwrap(); + assert_eq!(std::fs::metadata(copy).unwrap().permissions().mode() & 0o111, 0o111); +} diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 6ae3cc67..3a886af0 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -1606,54 +1606,15 @@ impl Backend for NativeBackend { self.check(true); } } - Command::McpState => { - self.shared.emit(mcp_state(&self.shared)); - } - Command::McpSetService { service_id, enabled } => { - let manifest = self.shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); - let snapshot = crate::detect::Snapshot::take(); - if let Some(p) = local_mcp::mcp_config_path() { - let mut servers = local_mcp::load_servers(&p); - // Rebuild from detection so the command path is current, then flip the flag. - if let Some(s) = local_mcp::installed_services(&manifest, &snapshot).into_iter().find(|s| s.id == service_id) { - if enabled { - local_mcp::enable_service(&mut servers, &s); - } else { - local_mcp::disable_service(&mut servers, &s); - } - } - if let Err(e) = local_mcp::save_servers(&p, &servers) { - self.shared.emit(Event::McpError { message: e }); - } - } - self.shared.emit(mcp_state(&self.shared)); - } - Command::McpSetBridge { port, enabled } => { - if let Some(p) = local_mcp::mcp_config_path() { - let mut servers = local_mcp::load_servers(&p); - if enabled { - local_mcp::enable_bridge(&mut servers, port); - } else { - local_mcp::disable_bridge(&mut servers); - } - if let Err(e) = local_mcp::save_servers(&p, &servers) { - self.shared.emit(Event::McpError { message: e }); - } - } - self.shared.emit(mcp_state(&self.shared)); - } - Command::McpSetAgents { enabled } => { - let services = detected_services(&self.shared); - if let Err(e) = crate::agents::set_enabled(enabled, &services) { - self.shared.emit(Event::McpError { message: e }); - } - self.shared.emit(mcp_state(&self.shared)); - } - Command::McpSetClient { client, added } => { - if let Err(e) = crate::agents::set_client(client, added) { - self.shared.emit(Event::McpError { message: e }); - } - self.shared.emit(mcp_state(&self.shared)); + cmd @ (Command::McpState + | Command::McpSetService { .. } + | Command::McpSetBridge { .. } + | Command::McpSetAgents { .. } + | Command::McpSetClient { .. }) => { + // Detection can run package-manager queries for seconds (flatpak on Linux): + // never on the UI thread that sends commands. + let shared = self.shared.clone(); + std::thread::spawn(move || run_mcp(&shared, cmd)); } } } @@ -1695,8 +1656,12 @@ impl Backend for NativeBackend { /// name so those created under a different id (e.g. a UUID by an earlier launcher version) are /// recognized and reported as already present. fn mcp_state(shared: &Shared) -> Event { - let detected = detected_services(shared); - let agents = crate::agents::state(&detected); + mcp_state_for(&detected_services(shared)) +} + +/// [`mcp_state`] for apps already detected. +fn mcp_state_for(detected: &[local_mcp::LocalService]) -> Event { + let agents = crate::agents::state(detected); let existing: Vec = match local_mcp::mcp_config_path() { Some(p) => local_mcp::load_servers(&p), @@ -1704,11 +1669,12 @@ fn mcp_state(shared: &Shared) -> Event { }; let services = detected - .into_iter() - .map(|s| { - // Read the current on/off state before moving `name` into the struct. - let enabled = local_mcp::service_enabled(&existing, &s.name); - McpService { id: s.id, name: s.name, command: s.cli_path.map(|c| c.display().to_string()).unwrap_or_default(), enabled } + .iter() + .map(|s| McpService { + id: s.id.clone(), + name: s.name.clone(), + command: s.cli_path.as_ref().map(|c| c.display().to_string()).unwrap_or_default(), + enabled: local_mcp::service_enabled(&existing, &s.name), }) .collect(); @@ -1725,6 +1691,44 @@ fn mcp_state(shared: &Shared) -> Event { } } +/// One MCP command, on a worker thread. Commands run one at a time, so a toggle and a refresh +/// never write `ng-mcp.json` or the client configurations at once; detection runs once per +/// command, and the new state is sent when it is done. +fn run_mcp(shared: &Shared, cmd: Command) { + static MCP_WORK: Mutex<()> = Mutex::new(()); + let _guard = MCP_WORK.lock().unwrap_or_else(PoisonError::into_inner); + let services = detected_services(shared); + let result = match cmd { + Command::McpSetService { service_id, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { + let mut servers = local_mcp::load_servers(&p); + if let Some(s) = services.iter().find(|s| s.id == service_id) { + if enabled { + local_mcp::enable_service(&mut servers, s); + } else { + local_mcp::disable_service(&mut servers, s); + } + } + local_mcp::save_servers(&p, &servers) + }), + Command::McpSetBridge { port, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { + let mut servers = local_mcp::load_servers(&p); + if enabled { + local_mcp::enable_bridge(&mut servers, port); + } else { + local_mcp::disable_bridge(&mut servers); + } + local_mcp::save_servers(&p, &servers) + }), + Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &services), + Command::McpSetClient { client, added } => crate::agents::set_client(client, added), + _ => Ok(()), + }; + if let Err(message) = result { + shared.emit(Event::McpError { message }); + } + shared.emit(mcp_state_for(&services)); +} + /// The installed apps with their CLIs, from a fresh detection snapshot. fn detected_services(shared: &Shared) -> Vec { let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index 355f445b..80281cd7 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -106,10 +106,8 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> }, Err(_) => None, // missing (or unreadable): start fresh }; - let array = match servers.iter().map(serde_json::to_value).collect::, _>>() { - Ok(a) => a, - Err(e) => return Err(e.to_string()), - }; + let old = existing.as_ref().and_then(|v| v.get("servers")).and_then(serde_json::Value::as_array).map(Vec::as_slice).unwrap_or_default(); + let array = merge_servers(old, servers)?; // Preserve any top-level keys other than `servers`; replace the array. If the file was not // a JSON object, it is not an `ng-mcp.json` shape and starts fresh. let mut map = serde_json::Map::new(); @@ -125,6 +123,53 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> crate::paths::write_atomic(path, out.as_bytes()) } +/// The new `servers` array: `servers` merged into the file's `old` entries. An entry this module +/// cannot read (another connection type, a missing field, a shape Bionic adds later) is kept as +/// it is and where it was; an entry it manages keeps any field it doesn't know; an entry it can +/// read but that is no longer in `servers` was removed on purpose and is left out. +fn merge_servers(old: &[serde_json::Value], servers: &[ServerEntry]) -> Result, String> { + let mut used = vec![false; servers.len()]; + let mut out = Vec::with_capacity(old.len().max(servers.len())); + for raw in old { + if serde_json::from_value::(raw.clone()).is_err() { + out.push(raw.clone()); + continue; + } + let id = raw.get("id").and_then(serde_json::Value::as_str); + let Some(i) = servers.iter().enumerate().position(|(i, s)| Some(s.id.as_str()) == id && !used.get(i).copied().unwrap_or(true)) else { + continue; + }; + if let (Some(flag), Some(entry)) = (used.get_mut(i), servers.get(i)) { + *flag = true; + out.push(overlay(raw, serde_json::to_value(entry).map_err(|e| e.to_string())?)); + } + } + for (entry, was_used) in servers.iter().zip(used) { + if !was_used { + out.push(serde_json::to_value(entry).map_err(|e| e.to_string())?); + } + } + Ok(out) +} + +/// `new` written over `raw`: fields only `raw` has are kept, one level into `connection` too +/// while its `type` is unchanged. +fn overlay(raw: &serde_json::Value, new: serde_json::Value) -> serde_json::Value { + let (Some(raw), serde_json::Value::Object(new)) = (raw.as_object(), new.clone()) else { + return new; + }; + let mut merged = raw.clone(); + for (k, v) in new { + let keep_inner = k == "connection" && raw.get("connection").and_then(|c| c.get("type")) == v.get("type"); + let value = match (keep_inner, raw.get(&k)) { + (true, Some(old @ serde_json::Value::Object(_))) => overlay(old, v), + _ => v, + }; + merged.insert(k, value); + } + serde_json::Value::Object(merged) +} + /// Every Craft App that has a usable CLI on this machine, in suite order. Detection is the single /// source of truth for "installed"; this just adds the CLI path each app would expose to MCP. pub fn installed_services(manifest: &Manifest, snapshot: &detect::Snapshot) -> Vec { @@ -523,6 +568,38 @@ mod tests { assert_eq!(load_servers(&path), vec![]); } + #[test] + fn save_keeps_entries_and_fields_it_does_not_manage() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ng-mcp.json"); + std::fs::write( + &path, + r#"{"servers":[ + {"id":"third","name":"Third","description":"","enabled":true,"connection":{"type":"stdio","command":"x","args":[]}}, + {"id":"sse","name":"Sse","description":"","enabled":true,"connection":{"type":"sse","url":"http://h"}}, + {"id":"craft-ai-mcp-wordcraft","name":"WordCraft","description":"","enabled":true,"note":"mine", + "connection":{"type":"stdio","command":"/x/wordcraft-cli.exe","args":["mcp"],"env":{},"cwd":"/w"}}, + {"id":"gone","name":"Gone","description":"","enabled":true,"connection":{"type":"stdio","command":"g","args":[],"env":{}}} + ]}"#, + ) + .unwrap(); + let mut servers = load_servers(&path); + assert_eq!(servers.len(), 2, "only the two complete stdio entries parse"); + servers.retain(|s| s.id != "gone"); + if let Some(w) = servers.iter_mut().find(|s| s.id == "craft-ai-mcp-wordcraft") { + w.enabled = false; + } + save_servers(&path, &servers).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + let ids: Vec<&str> = v["servers"].as_array().unwrap().iter().filter_map(|e| e["id"].as_str()).collect(); + assert_eq!(ids, vec!["third", "sse", "craft-ai-mcp-wordcraft"], "unreadable entries stay in place; a removed one goes"); + let w = &v["servers"][2]; + assert_eq!(w["enabled"], false); + assert_eq!(w["note"], "mine", "an unknown field of a managed entry stays"); + assert_eq!(w["connection"]["cwd"], "/w", "an unknown connection field stays"); + assert!(v["servers"][0]["connection"].get("env").is_none(), "an entry without env is left as it was"); + } + #[test] fn save_refuses_to_overwrite_a_malformed_config() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 559f5493..347de1e4 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -386,7 +386,10 @@ impl LauncherUi { let agents = self.mcp_agents.clone(); if !agents.gateway_found { ui.label(RichText::new(tl!("The Craft gateway (craft-ai-mcp) is not installed beside the launcher.")).size(12.0).color(t.muted)); - return; + // Turning on needs the gateway; turning off and removing entries never does. + if !agents.enabled { + return; + } } let mut on = agents.enabled; if ui.checkbox(&mut on, tl!("Let AI agents use Craft apps")).changed() && on != agents.enabled { @@ -398,13 +401,14 @@ impl LauncherUi { ui.label(RichText::new(tl!("Apps agents can reach: {count}").replace("{count}", &agents.apps.to_string())).size(12.0).color(t.muted)); ui.add_space(8.0); for c in &agents.clients { - self.draw_client_row(ui, &t, c); + self.draw_client_row(ui, &t, c, agents.gateway_found); } }); } - /// One MCP client: its name, and Add or Remove (or "Not installed" when it isn't). - fn draw_client_row(&mut self, ui: &mut Ui, t: &Tokens, c: &McpClientState) { + /// One MCP client: its name, and Add or Remove (or "Not installed" when it isn't). Add is + /// offered only while the gateway is there to add. + fn draw_client_row(&mut self, ui: &mut Ui, t: &Tokens, c: &McpClientState, can_add: bool) { ui.horizontal(|ui| { ui.label(c.name.as_str()); if c.added { @@ -412,11 +416,11 @@ impl LauncherUi { if ui.button(tl!("Remove")).clicked() { self.act_command(Command::McpSetClient { client: c.client, added: false }); } - } else if c.installed { + } else if c.installed && can_add { if ui.button(tl!("Add")).clicked() { self.act_command(Command::McpSetClient { client: c.client, added: true }); } - } else { + } else if !c.installed { ui.label(RichText::new(tl!("Not installed")).size(12.0).color(t.muted)); } }); diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 0aa39458..438306a7 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4471,3 +4471,36 @@ fn ai_agents_without_the_gateway_offer_no_switch() { h.get_by_label("The Craft gateway (craft-ai-mcp) is not installed beside the launcher."); assert!(h.query_by_label("Let AI agents use Craft apps").is_none()); } + +/// When the gateway went away while agents were on, they can still be turned off and the entries +/// removed; only adding is gone. +#[test] +fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { + use artcraft_launcher_core::protocol::{McpAgents, McpBridge, McpClient, McpClientState}; + let client = |client, name: &str, added| McpClientState { client, name: name.into(), installed: true, added }; + let mut evs = events(); + evs.push(Event::Mcp { + services: vec![], + bridge: McpBridge::default(), + agents: McpAgents { + gateway_found: false, + enabled: true, + apps: 2, + clients: vec![client(McpClient::ClaudeDesktop, "Claude Desktop", false), client(McpClient::Cursor, "Cursor", true)], + }, + }); + let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); + h.run_steps(6); + h.get_by_label("Settings").click(); + h.run_steps(4); + h.get_by_label("Apps agents can reach: 2").scroll_to_me(); + h.run_steps(6); + assert!(h.query_by_label("Add").is_none(), "nothing to add without the gateway"); + h.get_by_label("Remove").click(); + h.run_steps(3); + h.get_by_label("Let AI agents use Craft apps").click(); + h.run_steps(3); + let sent = sent.borrow(); + assert!(sent.iter().any(|c| matches!(c, Command::McpSetClient { client: McpClient::Cursor, added: false }))); + assert!(sent.iter().any(|c| matches!(c, Command::McpSetAgents { enabled: false }))); +} From 1cb228e87d3fe5d506d9f8f2b6f22f430d292c43 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 15:48:26 +0100 Subject: [PATCH 11/27] feat(settings): AI agents behind the AI-MCP feature flag Settings gets an Experimental features box with a switch per feature flag from craft-flags (storytold/craft-libs#1118): AI-MCP and AI-MODELS, off by default, shared with every Craft app through ArtCraft/flags.toml. A flag set by CRAFT_FLAGS shows as such and can't be switched. The AI agents box shows only while AI-MCP is on; the backend refuses to turn agents on or add a client without it, and turning AI-MCP off turns agents off and removes the client entries. craft-flags is pinned to the head of storytold/craft-libs#1119 until it merges. --- Cargo.lock | 20 ++++++++++++ Cargo.toml | 2 ++ crates/core/src/protocol.rs | 22 +++++++++++++ crates/native/Cargo.toml | 1 + crates/native/src/agents.rs | 45 +++++++++++++++++++++++++-- crates/native/src/backend.rs | 6 +++- crates/ui-egui/src/app.rs | 11 +++++-- crates/ui-egui/src/i18n/cs.tsv | 3 ++ crates/ui-egui/src/i18n/de.tsv | 3 ++ crates/ui-egui/src/i18n/es.tsv | 3 ++ crates/ui-egui/src/i18n/fr.tsv | 3 ++ crates/ui-egui/src/i18n/hu.tsv | 3 ++ crates/ui-egui/src/i18n/ja.tsv | 3 ++ crates/ui-egui/src/i18n/ka.tsv | 3 ++ crates/ui-egui/src/i18n/pl.tsv | 3 ++ crates/ui-egui/src/i18n/pt-BR.tsv | 3 ++ crates/ui-egui/src/i18n/ru.tsv | 3 ++ crates/ui-egui/src/i18n/zh-CN.tsv | 3 ++ crates/ui-egui/src/i18n/zh-TW.tsv | 3 ++ crates/ui-egui/src/settings_dialog.rs | 29 ++++++++++++++++- crates/ui-egui/tests/ui.rs | 33 +++++++++++++++++++- 21 files changed, 198 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 08a95f39..ad4df942 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -315,6 +315,7 @@ name = "artcraft-launcher-native" version = "0.19.2" dependencies = [ "artcraft-launcher-core", + "craft-flags", "craft-update", "dirs 6.0.0", "dunce", @@ -979,6 +980,24 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +dependencies = [ + "rustix 1.1.5", +] + +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +dependencies = [ + "craft-atomic", + "dirs 7.0.0", + "toml_edit 0.25.17+spec-1.1.0", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -5138,6 +5157,7 @@ dependencies = [ "indexmap", "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", + "toml_writer", "winnow 1.0.4", ] diff --git a/Cargo.toml b/Cargo.toml index 034ef0d1..72ee697b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,8 @@ semver = { version = "1", features = ["serde"] } log = "0.4" # All date/time conversion goes through jiff (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). jiff = "0.2" +# Feature flags (craft-libs#1118). Pinned to the pull request head craft-libs#1119 until it merges; re-pin then. +craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d6d6835dc888a270a96a575fba58ab01abf6c122" } craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-ui = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 14682ede..2c210735 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -95,6 +95,11 @@ pub enum Command { client: McpClient, added: bool, }, + /// Turn a feature flag on or off for the launcher and every Craft app (`ArtCraft/flags.toml`). + SetFlag { + id: String, + on: bool, + }, } /// Parent folders for new installs. Existing installations keep their recorded location. @@ -322,6 +327,10 @@ pub enum Event { McpError { message: String, }, + /// The feature flags and whether each is on. Sent with the MCP state and after a change. + Flags { + flags: Vec, + }, } /// One installed app that can be exposed as a stdio MCP server. `command` is the CLI path the @@ -343,6 +352,17 @@ pub struct McpBridge { pub enabled: bool, } +/// One feature flag as Settings shows it. +#[derive(Clone, Debug, PartialEq)] +pub struct FlagState { + pub id: String, + pub title: String, + pub description: String, + pub on: bool, + /// `CRAFT_FLAGS` decides it for this run, so the switch has no effect until that is gone. + pub forced: bool, +} + /// An MCP client the launcher can add the gateway entry to. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum McpClient { @@ -365,6 +385,8 @@ pub struct McpClientState { /// switch, and the MCP clients. #[derive(Clone, Debug, PartialEq, Default)] pub struct McpAgents { + /// The `AI-MCP` feature flag: without it Settings shows nothing about agents. + pub flag_on: bool, pub gateway_found: bool, pub enabled: bool, /// How many installed apps agents can reach (those with a CLI). diff --git a/crates/native/Cargo.toml b/crates/native/Cargo.toml index bb62e3c5..3dc1f8c7 100644 --- a/crates/native/Cargo.toml +++ b/crates/native/Cargo.toml @@ -18,6 +18,7 @@ local-mirror = [] [dependencies] artcraft-launcher-core = { workspace = true } +craft-flags = { workspace = true } craft-update = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index c3d7669d..f11dbb50 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard, PoisonError}; -use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; +use artcraft_launcher_core::protocol::{FlagState, McpAgents, McpClient, McpClientState}; use serde_json::{Map, Value, json}; use crate::local_mcp::LocalService; @@ -210,10 +210,11 @@ fn lock() -> MutexGuard<'static, ()> { /// first, so an app installed (or a gateway updated) since then is used too; a failed refresh /// keeps the previous ones. pub fn state(services: &[LocalService]) -> McpAgents { + let flag_on = flag_on(); let dir = mcp_dir(); let on = { let _guard = lock(); - let on = dir.as_deref().is_some_and(enabled); + let on = flag_on && dir.as_deref().is_some_and(enabled); if on && let Some(d) = &dir { let _ = write_apps(d, services); if let Some(src) = locate_gateway() { @@ -235,6 +236,7 @@ pub fn state(services: &[LocalService]) -> McpAgents { }) .collect(); McpAgents { + flag_on, gateway_found: locate_gateway().is_some(), enabled: on, apps: services.iter().filter(|s| s.cli_path.as_ref().is_some_and(|p| p.is_absolute())).count(), @@ -242,6 +244,39 @@ pub fn state(services: &[LocalService]) -> McpAgents { } } +/// Whether the `AI-MCP` feature flag is on (`ArtCraft/flags.toml`, `CRAFT_FLAGS`). +pub fn flag_on() -> bool { + craft_flags::load().enabled(&craft_flags::AI_MCP) +} + +const NO_FLAG: &str = "turn on \"AI agents (MCP)\" under Experimental features first"; + +/// Every feature flag, for Settings. +pub fn flags_state() -> Vec { + let flags = craft_flags::load(); + craft_flags::ALL + .iter() + .map(|f| FlagState { + id: f.id.to_string(), + title: f.title.to_string(), + description: f.description.to_string(), + on: flags.enabled(f), + forced: flags.forced(f.id).is_some(), + }) + .collect() +} + +/// Turn a feature flag on or off for the launcher and every app. Turning `AI-MCP` off also turns +/// agents off, so no client keeps an entry for a feature that is switched off. +pub fn set_flag(id: &str, on: bool, services: &[LocalService]) -> Result<(), String> { + let path = craft_flags::default_path().ok_or("couldn't find the per-user configuration folder")?; + craft_flags::set(&path, id, on).map_err(|e| e.to_string())?; + if id == craft_flags::AI_MCP.id && !on { + set_enabled(false, services)?; + } + Ok(()) +} + const NO_GATEWAY: &str = "the Craft gateway (craft-ai-mcp) is not installed beside the launcher"; /// Turn agents on (copy the gateway, write the app list) or off (remove the list, every client @@ -250,6 +285,9 @@ pub fn set_enabled(on: bool, services: &[LocalService]) -> Result<(), String> { let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; let _guard = lock(); if on { + if !flag_on() { + return Err(NO_FLAG.into()); + } let src = locate_gateway().ok_or(NO_GATEWAY)?; install_gateway(&src, &dir)?; return write_apps(&dir, services); @@ -274,6 +312,9 @@ pub fn set_client(client: McpClient, added: bool) -> Result<(), String> { if !added { return unregister(&config); } + if !flag_on() { + return Err(NO_FLAG.into()); + } let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; let _guard = lock(); if !enabled(&dir) { diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 3a886af0..d0f95e4c 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -359,6 +359,7 @@ impl NativeBackend { report_partial(app, &shared, &paths, platform); } // Local MCP state: which installed apps can be exposed + the unified bridge. + shared.emit(Event::Flags { flags: crate::agents::flags_state() }); shared.emit(mcp_state(&shared)); drop(busy); }); @@ -1610,7 +1611,8 @@ impl Backend for NativeBackend { | Command::McpSetService { .. } | Command::McpSetBridge { .. } | Command::McpSetAgents { .. } - | Command::McpSetClient { .. }) => { + | Command::McpSetClient { .. } + | Command::SetFlag { .. }) => { // Detection can run package-manager queries for seconds (flatpak on Linux): // never on the UI thread that sends commands. let shared = self.shared.clone(); @@ -1721,11 +1723,13 @@ fn run_mcp(shared: &Shared, cmd: Command) { }), Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &services), Command::McpSetClient { client, added } => crate::agents::set_client(client, added), + Command::SetFlag { id, on } => crate::agents::set_flag(&id, on, &services), _ => Ok(()), }; if let Err(message) = result { shared.emit(Event::McpError { message }); } + shared.emit(Event::Flags { flags: crate::agents::flags_state() }); shared.emit(mcp_state_for(&services)); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 4474d72c..0e1f83bb 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,8 +3,8 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, McpBridge, McpService, - PAUSED, Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, FlagState, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, McpBridge, + McpService, PAUSED, Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; @@ -149,6 +149,8 @@ pub struct LauncherUi { pub(crate) mcp_bridge: McpBridge, /// AI agents: the gateway switch and the MCP clients. pub(crate) mcp_agents: McpAgents, + /// The feature flags (Settings › Experimental features). + pub(crate) flags: Vec, /// Editable port text for the unified bridge; synced from events only once so user edits stick. pub(crate) bridge_port: String, pub(crate) bridge_port_initialized: bool, @@ -282,6 +284,7 @@ impl LauncherUi { mcp_services: Vec::new(), mcp_bridge: McpBridge::default(), mcp_agents: McpAgents::default(), + flags: Vec::new(), bridge_port: String::new(), bridge_port_initialized: false, mcp_requested: false, @@ -674,6 +677,10 @@ impl LauncherUi { } false } + Event::Flags { flags } => { + self.flags = flags; + false + } Event::McpError { message } => { // A failed MCP write (e.g. a full disk or an unreadable config) is surfaced so the // user knows their toggle did not take effect. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6e616066..0991c8df 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -442,3 +442,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Přidáno Remove Odebrat Add Přidat + Experimental features Experimentální funkce + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funkce, které se teprve vyvíjejí. Každá je vypnutá, dokud ji zde nezapnete, pro spouštěč i všechny aplikace Craft. + Set by CRAFT_FLAGS for this run. Pro toto spuštění nastaveno proměnnou CRAFT_FLAGS. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 854adad8..6cc86775 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -474,3 +474,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Hinzugefügt Remove Entfernen Add Hinzufügen + Experimental features Experimentelle Funktionen + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funktionen, die noch entstehen. Jede ist aus, bis du sie hier einschaltest, für den Launcher und jede Craft-App. + Set by CRAFT_FLAGS for this run. Für diesen Start durch CRAFT_FLAGS festgelegt. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7e6140df..1ea0b1c4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -455,3 +455,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Añadida Remove Quitar Add Añadir + Experimental features Funciones experimentales + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funciones que aún se están creando. Cada una está desactivada hasta que la actives aquí, para el lanzador y todas las apps Craft. + Set by CRAFT_FLAGS for this run. Fijado por CRAFT_FLAGS para esta ejecución. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8b095939..0ea47bf8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -472,3 +472,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Ajoutée Remove Retirer Add Ajouter + Experimental features Fonctions expérimentales + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Des fonctions encore en cours de création. Chacune reste désactivée jusqu'à ce que vous l'activiez ici, pour le lanceur et toutes les apps Craft. + Set by CRAFT_FLAGS for this run. Fixé par CRAFT_FLAGS pour ce lancement. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 989fded5..9860aa20 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -475,3 +475,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Hozzáadva Remove Eltávolítás Add Hozzáadás + Experimental features Kísérleti funkciók + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Még fejlesztés alatt álló funkciók. Mindegyik ki van kapcsolva, amíg itt be nem kapcsolja, az indítóban és minden Craft alkalmazásban. + Set by CRAFT_FLAGS for this run. Ehhez a futtatáshoz a CRAFT_FLAGS állítja be. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3fd76948..f82530c5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -477,3 +477,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 追加済み Remove 削除 Add 追加 + Experimental features 試験的な機能 + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 開発中の機能です。ここでオンにするまで、ランチャーとすべての Craft アプリでオフのままです。 + Set by CRAFT_FLAGS for this run. この起動では CRAFT_FLAGS で設定されています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fb031a1f..5663d10c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -473,3 +473,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added დამატებულია Remove წაშლა Add დამატება + Experimental features ექსპერიმენტული ფუნქციები + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. ფუნქციები, რომლებიც ჯერ კიდევ მზადდება. თითოეული გამორთულია, სანამ აქ არ ჩართავთ, გამშვებისა და ყველა Craft აპისთვის. + Set by CRAFT_FLAGS for this run. ამ გაშვებისთვის დაყენებულია CRAFT_FLAGS-ით. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 78d76751..a39bb265 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -476,3 +476,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Dodano Remove Usuń Add Dodaj + Experimental features Funkcje eksperymentalne + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funkcje, które wciąż powstają. Każda jest wyłączona, dopóki jej tu nie włączysz, dla launchera i każdej aplikacji Craft. + Set by CRAFT_FLAGS for this run. Ustawione przez CRAFT_FLAGS na to uruchomienie. diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 8c0a48d4..74396bfc 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -462,3 +462,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Adicionado Remove Remover Add Adicionar + Experimental features Recursos experimentais + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Recursos ainda em construção. Cada um fica desativado até você ativá-lo aqui, para o inicializador e todos os apps Craft. + Set by CRAFT_FLAGS for this run. Definido por CRAFT_FLAGS nesta execução. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f94e47ff..86721d68 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -470,3 +470,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Добавлено Remove Удалить Add Добавить + Experimental features Экспериментальные функции + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Функции, которые ещё в разработке. Каждая выключена, пока вы не включите её здесь, для лаунчера и всех приложений Craft. + Set by CRAFT_FLAGS for this run. Задано через CRAFT_FLAGS для этого запуска. diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 07e74560..bb882839 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -442,3 +442,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 已添加 Remove 移除 Add 添加 + Experimental features 实验性功能 + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 仍在开发中的功能。在此处开启前,它们在启动器和所有 Craft 应用中均处于关闭状态。 + Set by CRAFT_FLAGS for this run. 本次运行由 CRAFT_FLAGS 设定。 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index fb29726e..6b93f789 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -433,3 +433,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 已加入 Remove 移除 Add 加入 + Experimental features 實驗性功能 + Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 仍在開發中的功能。在此處開啟前,它們在啟動器和所有 Craft 應用程式中均為關閉。 + Set by CRAFT_FLAGS for this run. 本次執行由 CRAFT_FLAGS 設定。 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 347de1e4..6a47a88b 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -117,6 +117,7 @@ impl LauncherUi { this.settings_language(ui); this.settings_updates(ui); this.settings_appearance(ui); + this.settings_flags(ui); this.settings_agents(ui); this.settings_local_mcp(ui); }, @@ -376,7 +377,8 @@ impl LauncherUi { /// AI agents: one switch that lets MCP clients reach every installed Craft app through the /// `craft-ai-mcp` gateway, and one Add/Remove button per MCP client found on this machine. fn settings_agents(&mut self, ui: &mut Ui) { - if !self.caps.manage_apps { + // Behind the `AI-MCP` feature flag (Experimental features). + if !self.caps.manage_apps || !self.mcp_agents.flag_on { return; } let t = Tokens::get(ui.ctx()); @@ -406,6 +408,31 @@ impl LauncherUi { }); } + /// Experimental features: a switch per feature flag, shared with every Craft app. + fn settings_flags(&mut self, ui: &mut Ui) { + if !self.caps.manage_apps || self.flags.is_empty() { + return; + } + let t = Tokens::get(ui.ctx()); + let flags = self.flags.clone(); + sheet::panel(ui, tl!("Experimental features"), |ui| { + note(ui, tl!("Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app.")); + ui.add_space(8.0); + for f in &flags { + let mut on = f.on; + let toggle = ui.add_enabled(!f.forced, egui::Checkbox::new(&mut on, f.title.as_str())); + if toggle.changed() && on != f.on { + self.act_command(Command::SetFlag { id: f.id.clone(), on }); + } + ui.label(RichText::new(f.description.as_str()).size(12.0).color(t.muted)); + if f.forced { + ui.label(RichText::new(tl!("Set by CRAFT_FLAGS for this run.")).size(12.0).color(t.muted)); + } + ui.add_space(6.0); + } + }); + } + /// One MCP client: its name, and Add or Remove (or "Not installed" when it isn't). Add is /// offered only while the gateway is there to add. fn draw_client_row(&mut self, ui: &mut Ui, t: &Tokens, c: &McpClientState, can_add: bool) { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 438306a7..344d052b 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4422,6 +4422,7 @@ fn ai_agents_switch_and_client_buttons_send_their_commands() { services: vec![], bridge: McpBridge::default(), agents: McpAgents { + flag_on: true, gateway_found: true, enabled: true, apps: 3, @@ -4462,7 +4463,7 @@ fn ai_agents_without_the_gateway_offer_no_switch() { evs.push(Event::Mcp { services: vec![], bridge: artcraft_launcher_core::protocol::McpBridge::default(), - agents: artcraft_launcher_core::protocol::McpAgents::default(), + agents: artcraft_launcher_core::protocol::McpAgents { flag_on: true, ..Default::default() }, }); let (mut h, _sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); h.run_steps(6); @@ -4483,6 +4484,7 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { services: vec![], bridge: McpBridge::default(), agents: McpAgents { + flag_on: true, gateway_found: false, enabled: true, apps: 2, @@ -4504,3 +4506,32 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { assert!(sent.iter().any(|c| matches!(c, Command::McpSetClient { client: McpClient::Cursor, added: false }))); assert!(sent.iter().any(|c| matches!(c, Command::McpSetAgents { enabled: false }))); } + +/// With the `AI-MCP` flag off, Settings shows nothing about agents, only the flag to turn on. +#[test] +fn ai_agents_stay_hidden_until_their_flag_is_on() { + use artcraft_launcher_core::protocol::{FlagState, McpAgents, McpBridge}; + let flag = |id: &str, title: &str, on, forced| FlagState { id: id.into(), title: title.into(), description: "d".into(), on, forced }; + let mut evs = events(); + evs.push(Event::Flags { flags: vec![flag("AI-MCP", "AI agents (MCP)", false, false), flag("AI-MODELS", "AI models and services", false, true)] }); + evs.push(Event::Mcp { + services: vec![], + bridge: McpBridge::default(), + agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![] }, + }); + let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); + h.run_steps(6); + h.get_by_label("Settings").click(); + h.run_steps(4); + assert!(h.query_by_label("Let AI agents use Craft apps").is_none(), "no agents box without the flag"); + h.get_by_label("AI agents (MCP)").scroll_to_me(); + h.run_steps(6); + h.get_by_label("Set by CRAFT_FLAGS for this run."); + h.get_by_label("AI agents (MCP)").click(); + h.run_steps(3); + h.get_by_label("AI models and services").click(); + h.run_steps(3); + let sent = sent.borrow(); + assert!(sent.iter().any(|c| matches!(c, Command::SetFlag { id, on: true } if id == "AI-MCP"))); + assert!(!sent.iter().any(|c| matches!(c, Command::SetFlag { id, .. } if id == "AI-MODELS")), "a flag CRAFT_FLAGS sets can't be switched"); +} From 9bb5338e3b154182c4c34a6d3a8dbdcc0d76549e Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 16:14:11 +0100 Subject: [PATCH 12/27] build: pin craft-flags to its merge in craft-libs (86d6e8c5) --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad4df942..a40b2dca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -983,7 +983,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" dependencies = [ "rustix 1.1.5", ] @@ -991,7 +991,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6d6835dc888a270a96a575fba58ab01abf6c122#d6d6835dc888a270a96a575fba58ab01abf6c122" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" dependencies = [ "craft-atomic", "dirs 7.0.0", diff --git a/Cargo.toml b/Cargo.toml index 72ee697b..62a6bbb4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,8 +33,8 @@ semver = { version = "1", features = ["serde"] } log = "0.4" # All date/time conversion goes through jiff (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). jiff = "0.2" -# Feature flags (craft-libs#1118). Pinned to the pull request head craft-libs#1119 until it merges; re-pin then. -craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d6d6835dc888a270a96a575fba58ab01abf6c122" } +# Feature flags (craft-libs#1118, merged in craft-libs#1119). +craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-ui = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } From d631c5be977466799dac8371dbbd78e85723635f Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 16:55:21 +0100 Subject: [PATCH 13/27] fix(agents): second round of review findings - the gateway copy is compared byte for byte when the sizes match; a shipped build with an older timestamp still replaces it - MCP commands and every publication of the MCP state share one lock, so a state read before a command can't arrive after it - turning AI-MCP off cleans up first and writes the flag only then; a failed cleanup leaves the flag on and the controls to retry - ng-mcp.json: an entry added since the load is kept (only ids named as removed go), a `servers` that is not a list is never replaced, and entries of apps that are no longer installed are listed so they can be switched off - the bridge switch and port are disabled until the saved state is known, so a click can't overwrite a saved port with the default --- crates/native/src/agents.rs | 7 ++- crates/native/src/agents_tests.rs | 16 +++++ crates/native/src/backend.rs | 37 +++++++++--- crates/native/src/local_mcp.rs | 86 ++++++++++++++++++++++++--- crates/ui-egui/src/app.rs | 5 ++ crates/ui-egui/src/settings_dialog.rs | 6 +- 6 files changed, 134 insertions(+), 23 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index f11dbb50..0e17e919 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -175,7 +175,8 @@ pub fn gateway_copy(dir: &Path) -> PathBuf { pub fn install_gateway(src: &Path, dir: &Path) -> Result { let dest = gateway_copy(dir); let current = match (std::fs::metadata(src), std::fs::metadata(&dest)) { - (Ok(a), Ok(b)) => a.len() == b.len() && matches!((a.modified(), b.modified()), (Ok(ma), Ok(mb)) if mb >= ma), + // Same size: compare the bytes (a shipped build can keep an older timestamp). + (Ok(a), Ok(b)) => a.len() == b.len() && matches!((std::fs::read(src), std::fs::read(&dest)), (Ok(x), Ok(y)) if x == y), (Err(e), _) => return Err(format!("couldn't read the Craft gateway at {} ({e})", src.display())), _ => false, }; @@ -270,11 +271,11 @@ pub fn flags_state() -> Vec { /// agents off, so no client keeps an entry for a feature that is switched off. pub fn set_flag(id: &str, on: bool, services: &[LocalService]) -> Result<(), String> { let path = craft_flags::default_path().ok_or("couldn't find the per-user configuration folder")?; - craft_flags::set(&path, id, on).map_err(|e| e.to_string())?; + // Clean up first: if that fails, the flag stays on and Settings keeps the controls to retry. if id == craft_flags::AI_MCP.id && !on { set_enabled(false, services)?; } - Ok(()) + craft_flags::set(&path, id, on).map_err(|e| e.to_string()) } const NO_GATEWAY: &str = "the Craft gateway (craft-ai-mcp) is not installed beside the launcher"; diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 0bc2dc0e..3f52b4ab 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -152,3 +152,19 @@ fn the_gateway_copy_is_executable() { let copy = install_gateway(&src, dir.path()).unwrap(); assert_eq!(std::fs::metadata(copy).unwrap().permissions().mode() & 0o111, 0o111); } + +#[test] +fn a_gateway_of_the_same_size_but_other_bytes_replaces_the_copy() { + let src_dir = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let src = src_dir.path().join("craft-ai-mcp"); + std::fs::write(&src, b"aaaa").unwrap(); + let copy = install_gateway(&src, dir.path()).unwrap(); + // A new build of the same size whose timestamp is older than the copy. + std::fs::write(&src, b"bbbb").unwrap(); + let old = std::fs::File::options().write(true).open(&src).unwrap(); + old.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000)).unwrap(); + drop(old); + install_gateway(&src, dir.path()).unwrap(); + assert_eq!(std::fs::read(©).unwrap(), b"bbbb"); +} diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index d0f95e4c..122e9f02 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -359,8 +359,11 @@ impl NativeBackend { report_partial(app, &shared, &paths, platform); } // Local MCP state: which installed apps can be exposed + the unified bridge. - shared.emit(Event::Flags { flags: crate::agents::flags_state() }); - shared.emit(mcp_state(&shared)); + { + let _mcp = MCP_WORK.lock().unwrap_or_else(PoisonError::into_inner); + shared.emit(Event::Flags { flags: crate::agents::flags_state() }); + shared.emit(mcp_state(&shared)); + } drop(busy); }); } @@ -1670,7 +1673,7 @@ fn mcp_state_for(detected: &[local_mcp::LocalService]) -> Event { None => vec![], }; - let services = detected + let services: Vec = detected .iter() .map(|s| McpService { id: s.id.clone(), @@ -1678,6 +1681,12 @@ fn mcp_state_for(detected: &[local_mcp::LocalService]) -> Event { command: s.cli_path.as_ref().map(|c| c.display().to_string()).unwrap_or_default(), enabled: local_mcp::service_enabled(&existing, &s.name), }) + .chain(local_mcp::orphaned_entries(&existing, detected).into_iter().map(|(id, name, enabled)| McpService { + id, + name, + command: String::new(), + enabled, + })) .collect(); let bridge_path = local_mcp::locate_bridge(); @@ -1693,24 +1702,34 @@ fn mcp_state_for(detected: &[local_mcp::LocalService]) -> Event { } } +/// Serialises MCP commands and every publication of the MCP state, so a state read before a +/// command can't arrive after that command's own (newer) state. +static MCP_WORK: Mutex<()> = Mutex::new(()); + /// One MCP command, on a worker thread. Commands run one at a time, so a toggle and a refresh /// never write `ng-mcp.json` or the client configurations at once; detection runs once per /// command, and the new state is sent when it is done. fn run_mcp(shared: &Shared, cmd: Command) { - static MCP_WORK: Mutex<()> = Mutex::new(()); let _guard = MCP_WORK.lock().unwrap_or_else(PoisonError::into_inner); let services = detected_services(shared); let result = match cmd { Command::McpSetService { service_id, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { let mut servers = local_mcp::load_servers(&p); - if let Some(s) = services.iter().find(|s| s.id == service_id) { - if enabled { + match services.iter().find(|s| s.id == service_id) { + Some(s) if enabled => { local_mcp::enable_service(&mut servers, s); - } else { + } + Some(s) => { local_mcp::disable_service(&mut servers, s); } + // An app no longer installed: its saved entry can still be switched off. + None if !enabled => { + let gone = local_mcp::LocalService { id: service_id, name: String::new(), location: String::new(), cli_path: None }; + local_mcp::disable_service(&mut servers, &gone); + } + None => {} } - local_mcp::save_servers(&p, &servers) + local_mcp::save_servers(&p, &servers, &[]) }), Command::McpSetBridge { port, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { let mut servers = local_mcp::load_servers(&p); @@ -1719,7 +1738,7 @@ fn run_mcp(shared: &Shared, cmd: Command) { } else { local_mcp::disable_bridge(&mut servers); } - local_mcp::save_servers(&p, &servers) + local_mcp::save_servers(&p, &servers, &[]) }), Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &services), Command::McpSetClient { client, added } => crate::agents::set_client(client, added), diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs index 80281cd7..d52a8af6 100644 --- a/crates/native/src/local_mcp.rs +++ b/crates/native/src/local_mcp.rs @@ -95,7 +95,7 @@ pub fn load_servers(path: &Path) -> Vec { /// Save `servers` back to the config file, preserving any top-level keys other than `servers`. /// Writes atomically (temp file + rename) so a crash never leaves a half-written config. -pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> { +pub fn save_servers(path: &Path, servers: &[ServerEntry], removed: &[&str]) -> Result<(), String> { // Distinguish "no config yet" (safe to create) from "a config exists but is not valid JSON" // (refuse rather than clobber it). A file we cannot read as JSON may hold content the user // cares about; overwriting it would be a lossy write. @@ -106,8 +106,13 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> }, Err(_) => None, // missing (or unreadable): start fresh }; - let old = existing.as_ref().and_then(|v| v.get("servers")).and_then(serde_json::Value::as_array).map(Vec::as_slice).unwrap_or_default(); - let array = merge_servers(old, servers)?; + // A `servers` that is not a list is not ours to replace. + let old = match existing.as_ref().and_then(|v| v.get("servers")) { + None => &[][..], + Some(serde_json::Value::Array(a)) => a.as_slice(), + Some(_) => return Err(format!("`servers` in {} is not a list; refusing to overwrite it", path.display())), + }; + let array = merge_servers(old, servers, removed)?; // Preserve any top-level keys other than `servers`; replace the array. If the file was not // a JSON object, it is not an `ng-mcp.json` shape and starts fresh. let mut map = serde_json::Map::new(); @@ -126,8 +131,9 @@ pub fn save_servers(path: &Path, servers: &[ServerEntry]) -> Result<(), String> /// The new `servers` array: `servers` merged into the file's `old` entries. An entry this module /// cannot read (another connection type, a missing field, a shape Bionic adds later) is kept as /// it is and where it was; an entry it manages keeps any field it doesn't know; an entry it can -/// read but that is no longer in `servers` was removed on purpose and is left out. -fn merge_servers(old: &[serde_json::Value], servers: &[ServerEntry]) -> Result, String> { +/// read but that is not in `servers` stays too (another program may have added it since `servers` +/// was loaded), unless its id is in `removed`. +fn merge_servers(old: &[serde_json::Value], servers: &[ServerEntry], removed: &[&str]) -> Result, String> { let mut used = vec![false; servers.len()]; let mut out = Vec::with_capacity(old.len().max(servers.len())); for raw in old { @@ -137,6 +143,9 @@ fn merge_servers(old: &[serde_json::Value], servers: &[ServerEntry]) -> Result serde_json::Value serde_json::Value::Object(merged) } +/// Entries this module added (`craft-ai-mcp-`) for apps that are no longer installed, as +/// `(app id, name, enabled)`, so Settings can still switch them off. +pub fn orphaned_entries(servers: &[ServerEntry], installed: &[LocalService]) -> Vec<(String, String, bool)> { + servers + .iter() + .filter_map(|e| { + let id = e.id.strip_prefix("craft-ai-mcp-")?; + let known = installed.iter().any(|s| s.id == id || s.name == e.name); + (!known && is_stdio(e)).then(|| (id.to_string(), e.name.clone(), e.enabled)) + }) + .collect() +} + /// Every Craft App that has a usable CLI on this machine, in suite order. Detection is the single /// source of truth for "installed"; this just adds the CLI path each app would expose to MCP. pub fn installed_services(manifest: &Manifest, snapshot: &detect::Snapshot) -> Vec { @@ -525,7 +547,7 @@ mod tests { env: HashMap::new(), }, }]; - assert!(save_servers(&path, &servers).is_ok()); + assert!(save_servers(&path, &servers, &[]).is_ok()); let loaded = load_servers(&path); assert_eq!(loaded.len(), 1); @@ -564,7 +586,7 @@ mod tests { fn save_creates_the_file_when_it_is_missing() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("ng-mcp.json"); - assert!(save_servers(&path, &[]).is_ok()); + assert!(save_servers(&path, &[], &[]).is_ok()); assert_eq!(load_servers(&path), vec![]); } @@ -589,7 +611,7 @@ mod tests { if let Some(w) = servers.iter_mut().find(|s| s.id == "craft-ai-mcp-wordcraft") { w.enabled = false; } - save_servers(&path, &servers).unwrap(); + save_servers(&path, &servers, &["gone"]).unwrap(); let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); let ids: Vec<&str> = v["servers"].as_array().unwrap().iter().filter_map(|e| e["id"].as_str()).collect(); assert_eq!(ids, vec!["third", "sse", "craft-ai-mcp-wordcraft"], "unreadable entries stay in place; a removed one goes"); @@ -600,6 +622,52 @@ mod tests { assert!(v["servers"][0]["connection"].get("env").is_none(), "an entry without env is left as it was"); } + #[test] + fn save_keeps_an_entry_added_since_the_load_and_refuses_a_servers_object() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("ng-mcp.json"); + let entry = |id: &str| { + format!( + r#"{{"id":"{id}","name":"{id}","description":"","enabled":true,"connection":{{"type":"stdio","command":"x","args":[],"env":{{}}}}}}"# + ) + }; + std::fs::write(&path, format!(r#"{{"servers":[{}]}}"#, entry("mine"))).unwrap(); + let mut servers = load_servers(&path); + // Another program adds an entry after the load. + std::fs::write(&path, format!(r#"{{"servers":[{},{}]}}"#, entry("mine"), entry("theirs"))).unwrap(); + if let Some(s) = servers.first_mut() { + s.enabled = false; + } + save_servers(&path, &servers, &[]).unwrap(); + let ids: Vec = load_servers(&path).into_iter().map(|s| s.id).collect(); + assert_eq!(ids, vec!["mine", "theirs"], "the entry added since is kept"); + + let obj = dir.path().join("obj.json"); + let text = r#"{"servers":{"third-party":{"command":"x"}}}"#; + std::fs::write(&obj, text).unwrap(); + assert!(save_servers(&obj, &[], &[]).is_err()); + assert_eq!(std::fs::read_to_string(&obj).unwrap(), text, "left as it was"); + } + + #[test] + fn entries_of_apps_no_longer_installed_are_listed() { + let entry = |id: &str, name: &str| ServerEntry { + id: id.into(), + name: name.into(), + description: String::new(), + enabled: true, + connection: Connection::Stdio { command: "/x".into(), args: vec![], env: HashMap::new() }, + }; + let servers = vec![entry("craft-ai-mcp-wordcraft", "WordCraft"), entry("craft-ai-mcp-gone", "GoneCraft"), entry("other", "Other")]; + let installed = vec![LocalService { id: "wordcraft".into(), name: "WordCraft".into(), location: String::new(), cli_path: None }]; + assert_eq!(orphaned_entries(&servers, &installed), vec![("gone".to_string(), "GoneCraft".to_string(), true)]); + // Switching it off finds it by its id even without a name. + let mut servers = servers; + let gone = LocalService { id: "gone".into(), name: String::new(), location: String::new(), cli_path: None }; + assert!(disable_service(&mut servers, &gone)); + assert!(!servers.iter().any(|s| s.id == "craft-ai-mcp-gone" && s.enabled)); + } + #[test] fn save_refuses_to_overwrite_a_malformed_config() { let dir = tempfile::tempdir().unwrap(); @@ -614,7 +682,7 @@ mod tests { enabled: true, connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, }]; - let err = save_servers(&path, &servers).unwrap_err(); + let err = save_servers(&path, &servers, &[]).unwrap_err(); assert!(err.contains("not valid JSON"), "{err}"); // The original bytes are still on disk. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0e1f83bb..a7897de6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -147,6 +147,9 @@ pub struct LauncherUi { /// unified HTTP bridge. Empty until the first [`Event::Mcp`]. pub(crate) mcp_services: Vec, pub(crate) mcp_bridge: McpBridge, + /// The first MCP state arrived: until then the bridge's switch and port show defaults, not + /// the saved setup, and stay disabled. + pub(crate) mcp_state_known: bool, /// AI agents: the gateway switch and the MCP clients. pub(crate) mcp_agents: McpAgents, /// The feature flags (Settings › Experimental features). @@ -283,6 +286,7 @@ impl LauncherUi { .collect(), mcp_services: Vec::new(), mcp_bridge: McpBridge::default(), + mcp_state_known: false, mcp_agents: McpAgents::default(), flags: Vec::new(), bridge_port: String::new(), @@ -667,6 +671,7 @@ impl LauncherUi { } Event::Mcp { services, bridge, agents } => { self.mcp_agents = agents; + self.mcp_state_known = true; let port = bridge.port; self.mcp_services = services; self.mcp_bridge = bridge; diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 6a47a88b..09319d99 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -464,8 +464,10 @@ impl LauncherUi { note(ui, tl!("Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools.")); ui.add_space(8.0); - // Unified bridge (HTTP): editable port + toggle; status shown below the row. - self.draw_bridge_row(ui, &t); + // Unified bridge (HTTP): editable port + toggle; status shown below the row. Disabled + // until the saved state is known, so a click can't overwrite a saved port. + let known = self.mcp_state_known; + ui.add_enabled_ui(known, |ui| self.draw_bridge_row(ui, &t)); ui.add_space(12.0); // Per-app stdio services in a collapsible section. From 439249d1b8279d63c0ca2c56b6528b81c3001e54 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 18:58:42 +0100 Subject: [PATCH 14/27] feat(packaging): ship the craft-ai-mcp gateway beside the launcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit apps/craft-ai-mcp builds the gateway from storytold/craft-ai-integrations (crates/ai-mcp, craft_ai_mcp::cli) as craft-ai-mcp, and every package puts it beside the launcher, where Settings › AI agents finds it: - Windows: built with the launcher, PE-checked as a console program, signed, in the MSI (the launcher's component) and the portable zip; listed in the install policy's payloads - macOS: lipo'd and placed in Contents/MacOS, signed with the hardened runtime before the main executable - Linux: /usr/bin in the deb and rpm (nfpm), the tarball and the AppImage; /app/bin in both Flatpak manifests - FreeBSD: bin/, checked like the launcher The gateway needs only serde, serde_json and dirs. It is pinned to the head of storytold/craft-ai-integrations#197 until that merges. --- Cargo.lock | 17 ++++++++++++++++ apps/craft-ai-mcp/Cargo.toml | 20 +++++++++++++++++++ apps/craft-ai-mcp/src/main.rs | 15 ++++++++++++++ packaging/freebsd/package.sh | 9 +++++++-- ...i.storyteller.artcraft-launcher.bundle.yml | 1 + .../ai.storyteller.artcraft-launcher.yml | 3 ++- packaging/linux/nfpm.yaml | 4 ++++ packaging/linux/package.sh | 7 +++++-- packaging/macos/package.sh | 15 ++++++++++++-- packaging/windows/artcraft-launcher.wxs | 3 +++ packaging/windows/install-policy.json | 3 ++- packaging/windows/package.ps1 | 13 +++++++++++- 12 files changed, 101 insertions(+), 9 deletions(-) create mode 100644 apps/craft-ai-mcp/Cargo.toml create mode 100644 apps/craft-ai-mcp/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index a40b2dca..ad1f2ad3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,6 +310,13 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "artcraft-launcher-mcp" +version = "0.19.2" +dependencies = [ + "craft-ai-mcp", +] + [[package]] name = "artcraft-launcher-native" version = "0.19.2" @@ -980,6 +987,16 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-ai-mcp" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=dd6c269a1248b5a5e56d3489bc8666a54017fc6b#dd6c269a1248b5a5e56d3489bc8666a54017fc6b" +dependencies = [ + "dirs 7.0.0", + "serde", + "serde_json", +] + [[package]] name = "craft-atomic" version = "0.1.0" diff --git a/apps/craft-ai-mcp/Cargo.toml b/apps/craft-ai-mcp/Cargo.toml new file mode 100644 index 00000000..1cbdb511 --- /dev/null +++ b/apps/craft-ai-mcp/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "artcraft-launcher-mcp" +description = "The craft-ai-mcp gateway, built and shipped with the ArtCraft Launcher (Settings › AI agents)" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish = false + +[lints] +workspace = true + +[[bin]] +name = "craft-ai-mcp" +path = "src/main.rs" + +# The gateway from storytold/craft-ai-integrations (crates/ai-mcp), pinned like the craft-libs crates. +# Pinned to the head of storytold/craft-ai-integrations#197 until it merges; re-pin then. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "dd6c269a1248b5a5e56d3489bc8666a54017fc6b" } diff --git a/apps/craft-ai-mcp/src/main.rs b/apps/craft-ai-mcp/src/main.rs new file mode 100644 index 00000000..5881d344 --- /dev/null +++ b/apps/craft-ai-mcp/src/main.rs @@ -0,0 +1,15 @@ +//! `craft-ai-mcp`: the gateway through which MCP clients (Claude, Cursor, LM Studio) reach every +//! installed Craft app. The ArtCraft Launcher ships it beside itself; Settings › AI agents copies +//! it into `ArtCraft/mcp/bin` and registers that copy (`artcraft_launcher_native::agents`). The +//! program itself is `craft_ai_mcp::cli` from storytold/craft-ai-integrations. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + craft_ai_mcp::cli::main(std::env::args().skip(1).collect()) +} + +/// Desktop only: nothing to run in the browser build. +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 114edc78..8aa81b9d 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -57,7 +57,7 @@ echo "==> ArtCraft Launcher $VERSION for FreeBSD $ARCH" export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" if [[ "$SKIP_BUILD" = 0 ]]; then - (cd "$ROOT" && cargo build --release --locked -p "$PKG" ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"}) + (cd "$ROOT" && cargo build --release --locked -p "$PKG" -p artcraft-launcher-mcp ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"}) fi WORK="$CARGO_TARGET_DIR/freebsd-package" STAGE="$WORK/$BASENAME" @@ -74,6 +74,8 @@ if [[ "$DRY_RUN" = 1 ]]; then mkdir -p "$BIN" printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$PKG" "$VERSION" >"$BIN/$PKG" chmod 755 "$BIN/$PKG" + printf '#!/bin/sh\necho "craft-ai-mcp (dry-run stub)"\n' >"$BIN/craft-ai-mcp" + chmod 755 "$BIN/craft-ai-mcp" fi # ---- stage a /usr/local-style tree -------------------------------------------------------------- @@ -82,6 +84,9 @@ mkdir -p "$STAGE/bin" "$STAGE/share/applications" "$STAGE/share/metainfo" "$STAG "$STAGE/share/doc/$PKG" install -m 755 "$BIN/$PKG" "$STAGE/bin/" strip "$STAGE/bin/$PKG" 2>/dev/null || true +# The craft-ai-mcp gateway the launcher ships (Settings › AI agents), beside the launcher. +install -m 755 "$BIN/craft-ai-mcp" "$STAGE/bin/" +strip "$STAGE/bin/craft-ai-mcp" 2>/dev/null || true # The desktop entry, metainfo and icons are the freedesktop files Linux ships. install -m 644 "$LINUX/$APP_ID.desktop" "$STAGE/share/applications/$APP_ID.desktop" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$ARTCRAFT_LAUNCHER_BUILD_DATE/g" \ @@ -89,7 +94,7 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$ARTCRAFT_LAUNCHER_BUILD_DATE/g" \ cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/$PKG" -for f in "bin/$PKG" "share/applications/$APP_ID.desktop" \ +for f in "bin/$PKG" "bin/craft-ai-mcp" "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ "share/doc/$PKG/LICENSE-MIT" "share/doc/$PKG/LICENSE-APACHE"; do if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi diff --git a/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.bundle.yml b/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.bundle.yml index 2a523f67..49b9f7ed 100644 --- a/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.bundle.yml @@ -61,6 +61,7 @@ modules: buildsystem: simple build-commands: - install -Dm755 bin/artcraft-launcher /app/bin/artcraft-launcher + - install -Dm755 bin/craft-ai-mcp /app/bin/craft-ai-mcp - install -Dm644 share/applications/ai.storyteller.artcraft-launcher.desktop /app/share/applications/ai.storyteller.artcraft-launcher.desktop # Already has the release's version and date substituted by package.sh. - install -Dm644 share/metainfo/ai.storyteller.artcraft-launcher.metainfo.xml /app/share/metainfo/ai.storyteller.artcraft-launcher.metainfo.xml diff --git a/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.yml b/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.yml index a0572916..070edd20 100644 --- a/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.yml +++ b/packaging/linux/flatpak/ai.storyteller.artcraft-launcher.yml @@ -68,8 +68,9 @@ modules: CARGO_HOME: /run/build/artcraft-launcher/cargo CARGO_NET_OFFLINE: 'true' build-commands: - - cargo --offline build --release --locked -p artcraft-launcher + - cargo --offline build --release --locked -p artcraft-launcher -p artcraft-launcher-mcp - install -Dm755 target/release/artcraft-launcher /app/bin/artcraft-launcher + - install -Dm755 target/release/craft-ai-mcp /app/bin/craft-ai-mcp - install -Dm644 NOTICE /app/share/doc/artcraft-launcher/NOTICE - install -Dm644 packaging/linux/ai.storyteller.artcraft-launcher.desktop /app/share/applications/ai.storyteller.artcraft-launcher.desktop - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index f159039d..dc191339 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -70,6 +70,10 @@ contents: - src: ${STAGE}/usr/bin/artcraft-launcher dst: /usr/bin/artcraft-launcher file_info: { mode: 0755 } + # The craft-ai-mcp gateway the launcher ships (Settings › AI agents). + - src: ${STAGE}/usr/bin/craft-ai-mcp + dst: /usr/bin/craft-ai-mcp + file_info: { mode: 0755 } - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index cedbc778..ddaa86dc 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -64,9 +64,9 @@ echo "==> ArtCraft Launcher $VERSION for Linux $ARCH ($FORMATS)" if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then - (cd "$ROOT" && cargo build --release --locked -p "$PKG" --target "$CROSS_TARGET") + (cd "$ROOT" && cargo build --release --locked -p "$PKG" -p artcraft-launcher-mcp --target "$CROSS_TARGET") else - (cd "$ROOT" && cargo build --release --locked -p "$PKG") + (cd "$ROOT" && cargo build --release --locked -p "$PKG" -p artcraft-launcher-mcp) fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" @@ -77,6 +77,9 @@ rm -rf "$WORK" # ---- stage an FHS tree (shared by every format) ------------------------------------------------- install -Dm755 "$BIN/$PKG" "$STAGE/usr/bin/$PKG" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/$PKG" 2>/dev/null || true +# The craft-ai-mcp gateway the launcher ships (Settings › AI agents), beside the launcher. +install -Dm755 "$BIN/craft-ai-mcp" "$STAGE/usr/bin/craft-ai-mcp" +"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/craft-ai-mcp" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$ARTCRAFT_LAUNCHER_BUILD_DATE/g" \ diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index e9409d35..c2fe1ca5 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -18,6 +18,8 @@ HERE="$ROOT/packaging/macos" # ---- app-specific values ---------------------------------------------------------------------- PKG=artcraft-launcher # cargo package and binary +GATEWAY_PKG=artcraft-launcher-mcp # cargo package of the craft-ai-mcp gateway the launcher ships +GATEWAY_BIN=craft-ai-mcp # its binary, placed beside the launcher in Contents/MacOS APP_NAME="ArtCraft Launcher" # display name: bundle, executable, icon, DMG volume ARCH=universal @@ -60,7 +62,8 @@ echo "==> $APP_NAME $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $ if [[ "$SKIP_BUILD" = 0 ]]; then args=() for t in "${TARGETS[@]}"; do args+=(--target "$t"); done - (cd "$ROOT" && cargo build --release --locked -p "$PKG" "${args[@]}") + # The launcher and the craft-ai-mcp gateway it ships (Settings › AI agents). + (cd "$ROOT" && cargo build --release --locked -p "$PKG" -p "$GATEWAY_PKG" "${args[@]}") fi rm -rf "$WORK" @@ -69,6 +72,10 @@ inputs=() for t in "${TARGETS[@]}"; do inputs+=("$CARGO_TARGET_DIR/$t/release/$PKG"); done lipo -create -output "$WORK/bin/$PKG" "${inputs[@]}" lipo -info "$WORK/bin/$PKG" +gw_inputs=() +for t in "${TARGETS[@]}"; do gw_inputs+=("$CARGO_TARGET_DIR/$t/release/$GATEWAY_BIN"); done +lipo -create -output "$WORK/bin/$GATEWAY_BIN" "${gw_inputs[@]}" +lipo -info "$WORK/bin/$GATEWAY_BIN" # ---- signing helpers --------------------------------------------------------------------------- sign() { @@ -117,6 +124,8 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/$PKG" "$APP/Contents/MacOS/$APP_NAME" +# Beside the launcher, where Settings › AI agents looks for it (agents::locate_gateway). +cp "$WORK/bin/$GATEWAY_BIN" "$APP/Contents/MacOS/$GATEWAY_BIN" cp "$ROOT/assets/app-icon/$PKG.icns" "$APP/Contents/Resources/$APP_NAME.icns" cp "$ROOT/NOTICE" "$APP/Contents/Resources/" sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \ @@ -134,7 +143,9 @@ printf 'APPL????' >"$APP/Contents/PkgInfo" xattr -cr "$APP" # Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature). -# Today the only nested code is the main executable; frameworks/helpers would be signed here too. +# Nested code: the craft-ai-mcp gateway (a command-line helper, no entitlements) and the main +# executable; frameworks/helpers would be signed here too. +sign --options runtime "$APP/Contents/MacOS/$GATEWAY_BIN" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/$APP_NAME" sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" diff --git a/packaging/windows/artcraft-launcher.wxs b/packaging/windows/artcraft-launcher.wxs index 4cceff27..913ad144 100644 --- a/packaging/windows/artcraft-launcher.wxs +++ b/packaging/windows/artcraft-launcher.wxs @@ -155,6 +155,9 @@ + + diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json index 3f9d6176..9e2018d2 100644 --- a/packaging/windows/install-policy.json +++ b/packaging/windows/install-policy.json @@ -16,7 +16,8 @@ ], "payloads": [ "NOTICE", - "artcraft-launcher.exe" + "artcraft-launcher.exe", + "craft-ai-mcp.exe" ], "registry": [ [ diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 9d813918..7fda278f 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -29,6 +29,8 @@ $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path # ---- app-specific values ---------------------------------------------------------------------- $Pkg = 'artcraft-launcher' # cargo package and binary +$GatewayPkg = 'artcraft-launcher-mcp' # cargo package of the shipped craft-ai-mcp gateway +$GatewayExe = 'craft-ai-mcp.exe' $AppName = 'ArtCraft Launcher' # display name function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -67,7 +69,8 @@ if (-not $SkipBuild) { [Environment]::SetEnvironmentVariable($flagVar, '-C target-feature=+crt-static') # Fail the build (rather than warn) if the icon/VERSIONINFO can't be embedded. $env:ARTCRAFT_LAUNCHER_REQUIRE_WINRES = '1' - Invoke-Native "cargo build ($Target)" { cargo build --release --locked -p $Pkg --target $Target } + # The launcher and the craft-ai-mcp gateway it ships (Settings › AI agents). + Invoke-Native "cargo build ($Target)" { cargo build --release --locked -p $Pkg -p $GatewayPkg --target $Target } } $Bin = Join-Path $TargetDir "$Target\release" @@ -86,6 +89,11 @@ $h = Get-PeHeader (Join-Path $Bin $Exe) if ($h.Machine -ne $Machine) { throw "$Exe is for machine 0x$('{0:X}' -f $h.Machine), expected 0x$('{0:X}' -f $Machine) ($Arch)" } if ($h.Subsystem -ne 2) { throw "$Exe has PE subsystem $($h.Subsystem), expected 2 (Windows GUI)" } Write-Output "ok ${Exe}: $Arch, PE subsystem $($h.Subsystem)" +# The gateway talks to MCP clients over stdin and stdout, so it stays a console program (3). +$g = Get-PeHeader (Join-Path $Bin $GatewayExe) +if ($g.Machine -ne $Machine) { throw "$GatewayExe is for machine 0x$('{0:X}' -f $g.Machine), expected 0x$('{0:X}' -f $Machine) ($Arch)" } +if ($g.Subsystem -ne 3) { throw "$GatewayExe has PE subsystem $($g.Subsystem), expected 3 (console)" } +Write-Output "ok ${GatewayExe}: $Arch, PE subsystem $($g.Subsystem)" $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue @@ -93,8 +101,10 @@ New-Item -ItemType Directory -Force -Path $Stage | Out-Null # Dependency font notices are required even without optional craft-fonts. Copy-Item -LiteralPath (Join-Path $Root 'NOTICE') -Destination $Stage Copy-Item (Join-Path $Bin $Exe) $Stage +Copy-Item (Join-Path $Bin $GatewayExe) $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage $Exe) +& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage $GatewayExe) # ---- MSI --------------------------------------------------------------------------------------- # The setup wizard's art, drawn here (System.Drawing) in getartcraft.com's style so the MSI shows @@ -197,6 +207,7 @@ $Portable = Join-Path $TargetDir "windows-package\$Pkg-$Version-windows-$Arch-po Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage $Exe) $Portable +Copy-Item (Join-Path $Stage $GatewayExe) $Portable foreach ($f in 'README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } From e61b229c3adbb725024cc2f8e00c680475c79c2c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 19:11:15 +0100 Subject: [PATCH 15/27] refactor(settings): drop Local services; AI agents is the one MCP setting The Local services box from #1296 managed one LM Studio/Bionic entry per app and an HTTP bridge on port 12345 that craft-ai-mcp no longer serves. Both are replaced by the gateway: one craft-ai-mcp entry per MCP client. Removed: local_mcp.rs, the McpSetService/McpSetBridge commands, the McpService/McpBridge state, the Local services box and its strings. Kept, in agents.rs: detecting the installed apps and their CLIs (InstalledApp) and finding craft-ai-mcp beside the launcher (ARTCRAFT_LAUNCHER_GATEWAY_PATH for development). Event::Mcp carries the AI agents state only. --- crates/core/src/protocol.rs | 40 +- crates/native/src/agents.rs | 73 +- crates/native/src/agents_tests.rs | 4 +- crates/native/src/backend.rs | 101 +-- crates/native/src/lib.rs | 1 - crates/native/src/local_mcp.rs | 996 -------------------------- crates/ui-egui/src/app.rs | 30 +- crates/ui-egui/src/i18n/cs.tsv | 16 - crates/ui-egui/src/i18n/de.tsv | 16 - crates/ui-egui/src/i18n/es.tsv | 16 - crates/ui-egui/src/i18n/fr.tsv | 16 - crates/ui-egui/src/i18n/hu.tsv | 16 - crates/ui-egui/src/i18n/ja.tsv | 16 - crates/ui-egui/src/i18n/ka.tsv | 16 - crates/ui-egui/src/i18n/pl.tsv | 16 - crates/ui-egui/src/i18n/pt-BR.tsv | 16 - crates/ui-egui/src/i18n/ru.tsv | 16 - crates/ui-egui/src/i18n/zh-CN.tsv | 16 - crates/ui-egui/src/i18n/zh-TW.tsv | 16 - crates/ui-egui/src/settings_dialog.rs | 80 +-- crates/ui-egui/tests/ui.rs | 22 +- 21 files changed, 94 insertions(+), 1445 deletions(-) delete mode 100644 crates/native/src/local_mcp.rs diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 2c210735..b76eba99 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -73,18 +73,8 @@ pub enum Command { /// Change how the backend behaves. Configure(BackendOptions), - /// Ask for the current state of the local MCP services (installed apps + unified bridge). + /// Ask for the AI agents state (the gateway, the switch, the MCP clients). McpState, - /// Turn an installed app's stdio MCP entry on or off in LM Studio's config. - McpSetService { - service_id: String, - enabled: bool, - }, - /// Turn the unified-bridge HTTP MCP entry on or off at `port`. - McpSetBridge { - port: u16, - enabled: bool, - }, /// Let AI agents use the Craft apps (writes the gateway's app list), or stop them (removes the /// list and the client entries the launcher added). McpSetAgents { @@ -314,15 +304,12 @@ pub enum Event { rate_limited_until: Option, }, - /// The local MCP services: which installed apps can be exposed as stdio servers, their current - /// on/off state in LM Studio's config, plus the unified HTTP bridge (found? version? port? - /// enabled?). Sent after detection and after any change, so the settings panel is always in sync. + /// The AI agents state: the gateway, the switch and the MCP clients. Sent when Settings asks, + /// after detection and after any change. Mcp { - services: Vec, - bridge: McpBridge, agents: McpAgents, }, - /// A local MCP operation failed (e.g. writing `ng-mcp.json`). Carries a short, user-facing + /// An AI agents operation failed (e.g. writing a client configuration). Carries a short, user-facing /// message; the UI shows it as an error toast so a failed toggle is never silent. McpError { message: String, @@ -333,25 +320,6 @@ pub enum Event { }, } -/// One installed app that can be exposed as a stdio MCP server. `command` is the CLI path the -/// host would spawn; `enabled` is its current state in LM Studio's config. -#[derive(Clone, Debug, PartialEq)] -pub struct McpService { - pub id: String, - pub name: String, - pub command: String, - pub enabled: bool, -} - -/// The unified HTTP bridge. `found` when its binary exists on this machine; `version` when readable. -#[derive(Clone, Debug, PartialEq, Default)] -pub struct McpBridge { - pub found: bool, - pub version: Option, - pub port: u16, - pub enabled: bool, -} - /// One feature flag as Settings shows it. #[derive(Clone, Debug, PartialEq)] pub struct FlagState { diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 0e17e919..6a3c9333 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -15,7 +15,10 @@ use std::sync::{Mutex, MutexGuard, PoisonError}; use artcraft_launcher_core::protocol::{FlagState, McpAgents, McpClient, McpClientState}; use serde_json::{Map, Value, json}; -use crate::local_mcp::LocalService; +use artcraft_launcher_core::CraftApp; + +use crate::detect; +use crate::manifest::Manifest; /// The app list the gateway reads. pub const APPS_FILE: &str = "apps.json"; @@ -37,7 +40,7 @@ pub fn mcp_dir() -> Option { /// The app list for `services`: each app with a CLI, started as ` mcp`. Apps without a CLI /// beside them are left out. -pub fn apps_json(services: &[LocalService]) -> Value { +pub fn apps_json(services: &[InstalledApp]) -> Value { let apps: Vec = services .iter() .filter_map(|s| { @@ -54,7 +57,7 @@ pub fn enabled(dir: &Path) -> bool { } /// Write (or refresh) the app list in `dir`. -pub fn write_apps(dir: &Path, services: &[LocalService]) -> Result<(), String> { +pub fn write_apps(dir: &Path, services: &[InstalledApp]) -> Result<(), String> { let text = serde_json::to_string_pretty(&apps_json(services)).map_err(|e| e.to_string())?; crate::paths::write_atomic(&dir.join(APPS_FILE), text.as_bytes()) } @@ -153,10 +156,62 @@ pub fn unregister(config: &Path) -> Result<(), String> { crate::paths::write_atomic(config, text.as_bytes()) } -/// The `craft-ai-mcp` gateway binary as shipped: beside the launcher, or -/// `ARTCRAFT_LAUNCHER_BRIDGE_PATH`. +/// An installed Craft app, with the CLI beside it that serves MCP (`-cli mcp`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstalledApp { + /// The app id (`wordcraft`), stable across versions. + pub id: String, + /// Display name (`WordCraft`). + pub name: String, + /// The detected main executable; the CLI lives beside it. + pub location: String, + /// The `-cli` binary. `None` when detection found the app but no CLI beside it. + pub cli_path: Option, +} + +/// Every installed Craft app, in suite order. Detection decides what is installed; this adds the +/// CLI each app serves MCP from. +pub fn installed_apps(manifest: &Manifest, snapshot: &detect::Snapshot) -> Vec { + artcraft_launcher_core::SUITE + .iter() + .filter_map(|app| { + let installed = detect::detect(app, manifest, snapshot)?; + Some(InstalledApp { + id: app.id.to_string(), + name: app.name.to_string(), + location: installed.location.clone(), + cli_path: cli_path_for(&installed.location, app), + }) + }) + .collect() +} + +/// The `-cli` binary beside a detected main executable, under any name the app has shipped as +/// (current first), with or without `.exe`. +fn cli_path_for(location: &str, app: &CraftApp) -> Option { + let dir = Path::new(location).parent()?; + for stem in app.stems() { + for ext in ["", ".exe"] { + let candidate = dir.join(format!("{stem}-cli{ext}")); + if candidate.is_file() { + return Some(candidate); + } + } + } + None +} + +/// Names another `craft-ai-mcp` than the one beside the launcher (development, tests). +pub const GATEWAY_PATH_ENV: &str = "ARTCRAFT_LAUNCHER_GATEWAY_PATH"; + +/// The `craft-ai-mcp` gateway the launcher ships beside itself, or [`GATEWAY_PATH_ENV`]. pub fn locate_gateway() -> Option { - crate::local_mcp::locate_bridge() + if let Some(p) = std::env::var_os(GATEWAY_PATH_ENV).filter(|p| !p.is_empty()) { + let p = PathBuf::from(p); + return p.is_file().then_some(p); + } + let dir = std::env::current_exe().ok()?.parent()?.to_path_buf(); + ["craft-ai-mcp.exe", "craft-ai-mcp"].into_iter().map(|n| dir.join(n)).find(|p| p.is_file()) } /// The folder in [`mcp_dir`] that holds the gateway copy clients start. @@ -210,7 +265,7 @@ fn lock() -> MutexGuard<'static, ()> { /// What Settings shows. While agents are on, the app list and the gateway copy are refreshed /// first, so an app installed (or a gateway updated) since then is used too; a failed refresh /// keeps the previous ones. -pub fn state(services: &[LocalService]) -> McpAgents { +pub fn state(services: &[InstalledApp]) -> McpAgents { let flag_on = flag_on(); let dir = mcp_dir(); let on = { @@ -269,7 +324,7 @@ pub fn flags_state() -> Vec { /// Turn a feature flag on or off for the launcher and every app. Turning `AI-MCP` off also turns /// agents off, so no client keeps an entry for a feature that is switched off. -pub fn set_flag(id: &str, on: bool, services: &[LocalService]) -> Result<(), String> { +pub fn set_flag(id: &str, on: bool, services: &[InstalledApp]) -> Result<(), String> { let path = craft_flags::default_path().ok_or("couldn't find the per-user configuration folder")?; // Clean up first: if that fails, the flag stays on and Settings keeps the controls to retry. if id == craft_flags::AI_MCP.id && !on { @@ -282,7 +337,7 @@ const NO_GATEWAY: &str = "the Craft gateway (craft-ai-mcp) is not installed besi /// Turn agents on (copy the gateway, write the app list) or off (remove the list, every client /// entry this module added, and the copy). All clients are tried; the first error is returned. -pub fn set_enabled(on: bool, services: &[LocalService]) -> Result<(), String> { +pub fn set_enabled(on: bool, services: &[InstalledApp]) -> Result<(), String> { let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; let _guard = lock(); if on { diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 3f52b4ab..c6ec2238 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -4,8 +4,8 @@ use serde_json::{Value, json}; use super::*; -fn service(id: &str, name: &str, cli: Option) -> LocalService { - LocalService { id: id.into(), name: name.into(), location: String::new(), cli_path: cli } +fn service(id: &str, name: &str, cli: Option) -> InstalledApp { + InstalledApp { id: id.into(), name: name.into(), location: String::new(), cli_path: cli } } fn read(p: &Path) -> Value { diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 122e9f02..2f915080 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -9,8 +9,8 @@ use artcraft_launcher_core::catalog::{LAUNCHER, LAUNCHER_ID}; use artcraft_launcher_core::feed::{Feed, FeedAnswer}; use artcraft_launcher_core::platform::{Arch, Os, Platform, pick_asset}; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpBridge, McpService, Origin, - PAUSED, PausedDownload, Source, VersionTrack, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, Origin, PAUSED, PausedDownload, + Source, VersionTrack, }; use artcraft_launcher_core::release::{Asset, Release}; use artcraft_launcher_core::{CraftApp, Installed, PackageKind, version}; @@ -18,7 +18,6 @@ use artcraft_launcher_core::{CraftApp, Installed, PackageKind, version}; use crate::feed_throttle::{self, FeedThrottle, Outcome}; use crate::http::{self, Http, Stop}; use crate::install::{self, Job}; -use crate::local_mcp; use crate::manifest::Manifest; use crate::paths::Paths; use crate::process; @@ -1610,12 +1609,7 @@ impl Backend for NativeBackend { self.check(true); } } - cmd @ (Command::McpState - | Command::McpSetService { .. } - | Command::McpSetBridge { .. } - | Command::McpSetAgents { .. } - | Command::McpSetClient { .. } - | Command::SetFlag { .. }) => { + cmd @ (Command::McpState | Command::McpSetAgents { .. } | Command::McpSetClient { .. } | Command::SetFlag { .. }) => { // Detection can run package-manager queries for seconds (flatpak on Linux): // never on the UI thread that sends commands. let shared = self.shared.clone(); @@ -1655,108 +1649,43 @@ impl Backend for NativeBackend { } } -/// The current local MCP state: installed apps with usable CLIs (with their on/off state in -/// LM Studio's config) plus the unified HTTP bridge. Reads the manifest and ng-mcp.json, and takes -/// a fresh detection snapshot so it reflects what's on disk now. Entries are matched by display -/// name so those created under a different id (e.g. a UUID by an earlier launcher version) are -/// recognized and reported as already present. +/// The AI agents state, from a fresh detection of the installed apps. fn mcp_state(shared: &Shared) -> Event { - mcp_state_for(&detected_services(shared)) + mcp_state_for(&detected_apps(shared)) } /// [`mcp_state`] for apps already detected. -fn mcp_state_for(detected: &[local_mcp::LocalService]) -> Event { - let agents = crate::agents::state(detected); - - let existing: Vec = match local_mcp::mcp_config_path() { - Some(p) => local_mcp::load_servers(&p), - None => vec![], - }; - - let services: Vec = detected - .iter() - .map(|s| McpService { - id: s.id.clone(), - name: s.name.clone(), - command: s.cli_path.as_ref().map(|c| c.display().to_string()).unwrap_or_default(), - enabled: local_mcp::service_enabled(&existing, &s.name), - }) - .chain(local_mcp::orphaned_entries(&existing, detected).into_iter().map(|(id, name, enabled)| McpService { - id, - name, - command: String::new(), - enabled, - })) - .collect(); - - let bridge_path = local_mcp::locate_bridge(); - Event::Mcp { - services, - bridge: McpBridge { - found: bridge_path.is_some(), - version: bridge_path.as_deref().and_then(local_mcp::bridge_version).map(|v| v.to_string()), - port: local_mcp::bridge_port_current(&existing).unwrap_or(local_mcp::BRIDGE_PORT), - enabled: local_mcp::bridge_enabled(&existing), - }, - agents, - } +fn mcp_state_for(detected: &[crate::agents::InstalledApp]) -> Event { + Event::Mcp { agents: crate::agents::state(detected) } } /// Serialises MCP commands and every publication of the MCP state, so a state read before a /// command can't arrive after that command's own (newer) state. static MCP_WORK: Mutex<()> = Mutex::new(()); -/// One MCP command, on a worker thread. Commands run one at a time, so a toggle and a refresh -/// never write `ng-mcp.json` or the client configurations at once; detection runs once per -/// command, and the new state is sent when it is done. +/// One AI agents command, on a worker thread: detection can run package-manager queries for +/// seconds (flatpak on Linux). Commands run one at a time; the new state is sent when done. fn run_mcp(shared: &Shared, cmd: Command) { let _guard = MCP_WORK.lock().unwrap_or_else(PoisonError::into_inner); - let services = detected_services(shared); + let apps = detected_apps(shared); let result = match cmd { - Command::McpSetService { service_id, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { - let mut servers = local_mcp::load_servers(&p); - match services.iter().find(|s| s.id == service_id) { - Some(s) if enabled => { - local_mcp::enable_service(&mut servers, s); - } - Some(s) => { - local_mcp::disable_service(&mut servers, s); - } - // An app no longer installed: its saved entry can still be switched off. - None if !enabled => { - let gone = local_mcp::LocalService { id: service_id, name: String::new(), location: String::new(), cli_path: None }; - local_mcp::disable_service(&mut servers, &gone); - } - None => {} - } - local_mcp::save_servers(&p, &servers, &[]) - }), - Command::McpSetBridge { port, enabled } => local_mcp::mcp_config_path().map_or(Ok(()), |p| { - let mut servers = local_mcp::load_servers(&p); - if enabled { - local_mcp::enable_bridge(&mut servers, port); - } else { - local_mcp::disable_bridge(&mut servers); - } - local_mcp::save_servers(&p, &servers, &[]) - }), - Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &services), + Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &apps), Command::McpSetClient { client, added } => crate::agents::set_client(client, added), - Command::SetFlag { id, on } => crate::agents::set_flag(&id, on, &services), + Command::SetFlag { id, on } => crate::agents::set_flag(&id, on, &apps), _ => Ok(()), }; if let Err(message) = result { shared.emit(Event::McpError { message }); } shared.emit(Event::Flags { flags: crate::agents::flags_state() }); - shared.emit(mcp_state_for(&services)); + shared.emit(mcp_state_for(&apps)); } /// The installed apps with their CLIs, from a fresh detection snapshot. -fn detected_services(shared: &Shared) -> Vec { +fn detected_apps(shared: &Shared) -> Vec { let manifest = shared.manifest.lock().unwrap_or_else(PoisonError::into_inner).clone(); let snapshot = crate::detect::Snapshot::take(); - local_mcp::installed_services(&manifest, &snapshot) + crate::agents::installed_apps(&manifest, &snapshot) } #[cfg(test)] diff --git a/crates/native/src/lib.rs b/crates/native/src/lib.rs index 56929801..54f6dd52 100644 --- a/crates/native/src/lib.rs +++ b/crates/native/src/lib.rs @@ -15,7 +15,6 @@ pub mod feed_throttle; pub mod hosted_catalog; pub mod http; pub mod install; -pub mod local_mcp; pub mod login; pub mod manifest; #[cfg(any(windows, test))] diff --git a/crates/native/src/local_mcp.rs b/crates/native/src/local_mcp.rs deleted file mode 100644 index d52a8af6..00000000 --- a/crates/native/src/local_mcp.rs +++ /dev/null @@ -1,996 +0,0 @@ -//! Exposes installed Craft Apps as stdio MCP servers in LM Studio's Bionic config. -//! -//! The launcher already knows which Craft Apps are on this machine (see [`detect`](crate::detect)). -//! This module turns that into `ng-mcp.json` entries so LM Studio / Bionic can drive each app's -//! built-in tools over MCP stdio. Every path comes from detection, which reads the user's own -//! install location (`InstallLocation` on Windows, the App bundle or package dir elsewhere). Nothing -//! here hardcodes a folder; [`mcp_config_path`] derives LM Studio's config file from the user -//! profile and is overridable via `ARTCRAFT_LAUNCHER_MCP_CONFIG` for tests. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use artcraft_launcher_core::CraftApp; -use serde::{Deserialize, Serialize}; - -use crate::detect; -use crate::manifest::Manifest; - -/// A Craft App that has a usable CLI on this machine and can be exposed as an MCP server. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LocalService { - /// The app id (`wordcraft`), stable across versions. - pub id: String, - /// Display name (`WordCraft`). - pub name: String, - /// The detected main executable path; the CLI lives beside it. - pub location: String, - /// The `-cli` binary that speaks MCP stdio. `None` when detection found the app but no CLI - /// sits next to it. - #[serde(default)] - pub cli_path: Option, -} - -/// One entry in LM Studio's `ng-mcp.json` `servers` array, matching the file's shape exactly. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ServerEntry { - /// Stable id for this server; reused across toggles so Bionic keeps its own state keyed to it. - pub id: String, - pub name: String, - pub description: String, - pub enabled: bool, - pub connection: Connection, -} - -/// The transport a host uses to reach the server. Mirrors `ng-mcp.json`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "type")] -pub enum Connection { - /// A local process the host spawns. `command` is the CLI path; `args` are its arguments. - #[serde(rename = "stdio")] - Stdio { command: String, args: Vec, env: HashMap }, - /// A network endpoint the host connects to (reserved for HTTP-based services like the bridge). - #[serde(rename = "streamableHttp")] - StreamableHttp { url: String, headers: HashMap, auth: Option }, -} - -/// Credentials a streamable-HTTP host sends. `None` means no auth; Bionic writes this field only -/// when present. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "type")] -pub enum Auth { - #[serde(rename = "none")] - None, - #[serde(rename = "bearerToken")] - BearerToken { token: String }, -} - -/// The path to LM Studio / Bionic's MCP server config on this machine. -/// -/// Derived from the user profile, never hardcoded. Overridable via `ARTCRAFT_LAUNCHER_MCP_CONFIG` -/// (tests point it at a temp file). Returns `None` when the home directory can't be resolved. -pub fn mcp_config_path() -> Option { - if let Ok(p) = std::env::var("ARTCRAFT_LAUNCHER_MCP_CONFIG") { - return Some(PathBuf::from(&p)); - } - Some(dirs::home_dir()?.join(".lmstudio").join("apps").join("bionic").join(".internal").join("ng-mcp.json")) -} - -/// Load the `servers` array from a config file. A missing, unreadable, or malformed file yields an -/// empty list rather than an error, so a fresh install starts with no servers and never crashes. -pub fn load_servers(path: &Path) -> Vec { - let bytes = match std::fs::read(path) { - Ok(b) => b, - Err(_) => return vec![], - }; - let value = match serde_json::from_slice::(&bytes) { - Ok(v) => v, - Err(_) => return vec![], - }; - match value.get("servers").and_then(|s| s.as_array()) { - Some(arr) => arr.iter().filter_map(|e| serde_json::from_value(e.clone()).ok()).collect(), - None => vec![], - } -} - -/// Save `servers` back to the config file, preserving any top-level keys other than `servers`. -/// Writes atomically (temp file + rename) so a crash never leaves a half-written config. -pub fn save_servers(path: &Path, servers: &[ServerEntry], removed: &[&str]) -> Result<(), String> { - // Distinguish "no config yet" (safe to create) from "a config exists but is not valid JSON" - // (refuse rather than clobber it). A file we cannot read as JSON may hold content the user - // cares about; overwriting it would be a lossy write. - let existing: Option = match std::fs::read(path) { - Ok(b) => match serde_json::from_slice(&b) { - Ok(v) => Some(v), - Err(e) => return Err(format!("existing MCP config at {} is not valid JSON; refusing to overwrite it: {}", path.display(), e,)), - }, - Err(_) => None, // missing (or unreadable): start fresh - }; - // A `servers` that is not a list is not ours to replace. - let old = match existing.as_ref().and_then(|v| v.get("servers")) { - None => &[][..], - Some(serde_json::Value::Array(a)) => a.as_slice(), - Some(_) => return Err(format!("`servers` in {} is not a list; refusing to overwrite it", path.display())), - }; - let array = merge_servers(old, servers, removed)?; - // Preserve any top-level keys other than `servers`; replace the array. If the file was not - // a JSON object, it is not an `ng-mcp.json` shape and starts fresh. - let mut map = serde_json::Map::new(); - if let Some(obj) = existing.as_ref().and_then(serde_json::Value::as_object) { - for (k, v) in obj { - if k != "servers" { - map.insert(k.clone(), v.clone()); - } - } - } - map.insert("servers".to_string(), serde_json::json!(array)); - let out = serde_json::to_string_pretty(&serde_json::Value::Object(map)).map_err(|e| e.to_string())?; - crate::paths::write_atomic(path, out.as_bytes()) -} - -/// The new `servers` array: `servers` merged into the file's `old` entries. An entry this module -/// cannot read (another connection type, a missing field, a shape Bionic adds later) is kept as -/// it is and where it was; an entry it manages keeps any field it doesn't know; an entry it can -/// read but that is not in `servers` stays too (another program may have added it since `servers` -/// was loaded), unless its id is in `removed`. -fn merge_servers(old: &[serde_json::Value], servers: &[ServerEntry], removed: &[&str]) -> Result, String> { - let mut used = vec![false; servers.len()]; - let mut out = Vec::with_capacity(old.len().max(servers.len())); - for raw in old { - if serde_json::from_value::(raw.clone()).is_err() { - out.push(raw.clone()); - continue; - } - let id = raw.get("id").and_then(serde_json::Value::as_str); - let Some(i) = servers.iter().enumerate().position(|(i, s)| Some(s.id.as_str()) == id && !used.get(i).copied().unwrap_or(true)) else { - if !id.is_some_and(|id| removed.contains(&id)) { - out.push(raw.clone()); - } - continue; - }; - if let (Some(flag), Some(entry)) = (used.get_mut(i), servers.get(i)) { - *flag = true; - out.push(overlay(raw, serde_json::to_value(entry).map_err(|e| e.to_string())?)); - } - } - for (entry, was_used) in servers.iter().zip(used) { - if !was_used { - out.push(serde_json::to_value(entry).map_err(|e| e.to_string())?); - } - } - Ok(out) -} - -/// `new` written over `raw`: fields only `raw` has are kept, one level into `connection` too -/// while its `type` is unchanged. -fn overlay(raw: &serde_json::Value, new: serde_json::Value) -> serde_json::Value { - let (Some(raw), serde_json::Value::Object(new)) = (raw.as_object(), new.clone()) else { - return new; - }; - let mut merged = raw.clone(); - for (k, v) in new { - let keep_inner = k == "connection" && raw.get("connection").and_then(|c| c.get("type")) == v.get("type"); - let value = match (keep_inner, raw.get(&k)) { - (true, Some(old @ serde_json::Value::Object(_))) => overlay(old, v), - _ => v, - }; - merged.insert(k, value); - } - serde_json::Value::Object(merged) -} - -/// Entries this module added (`craft-ai-mcp-`) for apps that are no longer installed, as -/// `(app id, name, enabled)`, so Settings can still switch them off. -pub fn orphaned_entries(servers: &[ServerEntry], installed: &[LocalService]) -> Vec<(String, String, bool)> { - servers - .iter() - .filter_map(|e| { - let id = e.id.strip_prefix("craft-ai-mcp-")?; - let known = installed.iter().any(|s| s.id == id || s.name == e.name); - (!known && is_stdio(e)).then(|| (id.to_string(), e.name.clone(), e.enabled)) - }) - .collect() -} - -/// Every Craft App that has a usable CLI on this machine, in suite order. Detection is the single -/// source of truth for "installed"; this just adds the CLI path each app would expose to MCP. -pub fn installed_services(manifest: &Manifest, snapshot: &detect::Snapshot) -> Vec { - artcraft_launcher_core::SUITE - .iter() - .filter_map(|app| { - let installed = detect::detect(app, manifest, snapshot)?; - Some(LocalService { - id: app.id.to_string(), - name: app.name.to_string(), - location: installed.location.clone(), - cli_path: cli_path_for(&installed.location, app), - }) - }) - .collect() -} - -/// The `-cli` binary beside a detected main executable. Tries every stem the app has shipped as, -/// current first, and both the bare name (Unix) and `.exe` (Windows). `None` when no CLI exists -/// next to it. -fn cli_path_for(location: &str, app: &CraftApp) -> Option { - let dir = Path::new(location).parent()?; - for stem in app.stems() { - for ext in ["", ".exe"] { - let candidate = dir.join(format!("{stem}-cli{ext}")); - if candidate.is_file() { - return Some(candidate); - } - } - } - None -} - -/// The stable id this module uses for a given app, so enable/disable/remove agree. -pub fn entry_id(service_id: &str) -> String { - format!("craft-ai-mcp-{}", service_id) -} - -/// The stdio `ServerEntry` for a service, ready to drop into `ng-mcp.json`. Returns `None` when -/// the service has no usable CLI. -pub fn entry_for(service: &LocalService) -> Option { - let cli = service.cli_path.clone()?; - Some(ServerEntry { - id: entry_id(&service.id), - name: service.name.clone(), - description: format!("{} built-in tools over MCP.", service.name), - enabled: true, - connection: Connection::Stdio { command: cli.display().to_string(), args: vec!["mcp".into()], env: HashMap::new() }, - }) -} - -/// Index of an entry whose display name matches `name`, or None. Matching by name (rather than -/// id) lets us recognize and manage entries created with a different id, e.g. UUIDs from an -/// earlier launcher version. -fn find_by_name(servers: &[ServerEntry], name: &str) -> Option { - servers.iter().position(|e| e.name == name) -} - -/// Whether an entry is one of ours — a stdio CLI server — as opposed to the streamableHttp bridge -/// or some other tool's entry that happens to share a display name. We only manage entries we -/// created; matching by name must never flip, drop or rewrite an unrelated entry. -fn is_stdio(entry: &ServerEntry) -> bool { - matches!(&entry.connection, Connection::Stdio { .. }) -} - -/// Add or update the entry for `service`, enabling it. Manages any existing entry with the same -/// display name in place (keeping its id, refreshing the command); otherwise creates one under -/// the deterministic id. Returns false when there was no usable CLI. -pub fn enable_service(servers: &mut Vec, service: &LocalService) -> bool { - let Some(cli) = service.cli_path.as_deref() else { return false }; - // Manage an existing same-named entry only when it is one of ours (stdio); a same-named - // entry of another connection type is left alone and we create our own under the deterministic id. - match find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { - Some(i) => { - servers[i].enabled = true; - if let Connection::Stdio { command: c, .. } = &mut servers[i].connection { - *c = cli.display().to_string(); - } - } - None => servers.push(ServerEntry { - id: entry_id(&service.id), - name: service.name.clone(), - description: format!("{} built-in tools over MCP.", service.name), - enabled: true, - connection: Connection::Stdio { command: cli.display().to_string(), args: vec!["mcp".into()], env: HashMap::new() }, - }), - } - true -} - -/// Disable the entry for `service`, leaving it in the list (Bionic keeps a disabled row). Matches -/// by display name first, then the deterministic id. Returns false when there was nothing to disable. -pub fn disable_service(servers: &mut [ServerEntry], service: &LocalService) -> bool { - // Only disable an entry that is one of ours (stdio); a same-named entry of another connection - // type is left alone and we fall back to the deterministic id. - if let Some(i) = find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { - if servers[i].enabled { - servers[i].enabled = false; - return true; - } - return false; - } - let id = entry_id(&service.id); - match servers.iter_mut().find(|e| e.id == id) { - Some(e) if e.enabled => { - e.enabled = false; - true - } - _ => false, - } -} - -/// Remove the entry for `service`. Matches by display name first, then the deterministic id. -/// Returns false when there was nothing to remove. -pub fn remove_service(servers: &mut Vec, service: &LocalService) -> bool { - // Only remove an entry that is one of ours (stdio); a same-named entry of another connection - // type is left alone and we fall back to the deterministic id. - if let Some(i) = find_by_name(servers, &service.name).filter(|&i| is_stdio(&servers[i])) { - servers.remove(i); - return true; - } - let id = entry_id(&service.id); - let before = servers.len(); - servers.retain(|e| e.id != id); - servers.len() != before -} - -/// Whether an entry with display name `name` is currently enabled. -pub fn service_enabled(servers: &[ServerEntry], name: &str) -> bool { - find_by_name(servers, name).is_some_and(|i| servers[i].enabled) -} - -/// Port the unified `craft-ai-mcp` bridge listens on by default. -pub const BRIDGE_PORT: u16 = 12345; - -/// Stable id for the single unified-bridge entry in `ng-mcp.json`. -pub const BRIDGE_ID: &str = "craft-ai-mcp"; - -/// Locate the unified `craft-ai-mcp` bridge binary, if present. -/// -/// Checks, in order: -/// - `ARTCRAFT_LAUNCHER_BRIDGE_PATH` (dev/test override); -/// - a small set of derived install locations. -/// -/// Returns `None` when no bridge is found so callers can fall back to per-app stdio entries. -pub fn locate_bridge() -> Option { - let override_path = std::env::var("ARTCRAFT_LAUNCHER_BRIDGE_PATH").ok().map(PathBuf::from); - first_existing(override_path.as_deref(), &candidate_bridge_paths()) -} - -/// First existing path among `override` (checked first) then `candidates`. -fn first_existing(override_path: Option<&Path>, candidates: &[PathBuf]) -> Option { - if let Some(p) = override_path { - return p.is_file().then_some(PathBuf::from(p)); - } - candidates.iter().find(|p| p.is_file()).cloned() -} - -/// Candidate locations for the bridge binary. Derived from this launcher's own install, not -/// hardcoded to one machine's layout; extend as the ship story settles. -fn candidate_bridge_paths() -> Vec { - let mut out = Vec::new(); - if let Some(exe) = std::env::current_exe().ok() - && let Some(dir) = exe.parent() - { - for name in ["craft-ai-mcp.exe", "craft-ai-mcp"] { - out.push(dir.join(name)); - } - } - out -} - -/// The bridge binary's version, when readable. Reuses the launcher's existing PE-version reader so -/// the two branches agree on how a version is read; `None` off-Windows or without version info. -#[cfg(windows)] -pub fn bridge_version(path: &Path) -> Option { - crate::detect::windows::executable_version(path) -} - -#[cfg(not(windows))] -pub fn bridge_version(_path: &Path) -> Option { - None -} - -/// The single `streamableHttp` entry for the unified bridge at `port`. Named "Craft AI" so it is -/// recognized (and managed in place) even when an earlier launcher version created it under a UUID. -pub fn bridge_entry(port: u16) -> ServerEntry { - ServerEntry { - id: BRIDGE_ID.to_string(), - name: "Craft AI".to_string(), - description: "All Craft AI tools over one MCP endpoint.".to_string(), - enabled: true, - connection: Connection::StreamableHttp { url: format!("http://127.0.0.1:{port}/mcp"), headers: HashMap::new(), auth: Some(Auth::None) }, - } -} - -/// Index of the unified-bridge entry, or None: one whose id is the deterministic bridge id, or a -/// `streamableHttp` entry named "Craft AI" (created by an earlier launcher version under a UUID). -fn find_bridge(servers: &[ServerEntry]) -> Option { - servers - .iter() - .position(|e| e.id == BRIDGE_ID) - .or_else(|| servers.iter().position(|e| matches!(&e.connection, Connection::StreamableHttp { .. }) && e.name == "Craft AI")) -} - -/// The current port of the unified-bridge entry (parsed from its `streamableHttp` URL), or None -/// when there is no bridge entry. -pub fn bridge_port_current(servers: &[ServerEntry]) -> Option { - find_bridge(servers).and_then(|i| match &servers[i].connection { - Connection::StreamableHttp { url, .. } => parse_port(url), - _ => None, - }) -} - -/// Whether the unified-bridge entry is currently present and enabled. -pub fn bridge_enabled(servers: &[ServerEntry]) -> bool { - find_bridge(servers).is_some_and(|i| servers[i].enabled) -} - -/// Port from a `streamableHttp` URL like `http://127.0.0.1:12345/mcp`, or None when absent. -fn parse_port(url: &str) -> Option { - let parts: Vec<&str> = url.split('/').collect(); - if parts.len() < 3 { - return None; - } - // parts[0] is the scheme, parts[2] is `host[:port]`. - let host_port = parts[2]; - let port_str = host_port.rsplit_once(':').map(|(_, p)| p)?; - port_str.parse::().ok() -} - -/// Add or update the unified-bridge entry, enabling it. Manages any existing bridge entry in place -/// (keeping its id, refreshing the URL); otherwise creates one under the deterministic id. Returns -/// false for a zero port. -pub fn enable_bridge(servers: &mut Vec, port: u16) -> bool { - if port == 0 { - return false; - } - match find_bridge(servers) { - Some(i) => { - servers[i].enabled = true; - if let Connection::StreamableHttp { url, .. } = &mut servers[i].connection { - *url = format!("http://127.0.0.1:{port}/mcp"); - } - } - None => servers.push(bridge_entry(port)), - } - true -} - -/// Disable the unified-bridge entry (leaving it in the list). Returns false when absent or already off. -pub fn disable_bridge(servers: &mut [ServerEntry]) -> bool { - match find_bridge(servers) { - Some(i) if servers[i].enabled => { - servers[i].enabled = false; - true - } - _ => false, - } -} - -/// Remove the unified-bridge entry entirely. Returns false when absent. -pub fn remove_bridge(servers: &mut Vec) -> bool { - match find_bridge(servers) { - Some(i) => { - servers.remove(i); - true - } - None => false, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use artcraft_launcher_core::catalog::AppKind; - - /// A minimal Craft App for CLI-path tests. Only `id` and `former_ids` matter (they feed - /// [`CraftApp::stems`]); the rest are inert literals. String literals carry `'static`, which - /// every field here requires. - fn fake_app(id: &'static str, former_ids: &'static [&'static str]) -> CraftApp { - CraftApp { - id, - name: "TestCraft", - tagline: "A test app.", - color: [0; 3], - ink_light: [0; 3], - ink_dark: [0; 3], - repo: "storyteller/example", - former_ids, - former_names: &[], - mac_bundle_name: None, - kind: AppKind::Official, - publisher: "ArtCraft", - msi_publisher: None, - bundle: None, - former_bundles: &[], - site: None, - mac_team: None, - } - } - - #[test] - fn cli_path_prefers_the_current_stem_and_windows_extension() { - let dir = tempfile::tempdir().unwrap(); - // Main exe (what detection returns) plus a CLI under the current stem. - std::fs::write(dir.path().join("wordcraft.exe"), b"").unwrap(); - std::fs::write(dir.path().join("wordcraft-cli.exe"), b"cli").unwrap(); - let app = fake_app("wordcraft", &[]); - assert_eq!(cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), Some(dir.path().join("wordcraft-cli.exe"))); - } - - #[test] - fn cli_path_falls_back_to_a_former_stem() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("pdfcraft.exe"), b"").unwrap(); - // Only the former stem's CLI exists (e.g. an older install renamed to printcraft). - std::fs::write(dir.path().join("printcraft-cli.exe"), b"cli").unwrap(); - let app = fake_app("pdfcraft", &["printcraft"]); - assert_eq!(cli_path_for(&dir.path().join("pdfcraft.exe").display().to_string(), &app), Some(dir.path().join("printcraft-cli.exe"))); - } - - #[test] - fn cli_path_is_none_when_no_cli_sits_beside_the_exe() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("wordcraft.exe"), b"").unwrap(); - let app = fake_app("wordcraft", &[]); - assert_eq!(cli_path_for(&dir.path().join("wordcraft.exe").display().to_string(), &app), None); - } - - #[test] - fn cli_path_is_none_when_the_location_has_no_parent() { - // A bare file name with no directory component has no parent to look in. - let app = fake_app("wordcraft", &[]); - assert_eq!(cli_path_for("wordcraft.exe", &app), None); - } - - #[test] - fn save_then_load_round_trips_and_preserves_other_top_level_keys() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ng-mcp.json"); - // Seed a top-level key that is not `servers` to prove it survives. - std::fs::write(&path, r#"{"meta":{"note":"keep me"},"servers":[]}"#).unwrap(); - - let servers = vec![ServerEntry { - id: entry_id("wordcraft"), - name: "WordCraft".into(), - description: "WordCraft built-in tools over MCP.".into(), - enabled: true, - connection: Connection::Stdio { - command: dir.path().join("wordcraft-cli.exe").display().to_string(), - args: vec!["mcp".into()], - env: HashMap::new(), - }, - }]; - assert!(save_servers(&path, &servers, &[]).is_ok()); - - let loaded = load_servers(&path); - assert_eq!(loaded.len(), 1); - assert_eq!(loaded[0].id, entry_id("wordcraft")); - assert!(loaded[0].enabled); - match &loaded[0].connection { - Connection::Stdio { args, .. } => { - assert_eq!(args.len(), 1); - assert_eq!(args[0], "mcp"); - } - _ => panic!("expected a stdio connection"), - }; - - // The non-`servers` top-level key must survive the round trip. - let raw: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); - assert_eq!(raw["meta"]["note"], serde_json::json!("keep me")); - } - - #[test] - fn load_returns_empty_for_missing_malformed_and_serverless_files() { - let dir = tempfile::tempdir().unwrap(); - - // Missing file. - assert_eq!(load_servers(&dir.path().join("nope.json")), vec![]); - - // Malformed JSON. - std::fs::write(dir.path().join("bad.json"), b"{ not json").unwrap(); - assert_eq!(load_servers(&dir.path().join("bad.json")), vec![]); - - // Valid JSON with no `servers` key. - std::fs::write(dir.path().join("plain.json"), r#"{"other": 1}"#).unwrap(); - assert_eq!(load_servers(&dir.path().join("plain.json")), vec![]); - } - - #[test] - fn save_creates_the_file_when_it_is_missing() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ng-mcp.json"); - assert!(save_servers(&path, &[], &[]).is_ok()); - assert_eq!(load_servers(&path), vec![]); - } - - #[test] - fn save_keeps_entries_and_fields_it_does_not_manage() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ng-mcp.json"); - std::fs::write( - &path, - r#"{"servers":[ - {"id":"third","name":"Third","description":"","enabled":true,"connection":{"type":"stdio","command":"x","args":[]}}, - {"id":"sse","name":"Sse","description":"","enabled":true,"connection":{"type":"sse","url":"http://h"}}, - {"id":"craft-ai-mcp-wordcraft","name":"WordCraft","description":"","enabled":true,"note":"mine", - "connection":{"type":"stdio","command":"/x/wordcraft-cli.exe","args":["mcp"],"env":{},"cwd":"/w"}}, - {"id":"gone","name":"Gone","description":"","enabled":true,"connection":{"type":"stdio","command":"g","args":[],"env":{}}} - ]}"#, - ) - .unwrap(); - let mut servers = load_servers(&path); - assert_eq!(servers.len(), 2, "only the two complete stdio entries parse"); - servers.retain(|s| s.id != "gone"); - if let Some(w) = servers.iter_mut().find(|s| s.id == "craft-ai-mcp-wordcraft") { - w.enabled = false; - } - save_servers(&path, &servers, &["gone"]).unwrap(); - let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - let ids: Vec<&str> = v["servers"].as_array().unwrap().iter().filter_map(|e| e["id"].as_str()).collect(); - assert_eq!(ids, vec!["third", "sse", "craft-ai-mcp-wordcraft"], "unreadable entries stay in place; a removed one goes"); - let w = &v["servers"][2]; - assert_eq!(w["enabled"], false); - assert_eq!(w["note"], "mine", "an unknown field of a managed entry stays"); - assert_eq!(w["connection"]["cwd"], "/w", "an unknown connection field stays"); - assert!(v["servers"][0]["connection"].get("env").is_none(), "an entry without env is left as it was"); - } - - #[test] - fn save_keeps_an_entry_added_since_the_load_and_refuses_a_servers_object() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ng-mcp.json"); - let entry = |id: &str| { - format!( - r#"{{"id":"{id}","name":"{id}","description":"","enabled":true,"connection":{{"type":"stdio","command":"x","args":[],"env":{{}}}}}}"# - ) - }; - std::fs::write(&path, format!(r#"{{"servers":[{}]}}"#, entry("mine"))).unwrap(); - let mut servers = load_servers(&path); - // Another program adds an entry after the load. - std::fs::write(&path, format!(r#"{{"servers":[{},{}]}}"#, entry("mine"), entry("theirs"))).unwrap(); - if let Some(s) = servers.first_mut() { - s.enabled = false; - } - save_servers(&path, &servers, &[]).unwrap(); - let ids: Vec = load_servers(&path).into_iter().map(|s| s.id).collect(); - assert_eq!(ids, vec!["mine", "theirs"], "the entry added since is kept"); - - let obj = dir.path().join("obj.json"); - let text = r#"{"servers":{"third-party":{"command":"x"}}}"#; - std::fs::write(&obj, text).unwrap(); - assert!(save_servers(&obj, &[], &[]).is_err()); - assert_eq!(std::fs::read_to_string(&obj).unwrap(), text, "left as it was"); - } - - #[test] - fn entries_of_apps_no_longer_installed_are_listed() { - let entry = |id: &str, name: &str| ServerEntry { - id: id.into(), - name: name.into(), - description: String::new(), - enabled: true, - connection: Connection::Stdio { command: "/x".into(), args: vec![], env: HashMap::new() }, - }; - let servers = vec![entry("craft-ai-mcp-wordcraft", "WordCraft"), entry("craft-ai-mcp-gone", "GoneCraft"), entry("other", "Other")]; - let installed = vec![LocalService { id: "wordcraft".into(), name: "WordCraft".into(), location: String::new(), cli_path: None }]; - assert_eq!(orphaned_entries(&servers, &installed), vec![("gone".to_string(), "GoneCraft".to_string(), true)]); - // Switching it off finds it by its id even without a name. - let mut servers = servers; - let gone = LocalService { id: "gone".into(), name: String::new(), location: String::new(), cli_path: None }; - assert!(disable_service(&mut servers, &gone)); - assert!(!servers.iter().any(|s| s.id == "craft-ai-mcp-gone" && s.enabled)); - } - - #[test] - fn save_refuses_to_overwrite_a_malformed_config() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("ng-mcp.json"); - // A present but malformed file must not be clobbered. - std::fs::write(&path, b"{ this is not json").unwrap(); - - let servers = vec![ServerEntry { - id: entry_id("wordcraft"), - name: "WordCraft".into(), - description: "WordCraft built-in tools over MCP.".into(), - enabled: true, - connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, - }]; - let err = save_servers(&path, &servers, &[]).unwrap_err(); - assert!(err.contains("not valid JSON"), "{err}"); - - // The original bytes are still on disk. - assert_eq!(std::fs::read(&path).unwrap(), b"{ this is not json"); - } - - #[test] - fn enable_service_leaves_a_same_named_non_stdio_entry_alone() { - // A same-named streamableHttp entry (e.g. the bridge or another tool) must not be flipped - // or rewritten; we create our own stdio entry instead. - let mut servers = vec![ServerEntry { - id: "some-uuid".into(), - name: "WordCraft".into(), - description: "unrelated".into(), - enabled: false, - connection: Connection::StreamableHttp { url: "http://127.0.0.1:9999/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, - }]; - - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: Some("/x/wordcraft-cli.exe".into()), - }; - assert!(enable_service(&mut servers, &service)); - - // The unrelated entry is untouched (still disabled, still streamableHttp). - let first = &servers[0]; - assert_eq!(first.id, "some-uuid"); - assert!(!first.enabled); - assert!(matches!(&first.connection, Connection::StreamableHttp { .. })); - - // Our stdio entry was added under the deterministic id. - assert_eq!(servers.len(), 2); - let ours = &servers[1]; - assert_eq!(ours.id, entry_id("wordcraft")); - assert!(ours.enabled); - assert!(matches!(&ours.connection, Connection::Stdio { .. })); - } - - #[test] - fn enable_disable_remove_manage_the_server_list() { - let mut servers: Vec = Vec::new(); - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: Some("/x/wordcraft-cli.exe".into()), - }; - - // Enable adds it. - assert!(enable_service(&mut servers, &service)); - assert_eq!(servers.len(), 1); - assert!(servers[0].enabled); - assert_eq!(servers[0].id, entry_id("wordcraft")); - - // Enabling again is idempotent (no duplicate row). - assert!(enable_service(&mut servers, &service)); - assert_eq!(servers.len(), 1); - - // Disable keeps the row but turns it off (matched by display name). - assert!(disable_service(&mut servers, &service)); - assert!(!servers[0].enabled); - assert_eq!(servers.len(), 1); - - // Disabling again is a no-op that reports false. - assert!(!disable_service(&mut servers, &service)); - assert!(!servers[0].enabled); - - // Remove takes the row out. - assert!(remove_service(&mut servers, &service)); - assert_eq!(servers.len(), 0); - assert!(!remove_service(&mut servers, &service)); - } - - #[test] - fn entry_for_is_none_without_a_cli() { - let service = LocalService { id: "wordcraft".into(), name: "WordCraft".into(), location: "/x/wordcraft.exe".into(), cli_path: None }; - assert!(entry_for(&service).is_none()); - } - - #[cfg(windows)] - #[test] - fn detects_the_apps_installed_on_this_machine_when_requested() { - // Gated on an env var so it only runs where the suite is actually installed (a dev box), - // never in CI. Set ARTCRAFT_LAUNCHER_VERIFY_INSTALLED=1 to run it. - if std::env::var("ARTCRAFT_LAUNCHER_VERIFY_INSTALLED").is_err() { - return; - } - let paths = crate::paths::Paths::new().unwrap(); - let manifest = Manifest::load(&paths.manifest()); - let services = installed_services(&manifest, &detect::Snapshot::take()); - for s in &services { - assert!(s.cli_path.is_some(), "service {} has no CLI path: {:?}", s.id, s.location); - } - // WordCraft and PdfCraft are installed on the machine this test runs against. - assert!(services.iter().any(|s| s.id == "wordcraft"), "expected wordcraft to be detected"); - assert!(services.iter().any(|s| s.id == "pdfcraft"), "expected pdfcraft to be detected"); - } - - #[test] - fn bridge_entry_matches_the_streamable_http_shape() { - let entry = bridge_entry(BRIDGE_PORT); - assert_eq!(entry.id, BRIDGE_ID); - assert_eq!(entry.name, "Craft AI"); - assert!(entry.enabled); - match &entry.connection { - Connection::StreamableHttp { url, auth, .. } => { - assert_eq!(url, "http://127.0.0.1:12345/mcp"); - assert_eq!(*auth, Some(Auth::None)); - } - _ => panic!("expected a streamableHttp connection"), - }; - } - - #[test] - fn bridge_entry_uses_the_requested_port() { - let entry = bridge_entry(9000); - match &entry.connection { - Connection::StreamableHttp { url, .. } => assert_eq!(url, "http://127.0.0.1:9000/mcp"), - _ => panic!("expected a streamableHttp connection"), - }; - } - - #[test] - fn enable_disable_remove_bridge_manage_the_entry() { - let mut servers: Vec = Vec::new(); - assert!(!enable_bridge(&mut servers, 0)); // zero port is refused - assert_eq!(servers.len(), 0); - - assert!(enable_bridge(&mut servers, BRIDGE_PORT)); - assert_eq!(servers.len(), 1); - assert!(servers[0].enabled); - assert_eq!(servers[0].id, BRIDGE_ID); - - // Enabling again is idempotent (no duplicate row). - assert!(enable_bridge(&mut servers, BRIDGE_PORT)); - assert_eq!(servers.len(), 1); - - // Disabling turns it off. - assert!(disable_bridge(&mut servers)); - assert!(!servers[0].enabled); - // Disabling again is a no-op that reports false. - assert!(!disable_bridge(&mut servers)); - - // Remove takes the row out. - assert!(remove_bridge(&mut servers)); - assert_eq!(servers.len(), 0); - assert!(!remove_bridge(&mut servers)); - } - - #[test] - fn first_existing_prefers_the_override() { - let dir = tempfile::tempdir().unwrap(); - let present = dir.path().join("craft-ai-mcp.exe"); - std::fs::write(&present, b"").unwrap(); - let missing = dir.path().join("nope.exe"); - // Override wins even when a candidate also exists. - assert_eq!(first_existing(Some(present.as_ref()), &[missing.clone(), present.clone()]), Some(present),); - } - - #[test] - fn first_existing_falls_back_to_candidates_and_reports_none_when_missing() { - let dir = tempfile::tempdir().unwrap(); - let missing = dir.path().join("nope.exe"); - let present = dir.path().join("craft-ai-mcp.exe"); - std::fs::write(&present, b"").unwrap(); - // No override: the first existing candidate wins. - assert_eq!(first_existing(None, &[missing.clone(), present.clone()]), Some(present)); - // Nothing exists -> None. - assert_eq!(first_existing(None, &[missing]), None); - } - - /// Enabling a service manages an existing entry by display name (keeping its id) rather than - /// creating a duplicate under the deterministic id. - #[test] - fn enable_service_manages_an_existing_entry_by_name() { - let mut servers = vec![ServerEntry { - id: "uuid-1".into(), - name: "WordCraft".into(), - description: "old".into(), - enabled: false, - connection: Connection::Stdio { command: "/old/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, - }]; - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: Some("/x/wordcraft-cli.exe".into()), - }; - assert!(enable_service(&mut servers, &service)); - // Same single entry, original id preserved, command refreshed. - assert_eq!(servers.len(), 1); - assert_eq!(servers[0].id, "uuid-1"); - assert!(servers[0].enabled); - match &servers[0].connection { - Connection::Stdio { command, .. } => assert_eq!(command, "/x/wordcraft-cli.exe"), - _ => panic!("expected stdio"), - } - } - - /// Disabling matches by display name first (a UUID entry is found via its name). - #[test] - fn disable_service_matches_by_name_first() { - let mut servers = vec![ServerEntry { - id: "uuid-1".into(), - name: "WordCraft".into(), - description: String::new(), - enabled: true, - connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, - }]; - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: Some("/x/wordcraft-cli.exe".into()), - }; - assert!(disable_service(&mut servers, &service)); - assert!(!servers[0].enabled); - // The deterministic-id entry is not created. - assert_eq!(servers.len(), 1); - } - - /// Removing matches by display name first. - #[test] - fn remove_service_matches_by_name_first() { - let mut servers = vec![ServerEntry { - id: "uuid-1".into(), - name: "WordCraft".into(), - description: String::new(), - enabled: true, - connection: Connection::Stdio { command: "/x/wordcraft-cli.exe".into(), args: vec!["mcp".into()], env: HashMap::new() }, - }]; - let service = LocalService { - id: "wordcraft".into(), - name: "WordCraft".into(), - location: "/x/wordcraft.exe".into(), - cli_path: Some("/x/wordcraft-cli.exe".into()), - }; - assert!(remove_service(&mut servers, &service)); - assert_eq!(servers.len(), 0); - } - - /// Enabling the bridge manages an existing "Craft AI" entry by name (keeping its id, refreshing - /// the URL) rather than creating a duplicate. - #[test] - fn enable_bridge_manages_an_existing_entry_by_name() { - let mut servers = vec![ServerEntry { - id: "uuid-bridge".into(), - name: "Craft AI".into(), - description: String::new(), - enabled: false, - connection: Connection::StreamableHttp { url: "http://127.0.0.1:9999/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, - }]; - assert!(enable_bridge(&mut servers, BRIDGE_PORT)); - assert_eq!(servers.len(), 1); - assert_eq!(servers[0].id, "uuid-bridge"); - assert!(servers[0].enabled); - match &servers[0].connection { - Connection::StreamableHttp { url, .. } => assert_eq!(url, "http://127.0.0.1:12345/mcp"), - _ => panic!("expected streamableHttp"), - } - } - - /// bridge_port_current parses the port from an existing entry's URL. - #[test] - fn bridge_port_current_parses_the_url() { - let servers = vec![ServerEntry { - id: "uuid-bridge".into(), - name: "Craft AI".into(), - description: String::new(), - enabled: true, - connection: Connection::StreamableHttp { url: "http://127.0.0.1:9876/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, - }]; - assert_eq!(bridge_port_current(&servers), Some(9876)); - } - - /// bridge_enabled reports whether the existing entry is on. - #[test] - fn bridge_enabled_reports_the_existing_entry() { - let mut servers = vec![ServerEntry { - id: "uuid-bridge".into(), - name: "Craft AI".into(), - description: String::new(), - enabled: true, - connection: Connection::StreamableHttp { url: "http://127.0.0.1:12345/mcp".into(), headers: HashMap::new(), auth: Some(Auth::None) }, - }]; - assert!(bridge_enabled(&servers)); - servers[0].enabled = false; - assert!(!bridge_enabled(&servers)); - } - - /// Against the real `ng-mcp.json` on this machine: existing Craft app + bridge entries (created - /// under UUID ids by an earlier launcher version) must be recognized by display name and reported - /// as present. Gated on an env var so it only runs where the real config exists (a dev box), - /// never in CI. Set ARTCRAFT_LAUNCHER_VERIFY_MCP=1 to run it. - #[test] - fn mcp_state_recognizes_existing_entries_on_this_machine_when_requested() { - if std::env::var("ARTCRAFT_LAUNCHER_VERIFY_MCP").is_err() { - return; - } - let Some(path) = mcp_config_path() else { return }; - let servers = load_servers(&path); - // WordCraft and PdfCraft are installed here and already present as enabled stdio entries. - assert!(service_enabled(&servers, "WordCraft"), "WordCraft entry not recognized (by name) or disabled"); - assert!(service_enabled(&servers, "PdfCraft"), "PdfCraft entry not recognized (by name) or disabled"); - // The unified bridge is present at the default port and enabled. - assert_eq!(bridge_port_current(&servers), Some(BRIDGE_PORT)); - assert!(bridge_enabled(&servers), "bridge entry not recognized (by name) or disabled"); - } -} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a7897de6..874c2ef0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,8 +3,8 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, FlagState, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, McpBridge, - McpService, PAUSED, Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, FlagState, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, PAUSED, + Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; @@ -143,20 +143,10 @@ pub struct LauncherUi { pub(crate) backend: Box, pub settings: Settings, pub(crate) entries: Vec, - /// Local MCP services from the backend: installed apps exposed as stdio servers, plus the - /// unified HTTP bridge. Empty until the first [`Event::Mcp`]. - pub(crate) mcp_services: Vec, - pub(crate) mcp_bridge: McpBridge, - /// The first MCP state arrived: until then the bridge's switch and port show defaults, not - /// the saved setup, and stay disabled. - pub(crate) mcp_state_known: bool, /// AI agents: the gateway switch and the MCP clients. pub(crate) mcp_agents: McpAgents, /// The feature flags (Settings › Experimental features). pub(crate) flags: Vec, - /// Editable port text for the unified bridge; synced from events only once so user edits stick. - pub(crate) bridge_port: String, - pub(crate) bridge_port_initialized: bool, /// Whether we've asked for MCP state since the settings dialog last opened (reset when it closes). pub(crate) mcp_requested: bool, pub(crate) caps: Capabilities, @@ -284,13 +274,8 @@ impl LauncherUi { .filter(|a| platform.is_none_or(|p| a.runs_on(p.os))) .map(AppEntry::new) .collect(), - mcp_services: Vec::new(), - mcp_bridge: McpBridge::default(), - mcp_state_known: false, mcp_agents: McpAgents::default(), flags: Vec::new(), - bridge_port: String::new(), - bridge_port_initialized: false, mcp_requested: false, caps, platform, @@ -669,17 +654,8 @@ impl LauncherUi { self.rate_limited_until = rate_limited_until; true } - Event::Mcp { services, bridge, agents } => { + Event::Mcp { agents } => { self.mcp_agents = agents; - self.mcp_state_known = true; - let port = bridge.port; - self.mcp_services = services; - self.mcp_bridge = bridge; - // Sync the editable port only once so a user's typed value isn't clobbered by later events. - if !self.bridge_port_initialized && port != 0 { - self.bridge_port = port.to_string(); - self.bridge_port_initialized = true; - } false } Event::Flags { flags } => { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0991c8df..25ddd1b8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -418,22 +418,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? Aplikace {app} je uzamčena na verzi {version}. Přejít na nejnovější vydání? Unlock Odemknout - Local services Lokální služby - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Zveřejněte aplikace Craft AI jako MCP servery, aby LM Studio / Bionic mohlo ovládat jejich nástroje. - - Craft apps Aplikace Craft - - No installed Craft app has a usable CLI yet. Žádná nainstalovaná aplikace Craft zatím nemá dostupné CLI. - - Unified bridge Jednotný most - - Not found on this machine Není nalezeno na tomto počítači - - Found Nalezeno - - Port Port - Port applies when you toggle the bridge. Port se uplatní, když přepněte most. AI agents AI agenti One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jedna položka v Claude, Cursoru nebo LM Studiu dosáhne na každou nainstalovanou aplikaci Craft. Po přidání klienta restartujte. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brána Craft (craft-ai-mcp) není nainstalována vedle spouštěče. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6cc86775..b7e28efb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -450,22 +450,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} ist auf {version} festgelegt. Stattdessen der neuesten Version folgen? Unlock Entsperren - Local services Lokale Dienste - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft-AI-Apps als MCP-Server bereitstellen, damit LM Studio / Bionic ihre Tools steuern kann. - - Craft apps Craft-Apps - - No installed Craft app has a usable CLI yet. Ein installiertes Craft-App hat noch kein nutzbares CLI. - - Unified bridge Einheitliche Brücke - - Not found on this machine Auf diesem Rechner nicht gefunden - - Found Gefunden - - Port Port - Port applies when you toggle the bridge. Der Port wird angewendet, wenn Sie die Brücke umschalten. AI agents KI-Agenten One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Ein Eintrag in Claude, Cursor oder LM Studio erreicht jede installierte Craft-App. Starte den Client neu, nachdem du ihn hinzugefügt hast. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Das Craft-Gateway (craft-ai-mcp) ist nicht neben dem Launcher installiert. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1ea0b1c4..b13e440e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -431,22 +431,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} está fijado en la versión {version}. ¿Usar la versión más reciente? Unlock Desbloquear - Local services Servicios locales - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exponga las aplicaciones de Craft AI como servidores MCP para que LM Studio / Bionic pueda controlar sus herramientas. - - Craft apps Aplicaciones Craft - - No installed Craft app has a usable CLI yet. Ninguna aplicación de Craft instalada tiene aún un CLI utilizável. - - Unified bridge Puente unificado - - Not found on this machine No encontrado en esta máquina - - Found Encontrado - - Port Puerto - Port applies when you toggle the bridge. El puerto se aplica cuando cambias el puente. AI agents Agentes de IA One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Una sola entrada en Claude, Cursor o LM Studio llega a todas las apps Craft instaladas. Reinicia el cliente después de añadirla. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La pasarela Craft (craft-ai-mcp) no está instalada junto al lanzador. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0ea47bf8..741afc45 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -448,22 +448,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} est fixé à la version {version}. Suivre plutôt la dernière version ? Unlock Déverrouiller - Local services Services locaux - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exposer les applications Craft AI en tant que serveurs MCP afin que LM Studio / Bionic puisse piloter leurs outils. - - Craft apps Applications Craft - - No installed Craft app has a usable CLI yet. Aucune application Craft installée n'a encore de CLI utilisable. - - Unified bridge Pont unifié - - Not found on this machine Non trouvé sur cette machine - - Found Trouvé - - Port Port - Port applies when you toggle the bridge. Le port est appliqué lorsque vous basculez le pont. AI agents Agents IA One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Une seule entrée dans Claude, Cursor ou LM Studio atteint toutes les apps Craft installées. Redémarrez le client après l'avoir ajoutée. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La passerelle Craft (craft-ai-mcp) n'est pas installée à côté du lanceur. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9860aa20..98030e8f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -451,22 +451,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? A(z) {app} a(z) {version} verzióra van rögzítve. Inkább a legújabb kiadást kövesse? Unlock Feloldás - Local services Helyi szolgáltatások - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Javítsd ki a Craft AI alkalmazásokat MCP szerverként, hogy az LM Studio / Bionic kezelje a eszközeiket. - - Craft apps Craft alkalmazások - - No installed Craft app has a usable CLI yet. Egy nincsen még használható CLI-vel rendelkező telepített Craft alkalmazás. - - Unified bridge Egységes híd - - Not found on this machine Nem található ezen a gépen - - Found Találva - - Port Port - Port applies when you toggle the bridge. A port akkor lép hatályba, ha kikapcsolod a hidrat. AI agents AI-ügynökök One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Egyetlen bejegyzés a Claude-ban, a Cursorban vagy az LM Studióban eléri az összes telepített Craft alkalmazást. Hozzáadás után indítsa újra a klienst. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. A Craft átjáró (craft-ai-mcp) nincs telepítve az indító mellé. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f82530c5..527a325f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -453,22 +453,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} は {version} に固定されています。代わりに最新リリースを使用しますか? Unlock 固定を解除 - Local services ローカルサービス - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft AI アプリを MCP サーバーとして公開し、LM Studio / Bionic がそのツールを操作できるようにします。 - - Craft apps Craft アプリ - - No installed Craft app has a usable CLI yet. インストールされた Craft アプリにまだ利用可能な CLI がありません。 - - Unified bridge 統一ブリッジ - - Not found on this machine このマシンでは見つかりません - - Found 見つかりました - - Port ポート - Port applies when you toggle the bridge. ポートはブリッジを切り替えたときに適用されます。 AI agents AI エージェント One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Claude、Cursor、LM Studio に 1 つ登録するだけで、インストール済みのすべての Craft アプリを使えます。追加したらクライアントを再起動してください。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft ゲートウェイ (craft-ai-mcp) がランチャーと同じ場所にインストールされていません。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5663d10c..cad02f78 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -449,22 +449,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} ფიქსირებულია {version} ვერსიაზე. სანაცვლოდ გამოიყენოთ უახლესი გამოშვება? Unlock განბლოკვა - Local services ლოკალური სერვისები - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Craft AI აპლიკაციები MCP სერვერად გამოქეცეთ, რომ LM Studio / Bionic მათის ინსტРУმენტებს... - - Craft apps Craft აპლიკაციები - - No installed Craft app has a usable CLI yet. იnstallებული Craft აპლიკაცია ჯერ... CLI... - - Unified bridge ერთი ხიმის - - Not found on this machine ამ კომპიუტერში ვერა - - Found მოვიდა - - Port პორტი - Port applies when you toggle the bridge. პორტის ცვლილება მხოლოდ გათიშვისას მოქმედება. AI agents AI აგენტები One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. ერთი ჩანაწერი Claude-ში, Cursor-ში ან LM Studio-ში აღწევს ყველა დაინსტალირებულ Craft აპს. დამატების შემდეგ კლიენტი გადატვირთეთ. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft კარიბჭე (craft-ai-mcp) გამშვების გვერდით არ არის დაინსტალირებული. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a39bb265..81ed3b3e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -452,22 +452,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? Aplikacja {app} jest przypięta do wersji {version}. Zamiast tego śledzić najnowsze wydanie? Unlock Odblokuj - Local services Lokalne usługi - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Odsłaniaj aplikacje Craft AI jako serwery MCP, aby LM Studio / Bionic mogło sterować ich narzędziami. - - Craft apps Aplikacje Craft - - No installed Craft app has a usable CLI yet. Żadna zainstalowana aplikacja Craft nie ma jeszcze używalnego CLI. - - Unified bridge Zjednoczony most - - Not found on this machine Nie znaleziono na tym komputerze - - Found Znaleziono - - Port Port - Port applies when you toggle the bridge. Port jest stosowany, gdy przełączysz most. AI agents Agenci AI One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jeden wpis w Claude, Cursorze lub LM Studio daje dostęp do każdej zainstalowanej aplikacji Craft. Po dodaniu uruchom klienta ponownie. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brama Craft (craft-ai-mcp) nie jest zainstalowana obok launchera. diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 74396bfc..4c40d652 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -438,22 +438,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} está fixado na versão {version}. Usar a versão mais recente? Unlock Desbloquear - Local services Serviços locais - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Exponha os aplicativos do Craft AI como servidores MCP para que o LM Studio / Bionic possa controlar suas ferramentas. - - Craft apps Aplicativos Craft - - No installed Craft app has a usable CLI yet. Nenhum aplicativo Craft instalado ainda tem um CLI utilizável. - - Unified bridge Ponte unificada - - Not found on this machine Não encontrado neste computador - - Found Encontrado - - Port Porta - Port applies when you toggle the bridge. A porta é aplicada quando você alterna a ponte. AI agents Agentes de IA One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Uma única entrada no Claude, no Cursor ou no LM Studio alcança todos os apps Craft instalados. Reinicie o cliente depois de adicioná-la. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. O gateway Craft (craft-ai-mcp) não está instalado ao lado do inicializador. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 86721d68..f05ed2c3 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -446,22 +446,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? Для {app} закреплена версия {version}. Перейти на последнюю версию? Unlock Разблокировать - Local services Локальные службы - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. Предоставить приложения Craft AI в качестве MCP-серверов, чтобы LM Studio / Bionic могли управлять их инструментами. - - Craft apps Приложения Craft - - No installed Craft app has a usable CLI yet. Установленное приложение Craft пока не имеет доступного CLI. - - Unified bridge Единый мост - - Not found on this machine Не найдено на этом компьютере - - Found Найдено - - Port Порт - Port applies when you toggle the bridge. Порт применяется при переключении моста. AI agents ИИ-агенты One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Одна запись в Claude, Cursor или LM Studio открывает доступ ко всем установленным приложениям Craft. После добавления перезапустите клиент. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Шлюз Craft (craft-ai-mcp) не установлен рядом с лаунчером. diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index bb882839..85d0251d 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -418,22 +418,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} 已固定为 {version}。是否改为跟随最新版本? Unlock 解锁 - Local services 本地服务 - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. 将 Craft AI 应用暴露为 MCP 服务器,以便 LM Studio / Bionic 可以驱动其工具。 - - Craft apps Craft 应用 - - No installed Craft app has a usable CLI yet. 已安装的 Craft 应用目前还没有可用的 CLI。 - - Unified bridge 统一桥接 - - Not found on this machine 本机未找到 - - Found 已找到 - - Port 端口 - Port applies when you toggle the bridge. 端口在切换桥接时生效。 AI agents AI 智能体 One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中添加一个条目,即可使用所有已安装的 Craft 应用。添加后请重启客户端。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 启动器旁未安装 Craft 网关 (craft-ai-mcp)。 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index 6b93f789..abbf4898 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -409,22 +409,6 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s {app} is pinned to {version}. Follow the latest release instead? {app} 已鎖定為 {version}。是否改為使用最新版本? Unlock 解除鎖定 - Local services 本地服務 - - Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools. 將 Craft AI 應用公開為 MCP 伺服器,以便 LM Studio / Bionic 可以驅動其工具。 - - Craft apps Craft 應用 - - No installed Craft app has a usable CLI yet. 已安裝的 Craft 應用目前還沒有可用的 CLI。 - - Unified bridge 統一橋接 - - Not found on this machine 本機未找到 - - Found 已找到 - - Port 埠口 - Port applies when you toggle the bridge. 埠口在切換橋接時生效。 AI agents AI 代理 One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中加入一個項目,即可使用所有已安裝的 Craft 應用程式。加入後請重新啟動用戶端。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 啟動器旁未安裝 Craft 閘道 (craft-ai-mcp)。 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 09319d99..0bfe2134 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -1,7 +1,7 @@ //! The Settings dialog: a large card in the shape of the app page (see `sheet.rs`), with the //! groups of settings in boxes, two columns once the window is wide enough. -use artcraft_launcher_core::protocol::{Command, McpClientState, McpService}; +use artcraft_launcher_core::protocol::{Command, McpClientState}; use artcraft_launcher_core::{Os, PackageKind}; use egui::{RichText, Ui, vec2}; @@ -119,7 +119,6 @@ impl LauncherUi { this.settings_appearance(ui); this.settings_flags(ui); this.settings_agents(ui); - this.settings_local_mcp(ui); }, |ui| { let Ok(mut state) = state.try_borrow_mut() else { return }; @@ -452,81 +451,4 @@ impl LauncherUi { } }); } - - /// Local MCP services: turn Craft AI apps on or off as MCP servers for LM Studio / Bionic, and - /// manage the unified HTTP bridge. Only shown where the backend can manage installs (desktop). - fn settings_local_mcp(&mut self, ui: &mut Ui) { - if !self.caps.manage_apps { - return; - } - let t = Tokens::get(ui.ctx()); - sheet::panel(ui, tl!("Local services"), |ui| { - note(ui, tl!("Expose Craft AI apps as MCP servers so LM Studio / Bionic can drive their tools.")); - ui.add_space(8.0); - - // Unified bridge (HTTP): editable port + toggle; status shown below the row. Disabled - // until the saved state is known, so a click can't overwrite a saved port. - let known = self.mcp_state_known; - ui.add_enabled_ui(known, |ui| self.draw_bridge_row(ui, &t)); - ui.add_space(12.0); - - // Per-app stdio services in a collapsible section. - egui::CollapsingHeader::new(tl!("Craft apps")).id_salt("mcp-apps").default_open(true).show(ui, |ui| { - // Clone out of self so the per-row toggle (which needs &mut self) doesn't fight the list borrow. - let services = self.mcp_services.clone(); - if services.is_empty() { - note(ui, tl!("No installed Craft app has a usable CLI yet.")); - } else { - for (i, s) in services.iter().enumerate() { - if i > 0 { - ui.add_space(6.0); - } - self.draw_service_row(ui, &t, s); - } - } - }); - }); - } - - /// One row for the unified HTTP bridge: a toggle plus an editable port field; its status (found? - /// version?) is drawn beneath in muted text. - fn draw_bridge_row(&mut self, ui: &mut Ui, t: &Tokens) { - let mut enabled = self.mcp_bridge.enabled; - if ui.checkbox(&mut enabled, tl!("Unified bridge")).changed() && enabled != self.mcp_bridge.enabled { - // The port is applied when the toggle flips; a bad value falls back to the default. - let port: u16 = self.bridge_port.parse().unwrap_or(12345); - self.act_command(Command::McpSetBridge { port, enabled }); - } - ui.add_space(8.0); - // The port field needs an accessible name for screen readers (kittest). - let port_label = ui.label(tl!("Port")); - ui.add(egui::TextEdit::singleline(&mut self.bridge_port).id_salt("mcp-bridge-port").desired_width(72.0)).labelled_by(port_label.id); - // The port is only written when the toggle flips, so say so plainly rather than - // implying a live edit. - ui.label(RichText::new(tl!("Port applies when you toggle the bridge.")).size(12.0).color(t.muted)); - ui.label(RichText::new(self.bridge_status()).size(12.0).color(t.muted)); - } - - /// The bridge's one-line status: whether its binary is present and, when readable, its version. - fn bridge_status(&self) -> String { - if !self.mcp_bridge.found { - return tl!("Not found on this machine").to_string(); - } - match &self.mcp_bridge.version { - Some(v) => format!("{} · v{}", tl!("Found"), v), - None => tl!("Found").to_string(), - } - } - - /// One installed app exposed as a stdio MCP server: a toggle named after the app, with its CLI - /// path shown beneath in muted text. - fn draw_service_row(&mut self, ui: &mut Ui, t: &Tokens, s: &McpService) { - let mut enabled = s.enabled; - if ui.checkbox(&mut enabled, &s.name).changed() && enabled != s.enabled { - self.act_command(Command::McpSetService { service_id: s.id.clone(), enabled }); - } - if !s.command.is_empty() { - ui.label(RichText::new(s.command.as_str()).size(12.0).color(t.muted)); - } - } } diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 344d052b..696dc1f1 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4415,12 +4415,10 @@ fn launcher_version_padlock_confirms_and_returns_to_settings() { /// Settings › AI agents: the switch, and Add / Remove per MCP client, each sending one command. #[test] fn ai_agents_switch_and_client_buttons_send_their_commands() { - use artcraft_launcher_core::protocol::{McpAgents, McpBridge, McpClient, McpClientState}; + use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; let client = |client, name: &str, installed, added| McpClientState { client, name: name.into(), installed, added }; let mut evs = events(); evs.push(Event::Mcp { - services: vec![], - bridge: McpBridge::default(), agents: McpAgents { flag_on: true, gateway_found: true, @@ -4460,11 +4458,7 @@ fn ai_agents_switch_and_client_buttons_send_their_commands() { #[test] fn ai_agents_without_the_gateway_offer_no_switch() { let mut evs = events(); - evs.push(Event::Mcp { - services: vec![], - bridge: artcraft_launcher_core::protocol::McpBridge::default(), - agents: artcraft_launcher_core::protocol::McpAgents { flag_on: true, ..Default::default() }, - }); + evs.push(Event::Mcp { agents: artcraft_launcher_core::protocol::McpAgents { flag_on: true, ..Default::default() } }); let (mut h, _sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); h.run_steps(6); h.get_by_label("Settings").click(); @@ -4477,12 +4471,10 @@ fn ai_agents_without_the_gateway_offer_no_switch() { /// removed; only adding is gone. #[test] fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { - use artcraft_launcher_core::protocol::{McpAgents, McpBridge, McpClient, McpClientState}; + use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; let client = |client, name: &str, added| McpClientState { client, name: name.into(), installed: true, added }; let mut evs = events(); evs.push(Event::Mcp { - services: vec![], - bridge: McpBridge::default(), agents: McpAgents { flag_on: true, gateway_found: false, @@ -4510,15 +4502,11 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { /// With the `AI-MCP` flag off, Settings shows nothing about agents, only the flag to turn on. #[test] fn ai_agents_stay_hidden_until_their_flag_is_on() { - use artcraft_launcher_core::protocol::{FlagState, McpAgents, McpBridge}; + use artcraft_launcher_core::protocol::{FlagState, McpAgents}; let flag = |id: &str, title: &str, on, forced| FlagState { id: id.into(), title: title.into(), description: "d".into(), on, forced }; let mut evs = events(); evs.push(Event::Flags { flags: vec![flag("AI-MCP", "AI agents (MCP)", false, false), flag("AI-MODELS", "AI models and services", false, true)] }); - evs.push(Event::Mcp { - services: vec![], - bridge: McpBridge::default(), - agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![] }, - }); + evs.push(Event::Mcp { agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![] } }); let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); h.run_steps(6); h.get_by_label("Settings").click(); From b2ddff1f0af91f617e3faafb0732b5002708290b Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 20:22:36 +0100 Subject: [PATCH 16/27] Apps get the MCP arguments agents should use The app list gave every app plain `mcp`, so the gateway reached PhotoCraft only headless. PhotoCraft now gets `mcp --live` (the open window, through the connection it publishes, storytold/photocraft#13396) and VectorCraft `mcp --headless` (its plain `mcp` attaches to a control port with no token yet). Each is used only when that install's `mcp --help` names the argument, so an older release still gets plain `mcp` instead of a usage error. Co-Authored-By: Claude Opus 5.5 --- crates/native/src/agents.rs | 41 ++++++++++++++++++++++++-- crates/native/src/agents_tests.rs | 49 +++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 6a3c9333..81c04ee2 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -38,14 +38,49 @@ pub fn mcp_dir() -> Option { } } -/// The app list for `services`: each app with a CLI, started as ` mcp`. Apps without a CLI -/// beside them are left out. +/// Arguments after `mcp` for apps whose plain `mcp` is not what agents should get: +/// - PhotoCraft: `--live` reaches the open window through the connection the app publishes, and +/// starts it when it is closed (storytold/photocraft#13396). +/// - VectorCraft: plain `mcp` attaches to a control port that has no token yet whenever something +/// listens on 7979; `--headless` keeps agents in their own session until it authenticates. +/// +/// Each is used only when that install's CLI accepts it ([`cli_accepts`]), so an older release +/// still gets plain `mcp` instead of an error. +const MCP_EXTRA_ARGS: &[(&str, &[&str])] = &[("photocraft", &["--live"]), ("vectorcraft", &["--headless"])]; + +/// Whether `cli mcp --help` names every argument of `extra` ([`help_names`]). Asking the CLI to +/// parse them is no test: some CLIs print help and succeed whatever comes before `--help`. No +/// console window, standard input closed, 5 s at most. +fn cli_accepts(cli: &Path, extra: &[&str]) -> bool { + let Some(program) = cli.to_str() else { return false }; + crate::process::capture(program, &["mcp", "--help"], std::time::Duration::from_secs(5)).is_some_and(|help| help_names(&help, extra)) +} + +/// Whether `help` has each of `args` as a word of its own (`--live`, not `--lively`). +fn help_names(help: &str, args: &[&str]) -> bool { + let words: Vec<&str> = help.split(|c: char| c.is_whitespace() || "[]|,()=<>`'\"".contains(c)).collect(); + args.iter().all(|a| words.contains(a)) +} + +/// The app list for `services`: each app with a CLI, started as ` mcp` plus its +/// [`MCP_EXTRA_ARGS`]. Apps without a CLI beside them are left out. pub fn apps_json(services: &[InstalledApp]) -> Value { + apps_json_with(services, &cli_accepts) +} + +/// [`apps_json`], asking `accepts` whether a CLI takes an app's extra arguments. +fn apps_json_with(services: &[InstalledApp], accepts: &dyn Fn(&Path, &[&str]) -> bool) -> Value { let apps: Vec = services .iter() .filter_map(|s| { let cli = s.cli_path.as_ref().filter(|p| p.is_absolute())?; - Some(json!({"id": s.id, "name": s.name, "command": cli, "args": ["mcp"]})) + let mut args = vec!["mcp".to_string()]; + if let Some((_, extra)) = MCP_EXTRA_ARGS.iter().find(|(id, _)| *id == s.id) + && accepts(cli, extra) + { + args.extend(extra.iter().map(|a| (*a).to_string())); + } + Some(json!({"id": s.id, "name": s.name, "command": cli, "args": args})) }) .collect(); json!({"version": 1, "apps": apps}) diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index c6ec2238..3f43308f 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -30,6 +30,55 @@ fn the_app_list_has_every_app_with_a_cli_in_the_gateways_format() { assert_eq!(apps[0]["args"], json!(["mcp"])); } +#[test] +fn apps_get_their_extra_mcp_arguments_only_where_the_cli_takes_them() { + let dir = tempfile::tempdir().unwrap(); + let at = |name: &str| dir.path().join(name); + let services = [ + service("photocraft", "PhotoCraft", Some(at("photocraft-cli"))), + service("vectorcraft", "VectorCraft", Some(at("vectorcraft-cli"))), + service("filmcraft", "FilmCraft", Some(at("filmcraft-cli"))), + ]; + let asked = std::cell::RefCell::new(Vec::new()); + let new = apps_json_with(&services, &|cli: &Path, extra: &[&str]| { + asked.borrow_mut().push((cli.file_name().unwrap().to_string_lossy().into_owned(), extra.join(" "))); + true + }); + let args = |list: &Value, i: usize| list["apps"][i]["args"].clone(); + assert_eq!(args(&new, 0), json!(["mcp", "--live"]), "PhotoCraft: the open window"); + assert_eq!(args(&new, 1), json!(["mcp", "--headless"]), "VectorCraft: off its unauthenticated port"); + assert_eq!(args(&new, 2), json!(["mcp"]), "other apps as they are"); + assert_eq!( + *asked.borrow(), + [("photocraft-cli".into(), "--live".into()), ("vectorcraft-cli".into(), "--headless".into())], + "only apps with extras are asked" + ); + // An older release that doesn't know the argument gets plain `mcp`, not a usage error. + let old = apps_json_with(&services, &|_: &Path, _: &[&str]| false); + for i in 0..3 { + assert_eq!(args(&old, i), json!(["mcp"])); + } +} + +#[test] +fn the_help_text_must_name_the_argument_as_a_word() { + let help = "Usage: photocraft-cli mcp [OPTIONS] + --live + Reach the open window + vectorcraft-cli mcp [--connect ADDR | --headless]"; + assert!(help_names(help, &["--live"])); + assert!(help_names(help, &["--headless"]), "inside brackets"); + assert!(!help_names(" --lively", &["--live"])); + assert!(!help_names("bridge to a running app, or live", &["--live"])); + assert!(!help_names(help, &["--live", "--when-closed"]), "every argument"); +} + +#[test] +fn a_cli_that_cannot_run_takes_no_extra_arguments() { + let dir = tempfile::tempdir().unwrap(); + assert!(!cli_accepts(&dir.path().join("missing-cli"), &["--live"])); +} + #[test] fn switching_on_and_off() { let dir = tempfile::tempdir().unwrap(); From a68aa2c829e7c10694dfe8a303b198c3eef7d1df Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:07:21 +0100 Subject: [PATCH 17/27] Claude Desktop from the Store is found; flags only from flags.toml - Windows redirects a packaged app's %APPDATA% into its package, so the Microsoft Store install of Claude Desktop reads %LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\Claude and never sees %APPDATA%\Claude: Settings showed it as not installed. The launcher now uses the package's folder when only the Store install is there. - Settings no longer has an Experimental features box: AI-MCP and AI-MODELS are turned on in ArtCraft/flags.toml or with CRAFT_FLAGS, not by a switch. SetFlag, Event::Flags and FlagState go, with the box's strings in every catalog. The AI agents box still shows only while AI-MCP is on. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/protocol.rs | 20 ---------- crates/native/src/agents.rs | 55 +++++++++++++-------------- crates/native/src/agents_tests.rs | 14 +++++++ crates/native/src/backend.rs | 5 +-- crates/ui-egui/src/app.rs | 10 +---- crates/ui-egui/src/i18n/cs.tsv | 3 -- crates/ui-egui/src/i18n/de.tsv | 3 -- crates/ui-egui/src/i18n/es.tsv | 3 -- crates/ui-egui/src/i18n/fr.tsv | 3 -- crates/ui-egui/src/i18n/hu.tsv | 3 -- crates/ui-egui/src/i18n/ja.tsv | 3 -- crates/ui-egui/src/i18n/ka.tsv | 3 -- crates/ui-egui/src/i18n/pl.tsv | 3 -- crates/ui-egui/src/i18n/pt-BR.tsv | 3 -- crates/ui-egui/src/i18n/ru.tsv | 3 -- crates/ui-egui/src/i18n/zh-CN.tsv | 3 -- crates/ui-egui/src/i18n/zh-TW.tsv | 3 -- crates/ui-egui/src/settings_dialog.rs | 28 +------------- crates/ui-egui/tests/ui.rs | 21 +++------- 19 files changed, 49 insertions(+), 140 deletions(-) diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index b76eba99..0cca36f1 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -85,11 +85,6 @@ pub enum Command { client: McpClient, added: bool, }, - /// Turn a feature flag on or off for the launcher and every Craft app (`ArtCraft/flags.toml`). - SetFlag { - id: String, - on: bool, - }, } /// Parent folders for new installs. Existing installations keep their recorded location. @@ -314,21 +309,6 @@ pub enum Event { McpError { message: String, }, - /// The feature flags and whether each is on. Sent with the MCP state and after a change. - Flags { - flags: Vec, - }, -} - -/// One feature flag as Settings shows it. -#[derive(Clone, Debug, PartialEq)] -pub struct FlagState { - pub id: String, - pub title: String, - pub description: String, - pub on: bool, - /// `CRAFT_FLAGS` decides it for this run, so the switch has no effect until that is gone. - pub forced: bool, } /// An MCP client the launcher can add the gateway entry to. diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 81c04ee2..750c360b 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard, PoisonError}; -use artcraft_launcher_core::protocol::{FlagState, McpAgents, McpClient, McpClientState}; +use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; use serde_json::{Map, Value, json}; use artcraft_launcher_core::CraftApp; @@ -115,7 +115,7 @@ pub fn client_paths(client: McpClient) -> Option<(PathBuf, PathBuf)> { let home = dirs::home_dir()?; Some(match client { McpClient::ClaudeDesktop => { - let dir = dirs::config_dir()?.join("Claude"); + let dir = claude_desktop_dir(dirs::config_dir()?, std::env::var_os("LOCALAPPDATA").map(PathBuf::from).as_deref()); (dir.join("claude_desktop_config.json"), dir) } McpClient::ClaudeCode => (home.join(".claude.json"), home.join(".claude")), @@ -124,6 +124,29 @@ pub fn client_paths(client: McpClient) -> Option<(PathBuf, PathBuf)> { }) } +/// Claude Desktop's settings folder: `/Claude`, unless only the Microsoft Store package is +/// installed. Windows redirects a packaged app's `%APPDATA%` into its package, so that install +/// reads `%LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\Claude` and never sees +/// `%APPDATA%\Claude`. `local_appdata` is `None` outside Windows. +fn claude_desktop_dir(config: PathBuf, local_appdata: Option<&Path>) -> PathBuf { + let classic = config.join("Claude"); + if classic.is_dir() { + return classic; + } + let packaged = local_appdata.and_then(|local| { + let mut found: Vec = std::fs::read_dir(local.join("Packages")) + .ok()? + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("Claude_")) + .map(|e| e.path().join("LocalCache").join("Roaming").join("Claude")) + .filter(|d| d.is_dir()) + .collect(); + found.sort(); + found.into_iter().next() + }); + packaged.unwrap_or(classic) +} + /// A client's display name. pub fn client_name(client: McpClient) -> &'static str { match client { @@ -340,33 +363,7 @@ pub fn flag_on() -> bool { craft_flags::load().enabled(&craft_flags::AI_MCP) } -const NO_FLAG: &str = "turn on \"AI agents (MCP)\" under Experimental features first"; - -/// Every feature flag, for Settings. -pub fn flags_state() -> Vec { - let flags = craft_flags::load(); - craft_flags::ALL - .iter() - .map(|f| FlagState { - id: f.id.to_string(), - title: f.title.to_string(), - description: f.description.to_string(), - on: flags.enabled(f), - forced: flags.forced(f.id).is_some(), - }) - .collect() -} - -/// Turn a feature flag on or off for the launcher and every app. Turning `AI-MCP` off also turns -/// agents off, so no client keeps an entry for a feature that is switched off. -pub fn set_flag(id: &str, on: bool, services: &[InstalledApp]) -> Result<(), String> { - let path = craft_flags::default_path().ok_or("couldn't find the per-user configuration folder")?; - // Clean up first: if that fails, the flag stays on and Settings keeps the controls to retry. - if id == craft_flags::AI_MCP.id && !on { - set_enabled(false, services)?; - } - craft_flags::set(&path, id, on).map_err(|e| e.to_string()) -} +const NO_FLAG: &str = "the AI-MCP feature flag is off (ArtCraft/flags.toml or CRAFT_FLAGS)"; const NO_GATEWAY: &str = "the Craft gateway (craft-ai-mcp) is not installed beside the launcher"; diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 3f43308f..25d16063 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -60,6 +60,20 @@ fn apps_get_their_extra_mcp_arguments_only_where_the_cli_takes_them() { } } +#[test] +fn claude_desktop_from_the_microsoft_store_is_found_in_its_package() { + let dir = tempfile::tempdir().unwrap(); + let (config, local) = (dir.path().join("Roaming"), dir.path().join("Local")); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), config.join("Claude"), "nothing installed: the usual place"); + let packaged = local.join("Packages").join("Claude_pzs8sxrjxfjjc").join("LocalCache").join("Roaming").join("Claude"); + std::fs::create_dir_all(&packaged).unwrap(); + std::fs::create_dir_all(local.join("Packages").join("Other_123")).unwrap(); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), packaged, "only the Store package"); + std::fs::create_dir_all(config.join("Claude")).unwrap(); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), config.join("Claude"), "the classic install wins"); + assert_eq!(claude_desktop_dir(config.clone(), None), config.join("Claude")); +} + #[test] fn the_help_text_must_name_the_argument_as_a_word() { let help = "Usage: photocraft-cli mcp [OPTIONS] diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 2f915080..05d9e93c 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -360,7 +360,6 @@ impl NativeBackend { // Local MCP state: which installed apps can be exposed + the unified bridge. { let _mcp = MCP_WORK.lock().unwrap_or_else(PoisonError::into_inner); - shared.emit(Event::Flags { flags: crate::agents::flags_state() }); shared.emit(mcp_state(&shared)); } drop(busy); @@ -1609,7 +1608,7 @@ impl Backend for NativeBackend { self.check(true); } } - cmd @ (Command::McpState | Command::McpSetAgents { .. } | Command::McpSetClient { .. } | Command::SetFlag { .. }) => { + cmd @ (Command::McpState | Command::McpSetAgents { .. } | Command::McpSetClient { .. }) => { // Detection can run package-manager queries for seconds (flatpak on Linux): // never on the UI thread that sends commands. let shared = self.shared.clone(); @@ -1671,13 +1670,11 @@ fn run_mcp(shared: &Shared, cmd: Command) { let result = match cmd { Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &apps), Command::McpSetClient { client, added } => crate::agents::set_client(client, added), - Command::SetFlag { id, on } => crate::agents::set_flag(&id, on, &apps), _ => Ok(()), }; if let Err(message) = result { shared.emit(Event::McpError { message }); } - shared.emit(Event::Flags { flags: crate::agents::flags_state() }); shared.emit(mcp_state_for(&apps)); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 874c2ef0..fac6996c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -3,8 +3,7 @@ use std::time::Duration; use artcraft_launcher_core::protocol::{ - Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, FlagState, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, PAUSED, - Source, + Backend, BackendOptions, CANCELLED, Capabilities, Command, Event, INSTALL_CANCELLED, JobPhase, LatestRelease, McpAgents, PAUSED, Source, }; use artcraft_launcher_core::release::Release; use artcraft_launcher_core::status::AppStatus; @@ -145,8 +144,6 @@ pub struct LauncherUi { pub(crate) entries: Vec, /// AI agents: the gateway switch and the MCP clients. pub(crate) mcp_agents: McpAgents, - /// The feature flags (Settings › Experimental features). - pub(crate) flags: Vec, /// Whether we've asked for MCP state since the settings dialog last opened (reset when it closes). pub(crate) mcp_requested: bool, pub(crate) caps: Capabilities, @@ -275,7 +272,6 @@ impl LauncherUi { .map(AppEntry::new) .collect(), mcp_agents: McpAgents::default(), - flags: Vec::new(), mcp_requested: false, caps, platform, @@ -658,10 +654,6 @@ impl LauncherUi { self.mcp_agents = agents; false } - Event::Flags { flags } => { - self.flags = flags; - false - } Event::McpError { message } => { // A failed MCP write (e.g. a full disk or an unreadable config) is surfaced so the // user knows their toggle did not take effect. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 25ddd1b8..22398eab 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -426,6 +426,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Přidáno Remove Odebrat Add Přidat - Experimental features Experimentální funkce - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funkce, které se teprve vyvíjejí. Každá je vypnutá, dokud ji zde nezapnete, pro spouštěč i všechny aplikace Craft. - Set by CRAFT_FLAGS for this run. Pro toto spuštění nastaveno proměnnou CRAFT_FLAGS. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b7e28efb..74ec0f2a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -458,6 +458,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Hinzugefügt Remove Entfernen Add Hinzufügen - Experimental features Experimentelle Funktionen - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funktionen, die noch entstehen. Jede ist aus, bis du sie hier einschaltest, für den Launcher und jede Craft-App. - Set by CRAFT_FLAGS for this run. Für diesen Start durch CRAFT_FLAGS festgelegt. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b13e440e..4a9c2247 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -439,6 +439,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Añadida Remove Quitar Add Añadir - Experimental features Funciones experimentales - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funciones que aún se están creando. Cada una está desactivada hasta que la actives aquí, para el lanzador y todas las apps Craft. - Set by CRAFT_FLAGS for this run. Fijado por CRAFT_FLAGS para esta ejecución. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 741afc45..58e70ae1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -456,6 +456,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Ajoutée Remove Retirer Add Ajouter - Experimental features Fonctions expérimentales - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Des fonctions encore en cours de création. Chacune reste désactivée jusqu'à ce que vous l'activiez ici, pour le lanceur et toutes les apps Craft. - Set by CRAFT_FLAGS for this run. Fixé par CRAFT_FLAGS pour ce lancement. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 98030e8f..4e0a6bb7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -459,6 +459,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Hozzáadva Remove Eltávolítás Add Hozzáadás - Experimental features Kísérleti funkciók - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Még fejlesztés alatt álló funkciók. Mindegyik ki van kapcsolva, amíg itt be nem kapcsolja, az indítóban és minden Craft alkalmazásban. - Set by CRAFT_FLAGS for this run. Ehhez a futtatáshoz a CRAFT_FLAGS állítja be. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 527a325f..4f1d1014 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -461,6 +461,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 追加済み Remove 削除 Add 追加 - Experimental features 試験的な機能 - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 開発中の機能です。ここでオンにするまで、ランチャーとすべての Craft アプリでオフのままです。 - Set by CRAFT_FLAGS for this run. この起動では CRAFT_FLAGS で設定されています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cad02f78..f93d9c31 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -457,6 +457,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added დამატებულია Remove წაშლა Add დამატება - Experimental features ექსპერიმენტული ფუნქციები - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. ფუნქციები, რომლებიც ჯერ კიდევ მზადდება. თითოეული გამორთულია, სანამ აქ არ ჩართავთ, გამშვებისა და ყველა Craft აპისთვის. - Set by CRAFT_FLAGS for this run. ამ გაშვებისთვის დაყენებულია CRAFT_FLAGS-ით. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 81ed3b3e..543dce51 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -460,6 +460,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Dodano Remove Usuń Add Dodaj - Experimental features Funkcje eksperymentalne - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Funkcje, które wciąż powstają. Każda jest wyłączona, dopóki jej tu nie włączysz, dla launchera i każdej aplikacji Craft. - Set by CRAFT_FLAGS for this run. Ustawione przez CRAFT_FLAGS na to uruchomienie. diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 4c40d652..4efd4701 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -446,6 +446,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Adicionado Remove Remover Add Adicionar - Experimental features Recursos experimentais - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Recursos ainda em construção. Cada um fica desativado até você ativá-lo aqui, para o inicializador e todos os apps Craft. - Set by CRAFT_FLAGS for this run. Definido por CRAFT_FLAGS nesta execução. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f05ed2c3..52649086 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -454,6 +454,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added Добавлено Remove Удалить Add Добавить - Experimental features Экспериментальные функции - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. Функции, которые ещё в разработке. Каждая выключена, пока вы не включите её здесь, для лаунчера и всех приложений Craft. - Set by CRAFT_FLAGS for this run. Задано через CRAFT_FLAGS для этого запуска. diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 85d0251d..bf8143ef 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -426,6 +426,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 已添加 Remove 移除 Add 添加 - Experimental features 实验性功能 - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 仍在开发中的功能。在此处开启前,它们在启动器和所有 Craft 应用中均处于关闭状态。 - Set by CRAFT_FLAGS for this run. 本次运行由 CRAFT_FLAGS 设定。 diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index abbf4898..ca40eedc 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -417,6 +417,3 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Added 已加入 Remove 移除 Add 加入 - Experimental features 實驗性功能 - Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app. 仍在開發中的功能。在此處開啟前,它們在啟動器和所有 Craft 應用程式中均為關閉。 - Set by CRAFT_FLAGS for this run. 本次執行由 CRAFT_FLAGS 設定。 diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 0bfe2134..1584b1af 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -117,7 +117,6 @@ impl LauncherUi { this.settings_language(ui); this.settings_updates(ui); this.settings_appearance(ui); - this.settings_flags(ui); this.settings_agents(ui); }, |ui| { @@ -376,7 +375,7 @@ impl LauncherUi { /// AI agents: one switch that lets MCP clients reach every installed Craft app through the /// `craft-ai-mcp` gateway, and one Add/Remove button per MCP client found on this machine. fn settings_agents(&mut self, ui: &mut Ui) { - // Behind the `AI-MCP` feature flag (Experimental features). + // Behind the `AI-MCP` feature flag, set in `ArtCraft/flags.toml` or `CRAFT_FLAGS` only. if !self.caps.manage_apps || !self.mcp_agents.flag_on { return; } @@ -407,31 +406,6 @@ impl LauncherUi { }); } - /// Experimental features: a switch per feature flag, shared with every Craft app. - fn settings_flags(&mut self, ui: &mut Ui) { - if !self.caps.manage_apps || self.flags.is_empty() { - return; - } - let t = Tokens::get(ui.ctx()); - let flags = self.flags.clone(); - sheet::panel(ui, tl!("Experimental features"), |ui| { - note(ui, tl!("Features that are still being built. Each is off until you turn it on here, for the launcher and every Craft app.")); - ui.add_space(8.0); - for f in &flags { - let mut on = f.on; - let toggle = ui.add_enabled(!f.forced, egui::Checkbox::new(&mut on, f.title.as_str())); - if toggle.changed() && on != f.on { - self.act_command(Command::SetFlag { id: f.id.clone(), on }); - } - ui.label(RichText::new(f.description.as_str()).size(12.0).color(t.muted)); - if f.forced { - ui.label(RichText::new(tl!("Set by CRAFT_FLAGS for this run.")).size(12.0).color(t.muted)); - } - ui.add_space(6.0); - } - }); - } - /// One MCP client: its name, and Add or Remove (or "Not installed" when it isn't). Add is /// offered only while the gateway is there to add. fn draw_client_row(&mut self, ui: &mut Ui, t: &Tokens, c: &McpClientState, can_add: bool) { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 696dc1f1..9755a049 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4499,27 +4499,18 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { assert!(sent.iter().any(|c| matches!(c, Command::McpSetAgents { enabled: false }))); } -/// With the `AI-MCP` flag off, Settings shows nothing about agents, only the flag to turn on. +/// With the `AI-MCP` flag off, Settings shows nothing about agents, and nothing to switch flags: +/// they are set in `ArtCraft/flags.toml` or `CRAFT_FLAGS` only. #[test] fn ai_agents_stay_hidden_until_their_flag_is_on() { - use artcraft_launcher_core::protocol::{FlagState, McpAgents}; - let flag = |id: &str, title: &str, on, forced| FlagState { id: id.into(), title: title.into(), description: "d".into(), on, forced }; + use artcraft_launcher_core::protocol::McpAgents; let mut evs = events(); - evs.push(Event::Flags { flags: vec![flag("AI-MCP", "AI agents (MCP)", false, false), flag("AI-MODELS", "AI models and services", false, true)] }); evs.push(Event::Mcp { agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![] } }); - let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); + let (mut h, _sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); h.run_steps(6); h.get_by_label("Settings").click(); h.run_steps(4); assert!(h.query_by_label("Let AI agents use Craft apps").is_none(), "no agents box without the flag"); - h.get_by_label("AI agents (MCP)").scroll_to_me(); - h.run_steps(6); - h.get_by_label("Set by CRAFT_FLAGS for this run."); - h.get_by_label("AI agents (MCP)").click(); - h.run_steps(3); - h.get_by_label("AI models and services").click(); - h.run_steps(3); - let sent = sent.borrow(); - assert!(sent.iter().any(|c| matches!(c, Command::SetFlag { id, on: true } if id == "AI-MCP"))); - assert!(!sent.iter().any(|c| matches!(c, Command::SetFlag { id, .. } if id == "AI-MODELS")), "a flag CRAFT_FLAGS sets can't be switched"); + assert!(h.query_by_label("Experimental features").is_none(), "flags have no switches in Settings"); + assert!(h.query_by_label("AI agents (MCP)").is_none()); } From 8739008472c81b1c84c91f8ca063cbf405173e8a Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:17:22 +0100 Subject: [PATCH 18/27] Claude Desktop's settings in Claude-Data are found Current Windows versions of Claude Desktop keep their data in %LOCALAPPDATA%\Claude-Data\ and leave a .user-data-left.* marker in the Store package folder they moved out of. The launcher wrote its entry into that abandoned config, so Claude never saw it. Claude-Data now comes first, then %APPDATA%\Claude, then a package folder without the marker. Co-Authored-By: Claude Opus 5.5 --- crates/native/src/agents.rs | 49 +++++++++++++++++++++---------- crates/native/src/agents_tests.rs | 21 +++++++++++-- 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 750c360b..eff329a1 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -124,27 +124,44 @@ pub fn client_paths(client: McpClient) -> Option<(PathBuf, PathBuf)> { }) } -/// Claude Desktop's settings folder: `/Claude`, unless only the Microsoft Store package is -/// installed. Windows redirects a packaged app's `%APPDATA%` into its package, so that install -/// reads `%LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\Claude` and never sees -/// `%APPDATA%\Claude`. `local_appdata` is `None` outside Windows. +/// Claude Desktop's settings folder, where it reads `claude_desktop_config.json`, best first: +/// 1. `%LOCALAPPDATA%\Claude-Data\` (newest first): current Windows versions keep their +/// data there, outside the Microsoft Store package, and say so in that folder's README. +/// 2. `/Claude` (`%APPDATA%\Claude`): the classic installer, and every other platform. +/// 3. `%LOCALAPPDATA%\Packages\Claude_\LocalCache\Roaming\Claude`: older Store versions, where +/// Windows redirects the package's `%APPDATA%`. A folder whose data has moved on holds a +/// `.user-data-left.*` marker and is skipped. +/// +/// `local_appdata` is `None` outside Windows. With nothing found, the classic folder (not installed). fn claude_desktop_dir(config: PathBuf, local_appdata: Option<&Path>) -> PathBuf { + let subdirs = |dir: PathBuf| -> Vec { + std::fs::read_dir(dir).map(|it| it.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect()).unwrap_or_default() + }; + if let Some(local) = local_appdata { + let mut data = subdirs(local.join("Claude-Data")); + // Newest first; the name breaks ties so the choice is stable. + data.sort_by_key(|d| (std::cmp::Reverse(std::fs::metadata(d).and_then(|m| m.modified()).ok()), d.clone())); + if let Some(d) = data.into_iter().next() { + return d; + } + } let classic = config.join("Claude"); if classic.is_dir() { return classic; } - let packaged = local_appdata.and_then(|local| { - let mut found: Vec = std::fs::read_dir(local.join("Packages")) - .ok()? - .flatten() - .filter(|e| e.file_name().to_string_lossy().starts_with("Claude_")) - .map(|e| e.path().join("LocalCache").join("Roaming").join("Claude")) - .filter(|d| d.is_dir()) - .collect(); - found.sort(); - found.into_iter().next() - }); - packaged.unwrap_or(classic) + let moved = |d: &Path| { + std::fs::read_dir(d).map(|it| it.flatten().any(|e| e.file_name().to_string_lossy().starts_with(".user-data-left."))).unwrap_or(false) + }; + let mut packaged: Vec = local_appdata + .map(|local| subdirs(local.join("Packages"))) + .unwrap_or_default() + .into_iter() + .filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("Claude_"))) + .map(|p| p.join("LocalCache").join("Roaming").join("Claude")) + .filter(|d| d.is_dir() && !moved(d)) + .collect(); + packaged.sort(); + packaged.into_iter().next().unwrap_or(classic) } /// A client's display name. diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 25d16063..4e40b6e7 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -68,12 +68,29 @@ fn claude_desktop_from_the_microsoft_store_is_found_in_its_package() { let packaged = local.join("Packages").join("Claude_pzs8sxrjxfjjc").join("LocalCache").join("Roaming").join("Claude"); std::fs::create_dir_all(&packaged).unwrap(); std::fs::create_dir_all(local.join("Packages").join("Other_123")).unwrap(); - assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), packaged, "only the Store package"); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), packaged, "only an older Store package"); std::fs::create_dir_all(config.join("Claude")).unwrap(); - assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), config.join("Claude"), "the classic install wins"); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), config.join("Claude"), "the classic install wins over the package"); assert_eq!(claude_desktop_dir(config.clone(), None), config.join("Claude")); } +/// Current Windows versions keep their data in `%LOCALAPPDATA%\Claude-Data\` and leave a +/// marker in the package folder they moved out of: the config there is no longer read. +#[test] +fn claude_desktop_data_moved_to_claude_data_is_used() { + let dir = tempfile::tempdir().unwrap(); + let (config, local) = (dir.path().join("Roaming"), dir.path().join("Local")); + let packaged = local.join("Packages").join("Claude_pzs8sxrjxfjjc").join("LocalCache").join("Roaming").join("Claude"); + std::fs::create_dir_all(&packaged).unwrap(); + std::fs::write(packaged.join(".user-data-left.claude_pzs8sxrjxfjjc"), "{}").unwrap(); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), config.join("Claude"), "a package folder the data left is skipped"); + std::fs::create_dir_all(config.join("Claude")).unwrap(); + let data = local.join("Claude-Data").join("claude_pzs8sxrjxfjjc"); + std::fs::create_dir_all(&data).unwrap(); + std::fs::write(local.join("Claude-Data").join("README.txt"), "x").unwrap(); + assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), data, "Claude-Data wins, its README is no install"); +} + #[test] fn the_help_text_must_name_the_argument_as_a_word() { let help = "Usage: photocraft-cli mcp [OPTIONS] From 5d18e3e20cfeea95124b40853be863b4cd5eb5a1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:18:33 +0100 Subject: [PATCH 19/27] build: pin craft-ai-mcp to craft-ai-integrations#197 at 08a639a The gateway now asks the launcher's app list before every call: with the switch off it refuses every tool and stops the app servers it started, and it no longer falls back to CLIs on PATH. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 16 ++++++++-------- apps/craft-ai-mcp/Cargo.toml | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad1f2ad3..64baeeb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -990,7 +990,7 @@ dependencies = [ [[package]] name = "craft-ai-mcp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=dd6c269a1248b5a5e56d3489bc8666a54017fc6b#dd6c269a1248b5a5e56d3489bc8666a54017fc6b" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=08a639ae6fd36631f0ea18214387c020a94fc183#08a639ae6fd36631f0ea18214387c020a94fc183" dependencies = [ "dirs 7.0.0", "serde", @@ -1295,7 +1295,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1690,7 +1690,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3660,7 +3660,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4375,7 +4375,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4432,7 +4432,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4954,7 +4954,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5958,7 +5958,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/apps/craft-ai-mcp/Cargo.toml b/apps/craft-ai-mcp/Cargo.toml index 1cbdb511..9b8c1efd 100644 --- a/apps/craft-ai-mcp/Cargo.toml +++ b/apps/craft-ai-mcp/Cargo.toml @@ -17,4 +17,4 @@ path = "src/main.rs" # The gateway from storytold/craft-ai-integrations (crates/ai-mcp), pinned like the craft-libs crates. # Pinned to the head of storytold/craft-ai-integrations#197 until it merges; re-pin then. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "dd6c269a1248b5a5e56d3489bc8666a54017fc6b" } +craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "08a639ae6fd36631f0ea18214387c020a94fc183" } From 0477241be9e1b3c6d51e54006ab4d9e0ce18cd9c Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:25:14 +0100 Subject: [PATCH 20/27] AI agents box: the switch enables MCP, quick install, copy for other clients - The note says what the switch does: while it is on, MCP clients reach every installed Craft app through one entry; while it is off, no agent reaches them and the entries added here are removed. - Quick install: Add / Remove per client found here, with a note to restart the client. - Other clients: copy the configuration as JSON (`mcpServers`: Claude Desktop, Cursor, LM Studio, Windsurf and most others), for VS Code (`servers`, `type: stdio`) or for Codex (TOML `[mcp_servers.craft-apps]`), naming the gateway copy clients start (`McpAgents::gateway`). The formats live in `artcraft_launcher_core::mcp_config`, with `SERVER_KEY`. - Nine strings, translated in all twelve catalogs; the old note is gone. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/lib.rs | 1 + crates/core/src/mcp_config.rs | 73 +++++++++++++++++++++++++++ crates/core/src/protocol.rs | 2 + crates/native/src/agents.rs | 4 +- crates/ui-egui/src/i18n/cs.tsv | 10 +++- crates/ui-egui/src/i18n/de.tsv | 10 +++- crates/ui-egui/src/i18n/es.tsv | 10 +++- crates/ui-egui/src/i18n/fr.tsv | 10 +++- crates/ui-egui/src/i18n/hu.tsv | 10 +++- crates/ui-egui/src/i18n/ja.tsv | 10 +++- crates/ui-egui/src/i18n/ka.tsv | 10 +++- crates/ui-egui/src/i18n/pl.tsv | 10 +++- crates/ui-egui/src/i18n/pt-BR.tsv | 10 +++- crates/ui-egui/src/i18n/ru.tsv | 10 +++- crates/ui-egui/src/i18n/zh-CN.tsv | 10 +++- crates/ui-egui/src/i18n/zh-TW.tsv | 10 +++- crates/ui-egui/src/settings_dialog.rs | 36 +++++++++++-- crates/ui-egui/tests/ui.rs | 12 ++++- 18 files changed, 231 insertions(+), 17 deletions(-) create mode 100644 crates/core/src/mcp_config.rs diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 76c81705..286e50ee 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,7 @@ pub mod details; pub mod distro; pub mod feed; pub mod hosted_catalog; +pub mod mcp_config; pub mod platform; pub mod protocol; pub mod release; diff --git a/crates/core/src/mcp_config.rs b/crates/core/src/mcp_config.rs new file mode 100644 index 00000000..ae97b477 --- /dev/null +++ b/crates/core/src/mcp_config.rs @@ -0,0 +1,73 @@ +//! The configuration an MCP client needs to start the `craft-ai-mcp` gateway, in each format +//! clients use, for Settings › AI agents › Copy. Every format names the same one server. + +use serde_json::{Value, json}; + +/// The name the gateway's entry has in a client's configuration. +pub const SERVER_KEY: &str = "craft-apps"; + +/// A configuration format MCP clients read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum McpConfigFormat { + /// `{"mcpServers": {...}}`: Claude Desktop, Cursor, LM Studio, Windsurf and most others. + Json, + /// VS Code's `mcp.json`: `{"servers": {...}}` with `"type": "stdio"`. + VsCode, + /// Codex's `config.toml`: a `[mcp_servers.]` table. + CodexToml, +} + +impl McpConfigFormat { + /// Every format, in the order Settings offers them. + pub const ALL: [McpConfigFormat; 3] = [McpConfigFormat::Json, McpConfigFormat::VsCode, McpConfigFormat::CodexToml]; +} + +/// A TOML basic string: JSON's string escapes (`\\`, `\"`, `\uXXXX`) are valid TOML too. +fn toml_string(s: &str) -> String { + Value::String(s.to_string()).to_string() +} + +/// The configuration that starts `gateway --stdio` as [`SERVER_KEY`], in `format`. +pub fn mcp_config(format: McpConfigFormat, gateway: &str) -> String { + match format { + McpConfigFormat::Json => { + let v = json!({"mcpServers": {SERVER_KEY: {"command": gateway, "args": ["--stdio"]}}}); + serde_json::to_string_pretty(&v).unwrap_or_default() + } + McpConfigFormat::VsCode => { + let v = json!({"servers": {SERVER_KEY: {"type": "stdio", "command": gateway, "args": ["--stdio"]}}}); + serde_json::to_string_pretty(&v).unwrap_or_default() + } + McpConfigFormat::CodexToml => { + format!("[mcp_servers.{SERVER_KEY}]\ncommand = {}\nargs = [\"--stdio\"]\n", toml_string(gateway)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const GW: &str = r"C:\Users\a b\AppData\Local\ArtCraft\mcp\bin\craft-ai-mcp.exe"; + + #[test] + fn json_formats_name_the_gateway_with_stdio() { + let v: Value = serde_json::from_str(&mcp_config(McpConfigFormat::Json, GW)).unwrap(); + assert_eq!(v["mcpServers"][SERVER_KEY]["command"], GW); + assert_eq!(v["mcpServers"][SERVER_KEY]["args"], json!(["--stdio"])); + let v: Value = serde_json::from_str(&mcp_config(McpConfigFormat::VsCode, GW)).unwrap(); + assert_eq!(v["servers"][SERVER_KEY]["type"], "stdio"); + assert_eq!(v["servers"][SERVER_KEY]["command"], GW); + assert_eq!(v["servers"][SERVER_KEY]["args"], json!(["--stdio"])); + } + + #[test] + fn codex_toml_escapes_the_path() { + let t = mcp_config(McpConfigFormat::CodexToml, GW); + assert!(t.starts_with("[mcp_servers.craft-apps]\n"), "{t}"); + assert!(t.contains(r#"command = "C:\\Users\\a b\\AppData\\Local\\ArtCraft\\mcp\\bin\\craft-ai-mcp.exe""#), "{t}"); + assert!(t.contains("args = [\"--stdio\"]"), "{t}"); + let quoted = mcp_config(McpConfigFormat::CodexToml, "/opt/a\"b/craft-ai-mcp"); + assert!(quoted.contains(r#"command = "/opt/a\"b/craft-ai-mcp""#), "{quoted}"); + } +} diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index 0cca36f1..bef8b706 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -340,6 +340,8 @@ pub struct McpAgents { /// How many installed apps agents can reach (those with a CLI). pub apps: usize, pub clients: Vec, + /// The gateway clients start, while agents are on: what Copy puts in a configuration. + pub gateway: Option, } /// What a backend can do on this platform. diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index eff329a1..90bd9b28 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -25,7 +25,7 @@ pub const APPS_FILE: &str = "apps.json"; /// Same override the gateway honours (tests, portable installs). pub const DIR_ENV: &str = "CRAFT_MCP_DIR"; /// The key our entry has in a client's `mcpServers`. -pub const SERVER_KEY: &str = "craft-apps"; +pub use artcraft_launcher_core::mcp_config::SERVER_KEY; /// Largest client configuration read; anything bigger is not a configuration file. const MAX_CONFIG_BYTES: u64 = 64 << 20; @@ -366,10 +366,12 @@ pub fn state(services: &[InstalledApp]) -> McpAgents { } }) .collect(); + let gateway = dir.as_deref().filter(|_| on).map(gateway_copy).filter(|p| p.is_file()).map(|p| p.to_string_lossy().into_owned()); McpAgents { flag_on, gateway_found: locate_gateway().is_some(), enabled: on, + gateway, apps: services.iter().filter(|s| s.cli_path.as_ref().is_some_and(|p| p.is_absolute())).count(), clients, } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 22398eab..c3ad3439 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -419,7 +419,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Odemknout AI agents AI agenti - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jedna položka v Claude, Cursoru nebo LM Studiu dosáhne na každou nainstalovanou aplikaci Craft. Po přidání klienta restartujte. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Když je tato volba zapnutá, mohou aplikace AI, které používají MCP, například Claude, Cursor nebo LM Studio, pracovat přes jednu položku s každou nainstalovanou aplikací Craft. Když je vypnutá, žádný agent se k nim nedostane a položky přidané zde se odeberou. + Quick install Rychlá instalace + Adds the Craft apps to that client. Restart the client afterwards. Přidá aplikace Craft do tohoto klienta. Potom klienta restartujte. + Other clients Další klienti + Copy the configuration and paste it into the client's MCP settings. Zkopírujte konfiguraci a vložte ji do nastavení MCP klienta. + Copy JSON Kopírovat JSON + Copy for VS Code Kopírovat pro VS Code + Copy for Codex (TOML) Kopírovat pro Codex (TOML) + Configuration copied. Konfigurace zkopírována. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brána Craft (craft-ai-mcp) není nainstalována vedle spouštěče. Let AI agents use Craft apps Povolit AI agentům používat aplikace Craft Apps agents can reach: {count} Aplikace dostupné agentům: {count} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 74ec0f2a..23d223fc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -451,7 +451,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Entsperren AI agents KI-Agenten - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Ein Eintrag in Claude, Cursor oder LM Studio erreicht jede installierte Craft-App. Starte den Client neu, nachdem du ihn hinzugefügt hast. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Solange dies an ist, können KI-Apps mit MCP, etwa Claude, Cursor oder LM Studio, über einen Eintrag mit jeder installierten Craft-App arbeiten. Ist es aus, erreicht kein Agent sie, und die hier hinzugefügten Einträge werden entfernt. + Quick install Schnellinstallation + Adds the Craft apps to that client. Restart the client afterwards. Fügt die Craft-Apps zu diesem Client hinzu. Starte den Client danach neu. + Other clients Andere Clients + Copy the configuration and paste it into the client's MCP settings. Kopiere die Konfiguration und füge sie in die MCP-Einstellungen des Clients ein. + Copy JSON JSON kopieren + Copy for VS Code Für VS Code kopieren + Copy for Codex (TOML) Für Codex kopieren (TOML) + Configuration copied. Konfiguration kopiert. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Das Craft-Gateway (craft-ai-mcp) ist nicht neben dem Launcher installiert. Let AI agents use Craft apps KI-Agenten Craft-Apps nutzen lassen Apps agents can reach: {count} Apps, die Agenten erreichen: {count} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4a9c2247..b71d008b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -432,7 +432,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Desbloquear AI agents Agentes de IA - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Una sola entrada en Claude, Cursor o LM Studio llega a todas las apps Craft instaladas. Reinicia el cliente después de añadirla. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Mientras esto esté activado, las apps de IA que usan MCP, como Claude, Cursor o LM Studio, pueden trabajar con todas las apps Craft instaladas mediante una sola entrada. Si está desactivado, ningún agente puede llegar a ellas y se quitan las entradas añadidas aquí. + Quick install Instalación rápida + Adds the Craft apps to that client. Restart the client afterwards. Añade las apps Craft a ese cliente. Reinicia el cliente después. + Other clients Otros clientes + Copy the configuration and paste it into the client's MCP settings. Copia la configuración y pégala en los ajustes de MCP del cliente. + Copy JSON Copiar JSON + Copy for VS Code Copiar para VS Code + Copy for Codex (TOML) Copiar para Codex (TOML) + Configuration copied. Configuración copiada. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La pasarela Craft (craft-ai-mcp) no está instalada junto al lanzador. Let AI agents use Craft apps Permitir que los agentes de IA usen las apps Craft Apps agents can reach: {count} Apps que los agentes pueden usar: {count} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 58e70ae1..e80c366d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -449,7 +449,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Déverrouiller AI agents Agents IA - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Une seule entrée dans Claude, Cursor ou LM Studio atteint toutes les apps Craft installées. Redémarrez le client après l'avoir ajoutée. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Tant que cette option est activée, les apps d'IA qui utilisent MCP, comme Claude, Cursor ou LM Studio, peuvent travailler avec toutes les apps Craft installées grâce à une seule entrée. Désactivée, aucun agent ne peut les atteindre et les entrées ajoutées ici sont retirées. + Quick install Installation rapide + Adds the Craft apps to that client. Restart the client afterwards. Ajoute les apps Craft à ce client. Redémarrez ensuite le client. + Other clients Autres clients + Copy the configuration and paste it into the client's MCP settings. Copiez la configuration et collez-la dans les réglages MCP du client. + Copy JSON Copier le JSON + Copy for VS Code Copier pour VS Code + Copy for Codex (TOML) Copier pour Codex (TOML) + Configuration copied. Configuration copiée. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La passerelle Craft (craft-ai-mcp) n'est pas installée à côté du lanceur. Let AI agents use Craft apps Permettre aux agents IA d'utiliser les apps Craft Apps agents can reach: {count} Apps accessibles aux agents : {count} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4e0a6bb7..802672e3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -452,7 +452,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Feloldás AI agents AI-ügynökök - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Egyetlen bejegyzés a Claude-ban, a Cursorban vagy az LM Studióban eléri az összes telepített Craft alkalmazást. Hozzáadás után indítsa újra a klienst. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Amíg ez be van kapcsolva, az MCP-t használó AI-alkalmazások, például a Claude, a Cursor vagy az LM Studio, egyetlen bejegyzésen át dolgozhatnak minden telepített Craft alkalmazással. Kikapcsolva egyetlen ügynök sem éri el őket, és az itt hozzáadott bejegyzések törlődnek. + Quick install Gyors telepítés + Adds the Craft apps to that client. Restart the client afterwards. Hozzáadja a Craft alkalmazásokat ehhez a klienshez. Utána indítsa újra a klienst. + Other clients Más kliensek + Copy the configuration and paste it into the client's MCP settings. Másolja ki a konfigurációt, és illessze be a kliens MCP-beállításaiba. + Copy JSON JSON másolása + Copy for VS Code Másolás VS Code-hoz + Copy for Codex (TOML) Másolás Codexhez (TOML) + Configuration copied. Konfiguráció kimásolva. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. A Craft átjáró (craft-ai-mcp) nincs telepítve az indító mellé. Let AI agents use Craft apps AI-ügynökök használhatják a Craft alkalmazásokat Apps agents can reach: {count} Ügynökök által elérhető alkalmazások: {count} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4f1d1014..79174a04 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -454,7 +454,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock 固定を解除 AI agents AI エージェント - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Claude、Cursor、LM Studio に 1 つ登録するだけで、インストール済みのすべての Craft アプリを使えます。追加したらクライアントを再起動してください。 + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. これをオンにしている間、Claude、Cursor、LM Studio など MCP を使う AI アプリは、1 つの登録でインストール済みのすべての Craft アプリを使えます。オフにすると、どのエージェントもアクセスできなくなり、ここで追加した登録は削除されます。 + Quick install クイックインストール + Adds the Craft apps to that client. Restart the client afterwards. そのクライアントに Craft アプリを追加します。追加後にクライアントを再起動してください。 + Other clients その他のクライアント + Copy the configuration and paste it into the client's MCP settings. 設定をコピーして、クライアントの MCP 設定に貼り付けてください。 + Copy JSON JSON をコピー + Copy for VS Code VS Code 用にコピー + Copy for Codex (TOML) Codex 用にコピー (TOML) + Configuration copied. 設定をコピーしました。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft ゲートウェイ (craft-ai-mcp) がランチャーと同じ場所にインストールされていません。 Let AI agents use Craft apps AI エージェントに Craft アプリの使用を許可 Apps agents can reach: {count} エージェントが使えるアプリ: {count} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f93d9c31..28b1665f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -450,7 +450,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock განბლოკვა AI agents AI აგენტები - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. ერთი ჩანაწერი Claude-ში, Cursor-ში ან LM Studio-ში აღწევს ყველა დაინსტალირებულ Craft აპს. დამატების შემდეგ კლიენტი გადატვირთეთ. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. სანამ ეს ჩართულია, MCP-ის მქონე AI აპებს, მაგალითად Claude-ს, Cursor-ს ან LM Studio-ს, ერთი ჩანაწერით შეუძლიათ ყველა დაინსტალირებულ Craft აპთან მუშაობა. გამორთვისას ვერცერთი აგენტი ვერ მიაღწევს მათ და აქ დამატებული ჩანაწერები წაიშლება. + Quick install სწრაფი დაყენება + Adds the Craft apps to that client. Restart the client afterwards. ამატებს Craft აპებს ამ კლიენტში. შემდეგ კლიენტი გადატვირთეთ. + Other clients სხვა კლიენტები + Copy the configuration and paste it into the client's MCP settings. დააკოპირეთ კონფიგურაცია და ჩასვით კლიენტის MCP პარამეტრებში. + Copy JSON JSON-ის კოპირება + Copy for VS Code კოპირება VS Code-ისთვის + Copy for Codex (TOML) კოპირება Codex-ისთვის (TOML) + Configuration copied. კონფიგურაცია დაკოპირდა. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft კარიბჭე (craft-ai-mcp) გამშვების გვერდით არ არის დაინსტალირებული. Let AI agents use Craft apps AI აგენტებს Craft აპების გამოყენების ნება Apps agents can reach: {count} აგენტებისთვის ხელმისაწვდომი აპები: {count} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 543dce51..8f39817d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -453,7 +453,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Odblokuj AI agents Agenci AI - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Jeden wpis w Claude, Cursorze lub LM Studio daje dostęp do każdej zainstalowanej aplikacji Craft. Po dodaniu uruchom klienta ponownie. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Gdy ta opcja jest włączona, aplikacje AI korzystające z MCP, takie jak Claude, Cursor czy LM Studio, mogą przez jeden wpis pracować z każdą zainstalowaną aplikacją Craft. Gdy jest wyłączona, żaden agent nie ma do nich dostępu, a dodane tutaj wpisy są usuwane. + Quick install Szybka instalacja + Adds the Craft apps to that client. Restart the client afterwards. Dodaje aplikacje Craft do tego klienta. Potem uruchom klienta ponownie. + Other clients Inni klienci + Copy the configuration and paste it into the client's MCP settings. Skopiuj konfigurację i wklej ją w ustawieniach MCP klienta. + Copy JSON Kopiuj JSON + Copy for VS Code Kopiuj dla VS Code + Copy for Codex (TOML) Kopiuj dla Codex (TOML) + Configuration copied. Skopiowano konfigurację. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brama Craft (craft-ai-mcp) nie jest zainstalowana obok launchera. Let AI agents use Craft apps Pozwól agentom AI używać aplikacji Craft Apps agents can reach: {count} Aplikacje dostępne dla agentów: {count} diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 4efd4701..9d14ae6a 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -439,7 +439,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Desbloquear AI agents Agentes de IA - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Uma única entrada no Claude, no Cursor ou no LM Studio alcança todos os apps Craft instalados. Reinicie o cliente depois de adicioná-la. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Enquanto isto estiver ativado, apps de IA que usam MCP, como Claude, Cursor ou LM Studio, podem trabalhar com todos os apps Craft instalados por meio de uma única entrada. Desativado, nenhum agente consegue alcançá-los, e as entradas adicionadas aqui são removidas. + Quick install Instalação rápida + Adds the Craft apps to that client. Restart the client afterwards. Adiciona os apps Craft a esse cliente. Reinicie o cliente depois. + Other clients Outros clientes + Copy the configuration and paste it into the client's MCP settings. Copie a configuração e cole-a nas configurações de MCP do cliente. + Copy JSON Copiar JSON + Copy for VS Code Copiar para o VS Code + Copy for Codex (TOML) Copiar para o Codex (TOML) + Configuration copied. Configuração copiada. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. O gateway Craft (craft-ai-mcp) não está instalado ao lado do inicializador. Let AI agents use Craft apps Permitir que agentes de IA usem os apps Craft Apps agents can reach: {count} Apps que os agentes alcançam: {count} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 52649086..9db78cc4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -447,7 +447,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock Разблокировать AI agents ИИ-агенты - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. Одна запись в Claude, Cursor или LM Studio открывает доступ ко всем установленным приложениям Craft. После добавления перезапустите клиент. + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. Пока этот параметр включён, ИИ-приложения с поддержкой MCP, например Claude, Cursor или LM Studio, могут работать со всеми установленными приложениями Craft через одну запись. Когда он выключен, ни один агент не получит к ним доступ, а добавленные здесь записи удаляются. + Quick install Быстрая установка + Adds the Craft apps to that client. Restart the client afterwards. Добавляет приложения Craft в этот клиент. Затем перезапустите клиент. + Other clients Другие клиенты + Copy the configuration and paste it into the client's MCP settings. Скопируйте конфигурацию и вставьте её в настройки MCP клиента. + Copy JSON Копировать JSON + Copy for VS Code Копировать для VS Code + Copy for Codex (TOML) Копировать для Codex (TOML) + Configuration copied. Конфигурация скопирована. The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Шлюз Craft (craft-ai-mcp) не установлен рядом с лаунчером. Let AI agents use Craft apps Разрешить ИИ-агентам использовать приложения Craft Apps agents can reach: {count} Приложения, доступные агентам: {count} diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index bf8143ef..80160b2d 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -419,7 +419,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock 解锁 AI agents AI 智能体 - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中添加一个条目,即可使用所有已安装的 Craft 应用。添加后请重启客户端。 + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. 开启后,Claude、Cursor 或 LM Studio 等使用 MCP 的 AI 应用只需一个条目,即可使用所有已安装的 Craft 应用。关闭后,任何智能体都无法访问它们,并会移除在此添加的条目。 + Quick install 快速安装 + Adds the Craft apps to that client. Restart the client afterwards. 将 Craft 应用添加到该客户端。之后请重启客户端。 + Other clients 其他客户端 + Copy the configuration and paste it into the client's MCP settings. 复制配置,并将其粘贴到客户端的 MCP 设置中。 + Copy JSON 复制 JSON + Copy for VS Code 复制为 VS Code 格式 + Copy for Codex (TOML) 复制为 Codex 格式 (TOML) + Configuration copied. 已复制配置。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 启动器旁未安装 Craft 网关 (craft-ai-mcp)。 Let AI agents use Craft apps 允许 AI 智能体使用 Craft 应用 Apps agents can reach: {count} 智能体可用的应用:{count} diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index ca40eedc..0ac3aab8 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -410,7 +410,15 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Unlock 解除鎖定 AI agents AI 代理 - One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it. 在 Claude、Cursor 或 LM Studio 中加入一個項目,即可使用所有已安裝的 Craft 應用程式。加入後請重新啟動用戶端。 + While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed. 開啟後,Claude、Cursor 或 LM Studio 等使用 MCP 的 AI 應用程式只需一個項目,即可使用所有已安裝的 Craft 應用程式。關閉後,任何代理都無法存取它們,並會移除在此加入的項目。 + Quick install 快速安裝 + Adds the Craft apps to that client. Restart the client afterwards. 將 Craft 應用程式加入該用戶端。之後請重新啟動用戶端。 + Other clients 其他用戶端 + Copy the configuration and paste it into the client's MCP settings. 複製設定,並將其貼到用戶端的 MCP 設定中。 + Copy JSON 複製 JSON + Copy for VS Code 複製為 VS Code 格式 + Copy for Codex (TOML) 複製為 Codex 格式 (TOML) + Configuration copied. 已複製設定。 The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 啟動器旁未安裝 Craft 閘道 (craft-ai-mcp)。 Let AI agents use Craft apps 允許 AI 代理使用 Craft 應用程式 Apps agents can reach: {count} 代理可使用的應用程式:{count} diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 1584b1af..1ab9c3dc 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -1,6 +1,7 @@ //! The Settings dialog: a large card in the shape of the app page (see `sheet.rs`), with the //! groups of settings in boxes, two columns once the window is wide enough. +use artcraft_launcher_core::mcp_config::{McpConfigFormat, mcp_config}; use artcraft_launcher_core::protocol::{Command, McpClientState}; use artcraft_launcher_core::{Os, PackageKind}; use egui::{RichText, Ui, vec2}; @@ -373,7 +374,9 @@ impl LauncherUi { } /// AI agents: one switch that lets MCP clients reach every installed Craft app through the - /// `craft-ai-mcp` gateway, and one Add/Remove button per MCP client found on this machine. + /// `craft-ai-mcp` gateway (it is the person's consent: off, no agent reaches any app), then + /// quick install (Add/Remove per MCP client found here) and the configuration to copy for any + /// other client. fn settings_agents(&mut self, ui: &mut Ui) { // Behind the `AI-MCP` feature flag, set in `ArtCraft/flags.toml` or `CRAFT_FLAGS` only. if !self.caps.manage_apps || !self.mcp_agents.flag_on { @@ -381,7 +384,12 @@ impl LauncherUi { } let t = Tokens::get(ui.ctx()); sheet::panel(ui, tl!("AI agents"), |ui| { - note(ui, tl!("One entry in Claude, Cursor or LM Studio reaches every installed Craft app. Restart the client after adding it.")); + note( + ui, + tl!( + "While this is on, AI apps that use MCP, such as Claude, Cursor or LM Studio, can work with every installed Craft app through one entry. While it is off, no agent can reach them, and the entries added here are removed." + ), + ); ui.add_space(8.0); let agents = self.mcp_agents.clone(); if !agents.gateway_found { @@ -399,10 +407,32 @@ impl LauncherUi { return; } ui.label(RichText::new(tl!("Apps agents can reach: {count}").replace("{count}", &agents.apps.to_string())).size(12.0).color(t.muted)); - ui.add_space(8.0); + ui.add_space(10.0); + ui.label(RichText::new(tl!("Quick install")).strong()); + note(ui, tl!("Adds the Craft apps to that client. Restart the client afterwards.")); + ui.add_space(4.0); for c in &agents.clients { self.draw_client_row(ui, &t, c, agents.gateway_found); } + if let Some(gateway) = agents.gateway.as_deref() { + ui.add_space(10.0); + ui.label(RichText::new(tl!("Other clients")).strong()); + note(ui, tl!("Copy the configuration and paste it into the client's MCP settings.")); + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + for format in McpConfigFormat::ALL { + let label = match format { + McpConfigFormat::Json => tl!("Copy JSON"), + McpConfigFormat::VsCode => tl!("Copy for VS Code"), + McpConfigFormat::CodexToml => tl!("Copy for Codex (TOML)"), + }; + if ui.button(label).clicked() { + ui.ctx().copy_text(mcp_config(format, gateway)); + self.toast(tl!("Configuration copied."), false); + } + } + }); + } }); } diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 9755a049..638a605b 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4429,6 +4429,7 @@ fn ai_agents_switch_and_client_buttons_send_their_commands() { client(McpClient::Cursor, "Cursor", true, true), client(McpClient::LmStudio, "LM Studio", false, false), ], + gateway: Some("C:/gw/craft-ai-mcp.exe".into()), }, }); let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); @@ -4438,6 +4439,14 @@ fn ai_agents_switch_and_client_buttons_send_their_commands() { h.get_by_label("Apps agents can reach: 3").scroll_to_me(); h.run_steps(6); snapshot(&mut h, "settings-ai-agents"); + // Other clients: the configuration in each format, copied with a note saying so. + for label in ["Copy JSON", "Copy for VS Code", "Copy for Codex (TOML)"] { + h.get_by_label(label).scroll_to_me(); + h.run_steps(2); + h.get_by_label(label).click(); + h.run_steps(3); + assert!(h.query_all_by_label("Configuration copied.").next().is_some(), "{label}"); + } h.get_by_label("Add").click(); h.run_steps(3); h.get_by_label("Remove").click(); @@ -4481,6 +4490,7 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { enabled: true, apps: 2, clients: vec![client(McpClient::ClaudeDesktop, "Claude Desktop", false), client(McpClient::Cursor, "Cursor", true)], + gateway: None, }, }); let (mut h, sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); @@ -4505,7 +4515,7 @@ fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { fn ai_agents_stay_hidden_until_their_flag_is_on() { use artcraft_launcher_core::protocol::McpAgents; let mut evs = events(); - evs.push(Event::Mcp { agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![] } }); + evs.push(Event::Mcp { agents: McpAgents { flag_on: false, gateway_found: true, enabled: true, apps: 3, clients: vec![], gateway: None } }); let (mut h, _sent) = harness_with(evs, ViewMode::Grid, egui::Theme::Dark, true, 1.0); h.run_steps(6); h.get_by_label("Settings").click(); From afaaa8f872a6a3d8f02b552b3f086e058bf45dbf Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 21:58:10 +0100 Subject: [PATCH 21/27] MCP entry is named ArtCraft; offer to restart Claude Desktop after adding - The entry in a client's configuration (and in the copied JSON, VS Code and Codex formats) is `ArtCraft`, which clients show as the integration's name, instead of `craft-apps`. - Right after Add, a client the launcher can restart (Claude Desktop on Windows and macOS) gets a note on why it must restart (it loads MCP servers only when it starts; restarting closes it, including a reply in progress) and a Restart button (`Command::McpRestartClient`). On Windows only Claude Desktop's processes are stopped, picked by install folder (Store package or classic install), never `claude.exe` by name, which is also Claude Code's CLI; it is started again through its Start menu entry. On macOS it quits through AppleScript and `open -a Claude` starts it. - Three strings in all twelve catalogs. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/mcp_config.rs | 7 +++-- crates/core/src/protocol.rs | 6 ++++ crates/native/src/agents.rs | 17 ++++++++++- crates/native/src/backend.rs | 3 +- crates/native/src/process.rs | 38 ++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 4 +++ crates/ui-egui/src/i18n/cs.tsv | 3 ++ crates/ui-egui/src/i18n/de.tsv | 3 ++ crates/ui-egui/src/i18n/es.tsv | 3 ++ crates/ui-egui/src/i18n/fr.tsv | 3 ++ crates/ui-egui/src/i18n/hu.tsv | 3 ++ crates/ui-egui/src/i18n/ja.tsv | 3 ++ crates/ui-egui/src/i18n/ka.tsv | 3 ++ crates/ui-egui/src/i18n/pl.tsv | 3 ++ crates/ui-egui/src/i18n/pt-BR.tsv | 3 ++ crates/ui-egui/src/i18n/ru.tsv | 3 ++ crates/ui-egui/src/i18n/zh-CN.tsv | 3 ++ crates/ui-egui/src/i18n/zh-TW.tsv | 3 ++ crates/ui-egui/src/settings_dialog.rs | 24 +++++++++++++++ crates/ui-egui/tests/ui.rs | 42 +++++++++++++++++++++++++-- 20 files changed, 170 insertions(+), 7 deletions(-) diff --git a/crates/core/src/mcp_config.rs b/crates/core/src/mcp_config.rs index ae97b477..3b1e8972 100644 --- a/crates/core/src/mcp_config.rs +++ b/crates/core/src/mcp_config.rs @@ -3,8 +3,9 @@ use serde_json::{Value, json}; -/// The name the gateway's entry has in a client's configuration. -pub const SERVER_KEY: &str = "craft-apps"; +/// The name the gateway's entry has in a client's configuration. Clients show it as the +/// integration's name, so it is the suite's name. +pub const SERVER_KEY: &str = "ArtCraft"; /// A configuration format MCP clients read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -64,7 +65,7 @@ mod tests { #[test] fn codex_toml_escapes_the_path() { let t = mcp_config(McpConfigFormat::CodexToml, GW); - assert!(t.starts_with("[mcp_servers.craft-apps]\n"), "{t}"); + assert!(t.starts_with("[mcp_servers.ArtCraft]\n"), "{t}"); assert!(t.contains(r#"command = "C:\\Users\\a b\\AppData\\Local\\ArtCraft\\mcp\\bin\\craft-ai-mcp.exe""#), "{t}"); assert!(t.contains("args = [\"--stdio\"]"), "{t}"); let quoted = mcp_config(McpConfigFormat::CodexToml, "/opt/a\"b/craft-ai-mcp"); diff --git a/crates/core/src/protocol.rs b/crates/core/src/protocol.rs index bef8b706..48f986f7 100644 --- a/crates/core/src/protocol.rs +++ b/crates/core/src/protocol.rs @@ -85,6 +85,10 @@ pub enum Command { client: McpClient, added: bool, }, + /// Quit an MCP client and start it again, so it loads the entry just added. + McpRestartClient { + client: McpClient, + }, } /// Parent folders for new installs. Existing installations keep their recorded location. @@ -327,6 +331,8 @@ pub struct McpClientState { pub name: String, pub installed: bool, pub added: bool, + /// The launcher can quit and start it again ([`Command::McpRestartClient`]). + pub restartable: bool, } /// AI agents and the Craft apps: the `craft-ai-mcp` gateway (found beside the launcher?), the diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 90bd9b28..078723ab 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -3,7 +3,7 @@ //! With the switch on, the launcher writes the installed apps and their CLIs into //! `ArtCraft/mcp/apps.json` (the list the `craft-ai-mcp` gateway reads, see //! `docs/CRAFT-AI-MCP.md` in storytold/craft-ai-integrations), and can add one stdio entry, -//! `craft-apps` → `craft-ai-mcp --stdio`, to Claude Desktop, Claude Code, Cursor and LM Studio. +//! `ArtCraft` → `craft-ai-mcp --stdio`, to Claude Desktop, Claude Code, Cursor and LM Studio. //! Through that one entry an agent reaches every installed app, without one entry per app. //! //! Turning the switch off removes the list and the entries this module added. A client @@ -363,6 +363,7 @@ pub fn state(services: &[InstalledApp]) -> McpAgents { name: client_name(*c).to_string(), installed: paths.as_ref().is_some_and(|(config, folder)| folder.is_dir() || config.is_file()), added: paths.as_ref().is_some_and(|(config, _)| registered(config)), + restartable: restartable(*c), } }) .collect(); @@ -436,6 +437,20 @@ pub fn set_client(client: McpClient, added: bool) -> Result<(), String> { register(&config, &gateway) } +/// Whether the launcher can restart `client` here: Claude Desktop on Windows and macOS. The other +/// clients are left to the person (Claude Code runs in their terminal sessions). +pub fn restartable(client: McpClient) -> bool { + client == McpClient::ClaudeDesktop && (cfg!(windows) || cfg!(target_os = "macos")) +} + +/// Quit `client` and start it again, so it loads the entry just added. +pub fn restart_client(client: McpClient) -> Result<(), String> { + if !restartable(client) { + return Err(format!("the launcher can't restart {} here; restart it yourself", client_name(client))); + } + crate::process::restart_claude_desktop() +} + #[cfg(test)] #[path = "agents_tests.rs"] mod tests; diff --git a/crates/native/src/backend.rs b/crates/native/src/backend.rs index 05d9e93c..93674685 100644 --- a/crates/native/src/backend.rs +++ b/crates/native/src/backend.rs @@ -1608,7 +1608,7 @@ impl Backend for NativeBackend { self.check(true); } } - cmd @ (Command::McpState | Command::McpSetAgents { .. } | Command::McpSetClient { .. }) => { + cmd @ (Command::McpState | Command::McpSetAgents { .. } | Command::McpSetClient { .. } | Command::McpRestartClient { .. }) => { // Detection can run package-manager queries for seconds (flatpak on Linux): // never on the UI thread that sends commands. let shared = self.shared.clone(); @@ -1670,6 +1670,7 @@ fn run_mcp(shared: &Shared, cmd: Command) { let result = match cmd { Command::McpSetAgents { enabled } => crate::agents::set_enabled(enabled, &apps), Command::McpSetClient { client, added } => crate::agents::set_client(client, added), + Command::McpRestartClient { client } => crate::agents::restart_client(client), _ => Ok(()), }; if let Err(message) = result { diff --git a/crates/native/src/process.rs b/crates/native/src/process.rs index ce762e21..cb208cf8 100644 --- a/crates/native/src/process.rs +++ b/crates/native/src/process.rs @@ -505,6 +505,44 @@ fn explorer_select_arg(path: &Path) -> Option { Some(arg) } +/// The PowerShell script that restarts Claude Desktop on Windows. Its processes are picked by +/// install folder (the Microsoft Store package or the classic per-user install), never by name +/// alone: `claude.exe` is also Claude Code's command-line program, whose sessions must keep running. +/// It is started again through its Start menu entry, which works for both installs. +pub const CLAUDE_DESKTOP_RESTART_PS: &str = r#"$ErrorActionPreference = 'Stop' +$app = Get-StartApps | Where-Object { $_.Name -eq 'Claude' } | Select-Object -First 1 +if (-not $app) { throw 'Claude Desktop is not in the Start menu.' } +$running = @(Get-Process -Name claude -ErrorAction SilentlyContinue | Where-Object { $_.Path -like '*\WindowsApps\Claude_*' -or $_.Path -like '*\AnthropicClaude\*' }) +$running | Stop-Process -Force -ErrorAction SilentlyContinue +foreach ($p in $running) { $null = $p.WaitForExit(10000) } +Start-Process ('shell:AppsFolder\' + $app.AppID) +"#; + +/// The AppleScript that quits Claude Desktop on macOS (as Quit in its menu does, waiting up to +/// 10 s), before `open -a Claude` starts it again. +pub const CLAUDE_DESKTOP_QUIT_APPLESCRIPT: &str = r#"if application "Claude" is running then + tell application "Claude" to quit + repeat 50 times + if application "Claude" is not running then exit repeat + delay 0.2 + end repeat +end if"#; + +/// Quit Claude Desktop and start it again, so it loads the MCP servers in its configuration. +pub fn restart_claude_desktop() -> Result<(), String> { + if cfg!(windows) { + let exe = windows_system_program(r"System32\WindowsPowerShell\v1.0\powershell.exe")?; + let mut cmd = command(exe); + cmd.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", CLAUDE_DESKTOP_RESTART_PS]); + run_command(cmd, "powershell", Duration::from_secs(30)).map(|_| ()) + } else if cfg!(target_os = "macos") { + run("osascript", &["-e", CLAUDE_DESKTOP_QUIT_APPLESCRIPT], Duration::from_secs(20))?; + run("open", &["-a", "Claude"], Duration::from_secs(10)).map(|_| ()) + } else { + Err("restarting Claude Desktop isn't supported on this system".into()) + } +} + /// Whether a process started from inside `path` (an exe, an AppImage, or a `.app`) is running. pub fn is_running(path: &Path) -> bool { if cfg!(windows) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fac6996c..ab7bfea8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -146,6 +146,9 @@ pub struct LauncherUi { pub(crate) mcp_agents: McpAgents, /// Whether we've asked for MCP state since the settings dialog last opened (reset when it closes). pub(crate) mcp_requested: bool, + /// The MCP client just added here, which only loads the entry when it starts: Settings offers + /// to restart it until that is done or the entry is removed. + pub(crate) mcp_restart_offer: Option, pub(crate) caps: Capabilities, pub(crate) platform: Option, pub(crate) checking: bool, @@ -273,6 +276,7 @@ impl LauncherUi { .collect(), mcp_agents: McpAgents::default(), mcp_requested: false, + mcp_restart_offer: None, caps, platform, checking: false, diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c3ad3439..f84521ca 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -428,6 +428,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Kopírovat pro VS Code Copy for Codex (TOML) Kopírovat pro Codex (TOML) Configuration copied. Konfigurace zkopírována. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} načítá své servery MCP jen při spuštění, takže aplikace Craft se objeví až po restartu. Restart zavře {client} včetně odpovědi, kterou právě píše. + Restart {client} Restartovat {client} + Restarting {client}… Restartuje se {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brána Craft (craft-ai-mcp) není nainstalována vedle spouštěče. Let AI agents use Craft apps Povolit AI agentům používat aplikace Craft Apps agents can reach: {count} Aplikace dostupné agentům: {count} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 23d223fc..7903b39a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -460,6 +460,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Für VS Code kopieren Copy for Codex (TOML) Für Codex kopieren (TOML) Configuration copied. Konfiguration kopiert. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} lädt seine MCP-Server nur beim Start, daher erscheinen die Craft-Apps erst nach einem Neustart. Der Neustart schließt {client}, auch eine Antwort, die gerade geschrieben wird. + Restart {client} {client} neu starten + Restarting {client}… {client} wird neu gestartet… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Das Craft-Gateway (craft-ai-mcp) ist nicht neben dem Launcher installiert. Let AI agents use Craft apps KI-Agenten Craft-Apps nutzen lassen Apps agents can reach: {count} Apps, die Agenten erreichen: {count} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b71d008b..cf54c3d4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -441,6 +441,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Copiar para VS Code Copy for Codex (TOML) Copiar para Codex (TOML) Configuration copied. Configuración copiada. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} solo carga sus servidores MCP al iniciarse, así que las apps Craft aparecen después de reiniciarlo. Al reiniciar se cierra {client}, incluida una respuesta que esté escribiendo. + Restart {client} Reiniciar {client} + Restarting {client}… Reiniciando {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La pasarela Craft (craft-ai-mcp) no está instalada junto al lanzador. Let AI agents use Craft apps Permitir que los agentes de IA usen las apps Craft Apps agents can reach: {count} Apps que los agentes pueden usar: {count} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e80c366d..06e4bba1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -458,6 +458,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Copier pour VS Code Copy for Codex (TOML) Copier pour Codex (TOML) Configuration copied. Configuration copiée. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} ne charge ses serveurs MCP qu'au démarrage : les apps Craft apparaissent après un redémarrage. Le redémarrage ferme {client}, y compris une réponse en cours de rédaction. + Restart {client} Redémarrer {client} + Restarting {client}… Redémarrage de {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. La passerelle Craft (craft-ai-mcp) n'est pas installée à côté du lanceur. Let AI agents use Craft apps Permettre aux agents IA d'utiliser les apps Craft Apps agents can reach: {count} Apps accessibles aux agents : {count} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 802672e3..f5cc53e4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -461,6 +461,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Másolás VS Code-hoz Copy for Codex (TOML) Másolás Codexhez (TOML) Configuration copied. Konfiguráció kimásolva. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. A(z) {client} csak induláskor tölti be az MCP-kiszolgálóit, ezért a Craft alkalmazások újraindítás után jelennek meg. Az újraindítás bezárja a(z) {client} alkalmazást, a még íródó választ is. + Restart {client} {client} újraindítása + Restarting {client}… {client} újraindítása… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. A Craft átjáró (craft-ai-mcp) nincs telepítve az indító mellé. Let AI agents use Craft apps AI-ügynökök használhatják a Craft alkalmazásokat Apps agents can reach: {count} Ügynökök által elérhető alkalmazások: {count} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 79174a04..8eab086a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -463,6 +463,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code VS Code 用にコピー Copy for Codex (TOML) Codex 用にコピー (TOML) Configuration copied. 設定をコピーしました。 + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} は起動時にのみ MCP サーバーを読み込むため、Craft アプリは再起動後に表示されます。再起動すると {client} が終了し、作成中の返信も中断されます。 + Restart {client} {client} を再起動 + Restarting {client}… {client} を再起動しています… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft ゲートウェイ (craft-ai-mcp) がランチャーと同じ場所にインストールされていません。 Let AI agents use Craft apps AI エージェントに Craft アプリの使用を許可 Apps agents can reach: {count} エージェントが使えるアプリ: {count} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 28b1665f..3e50fd81 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -459,6 +459,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code კოპირება VS Code-ისთვის Copy for Codex (TOML) კოპირება Codex-ისთვის (TOML) Configuration copied. კონფიგურაცია დაკოპირდა. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} MCP სერვერებს მხოლოდ გაშვებისას ტვირთავს, ამიტომ Craft აპები გადატვირთვის შემდეგ გამოჩნდება. გადატვირთვა ხურავს {client}-ს, მათ შორის პასუხს, რომელსაც ახლა წერს. + Restart {client} {client}-ის გადატვირთვა + Restarting {client}… {client} გადაიტვირთება… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Craft კარიბჭე (craft-ai-mcp) გამშვების გვერდით არ არის დაინსტალირებული. Let AI agents use Craft apps AI აგენტებს Craft აპების გამოყენების ნება Apps agents can reach: {count} აგენტებისთვის ხელმისაწვდომი აპები: {count} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8f39817d..34180389 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -462,6 +462,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Kopiuj dla VS Code Copy for Codex (TOML) Kopiuj dla Codex (TOML) Configuration copied. Skopiowano konfigurację. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} wczytuje serwery MCP tylko przy uruchomieniu, więc aplikacje Craft pojawią się po ponownym uruchomieniu. Ponowne uruchomienie zamyka {client}, także odpowiedź, którą właśnie pisze. + Restart {client} Uruchom ponownie {client} + Restarting {client}… Ponowne uruchamianie {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Brama Craft (craft-ai-mcp) nie jest zainstalowana obok launchera. Let AI agents use Craft apps Pozwól agentom AI używać aplikacji Craft Apps agents can reach: {count} Aplikacje dostępne dla agentów: {count} diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 9d14ae6a..dd576cd7 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -448,6 +448,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Copiar para o VS Code Copy for Codex (TOML) Copiar para o Codex (TOML) Configuration copied. Configuração copiada. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. O {client} só carrega os servidores MCP ao iniciar, então os apps Craft aparecem depois de reiniciá-lo. Reiniciar fecha o {client}, inclusive uma resposta que ele ainda esteja escrevendo. + Restart {client} Reiniciar {client} + Restarting {client}… Reiniciando {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. O gateway Craft (craft-ai-mcp) não está instalado ao lado do inicializador. Let AI agents use Craft apps Permitir que agentes de IA usem os apps Craft Apps agents can reach: {count} Apps que os agentes alcançam: {count} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9db78cc4..3c1b5bd2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -456,6 +456,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code Копировать для VS Code Copy for Codex (TOML) Копировать для Codex (TOML) Configuration copied. Конфигурация скопирована. + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} загружает MCP-серверы только при запуске, поэтому приложения Craft появятся после перезапуска. Перезапуск закроет {client}, включая ответ, который он ещё пишет. + Restart {client} Перезапустить {client} + Restarting {client}… Перезапуск {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. Шлюз Craft (craft-ai-mcp) не установлен рядом с лаунчером. Let AI agents use Craft apps Разрешить ИИ-агентам использовать приложения Craft Apps agents can reach: {count} Приложения, доступные агентам: {count} diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 80160b2d..69e6361f 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -428,6 +428,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code 复制为 VS Code 格式 Copy for Codex (TOML) 复制为 Codex 格式 (TOML) Configuration copied. 已复制配置。 + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} 只在启动时加载 MCP 服务器,因此 Craft 应用会在重启后出现。重启会关闭 {client},包括正在生成的回复。 + Restart {client} 重启 {client} + Restarting {client}… 正在重启 {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 启动器旁未安装 Craft 网关 (craft-ai-mcp)。 Let AI agents use Craft apps 允许 AI 智能体使用 Craft 应用 Apps agents can reach: {count} 智能体可用的应用:{count} diff --git a/crates/ui-egui/src/i18n/zh-TW.tsv b/crates/ui-egui/src/i18n/zh-TW.tsv index 0ac3aab8..e149cbdc 100644 --- a/crates/ui-egui/src/i18n/zh-TW.tsv +++ b/crates/ui-egui/src/i18n/zh-TW.tsv @@ -419,6 +419,9 @@ anicraft Classic tweens with eight easing presets and custom ease curves, plus s Copy for VS Code 複製為 VS Code 格式 Copy for Codex (TOML) 複製為 Codex 格式 (TOML) Configuration copied. 已複製設定。 + {client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing. {client} 只在啟動時載入 MCP 伺服器,因此 Craft 應用程式會在重新啟動後出現。重新啟動會關閉 {client},包括正在產生的回覆。 + Restart {client} 重新啟動 {client} + Restarting {client}… 正在重新啟動 {client}… The Craft gateway (craft-ai-mcp) is not installed beside the launcher. 啟動器旁未安裝 Craft 閘道 (craft-ai-mcp)。 Let AI agents use Craft apps 允許 AI 代理使用 Craft 應用程式 Apps agents can reach: {count} 代理可使用的應用程式:{count} diff --git a/crates/ui-egui/src/settings_dialog.rs b/crates/ui-egui/src/settings_dialog.rs index 1ab9c3dc..f81718b0 100644 --- a/crates/ui-egui/src/settings_dialog.rs +++ b/crates/ui-egui/src/settings_dialog.rs @@ -445,14 +445,38 @@ impl LauncherUi { ui.label(RichText::new(tl!("Added")).size(12.0).color(t.muted)); if ui.button(tl!("Remove")).clicked() { self.act_command(Command::McpSetClient { client: c.client, added: false }); + self.mcp_restart_offer = None; } } else if c.installed && can_add { if ui.button(tl!("Add")).clicked() { self.act_command(Command::McpSetClient { client: c.client, added: true }); + if c.restartable { + self.mcp_restart_offer = Some(c.client); + } } } else if !c.installed { ui.label(RichText::new(tl!("Not installed")).size(12.0).color(t.muted)); } }); + // A client reads its MCP servers only when it starts: right after adding, say so and offer + // to do the restart, which people otherwise miss. + if c.added && c.restartable && self.mcp_restart_offer == Some(c.client) { + let name = [("client", c.name.as_str())]; + note( + ui, + &fmt( + tl!( + "{client} loads its MCP servers only when it starts, so the Craft apps appear after a restart. Restarting closes {client}, including a reply it is still writing." + ), + &name, + ), + ); + if ui.button(fmt(tl!("Restart {client}"), &name)).clicked() { + self.act_command(Command::McpRestartClient { client: c.client }); + self.mcp_restart_offer = None; + self.toast(fmt(tl!("Restarting {client}…"), &name), false); + } + ui.add_space(4.0); + } } } diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 638a605b..f4066c3d 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -4416,7 +4416,7 @@ fn launcher_version_padlock_confirms_and_returns_to_settings() { #[test] fn ai_agents_switch_and_client_buttons_send_their_commands() { use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; - let client = |client, name: &str, installed, added| McpClientState { client, name: name.into(), installed, added }; + let client = |client, name: &str, installed, added| McpClientState { client, name: name.into(), installed, added, restartable: false }; let mut evs = events(); evs.push(Event::Mcp { agents: McpAgents { @@ -4463,6 +4463,44 @@ fn ai_agents_switch_and_client_buttons_send_their_commands() { ); } +/// Adding Claude Desktop says why it must restart and offers to do it; the button sends the +/// restart and goes away. Clients the launcher can't restart get no such offer. +#[test] +fn ai_agents_offer_to_restart_a_client_right_after_adding_it() { + use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; + let agents = |added| McpAgents { + flag_on: true, + gateway_found: true, + enabled: true, + apps: 3, + clients: vec![ + McpClientState { client: McpClient::ClaudeDesktop, name: "Claude Desktop".into(), installed: true, added, restartable: true }, + McpClientState { client: McpClient::ClaudeCode, name: "Claude Code".into(), installed: true, added, restartable: false }, + ], + gateway: Some("C:/gw/craft-ai-mcp.exe".into()), + }; + let machine = Machine { more: vec![Event::Mcp { agents: agents(false) }], ..Default::default() }; + let (mut h, sent, queue) = versions_harness(machine, None, vec![]); + h.get_by_label("Settings").click(); + h.run_steps(4); + h.get_by_label("Quick install").scroll_to_me(); + h.run_steps(4); + assert!(h.query_by_label("Restart Claude Desktop").is_none(), "nothing to restart before adding"); + let adds: Vec<_> = h.get_all_by_label("Add").collect(); + adds[0].click(); + adds[1].click(); + h.run_steps(2); + queue.borrow_mut().push(Event::Mcp { agents: agents(true) }); + h.run_steps(4); + h.get_by_label_contains("loads its MCP servers only when it starts"); + assert!(h.query_by_label("Restart Claude Code").is_none(), "the launcher can't restart Claude Code"); + h.get_by_label("Restart Claude Desktop").click(); + h.run_steps(4); + assert!(sent.borrow().iter().any(|c| matches!(c, Command::McpRestartClient { client: McpClient::ClaudeDesktop }))); + assert!(h.query_by_label("Restart Claude Desktop").is_none(), "offered once"); + assert!(h.query_all_by_label("Restarting Claude Desktop…").next().is_some(), "a note says it is happening"); +} + /// Without the gateway beside the launcher, Settings says so and offers no switch. #[test] fn ai_agents_without_the_gateway_offer_no_switch() { @@ -4481,7 +4519,7 @@ fn ai_agents_without_the_gateway_offer_no_switch() { #[test] fn ai_agents_left_on_without_the_gateway_can_still_be_turned_off() { use artcraft_launcher_core::protocol::{McpAgents, McpClient, McpClientState}; - let client = |client, name: &str, added| McpClientState { client, name: name.into(), installed: true, added }; + let client = |client, name: &str, added| McpClientState { client, name: name.into(), installed: true, added, restartable: false }; let mut evs = events(); evs.push(Event::Mcp { agents: McpAgents { From acbf667f494596f090f4dc53c2eefc70a2c1e414 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 22:12:09 +0100 Subject: [PATCH 22/27] fix: gateway copy keeps its execute bit; packaging test ships a gateway fixture - install_gateway returned an identical copy before setting its mode, so a copy that had lost its execute bit was reused and clients couldn't start it. The mode is now checked on both paths (Unix). Test extended: a 0644 copy with the right bytes comes back executable (fails without the fix; run in Linux). - packaging/linux/test-package-metadata.sh builds packages from a fake release folder; it now has a craft-ai-mcp fixture too, since the packages install the gateway beside the launcher. Co-Authored-By: Claude Opus 5.5 --- crates/native/src/agents.rs | 41 ++++++++++++++++-------- crates/native/src/agents_tests.rs | 7 +++- packaging/linux/test-package-metadata.sh | 3 ++ 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 078723ab..31ecf34a 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -310,24 +310,37 @@ pub fn install_gateway(src: &Path, dir: &Path) -> Result { (Err(e), _) => return Err(format!("couldn't read the Craft gateway at {} ({e})", src.display())), _ => false, }; - if current { - return Ok(dest); - } - let bytes = std::fs::read(src).map_err(|e| format!("couldn't read the Craft gateway at {} ({e})", src.display()))?; - match crate::paths::write_atomic(&dest, &bytes) { - Ok(()) => {} - Err(_) if dest.is_file() => return Ok(dest), - Err(e) => return Err(e), - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("couldn't make {} executable ({e})", dest.display()))?; + if !current { + let bytes = std::fs::read(src).map_err(|e| format!("couldn't read the Craft gateway at {} ({e})", src.display()))?; + match crate::paths::write_atomic(&dest, &bytes) { + Ok(()) => {} + // A client still running the old copy keeps it busy on Windows: keep using it. + Err(_) if dest.is_file() => {} + Err(e) => return Err(e), + } } + // Also for a copy with the right bytes: one that lost its execute bit couldn't be started. + make_executable(&dest)?; Ok(dest) } +/// Make the gateway copy executable for everyone who may run it (`0755`) when it isn't already. +#[cfg(unix)] +fn make_executable(path: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(path).map_err(|e| format!("couldn't read {} ({e})", path.display()))?.permissions().mode(); + if mode & 0o111 == 0o111 { + return Ok(()); + } + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).map_err(|e| format!("couldn't make {} executable ({e})", path.display())) +} + +/// Windows has no execute bit. +#[cfg(not(unix))] +fn make_executable(_path: &Path) -> Result<(), String> { + Ok(()) +} + /// Serialises every change to the app list and the gateway copy. Detection refreshes them on a /// background thread while Settings may be turning agents off; without this, a refresh that /// read "on" just before the switch could write the list back after it was removed. diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 4e40b6e7..171f4860 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -230,7 +230,12 @@ fn the_gateway_copy_is_executable() { let src = src_dir.path().join("craft-ai-mcp"); std::fs::write(&src, b"#!/bin/sh\n").unwrap(); let copy = install_gateway(&src, dir.path()).unwrap(); - assert_eq!(std::fs::metadata(copy).unwrap().permissions().mode() & 0o111, 0o111); + assert_eq!(std::fs::metadata(©).unwrap().permissions().mode() & 0o111, 0o111); + // A copy with the right bytes that lost its execute bit gets it back instead of being reused + // as it is: clients couldn't start it. + std::fs::set_permissions(©, std::fs::Permissions::from_mode(0o644)).unwrap(); + let again = install_gateway(&src, dir.path()).unwrap(); + assert_eq!(std::fs::metadata(again).unwrap().permissions().mode() & 0o111, 0o111); } #[test] diff --git a/packaging/linux/test-package-metadata.sh b/packaging/linux/test-package-metadata.sh index d24dc2a7..141f374e 100755 --- a/packaging/linux/test-package-metadata.sh +++ b/packaging/linux/test-package-metadata.sh @@ -16,6 +16,9 @@ check_packages() { mkdir -p "$work/target/$target/release" printf '#!/bin/sh\necho "ArtCraft Launcher packaging fixture"\n' >"$work/target/$target/release/artcraft-launcher" chmod +x "$work/target/$target/release/artcraft-launcher" + # The packages ship the craft-ai-mcp gateway beside the launcher (Settings › AI agents). + printf '#!/bin/sh\necho "craft-ai-mcp packaging fixture"\n' >"$work/target/$target/release/craft-ai-mcp" + chmod +x "$work/target/$target/release/craft-ai-mcp" # A set cross target skips the version smoke execution; no target binary is run. ( unset EMULATOR From 31c3573274274e6015c0a299df15f167c121ffa0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 22:57:45 +0100 Subject: [PATCH 23/27] The app list goes through craft-ai-agents; every app gets plain `mcp` - The launcher writes, reads and removes ArtCraft/mcp/apps.json through `craft-ai-agents` (storytold/craft-ai-integrations#197), the same crate the gateway reads it with and every Craft app checks the switch with, instead of its own copy of the format. - Every app is started as plain `-cli mcp`: by the suite's rule that command works in the open window when the app runs and accepts agents, and headless otherwise. The per-app argument table (`--live` for PhotoCraft, `--headless` for VectorCraft) and reading each CLI's `--help` to see whether it takes them are gone. - Gateway and craft-ai-agents pinned to the head of #197 (35e0352). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 14 +++++- Cargo.toml | 3 ++ apps/craft-ai-mcp/Cargo.toml | 2 +- crates/native/Cargo.toml | 1 + crates/native/src/agents.rs | 74 ++++++----------------------- crates/native/src/agents_tests.rs | 79 ++++++++----------------------- 6 files changed, 52 insertions(+), 121 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 64baeeb2..936fe148 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -322,6 +322,7 @@ name = "artcraft-launcher-native" version = "0.19.2" dependencies = [ "artcraft-launcher-core", + "craft-ai-agents", "craft-flags", "craft-update", "dirs 6.0.0", @@ -987,11 +988,22 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +dependencies = [ + "dirs 7.0.0", + "serde", + "serde_json", +] + [[package]] name = "craft-ai-mcp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=08a639ae6fd36631f0ea18214387c020a94fc183#08a639ae6fd36631f0ea18214387c020a94fc183" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" dependencies = [ + "craft-ai-agents", "dirs 7.0.0", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 62a6bbb4..20aa409e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,9 @@ log = "0.4" jiff = "0.2" # Feature flags (craft-libs#1118, merged in craft-libs#1119). craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } +# The agents switch and app list (Settings › AI agents), shared with the craft-ai-mcp gateway and +# every Craft app. Pinned to the head of storytold/craft-ai-integrations#197 until it merges. +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-ui = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } diff --git a/apps/craft-ai-mcp/Cargo.toml b/apps/craft-ai-mcp/Cargo.toml index 9b8c1efd..0a89c805 100644 --- a/apps/craft-ai-mcp/Cargo.toml +++ b/apps/craft-ai-mcp/Cargo.toml @@ -17,4 +17,4 @@ path = "src/main.rs" # The gateway from storytold/craft-ai-integrations (crates/ai-mcp), pinned like the craft-libs crates. # Pinned to the head of storytold/craft-ai-integrations#197 until it merges; re-pin then. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "08a639ae6fd36631f0ea18214387c020a94fc183" } +craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } diff --git a/crates/native/Cargo.toml b/crates/native/Cargo.toml index 3dc1f8c7..c7412bd6 100644 --- a/crates/native/Cargo.toml +++ b/crates/native/Cargo.toml @@ -19,6 +19,7 @@ local-mirror = [] [dependencies] artcraft-launcher-core = { workspace = true } craft-flags = { workspace = true } +craft-ai-agents = { workspace = true } craft-update = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 31ecf34a..2977e430 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -20,90 +20,46 @@ use artcraft_launcher_core::CraftApp; use crate::detect; use crate::manifest::Manifest; -/// The app list the gateway reads. -pub const APPS_FILE: &str = "apps.json"; -/// Same override the gateway honours (tests, portable installs). -pub const DIR_ENV: &str = "CRAFT_MCP_DIR"; /// The key our entry has in a client's `mcpServers`. pub use artcraft_launcher_core::mcp_config::SERVER_KEY; +/// The app list and its folder override, from `craft-ai-agents` (the one place that reads and +/// writes them, for the launcher, the gateway and every app). +pub use craft_ai_agents::{APPS_FILE, DIR_ENV}; /// Largest client configuration read; anything bigger is not a configuration file. const MAX_CONFIG_BYTES: u64 = 64 << 20; -/// The gateway's folder: [`DIR_ENV`], otherwise `ArtCraft/mcp` in the per-user local +/// The app list's folder: [`DIR_ENV`], otherwise `ArtCraft/mcp` in the per-user local /// configuration folder (beside the AI layer's `ArtCraft/ai`). pub fn mcp_dir() -> Option { - match std::env::var_os(DIR_ENV) { - Some(d) if !d.is_empty() => Some(PathBuf::from(d)), - _ => dirs::config_local_dir().map(|b| b.join("ArtCraft").join("mcp")), - } + craft_ai_agents::agents_dir() } -/// Arguments after `mcp` for apps whose plain `mcp` is not what agents should get: -/// - PhotoCraft: `--live` reaches the open window through the connection the app publishes, and -/// starts it when it is closed (storytold/photocraft#13396). -/// - VectorCraft: plain `mcp` attaches to a control port that has no token yet whenever something -/// listens on 7979; `--headless` keeps agents in their own session until it authenticates. -/// -/// Each is used only when that install's CLI accepts it ([`cli_accepts`]), so an older release -/// still gets plain `mcp` instead of an error. -const MCP_EXTRA_ARGS: &[(&str, &[&str])] = &[("photocraft", &["--live"]), ("vectorcraft", &["--headless"])]; - -/// Whether `cli mcp --help` names every argument of `extra` ([`help_names`]). Asking the CLI to -/// parse them is no test: some CLIs print help and succeed whatever comes before `--help`. No -/// console window, standard input closed, 5 s at most. -fn cli_accepts(cli: &Path, extra: &[&str]) -> bool { - let Some(program) = cli.to_str() else { return false }; - crate::process::capture(program, &["mcp", "--help"], std::time::Duration::from_secs(5)).is_some_and(|help| help_names(&help, extra)) -} - -/// Whether `help` has each of `args` as a word of its own (`--live`, not `--lively`). -fn help_names(help: &str, args: &[&str]) -> bool { - let words: Vec<&str> = help.split(|c: char| c.is_whitespace() || "[]|,()=<>`'\"".contains(c)).collect(); - args.iter().all(|a| words.contains(a)) -} - -/// The app list for `services`: each app with a CLI, started as ` mcp` plus its -/// [`MCP_EXTRA_ARGS`]. Apps without a CLI beside them are left out. -pub fn apps_json(services: &[InstalledApp]) -> Value { - apps_json_with(services, &cli_accepts) -} - -/// [`apps_json`], asking `accepts` whether a CLI takes an app's extra arguments. -fn apps_json_with(services: &[InstalledApp], accepts: &dyn Fn(&Path, &[&str]) -> bool) -> Value { - let apps: Vec = services +/// The app list for `services`: each app with a CLI, started as plain ` mcp`. By the suite's +/// rule that command works in the app's open window when the app runs and accepts agents, and +/// headless otherwise, so no app needs other arguments. Apps without a CLI beside them are left out. +pub fn app_entries(services: &[InstalledApp]) -> Vec { + services .iter() .filter_map(|s| { let cli = s.cli_path.as_ref().filter(|p| p.is_absolute())?; - let mut args = vec!["mcp".to_string()]; - if let Some((_, extra)) = MCP_EXTRA_ARGS.iter().find(|(id, _)| *id == s.id) - && accepts(cli, extra) - { - args.extend(extra.iter().map(|a| (*a).to_string())); - } - Some(json!({"id": s.id, "name": s.name, "command": cli, "args": args})) + Some(craft_ai_agents::AppEntry { id: s.id.clone(), name: s.name.clone(), command: cli.clone(), args: vec!["mcp".to_string()] }) }) - .collect(); - json!({"version": 1, "apps": apps}) + .collect() } /// Whether agents are on: the app list exists in `dir`. pub fn enabled(dir: &Path) -> bool { - dir.join(APPS_FILE).is_file() + craft_ai_agents::switched_on_in(dir) } /// Write (or refresh) the app list in `dir`. pub fn write_apps(dir: &Path, services: &[InstalledApp]) -> Result<(), String> { - let text = serde_json::to_string_pretty(&apps_json(services)).map_err(|e| e.to_string())?; - crate::paths::write_atomic(&dir.join(APPS_FILE), text.as_bytes()) + craft_ai_agents::write(dir, &app_entries(services)) } /// Remove the app list in `dir`. A missing list is fine. pub fn remove_apps(dir: &Path) -> Result<(), String> { - match std::fs::remove_file(dir.join(APPS_FILE)) { - Ok(()) => Ok(()), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(e) => Err(format!("couldn't remove {} ({e})", dir.join(APPS_FILE).display())), - } + craft_ai_agents::remove(dir) } /// Every client the launcher can add the entry to. diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index 171f4860..ceea4b9e 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -13,51 +13,29 @@ fn read(p: &Path) -> Value { } #[test] -fn the_app_list_has_every_app_with_a_cli_in_the_gateways_format() { +fn the_app_list_has_every_app_with_a_cli_started_as_plain_mcp() { let dir = tempfile::tempdir().unwrap(); - let cli = dir.path().join("photocraft-cli.exe"); - let list = apps_json(&[ - service("photocraft", "PhotoCraft", Some(cli.clone())), + let cli = |name: &str| dir.path().join(name); + let services = [ + service("photocraft", "PhotoCraft", Some(cli("photocraft-cli.exe"))), + service("vectorcraft", "VectorCraft", Some(cli("vectorcraft-cli.exe"))), service("wordcraft", "WordCraft", None), service("relcraft", "RelCraft", Some(PathBuf::from("relative/cli"))), - ]); - assert_eq!(list["version"], 1); - let apps = list["apps"].as_array().unwrap(); - assert_eq!(apps.len(), 1, "apps without an absolute CLI are left out"); - assert_eq!(apps[0]["id"], "photocraft"); - assert_eq!(apps[0]["name"], "PhotoCraft"); - assert_eq!(apps[0]["command"], cli.to_string_lossy().as_ref()); - assert_eq!(apps[0]["args"], json!(["mcp"])); -} - -#[test] -fn apps_get_their_extra_mcp_arguments_only_where_the_cli_takes_them() { - let dir = tempfile::tempdir().unwrap(); - let at = |name: &str| dir.path().join(name); - let services = [ - service("photocraft", "PhotoCraft", Some(at("photocraft-cli"))), - service("vectorcraft", "VectorCraft", Some(at("vectorcraft-cli"))), - service("filmcraft", "FilmCraft", Some(at("filmcraft-cli"))), ]; - let asked = std::cell::RefCell::new(Vec::new()); - let new = apps_json_with(&services, &|cli: &Path, extra: &[&str]| { - asked.borrow_mut().push((cli.file_name().unwrap().to_string_lossy().into_owned(), extra.join(" "))); - true - }); - let args = |list: &Value, i: usize| list["apps"][i]["args"].clone(); - assert_eq!(args(&new, 0), json!(["mcp", "--live"]), "PhotoCraft: the open window"); - assert_eq!(args(&new, 1), json!(["mcp", "--headless"]), "VectorCraft: off its unauthenticated port"); - assert_eq!(args(&new, 2), json!(["mcp"]), "other apps as they are"); - assert_eq!( - *asked.borrow(), - [("photocraft-cli".into(), "--live".into()), ("vectorcraft-cli".into(), "--headless".into())], - "only apps with extras are asked" - ); - // An older release that doesn't know the argument gets plain `mcp`, not a usage error. - let old = apps_json_with(&services, &|_: &Path, _: &[&str]| false); - for i in 0..3 { - assert_eq!(args(&old, i), json!(["mcp"])); - } + let apps = app_entries(&services); + assert_eq!(apps.len(), 2, "apps without an absolute CLI are left out"); + assert_eq!((apps[0].id.as_str(), apps[0].name.as_str()), ("photocraft", "PhotoCraft")); + assert_eq!(apps[0].command, cli("photocraft-cli.exe")); + // Every app's plain `mcp` works in its open window when it may: no per-app arguments. + assert!(apps.iter().all(|a| a.args == ["mcp"]), "{apps:?}"); + // Written in the gateway's format, which the gateway reads back the same. + let list = dir.path().join("list"); + write_apps(&list, &services).unwrap(); + let (back, skipped) = craft_ai_agents::load(&list).unwrap().unwrap(); + assert!(skipped.is_empty(), "{skipped:?}"); + assert_eq!(back, apps); + let v = read(&list.join(APPS_FILE)); + assert_eq!(v["version"], 1); } #[test] @@ -91,25 +69,6 @@ fn claude_desktop_data_moved_to_claude_data_is_used() { assert_eq!(claude_desktop_dir(config.clone(), Some(&local)), data, "Claude-Data wins, its README is no install"); } -#[test] -fn the_help_text_must_name_the_argument_as_a_word() { - let help = "Usage: photocraft-cli mcp [OPTIONS] - --live - Reach the open window - vectorcraft-cli mcp [--connect ADDR | --headless]"; - assert!(help_names(help, &["--live"])); - assert!(help_names(help, &["--headless"]), "inside brackets"); - assert!(!help_names(" --lively", &["--live"])); - assert!(!help_names("bridge to a running app, or live", &["--live"])); - assert!(!help_names(help, &["--live", "--when-closed"]), "every argument"); -} - -#[test] -fn a_cli_that_cannot_run_takes_no_extra_arguments() { - let dir = tempfile::tempdir().unwrap(); - assert!(!cli_accepts(&dir.path().join("missing-cli"), &["--live"])); -} - #[test] fn switching_on_and_off() { let dir = tempfile::tempdir().unwrap(); From c1735268864446780a9eb6a06e4d278631618b01 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 00:19:57 +0100 Subject: [PATCH 24/27] build: pin craft-ai-mcp and craft-ai-agents to craft-ai-integrations#197 at 94a3fb5 The gateway now holds only an app's connection during a call (listing, searching and describing answer at once) and asks the switch again once a queued call has its app, so it never starts after agents are turned off. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 12 ++++++------ Cargo.toml | 2 +- apps/craft-ai-mcp/Cargo.toml | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 936fe148..d21558b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -253,7 +253,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.59.0", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -901,7 +901,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" dependencies = [ "lazy_static", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -991,7 +991,7 @@ dependencies = [ [[package]] name = "craft-ai-agents" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=94a3fb570938614927debefbc660e5d8271d816a#94a3fb570938614927debefbc660e5d8271d816a" dependencies = [ "dirs 7.0.0", "serde", @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-ai-mcp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=94a3fb570938614927debefbc660e5d8271d816a#94a3fb570938614927debefbc660e5d8271d816a" dependencies = [ "craft-ai-agents", "dirs 7.0.0", @@ -1307,7 +1307,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4374,7 +4374,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 20aa409e..9fea5472 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ jiff = "0.2" craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } # The agents switch and app list (Settings › AI agents), shared with the craft-ai-mcp gateway and # every Craft app. Pinned to the head of storytold/craft-ai-integrations#197 until it merges. -craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "94a3fb570938614927debefbc660e5d8271d816a" } craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-ui = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } diff --git a/apps/craft-ai-mcp/Cargo.toml b/apps/craft-ai-mcp/Cargo.toml index 0a89c805..e4df4721 100644 --- a/apps/craft-ai-mcp/Cargo.toml +++ b/apps/craft-ai-mcp/Cargo.toml @@ -17,4 +17,4 @@ path = "src/main.rs" # The gateway from storytold/craft-ai-integrations (crates/ai-mcp), pinned like the craft-libs crates. # Pinned to the head of storytold/craft-ai-integrations#197 until it merges; re-pin then. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } +craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "94a3fb570938614927debefbc660e5d8271d816a" } From 02926e1e9f456dbd19ab0e3485e7d8c9f81ce0c9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 10:44:03 +0100 Subject: [PATCH 25/27] fix(agents): keep an ArtCraft MCP entry the launcher did not write The launcher treated any `mcpServers.ArtCraft` key as its own: Add replaced it, and Remove or turning agents off deleted it from every client. Now an entry is ours only when it starts craft-ai-mcp with exactly `--stdio` and no environment. Any other ArtCraft entry is never replaced (Add reports it) or removed, and Settings no longer shows it as added. Co-Authored-By: Claude Opus 5.5 --- crates/native/src/agents.rs | 39 +++++++++++++++++++++++++++---- crates/native/src/agents_tests.rs | 39 +++++++++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index 2977e430..eaa86ac0 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -152,32 +152,61 @@ fn read_config(path: &Path) -> Result>, String> { } } -/// Whether `config` holds our entry. +/// Whether `entry` is one the launcher wrote: it starts the gateway (`craft-ai-mcp`, wherever its +/// copy is) with exactly `--stdio` and sets no environment. Anything else under [`SERVER_KEY`] was +/// set up by the person or another tool, and the launcher never replaces or removes it. +fn ours(entry: &Value) -> bool { + let Value::Object(e) = entry else { + return false; + }; + let gateway = format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX); + let command_is_gateway = e + .get("command") + .and_then(Value::as_str) + .and_then(|c| Path::new(c).file_name()) + .and_then(|n| n.to_str()) + .is_some_and(|n| if cfg!(windows) { n.eq_ignore_ascii_case(&gateway) } else { n == gateway }); + let no_env = match e.get("env") { + None => true, + Some(Value::Object(env)) => env.is_empty(), + Some(_) => false, + }; + command_is_gateway && e.get("args") == Some(&json!(["--stdio"])) && no_env +} + +/// Whether `config` holds our entry (not merely some entry named [`SERVER_KEY`]). pub fn registered(config: &Path) -> bool { - matches!(read_config(config), Ok(Some(m)) if m.get("mcpServers").and_then(|s| s.get(SERVER_KEY)).is_some()) + matches!(read_config(config), Ok(Some(m)) if m.get("mcpServers").and_then(|s| s.get(SERVER_KEY)).is_some_and(ours)) } /// Add (or update) our entry in the client configuration at `config`, starting `gateway`. -/// Everything else in the file is kept. +/// Everything else in the file is kept. An entry named [`SERVER_KEY`] that the launcher did not +/// write is an error, so a person's own configuration is never replaced. pub fn register(config: &Path, gateway: &Path) -> Result<(), String> { let mut root = read_config(config)?.unwrap_or_default(); let servers = root.entry("mcpServers").or_insert_with(|| Value::Object(Map::new())); let Value::Object(servers) = servers else { return Err(format!("`mcpServers` in {} is not an object; the launcher leaves it unchanged", config.display())); }; + if servers.get(SERVER_KEY).is_some_and(|e| !ours(e)) { + return Err(format!( + "{} already has its own `{SERVER_KEY}` entry; the launcher leaves it unchanged. Rename or remove it to add the launcher's", + config.display() + )); + } servers.insert(SERVER_KEY.to_string(), json!({"command": gateway.to_string_lossy(), "args": ["--stdio"]})); let text = serde_json::to_string_pretty(&Value::Object(root)).map_err(|e| e.to_string())?; crate::paths::write_atomic(config, text.as_bytes()) } /// Remove our entry from the client configuration at `config`. Nothing to do when the file or -/// the entry is missing. +/// our entry is missing; an entry named [`SERVER_KEY`] the launcher did not write is kept. pub fn unregister(config: &Path) -> Result<(), String> { let Some(mut root) = read_config(config)? else { return Ok(()); }; let removed = match root.get_mut("mcpServers") { - Some(Value::Object(servers)) => servers.remove(SERVER_KEY).is_some(), + Some(Value::Object(servers)) if servers.get(SERVER_KEY).is_some_and(ours) => servers.remove(SERVER_KEY).is_some(), _ => false, }; if !removed { diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index ceea4b9e..d18ea3c2 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -84,7 +84,7 @@ fn switching_on_and_off() { fn register_creates_a_config_and_keeps_other_servers_and_keys() { let dir = tempfile::tempdir().unwrap(); let fresh = dir.path().join("new").join("mcp.json"); - let gw = dir.path().join("craft-ai-mcp.exe"); + let gw = dir.path().join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX)); register(&fresh, &gw).unwrap(); assert_eq!(read(&fresh)["mcpServers"][SERVER_KEY]["args"], json!(["--stdio"])); assert!(registered(&fresh)); @@ -124,7 +124,7 @@ fn an_empty_config_counts_as_fresh_and_a_missing_one_needs_no_unregister() { let dir = tempfile::tempdir().unwrap(); let p = dir.path().join("empty.json"); std::fs::write(&p, " \n").unwrap(); - register(&p, &dir.path().join("gw")).unwrap(); + register(&p, &dir.path().join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX))).unwrap(); assert!(registered(&p)); unregister(&dir.path().join("missing.json")).unwrap(); assert!(!dir.path().join("missing.json").exists()); @@ -140,6 +140,41 @@ fn unregister_leaves_a_file_without_our_entry_untouched() { assert_eq!(std::fs::read_to_string(&p).unwrap(), text); } +/// A person's own `ArtCraft` entry (another command, other arguments, its own environment) is +/// never replaced by Add, and neither Remove nor turning agents off deletes it. +#[test] +fn an_artcraft_entry_the_launcher_did_not_write_is_kept() { + let dir = tempfile::tempdir().unwrap(); + let gw = dir.path().join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX)); + let theirs = [ + json!({"command": "node", "args": ["my-artcraft.js"]}), + json!({"url": "http://localhost:9000/mcp"}), + json!({"command": gw.to_string_lossy(), "args": ["--stdio", "--verbose"]}), + json!({"command": gw.to_string_lossy(), "args": ["--stdio"], "env": {"TOKEN": "x"}}), + json!("not an object"), + ]; + for (i, entry) in theirs.iter().enumerate() { + let p = dir.path().join(format!("c{i}.json")); + let text = serde_json::to_string_pretty(&json!({"mcpServers": {SERVER_KEY: entry}})).unwrap(); + std::fs::write(&p, &text).unwrap(); + assert!(!registered(&p), "{entry}"); + assert!(register(&p, &gw).is_err(), "{entry}"); + unregister(&p).unwrap(); + assert_eq!(std::fs::read_to_string(&p).unwrap(), text, "{entry} changed"); + } + + // Our own entry, wherever its gateway copy is (and with an empty `env` a client may add), is ours. + let p = dir.path().join("ours.json"); + let moved = dir.path().join("elsewhere").join(gw.file_name().unwrap()); + std::fs::write(&p, json!({"mcpServers": {SERVER_KEY: {"command": moved.to_string_lossy(), "args": ["--stdio"], "env": {}}}}).to_string()) + .unwrap(); + assert!(registered(&p)); + register(&p, &gw).unwrap(); + assert_eq!(read(&p)["mcpServers"][SERVER_KEY]["command"], gw.to_string_lossy().as_ref()); + unregister(&p).unwrap(); + assert!(read(&p)["mcpServers"].get(SERVER_KEY).is_none()); +} + #[test] fn a_folder_in_place_of_the_config_is_an_error() { let dir = tempfile::tempdir().unwrap(); From 5bccf77b78227f572893a4e75bd4d4adcd8d906a Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 20:56:41 +0100 Subject: [PATCH 26/27] build: pin craft-ai-mcp and craft-ai-agents to the merge of craft-ai-integrations#197 Moves both pins from 94a3fb5 (the PR head at the time) to 0d76ea0, the merge. That brings in the last two review fixes: an app briefly in use is stopped when agents go off, and an apps.json that can't be read counts as agents off. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 6 +++--- Cargo.toml | 4 ++-- apps/craft-ai-mcp/Cargo.toml | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d21558b7..077fc81f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -991,7 +991,7 @@ dependencies = [ [[package]] name = "craft-ai-agents" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=94a3fb570938614927debefbc660e5d8271d816a#94a3fb570938614927debefbc660e5d8271d816a" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=0d76ea02a06299a5a6eee1993863fbcafe9c2cc3#0d76ea02a06299a5a6eee1993863fbcafe9c2cc3" dependencies = [ "dirs 7.0.0", "serde", @@ -1001,7 +1001,7 @@ dependencies = [ [[package]] name = "craft-ai-mcp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-ai-integrations?rev=94a3fb570938614927debefbc660e5d8271d816a#94a3fb570938614927debefbc660e5d8271d816a" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=0d76ea02a06299a5a6eee1993863fbcafe9c2cc3#0d76ea02a06299a5a6eee1993863fbcafe9c2cc3" dependencies = [ "craft-ai-agents", "dirs 7.0.0", @@ -1307,7 +1307,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9fea5472..d1312a16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,8 +36,8 @@ jiff = "0.2" # Feature flags (craft-libs#1118, merged in craft-libs#1119). craft-flags = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } # The agents switch and app list (Settings › AI agents), shared with the craft-ai-mcp gateway and -# every Craft app. Pinned to the head of storytold/craft-ai-integrations#197 until it merges. -craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "94a3fb570938614927debefbc660e5d8271d816a" } +# every Craft app. Pinned to the merge of storytold/craft-ai-integrations#197. +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "0d76ea02a06299a5a6eee1993863fbcafe9c2cc3" } craft-update = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-ui = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } diff --git a/apps/craft-ai-mcp/Cargo.toml b/apps/craft-ai-mcp/Cargo.toml index e4df4721..1f6f382f 100644 --- a/apps/craft-ai-mcp/Cargo.toml +++ b/apps/craft-ai-mcp/Cargo.toml @@ -15,6 +15,6 @@ name = "craft-ai-mcp" path = "src/main.rs" # The gateway from storytold/craft-ai-integrations (crates/ai-mcp), pinned like the craft-libs crates. -# Pinned to the head of storytold/craft-ai-integrations#197 until it merges; re-pin then. +# Pinned to the merge of storytold/craft-ai-integrations#197. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "94a3fb570938614927debefbc660e5d8271d816a" } +craft-ai-mcp = { git = "https://github.com/storytold/craft-ai-integrations", rev = "0d76ea02a06299a5a6eee1993863fbcafe9c2cc3" } From 76727879f3cd86184e0b20317ee1a6361f40a2a0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:11:22 +0100 Subject: [PATCH 27/27] fix(agents): preserve customized MCP client entries --- crates/native/src/agents.rs | 36 ++++++++++------------- crates/native/src/agents_tests.rs | 49 ++++++++++++++++++++----------- 2 files changed, 47 insertions(+), 38 deletions(-) diff --git a/crates/native/src/agents.rs b/crates/native/src/agents.rs index eaa86ac0..b57c0572 100644 --- a/crates/native/src/agents.rs +++ b/crates/native/src/agents.rs @@ -152,31 +152,25 @@ fn read_config(path: &Path) -> Result>, String> { } } -/// Whether `entry` is one the launcher wrote: it starts the gateway (`craft-ai-mcp`, wherever its -/// copy is) with exactly `--stdio` and sets no environment. Anything else under [`SERVER_KEY`] was -/// set up by the person or another tool, and the launcher never replaces or removes it. -fn ours(entry: &Value) -> bool { +/// Whether this is the uncustomized entry for the launcher's stable gateway copy. +/// A matching filename alone is not ownership: preserve other paths and client options. +fn ours(entry: &Value, gateway: &Path) -> bool { let Value::Object(e) = entry else { return false; }; - let gateway = format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX); - let command_is_gateway = e - .get("command") - .and_then(Value::as_str) - .and_then(|c| Path::new(c).file_name()) - .and_then(|n| n.to_str()) - .is_some_and(|n| if cfg!(windows) { n.eq_ignore_ascii_case(&gateway) } else { n == gateway }); + let command_is_gateway = e.get("command").and_then(Value::as_str).is_some_and(|c| Path::new(c).is_absolute() && Path::new(c) == gateway); let no_env = match e.get("env") { None => true, Some(Value::Object(env)) => env.is_empty(), Some(_) => false, }; - command_is_gateway && e.get("args") == Some(&json!(["--stdio"])) && no_env + let no_custom_options = e.keys().all(|k| matches!(k.as_str(), "command" | "args" | "env")); + command_is_gateway && e.get("args") == Some(&json!(["--stdio"])) && no_env && no_custom_options } /// Whether `config` holds our entry (not merely some entry named [`SERVER_KEY`]). -pub fn registered(config: &Path) -> bool { - matches!(read_config(config), Ok(Some(m)) if m.get("mcpServers").and_then(|s| s.get(SERVER_KEY)).is_some_and(ours)) +pub fn registered(config: &Path, gateway: &Path) -> bool { + matches!(read_config(config), Ok(Some(m)) if m.get("mcpServers").and_then(|s| s.get(SERVER_KEY)).is_some_and(|e| ours(e, gateway))) } /// Add (or update) our entry in the client configuration at `config`, starting `gateway`. @@ -188,7 +182,7 @@ pub fn register(config: &Path, gateway: &Path) -> Result<(), String> { let Value::Object(servers) = servers else { return Err(format!("`mcpServers` in {} is not an object; the launcher leaves it unchanged", config.display())); }; - if servers.get(SERVER_KEY).is_some_and(|e| !ours(e)) { + if servers.get(SERVER_KEY).is_some_and(|e| !ours(e, gateway)) { return Err(format!( "{} already has its own `{SERVER_KEY}` entry; the launcher leaves it unchanged. Rename or remove it to add the launcher's", config.display() @@ -201,12 +195,12 @@ pub fn register(config: &Path, gateway: &Path) -> Result<(), String> { /// Remove our entry from the client configuration at `config`. Nothing to do when the file or /// our entry is missing; an entry named [`SERVER_KEY`] the launcher did not write is kept. -pub fn unregister(config: &Path) -> Result<(), String> { +pub fn unregister(config: &Path, gateway: &Path) -> Result<(), String> { let Some(mut root) = read_config(config)? else { return Ok(()); }; let removed = match root.get_mut("mcpServers") { - Some(Value::Object(servers)) if servers.get(SERVER_KEY).is_some_and(ours) => servers.remove(SERVER_KEY).is_some(), + Some(Value::Object(servers)) if servers.get(SERVER_KEY).is_some_and(|e| ours(e, gateway)) => servers.remove(SERVER_KEY).is_some(), _ => false, }; if !removed { @@ -360,7 +354,7 @@ pub fn state(services: &[InstalledApp]) -> McpAgents { client: *c, name: client_name(*c).to_string(), installed: paths.as_ref().is_some_and(|(config, folder)| folder.is_dir() || config.is_file()), - added: paths.as_ref().is_some_and(|(config, _)| registered(config)), + added: paths.as_ref().is_some_and(|(config, _)| dir.as_deref().is_some_and(|d| registered(config, &gateway_copy(d)))), restartable: restartable(*c), } }) @@ -401,7 +395,7 @@ pub fn set_enabled(on: bool, services: &[InstalledApp]) -> Result<(), String> { let mut first_error = remove_apps(&dir).err(); for c in CLIENTS { if let Some((config, _)) = client_paths(c) - && let Err(e) = unregister(&config) + && let Err(e) = unregister(&config, &gateway_copy(&dir)) { first_error.get_or_insert(e); } @@ -415,13 +409,13 @@ pub fn set_enabled(on: bool, services: &[InstalledApp]) -> Result<(), String> { /// gateway copy in [`mcp_dir`]. pub fn set_client(client: McpClient, added: bool) -> Result<(), String> { let (config, _) = client_paths(client).ok_or("couldn't find the home folder")?; + let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; if !added { - return unregister(&config); + return unregister(&config, &gateway_copy(&dir)); } if !flag_on() { return Err(NO_FLAG.into()); } - let dir = mcp_dir().ok_or("couldn't find the per-user configuration folder")?; let _guard = lock(); if !enabled(&dir) { return Err("turn on \"Let AI agents use Craft apps\" first".into()); diff --git a/crates/native/src/agents_tests.rs b/crates/native/src/agents_tests.rs index d18ea3c2..7e3810d0 100644 --- a/crates/native/src/agents_tests.rs +++ b/crates/native/src/agents_tests.rs @@ -80,6 +80,17 @@ fn switching_on_and_off() { remove_apps(dir.path()).unwrap(); } +#[test] +fn a_broken_app_list_does_not_grant_agents_access() { + let dir = tempfile::tempdir().unwrap(); + write_apps(dir.path(), &[]).unwrap(); + assert!(enabled(dir.path())); + std::fs::write(dir.path().join(APPS_FILE), b"not json").unwrap(); + assert!(!enabled(dir.path())); + std::fs::write(dir.path().join(APPS_FILE), br#"{"version":999,"apps":[]}"#).unwrap(); + assert!(!enabled(dir.path())); +} + #[test] fn register_creates_a_config_and_keeps_other_servers_and_keys() { let dir = tempfile::tempdir().unwrap(); @@ -87,7 +98,7 @@ fn register_creates_a_config_and_keeps_other_servers_and_keys() { let gw = dir.path().join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX)); register(&fresh, &gw).unwrap(); assert_eq!(read(&fresh)["mcpServers"][SERVER_KEY]["args"], json!(["--stdio"])); - assert!(registered(&fresh)); + assert!(registered(&fresh, &gw)); let existing = dir.path().join("claude.json"); std::fs::write(&existing, r#"{"theme":"dark","mcpServers":{"other":{"command":"x"}}}"#).unwrap(); @@ -97,11 +108,11 @@ fn register_creates_a_config_and_keeps_other_servers_and_keys() { assert_eq!(v["mcpServers"]["other"]["command"], "x"); assert_eq!(v["mcpServers"][SERVER_KEY]["command"], gw.to_string_lossy().as_ref()); - unregister(&existing).unwrap(); + unregister(&existing, &gw).unwrap(); let v = read(&existing); assert!(v["mcpServers"].get(SERVER_KEY).is_none()); assert_eq!(v["mcpServers"]["other"]["command"], "x"); - assert!(!registered(&existing)); + assert!(!registered(&existing, &gw)); } #[test] @@ -115,8 +126,8 @@ fn a_broken_config_is_never_overwritten() { assert_eq!(std::fs::read_to_string(&p).unwrap(), text, "{name} changed"); } let bad = dir.path().join("bad.json"); - assert!(unregister(&bad).is_err()); - assert!(!registered(&bad)); + assert!(unregister(&bad, &gw).is_err()); + assert!(!registered(&bad, &gw)); } #[test] @@ -124,19 +135,21 @@ fn an_empty_config_counts_as_fresh_and_a_missing_one_needs_no_unregister() { let dir = tempfile::tempdir().unwrap(); let p = dir.path().join("empty.json"); std::fs::write(&p, " \n").unwrap(); - register(&p, &dir.path().join(format!("craft-ai-mcp{}", std::env::consts::EXE_SUFFIX))).unwrap(); - assert!(registered(&p)); - unregister(&dir.path().join("missing.json")).unwrap(); + let gw = gateway_copy(dir.path()); + register(&p, &gw).unwrap(); + assert!(registered(&p, &gw)); + unregister(&dir.path().join("missing.json"), &gw).unwrap(); assert!(!dir.path().join("missing.json").exists()); } #[test] fn unregister_leaves_a_file_without_our_entry_untouched() { let dir = tempfile::tempdir().unwrap(); + let gw = gateway_copy(dir.path()); let p = dir.path().join("c.json"); let text = "{\"mcpServers\": {\"other\": {}}}"; std::fs::write(&p, text).unwrap(); - unregister(&p).unwrap(); + unregister(&p, &gw).unwrap(); assert_eq!(std::fs::read_to_string(&p).unwrap(), text); } @@ -151,27 +164,29 @@ fn an_artcraft_entry_the_launcher_did_not_write_is_kept() { json!({"url": "http://localhost:9000/mcp"}), json!({"command": gw.to_string_lossy(), "args": ["--stdio", "--verbose"]}), json!({"command": gw.to_string_lossy(), "args": ["--stdio"], "env": {"TOKEN": "x"}}), + json!({"command": dir.path().join("elsewhere").join(gw.file_name().unwrap()), "args": ["--stdio"]}), + json!({"command": gw.to_string_lossy(), "args": ["--stdio"], "cwd": "/custom"}), + json!({"command": gw.to_string_lossy(), "args": ["--stdio"], "disabled": true}), + json!({"command": gw.to_string_lossy(), "args": ["--stdio"], "timeout": 42}), json!("not an object"), ]; for (i, entry) in theirs.iter().enumerate() { let p = dir.path().join(format!("c{i}.json")); let text = serde_json::to_string_pretty(&json!({"mcpServers": {SERVER_KEY: entry}})).unwrap(); std::fs::write(&p, &text).unwrap(); - assert!(!registered(&p), "{entry}"); + assert!(!registered(&p, &gw), "{entry}"); assert!(register(&p, &gw).is_err(), "{entry}"); - unregister(&p).unwrap(); + unregister(&p, &gw).unwrap(); assert_eq!(std::fs::read_to_string(&p).unwrap(), text, "{entry} changed"); } - // Our own entry, wherever its gateway copy is (and with an empty `env` a client may add), is ours. + // The exact stable gateway entry, with an empty environment a client may add, is ours. let p = dir.path().join("ours.json"); - let moved = dir.path().join("elsewhere").join(gw.file_name().unwrap()); - std::fs::write(&p, json!({"mcpServers": {SERVER_KEY: {"command": moved.to_string_lossy(), "args": ["--stdio"], "env": {}}}}).to_string()) - .unwrap(); - assert!(registered(&p)); + std::fs::write(&p, json!({"mcpServers": {SERVER_KEY: {"command": gw.to_string_lossy(), "args": ["--stdio"], "env": {}}}}).to_string()).unwrap(); + assert!(registered(&p, &gw)); register(&p, &gw).unwrap(); assert_eq!(read(&p)["mcpServers"][SERVER_KEY]["command"], gw.to_string_lossy().as_ref()); - unregister(&p).unwrap(); + unregister(&p, &gw).unwrap(); assert!(read(&p)["mcpServers"].get(SERVER_KEY).is_none()); }