diff --git a/crates/agents/src/lib.rs b/crates/agents/src/lib.rs index 4301c432b..7c764783e 100644 --- a/crates/agents/src/lib.rs +++ b/crates/agents/src/lib.rs @@ -55,6 +55,7 @@ pub mod managed_toolchain; pub mod management_boundary; pub mod management_state; pub mod manager; +mod mcp_wire; pub mod metadata; pub mod native_config; mod native_steering; diff --git a/crates/agents/src/manager/runner/replay.rs b/crates/agents/src/manager/runner/replay.rs index 246595c9d..c08107023 100644 --- a/crates/agents/src/manager/runner/replay.rs +++ b/crates/agents/src/manager/runner/replay.rs @@ -473,7 +473,9 @@ impl AgentConnectionRunner { }, ); } - servers + // Independent sources may name the same server; adapters reject a + // repeated name, so the first source wins. + crate::mcp_wire::dedupe_by_name(servers) } pub(in crate::manager) async fn session_mcp_servers(&self) -> Vec { diff --git a/crates/agents/src/mcp_wire.rs b/crates/agents/src/mcp_wire.rs new file mode 100644 index 000000000..c5a4e29c9 --- /dev/null +++ b/crates/agents/src/mcp_wire.rs @@ -0,0 +1,67 @@ +//! Wire-level helpers for the `session/new` `mcpServers` list. +//! +//! The Host assembles that list from independent sources — the global remote +//! server list, the injected companion, and the Agent's own config projection +//! (`~/.omp/agent/mcp.json`, `~/.dsh/mcp.json`, …). ACP adapters reject two +//! entries that normalize to the same name, so every merged list goes through +//! [`dedupe_by_name`] before it reaches the adapter. + +use agent_client_protocol::schema::v1::McpServer; + +/// The name an ACP adapter keys a `session/new.mcpServers` entry by. +pub(crate) fn server_name(server: &McpServer) -> &str { + match server { + McpServer::Stdio(server) => &server.name, + McpServer::Http(server) => &server.name, + McpServer::Sse(server) => &server.name, + #[allow(unreachable_patterns)] + _ => "", + } +} + +/// Keep the first entry for each name, preserving order. An entry without a +/// name cannot collide, so it survives. +pub(crate) fn dedupe_by_name(servers: Vec) -> Vec { + let mut seen = std::collections::HashSet::new(); + servers + .into_iter() + .filter(|server| { + let name = server_name(server); + name.is_empty() || seen.insert(name.to_owned()) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use agent_client_protocol::schema::v1::{McpServerHttp, McpServerSse, McpServerStdio}; + + #[test] + fn first_entry_wins_for_a_repeated_name() { + let deduped = dedupe_by_name(vec![ + McpServer::Http(McpServerHttp::new("shared", "https://global")), + McpServer::Stdio(McpServerStdio::new("shared", "agent-config")), + McpServer::Sse(McpServerSse::new("events", "https://events")), + ]); + + assert_eq!(deduped.len(), 2); + assert!( + matches!(&deduped[0], McpServer::Http(_)), + "the global source keeps its entry" + ); + assert!(matches!(&deduped[1], McpServer::Sse(server) if server.name == "events")); + } + + #[test] + fn distinct_names_survive_in_order() { + let deduped = dedupe_by_name(vec![ + McpServer::Stdio(McpServerStdio::new("a", "a")), + McpServer::Stdio(McpServerStdio::new("b", "b")), + ]); + + assert_eq!(deduped.len(), 2); + assert!(matches!(&deduped[0], McpServer::Stdio(server) if server.name == "a")); + assert!(matches!(&deduped[1], McpServer::Stdio(server) if server.name == "b")); + } +} diff --git a/crates/agents/src/omp_mcp.rs b/crates/agents/src/omp_mcp.rs index af03a7b7d..b3d446236 100644 --- a/crates/agents/src/omp_mcp.rs +++ b/crates/agents/src/omp_mcp.rs @@ -12,7 +12,7 @@ use agent_client_protocol::schema::v1::{ }; use serde_json::Value; -use crate::omp_auth::agent_dir; +use crate::{mcp_wire::server_name, omp_auth::agent_dir}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct SessionMcpOffer { @@ -244,16 +244,6 @@ fn string_map(value: Option<&Value>) -> BTreeMap { .collect() } -fn server_name(server: &McpServer) -> &str { - match server { - McpServer::Http(server) => &server.name, - McpServer::Sse(server) => &server.name, - McpServer::Stdio(server) => &server.name, - #[allow(unreachable_patterns)] - _ => "", - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/agents/src/profiles/mod.rs b/crates/agents/src/profiles/mod.rs index 77503a446..20dca93fd 100644 --- a/crates/agents/src/profiles/mod.rs +++ b/crates/agents/src/profiles/mod.rs @@ -299,17 +299,16 @@ impl BuiltInProfile { } /// Whether Host may put `mcpServers` on `session/new`, `session/load`, and - /// `session/resume`. OpenClaw rejects a non-empty list. Cline, Pi, and - /// DeepSeek Harness accept the field but load their companion MCP servers - /// from their own config file on disk (`~/.dsh/mcp.json` for DeepSeek), - /// so injecting via `session/new` would cause a duplicate that fails - /// `failOnStartupError` in the agent's MCP client. + /// `session/resume`. OpenClaw rejects a non-empty list. Cline and Pi accept + /// the field but never connect those servers (companion is wire-only). + /// + /// DeepSeek Harness stays deliverable: its ACP adapter mounts the + /// `session/new` list itself, so the Host keeps `~/.dsh/mcp.json` for the + /// adapter's own runs and injects the same servers per session. pub fn delivers_session_mcp(&self) -> bool { !matches!( AgentKind::from_lenient(self.agent_id.as_str()), - Some( - AgentKind::Openclaw | AgentKind::Cline | AgentKind::Pi | AgentKind::DeepseekHarness - ) + Some(AgentKind::Openclaw | AgentKind::Cline | AgentKind::Pi) ) } diff --git a/crates/agents/tests/built_in_profiles.rs b/crates/agents/tests/built_in_profiles.rs index 2deea2e3f..7422b7d2a 100644 --- a/crates/agents/tests/built_in_profiles.rs +++ b/crates/agents/tests/built_in_profiles.rs @@ -355,10 +355,7 @@ fn agents_that_skip_session_mcp() { let catalog = BuiltInProfileCatalog::bundled(); for profile in catalog.profiles() { let delivers = profile.delivers_session_mcp(); - let skips = matches!( - profile.agent_id.as_str(), - "openclaw" | "cline" | "pi" | "deepseek_harness" - ); + let skips = matches!(profile.agent_id.as_str(), "openclaw" | "cline" | "pi"); assert_eq!( delivers, !skips, "{} session MCP delivery", @@ -374,9 +371,10 @@ fn agents_that_skip_session_mcp() { assert!(!agents::profile_delivers_session_mcp( &AgentId::parse("pi").unwrap() )); - assert!(!agents::profile_delivers_session_mcp( - &AgentId::parse("deepseek_harness").unwrap() - )); + assert!( + agents::profile_delivers_session_mcp(&AgentId::parse("deepseek_harness").unwrap()), + "DeepSeek Harness mounts the session/new list through its ACP adapter" + ); assert!(agents::profile_delivers_session_mcp( &AgentId::parse("claude_code").unwrap() )); diff --git a/crates/dimo-mcp/src/main.rs b/crates/dimo-mcp/src/main.rs index eda862d3c..50f1065bc 100644 --- a/crates/dimo-mcp/src/main.rs +++ b/crates/dimo-mcp/src/main.rs @@ -583,9 +583,18 @@ impl Companion { "ping" => respond(id, modernize_result(params, json!({}), &self.product)) .map(LineAction::Respond) .unwrap_or(LineAction::Ignore), + // The 2026-07-28 revision makes `tools/list` carry cache hints and + // its SDK schema requires both fields, so a modern client rejects + // the list outright when they are absent. This list depends on the + // session's `--features` and conversation scope, so it is never + // publicly cacheable. "tools/list" => respond( id, - modernize_result(params, json!({ "tools": self.tools }), &self.product), + modernize_result( + params, + json!({ "tools": self.tools, "ttlMs": 0, "cacheScope": "private" }), + &self.product, + ), ) .map(LineAction::Respond) .unwrap_or(LineAction::Ignore), @@ -1266,10 +1275,15 @@ fn meta_protocol_version(params: Option<&Value>) -> Option<&str> { } fn discover_result(product: &str) -> Value { + // rmcp decodes this reply as `DiscoverResult`, whose `ttl_ms` and + // `cache_scope` are required; without them the reply falls through to + // another result variant and the modern handshake fails. json!({ "resultType": "complete", "supportedVersions": [MODERN_MCP_PROTOCOL], "capabilities": { "tools": {} }, + "ttlMs": 0, + "cacheScope": "private", "_meta": { MCP_SERVER_INFO_META: server_info(product) } }) } diff --git a/crates/dimo-mcp/src/tests.rs b/crates/dimo-mcp/src/tests.rs index 7c2902800..06fb9e15b 100644 --- a/crates/dimo-mcp/src/tests.rs +++ b/crates/dimo-mcp/src/tests.rs @@ -105,6 +105,11 @@ fn discover_answers_claude_code_2026_stdio_probe() { "listing only the modern revision keeps Claude on 2026-07-28 after the probe" ); assert_eq!(value["result"]["capabilities"]["tools"], json!({})); + assert_eq!( + value["result"]["ttlMs"], 0, + "DiscoverResult requires a cache TTL; its absence makes rmcp decode the reply as another result variant" + ); + assert_eq!(value["result"]["cacheScope"], "private"); assert_eq!( value["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "dimo-mcp" @@ -119,6 +124,14 @@ fn tools_list_after_modern_discover_does_not_need_initialize() { )); assert!(value["result"]["tools"].is_array()); assert_eq!(value["result"]["resultType"], "complete"); + assert_eq!( + value["result"]["ttlMs"], 0, + "the 2026-07-28 tools/list schema requires a cache TTL" + ); + assert_eq!( + value["result"]["cacheScope"], "private", + "the tool set depends on the session, so it must not be cached publicly" + ); assert_eq!( value["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "dimo-mcp" diff --git a/crates/server/src/composition.rs b/crates/server/src/composition.rs index 27a14d04c..b8190aabc 100644 --- a/crates/server/src/composition.rs +++ b/crates/server/src/composition.rs @@ -1177,6 +1177,13 @@ async fn initialize_plugins_and_runtime( { tracing::warn!(%error, "official product runtime sync failed"); } + // Projections of Plugins uninstalled while the Host was not running are + // invisible to every later refresh, so sweep them once per boot. Desktop + // runs this inside the deferred startup task; headless runs it here. + crate::host::plugin_projections::reconcile_disabled_and_uninstalled_plugin_projections( + &ctx.plugin_control_plane, + ) + .await; Ok(()) } diff --git a/crates/server/src/host/plugin_projections.rs b/crates/server/src/host/plugin_projections.rs index 248f86ffb..19947047e 100644 --- a/crates/server/src/host/plugin_projections.rs +++ b/crates/server/src/host/plugin_projections.rs @@ -568,11 +568,19 @@ async fn sync_host_delegation_native_mcp(gate: &plugins::OfficialMcpRuntime, ena Some(&http_base), Some(&token), ); + // Every assignable Agent except Cline takes the companion through + // `session/new.mcpServers` (ACP) or the native engine's per-session + // `mcp_servers` config, and only that path can carry `--conversation-id`. + // A config-file copy cannot bind a conversation, so a globally projected one + // both competes with the per-session entry of the same name and leaves + // Codex without a ready client for threads Dimo did not launch. Target only + // Cline, which never mounts session MCP; `set_targets` removes the entry + // from every other Agent config written by older Hosts. if let Err(error) = services::services::mcp::upsert_local_server( plugins::SUPERAGENT_MCP_NAME.to_string(), spec, - true, - Vec::new(), + false, + vec![services::services::mcp::McpAppType::Cline], ) .await { @@ -801,6 +809,21 @@ pub async fn reconcile_disabled_and_uninstalled_plugin_projections( } } + // An uninstalled Plugin leaves its Agent-config entry pointing at runtime + // files that no longer exist, and no later refresh revisits it: the local + // store stops listing it, so only the Agent config files still carry it. + // A dead path is the one signal that survives the uninstall, so sweep it + // without touching a projection whose files are still there. + for server in &local_servers { + if spec_plugin_id(&server.spec).is_some() && !spec_runtime_paths_exist(&server.spec) { + tracing::info!( + mcp_server_id = %server.id, + "removing Plugin MCP projection whose runtime files are gone" + ); + stale_mcp_server_ids.insert(server.id.clone()); + } + } + for server_id in stale_mcp_server_ids { if local_server_ids.contains(&server_id) && let Err(error) = services::services::mcp::uninstall_server(server_id.clone()).await @@ -814,6 +837,52 @@ pub async fn reconcile_disabled_and_uninstalled_plugin_projections( } } +/// Whether every filesystem path a projected MCP spec points at still exists. +/// +/// Bare executable names (`npx`, `node`) resolve through `PATH` and are skipped; +/// only entries that name a path are checked. +fn spec_runtime_paths_exist(spec: &Value) -> bool { + fn is_path(value: &str) -> bool { + // Only absolute paths are checkable. A bare command resolves through + // `PATH`, and `@scope/package` or a relative argument is not a file we + // can judge from the projection alone. + let bytes = value.as_bytes(); + let drive_rooted = bytes.len() > 2 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && (bytes[2] == b'\\' || bytes[2] == b'/'); + drive_rooted || value.starts_with("\\\\") || value.starts_with('/') + } + fn exists(value: &str) -> bool { + !value.is_empty() && std::path::Path::new(value).exists() + } + + if let Some(command) = spec.get("command").and_then(Value::as_str) + && is_path(command) + && !exists(command) + { + return false; + } + if let Some(cwd) = spec.get("cwd").and_then(Value::as_str) + && !cwd.is_empty() + && !exists(cwd) + { + return false; + } + if let Some(args) = spec.get("args").and_then(Value::as_array) { + for arg in args.iter().filter_map(Value::as_str) { + // `--token`-style flags and bare values are not paths. + if arg.starts_with('-') || !is_path(arg) { + continue; + } + if !exists(arg) { + return false; + } + } + } + true +} + enum McpProjectionSelection<'a> { Configure { all_agents: bool, @@ -1232,6 +1301,43 @@ mod tests { use super::*; + #[test] + fn spec_runtime_paths_detect_a_missing_plugin_snapshot() { + let temp = tempfile::tempdir().unwrap(); + let entry = temp.path().join("computer-use.mjs"); + std::fs::write(&entry, "//").unwrap(); + let command = temp.path().join("node.exe"); + std::fs::write(&command, "MZ").unwrap(); + + let live = json!({ + "type": "stdio", + "command": command.to_string_lossy(), + "args": [entry.to_string_lossy()], + "cwd": temp.path().to_string_lossy(), + }); + assert!(spec_runtime_paths_exist(&live)); + + let dead = json!({ + "type": "stdio", + "command": command.to_string_lossy(), + "args": [temp.path().join("removed.mjs").to_string_lossy()], + }); + assert!( + !spec_runtime_paths_exist(&dead), + "an uninstalled Plugin leaves an argument pointing at a deleted snapshot" + ); + } + + #[test] + fn spec_runtime_paths_ignore_bare_commands_and_flags() { + let spec = json!({ + "type": "stdio", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github", "--token", "value", "src/server.mjs"], + }); + assert!(spec_runtime_paths_exist(&spec)); + } + #[tokio::test] async fn mcp_update_failure_preserves_each_servers_desired_agents() { let pool = sqlx::sqlite::SqlitePoolOptions::new() diff --git a/plugins/browser/dist/mcp/mcp-server.mjs b/plugins/browser/dist/mcp/mcp-server.mjs index d5c1102c1..18d2f6c6c 100644 --- a/plugins/browser/dist/mcp/mcp-server.mjs +++ b/plugins/browser/dist/mcp/mcp-server.mjs @@ -6,7 +6,7 @@ import{Buffer}from"node:buffer";import{readFileSync}from"node:fs";import{dirname \`\`\`json ${JSON.stringify(result)} -\`\`\``;return[{type:"text",text}]}function renderEvalResult(result){const lines=["### Eval result",`- Tab: \`${result.tabId}\``,`- Value: ${result.value??"undefined"}`,"","```json",JSON.stringify(result),"```"];return[{type:"text",text:lines.join("\n")}]}function formatToolOutput(toolName,result){switch(toolName){case"browser_list_tabs":return renderTabsResult(result);case"browser_open_tab":return renderTabOpResult("opened",result);case"browser_navigate":return renderTabOpResult("navigated",result);case"browser_close_tab":return renderTabOpResult("closed",result);case"browser_snapshot":return renderSnapshotResult(result);case"browser_console_messages":return renderConsoleResult(result);case"browser_screenshot":return renderCaptureResult(result);case"browser_prefer":return renderPreferResult(result);case"browser_click":return renderActResult("click",result);case"browser_hover":return renderActResult("hover",result);case"browser_type":return renderActResult("type",result);case"browser_press_key":return renderActResult("press",result);case"browser_select_option":return renderActResult("select",result);case"browser_eval":return renderEvalResult(result);default:return[{type:"text",text:JSON.stringify(result)}]}}var MODERN_MCP_PROTOCOL="2026-07-28";var SERVER_INFO={name:"dimo-browser",version:"1.0.0"};function negotiateProtocol(requested){if(typeof requested==="string"&&SUPPORTED_PROTOCOLS.includes(requested)){return requested}return"2025-11-25"}function isModernRequest(params){return params&¶ms._meta&¶ms._meta["io.modelcontextprotocol/protocolVersion"]===MODERN_MCP_PROTOCOL}function discoverResult(){return{resultType:"complete",supportedVersions:[MODERN_MCP_PROTOCOL],capabilities:{tools:{}},_meta:{"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function modernize(params,result){if(!isModernRequest(params))return result;return{resultType:"complete",...result,_meta:{...result._meta||{},"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function isUnimplementedHostError(error){const msg=error instanceof Error?error.message:String(error??"");return msg.includes("capability_unimplemented")||msg.includes("is not implemented")||msg.includes("browser_unsupported_operation")}async function resolveFallbackTab(explicitTabId){const listed=await callHost("browser","tab.list",{});const tabs=Array.isArray(listed?.tabs)?listed.tabs:[];if(explicitTabId){const found=tabs.find(t=>t.tabId===explicitTabId);if(!found)throw new Error(`browser_no_such_tab: no tab ${explicitTabId}`);return found}if(tabs.length===1)return tabs[0];if(tabs.length===0){throw new Error("browser_no_such_tab: no browser tab is open; open a tab first")}throw new Error("browser_invalid: more than one browser tab is open; pass tabId (see browser_list_tabs)")}function buildPreferEvalScript(args){const reducedMotion=typeof args.reducedMotion==="boolean"?args.reducedMotion:null;const colorScheme=args.colorScheme==="light"||args.colorScheme==="dark"||args.colorScheme==="no-preference"?args.colorScheme:null;const settle=args.settle!==false;return`(function(){ +\`\`\``;return[{type:"text",text}]}function renderEvalResult(result){const lines=["### Eval result",`- Tab: \`${result.tabId}\``,`- Value: ${result.value??"undefined"}`,"","```json",JSON.stringify(result),"```"];return[{type:"text",text:lines.join("\n")}]}function formatToolOutput(toolName,result){switch(toolName){case"browser_list_tabs":return renderTabsResult(result);case"browser_open_tab":return renderTabOpResult("opened",result);case"browser_navigate":return renderTabOpResult("navigated",result);case"browser_close_tab":return renderTabOpResult("closed",result);case"browser_snapshot":return renderSnapshotResult(result);case"browser_console_messages":return renderConsoleResult(result);case"browser_screenshot":return renderCaptureResult(result);case"browser_prefer":return renderPreferResult(result);case"browser_click":return renderActResult("click",result);case"browser_hover":return renderActResult("hover",result);case"browser_type":return renderActResult("type",result);case"browser_press_key":return renderActResult("press",result);case"browser_select_option":return renderActResult("select",result);case"browser_eval":return renderEvalResult(result);default:return[{type:"text",text:JSON.stringify(result)}]}}var MODERN_MCP_PROTOCOL="2026-07-28";var SERVER_INFO={name:"dimo-browser",version:"1.0.0"};function negotiateProtocol(requested){if(typeof requested==="string"&&SUPPORTED_PROTOCOLS.includes(requested)){return requested}return"2025-11-25"}function isModernRequest(params){return params&¶ms._meta&¶ms._meta["io.modelcontextprotocol/protocolVersion"]===MODERN_MCP_PROTOCOL}function discoverResult(){return{resultType:"complete",supportedVersions:[MODERN_MCP_PROTOCOL],capabilities:{tools:{}},ttlMs:0,cacheScope:"private",_meta:{"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function modernize(params,result){if(!isModernRequest(params))return result;return{resultType:"complete",...Array.isArray(result.tools)?{ttlMs:0,cacheScope:"private"}:{},...result,_meta:{...result._meta||{},"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function isUnimplementedHostError(error){const msg=error instanceof Error?error.message:String(error??"");return msg.includes("capability_unimplemented")||msg.includes("is not implemented")||msg.includes("browser_unsupported_operation")}async function resolveFallbackTab(explicitTabId){const listed=await callHost("browser","tab.list",{});const tabs=Array.isArray(listed?.tabs)?listed.tabs:[];if(explicitTabId){const found=tabs.find(t=>t.tabId===explicitTabId);if(!found)throw new Error(`browser_no_such_tab: no tab ${explicitTabId}`);return found}if(tabs.length===1)return tabs[0];if(tabs.length===0){throw new Error("browser_no_such_tab: no browser tab is open; open a tab first")}throw new Error("browser_invalid: more than one browser tab is open; pass tabId (see browser_list_tabs)")}function buildPreferEvalScript(args){const reducedMotion=typeof args.reducedMotion==="boolean"?args.reducedMotion:null;const colorScheme=args.colorScheme==="light"||args.colorScheme==="dark"||args.colorScheme==="no-preference"?args.colorScheme:null;const settle=args.settle!==false;return`(function(){ var rm = ${JSON.stringify(reducedMotion)}; var cs = ${JSON.stringify(colorScheme)}; var styleId = '__dimo_prefer_reduced_motion'; diff --git a/plugins/browser/runtime/mcp-server.mjs b/plugins/browser/runtime/mcp-server.mjs index 0a00db87b..915fc0a44 100644 --- a/plugins/browser/runtime/mcp-server.mjs +++ b/plugins/browser/runtime/mcp-server.mjs @@ -708,6 +708,10 @@ function discoverResult() { resultType: 'complete', supportedVersions: [MODERN_MCP_PROTOCOL], capabilities: { tools: {} }, + // DiscoverResult requires both cache hints; rmcp falls back to another + // result variant and fails the handshake when either is missing. + ttlMs: 0, + cacheScope: 'private', _meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO }, }; } @@ -716,6 +720,8 @@ function modernize(params, result) { if (!isModernRequest(params)) return result; return { resultType: 'complete', + // 2026-07-28 requires both cache hints on a list result; without them a modern client rejects the whole list. + ...(Array.isArray(result.tools) ? { ttlMs: 0, cacheScope: 'private' } : {}), ...result, _meta: { ...(result._meta || {}), diff --git a/plugins/computer-use/dist/mcp/computer-use.mjs b/plugins/computer-use/dist/mcp/computer-use.mjs index 8b89ef395..a1ba4a909 100644 --- a/plugins/computer-use/dist/mcp/computer-use.mjs +++ b/plugins/computer-use/dist/mcp/computer-use.mjs @@ -1,3 +1,3 @@ #!/usr/bin/env node import{spawn,spawnSync}from"node:child_process";import fs from"node:fs";import os from"node:os";import path from"node:path";import readline from"node:readline";import{fileURLToPath}from"node:url";function resolvePluginRoot(){const candidates=[process.env.DIMO_PLUGIN_ROOT,path.dirname(fileURLToPath(import.meta.url)),process.cwd()].filter(Boolean);for(const start of candidates){let dir=path.resolve(start);for(let i=0;i<6;i+=1){if(fs.existsSync(path.join(dir,".dimo-plugin","plugin.json"))){return dir}const parent=path.dirname(dir);if(parent===dir)break;dir=parent}}return process.cwd()}function defaultUserDataDir(){const base=process.platform==="win32"?process.env.LOCALAPPDATA||path.join(os.homedir(),"AppData","Local"):process.platform==="darwin"?path.join(os.homedir(),"Library","Application Support"):process.env.XDG_DATA_HOME||path.join(os.homedir(),".local","share");return path.join(base,"dimo-plugin-computer-use")}function resolveDataDir(envOrCtx){if(envOrCtx&&typeof envOrCtx==="object"&&typeof envOrCtx.pluginDataDir==="string"&&envOrCtx.pluginDataDir){return envOrCtx.pluginDataDir}if(process.env.DIMO_PLUGIN_DATA_DIR){return process.env.DIMO_PLUGIN_DATA_DIR}return defaultUserDataDir()}function resolveHelperBinary(pluginRoot=resolvePluginRoot()){const exeName=process.platform==="win32"?"dimo-computer-helper.exe":"dimo-computer-helper";const repoRootFromSnapshot=path.resolve(pluginRoot,"..","..","..","..","..");const candidates=[path.join(pluginRoot,"bin",exeName),path.join(pluginRoot,"native","target","release",exeName),path.join(pluginRoot,"native","target","debug",exeName),path.join(pluginRoot,".git","cargo-target","release",exeName),path.join(pluginRoot,".git","cargo-target","debug",exeName),path.join(repoRootFromSnapshot,"plugins","computer-use","bin",exeName),path.join(repoRootFromSnapshot,"plugins","computer-use","native","target","release",exeName),path.join(repoRootFromSnapshot,"plugins","computer-use","native","target","debug",exeName),path.join(pluginRoot,"..","..","dev_assets","plugins","runtimes","plugins","snapshots","dimo-plugin-computer-use","bin",exeName)];for(const candidate of candidates){if(fs.existsSync(candidate)){return candidate}}return candidates[0]}async function isDaemonHealthy(url,token){if(!url||!token)return false;let timer=null;try{const res=await Promise.race([fetch(`${url}/health`,{headers:{authorization:`Bearer ${token}`}}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("timeout")),1500)})]);if(timer)clearTimeout(timer);if(!res||!res.ok)return false;const data=await res.json();return Boolean(data&&data.ok&&data.auth===true)}catch{if(timer)clearTimeout(timer);return false}}function readDaemonInfo(dataDir){const file=path.join(dataDir,"daemon.json");try{if(fs.existsSync(file)){const parsed=JSON.parse(fs.readFileSync(file,"utf8"));if(parsed&&typeof parsed.url==="string"&&parsed.url&&typeof parsed.token==="string"&&parsed.token){return{url:parsed.url,token:parsed.token}}}}catch{}return null}var cachedDaemon=null;var lastHealthyAt=0;var spawningPromise=null;var HEALTH_TTL_MS=4e3;function markHealthy(info){cachedDaemon=info;lastHealthyAt=Date.now()}async function ensureDaemonAuth(envOrCtx){if(cachedDaemon&&Date.now()-lastHealthyAt{try{let bin=resolveHelperBinary(pluginRoot);if(!fs.existsSync(bin)){const repoRootFromSnapshot=path.resolve(pluginRoot,"..","..","..","..","..");const manifestCandidates=[path.join(pluginRoot,"native","Cargo.toml"),path.join(repoRootFromSnapshot,"plugins","computer-use","native","Cargo.toml")];const manifestPath=manifestCandidates.find(candidate=>fs.existsSync(candidate));if(manifestPath){spawnSync("cargo",["build","--release","--manifest-path",manifestPath],{stdio:"ignore"});bin=resolveHelperBinary(pluginRoot)}}if(!fs.existsSync(bin)){throw new Error(`Computer helper binary not found at ${bin}`)}fs.mkdirSync(dataDir,{recursive:true});const child=spawn(bin,["--daemon","--data-dir",dataDir],{cwd:pluginRoot,detached:true,stdio:["ignore","pipe","pipe"],windowsHide:false});const readyUrl=await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(new Error("Timed out waiting for computer daemon to start"))},1e4);const rl=readline.createInterface({input:child.stdout});rl.on("line",line=>{const trimmed=line.trim();if(trimmed.startsWith("DAEMON_READY ")){clearTimeout(timeout);const url=trimmed.slice("DAEMON_READY ".length).trim();rl.close();resolve(url)}});let stderrBuf="";child.stderr.on("data",chunk=>{stderrBuf+=String(chunk)});child.once("error",err=>{clearTimeout(timeout);reject(err)});child.once("exit",code=>{clearTimeout(timeout);reject(new Error(`Computer daemon exited early (code ${code}): ${stderrBuf.trim()}`))})});child.stdout?.destroy();child.stderr?.destroy();child.unref();const info=readDaemonInfo(dataDir);if(!info||info.url!==readyUrl){throw new Error("Computer daemon started without valid daemon.json credentials")}markHealthy(info);return info}finally{spawningPromise=null}})();return spawningPromise}async function callDaemon(envOrCtx,method,params={}){let info=await ensureDaemonAuth(envOrCtx);let res=await fetch(`${info.url}/rpc`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${info.token}`},body:JSON.stringify({method,params:params??{}})});if(res.status===401){cachedDaemon=null;lastHealthyAt=0;info=await ensureDaemonAuth(envOrCtx);res=await fetch(`${info.url}/rpc`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${info.token}`},body:JSON.stringify({method,params:params??{}})})}if(!res.ok){throw new Error(`Daemon HTTP ${res.status} for ${method}`)}const body=await res.json();if(!body.ok){throw new Error(body.error||`Daemon RPC error in ${method}`)}markHealthy(info);return body.result}var FALLBACK_TOOLS=[{name:"computer_list_apps",description:"List desktop applications installed or running on this computer that may be launched or inspected.",inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"computer_list_windows",description:"List currently shared desktop windows and their targetIds, bounds, and grant levels.",inputSchema:{type:"object",properties:{pid:{type:"integer"}},additionalProperties:false}},{name:"computer_snapshot",description:"Read the accessibility tree of a shared window, assigning numeric element refs (@N) for subsequent actions.",inputSchema:{type:"object",properties:{targetId:{type:"string"},root:{type:"string"},depth:{type:"integer"},maxChars:{type:"integer"},filter:{type:"string",enum:["all","interactive"]}},required:["targetId"],additionalProperties:false}},{name:"computer_screenshot",description:"Capture a PNG screenshot (or a multi-frame contact sheet when overMs and everyMs are set) of a shared window or screen.",inputSchema:{type:"object",properties:{targetId:{type:"string"},maxDimension:{type:"integer"},overMs:{type:"integer",description:"Optional contact-sheet burst window in milliseconds (up to 10000)."},everyMs:{type:"integer",description:"Optional frame sampling interval in milliseconds (minimum 50) for contact-sheet burst capture."}},required:["targetId"],additionalProperties:false}},{name:"computer_verify",description:"Check a condition against the live accessibility tree of a shared window without returning the full tree.",inputSchema:{type:"object",properties:{targetId:{type:"string"},kind:{type:"string"},role:{type:"string"},title:{type:"string"},value:{type:"string"},element:{type:"string"},count:{type:"integer"},comparison:{type:"string"}},required:["targetId","kind"],additionalProperties:false}},{name:"computer_click",description:"Click an element (@N) or window-local coordinates (x, y) inside a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},x:{type:"number"},y:{type:"number"},button:{type:"string",enum:["left","right","middle"]},clickCount:{type:"integer"},modifiers:{type:"array",items:{type:"string"}},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId"],additionalProperties:false}},{name:"computer_drag",description:"Drag between elements or coordinates inside a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},fromElement:{type:"string"},fromX:{type:"number"},fromY:{type:"number"},toElement:{type:"string"},toX:{type:"number"},toY:{type:"number"},button:{type:"string",enum:["left","right","middle"]},modifiers:{type:"array",items:{type:"string"}},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId"],additionalProperties:false}},{name:"computer_scroll",description:"Scroll inside a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},x:{type:"number"},y:{type:"number"},deltaX:{type:"number"},deltaY:{type:"number"},unit:{type:"string",enum:["line","pixel"]},modifiers:{type:"array",items:{type:"string"}},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId"],additionalProperties:false}},{name:"computer_type",description:"Type text into a window or element shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},text:{type:"string"},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId","text"],additionalProperties:false}},{name:"computer_press_key",description:"Press a key or key chord in a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},key:{type:"string"},repeat:{type:"integer"},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId","key"],additionalProperties:false}},{name:"computer_hold_key",description:"Hold a key or key chord down for a duration in milliseconds in a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},key:{type:"string"},durationMs:{type:"integer"},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId","key","durationMs"],additionalProperties:false}},{name:"computer_set_value",description:"Set the accessibility value of an element (@N) directly in a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},element:{type:"string"},value:{type:"string"}},required:["targetId","element","value"],additionalProperties:false}},{name:"computer_restore",description:"Unminimize or restore a minimized window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"],additionalProperties:false}},{name:"computer_invoke_menu",description:"Invoke a menu bar item by path in a window shared for Control.",inputSchema:{type:"object",properties:{targetId:{type:"string"},path:{type:"array",items:{type:"string"}},delivery:{type:"string",enum:["background","foreground"]}},required:["targetId","path"],additionalProperties:false}},{name:"computer_launch_app",description:"Launch an application by name or key when allowed by settings.",inputSchema:{type:"object",properties:{name:{type:"string"},key:{type:"string"}},additionalProperties:false}},{name:"computer_set_window_frame",description:"Move or resize a window shared for Control when allowed by settings.",inputSchema:{type:"object",properties:{targetId:{type:"string"},x:{type:"number"},y:{type:"number"},width:{type:"number"},height:{type:"number"}},required:["targetId"],additionalProperties:false}},{name:"computer_clipboard_read",description:"Read text from the clipboard when allowed by settings.",inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"computer_clipboard_write",description:"Write text to the clipboard when allowed by settings.",inputSchema:{type:"object",properties:{text:{type:"string"}},required:["text"],additionalProperties:false}}];var MODERN_MCP_PROTOCOL="2026-07-28";var SERVER_INFO={name:"dimo-computer-use",version:"0.34.0"};function send(message){process.stdout.write(`${JSON.stringify(message)} -`)}function isModernRequest(params){return params&¶ms._meta&¶ms._meta["io.modelcontextprotocol/protocolVersion"]===MODERN_MCP_PROTOCOL}function discoverResult(){return{resultType:"complete",supportedVersions:[MODERN_MCP_PROTOCOL],capabilities:{tools:{}},_meta:{"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function modernize(params,result){if(!isModernRequest(params))return result;return{resultType:"complete",...result,_meta:{...result._meta||{},"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}async function isHostAuthorized(){const hostUrl=(process.env.DIMO_HOST_CALL_URL||"").trim();const hostToken=(process.env.DIMO_HOST_CALL_TOKEN||"").trim();const hasProjectedEnv=Boolean(hostUrl||hostToken||process.env.DIMO_PLUGIN_MCP_TOKEN||process.env.DIMO_PLUGIN_ID);if(!hasProjectedEnv){return Boolean(process.env.NODE_TEST_CONTEXT||process.env.VITEST||process.env.DIMO_COMPUTER_USE_STANDALONE_TEST==="1")}if(!hostUrl||!hostToken){return false}try{const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),1500);const res=await fetch(hostUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${hostToken}`},body:JSON.stringify({capability:"host",operation:"ping",input:{}}),signal:controller.signal});clearTimeout(timer);if(res.status===401||res.status===403){return false}return res.ok||res.status===400}catch{return false}}async function handle(message){if(!message||typeof message!=="object")return;const{id,method,params}=message;if(method==="initialize"){const requested=params&¶ms.protocolVersion;const protocolVersion=["2024-11-05","2025-03-26","2025-06-18","2025-11-25","2026-07-28"].includes(requested)?requested:"2025-11-25";send({jsonrpc:"2.0",id,result:{protocolVersion,capabilities:{tools:{}},serverInfo:SERVER_INFO}});return}if(method==="notifications/initialized"||method==="initialized"){return}if(method==="server/discover"){send({jsonrpc:"2.0",id,result:discoverResult()});return}if(method==="ping"){send({jsonrpc:"2.0",id,result:modernize(params,{})});return}if(method==="tools/list"){if(!await isHostAuthorized()){send({jsonrpc:"2.0",id,result:modernize(params,{tools:[]})});return}try{const res=await callDaemon(null,"mcp.listTools",{});const tools=res&&Array.isArray(res.tools)&&res.tools.length>0?res.tools:FALLBACK_TOOLS;send({jsonrpc:"2.0",id,result:modernize(params,{tools})})}catch{send({jsonrpc:"2.0",id,result:modernize(params,{tools:FALLBACK_TOOLS})})}return}if(method==="tools/call"){if(!await isHostAuthorized()){send({jsonrpc:"2.0",id,result:modernize(params,{content:[{type:"text",text:"computer_use_disabled: Computer Use plugin is not installed or enabled in Dimo."}],isError:true})});return}const toolName=params&&typeof params.name==="string"?params.name:"";const args=params&¶ms.arguments&&typeof params.arguments==="object"?params.arguments:{};try{const result=await callDaemon(null,"mcp.callTool",{name:toolName,arguments:args});send({jsonrpc:"2.0",id,result:modernize(params,result??{content:[{type:"text",text:"Empty tool response"}],isError:true})})}catch(error){send({jsonrpc:"2.0",id,result:modernize(params,{content:[{type:"text",text:error instanceof Error?error.message:String(error)}],isError:true})})}return}if(id!=null){send({jsonrpc:"2.0",id,error:{code:-32601,message:`Method not found: ${String(method||"")}`}})}}var buf=Buffer.alloc(0);process.stdin.on("data",chunk=>{buf=Buffer.concat([buf,chunk]);while(true){const nl=buf.indexOf(10);if(nl<0)break;const line=buf.subarray(0,nl).toString("utf8").trim();buf=buf.subarray(nl+1);if(!line)continue;try{const parsed=JSON.parse(line);void handle(parsed)}catch{}}});process.stdin.resume(); +`)}function isModernRequest(params){return params&¶ms._meta&¶ms._meta["io.modelcontextprotocol/protocolVersion"]===MODERN_MCP_PROTOCOL}function discoverResult(){return{resultType:"complete",supportedVersions:[MODERN_MCP_PROTOCOL],capabilities:{tools:{}},ttlMs:0,cacheScope:"private",_meta:{"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}function modernize(params,result){if(!isModernRequest(params))return result;return{resultType:"complete",...Array.isArray(result.tools)?{ttlMs:0,cacheScope:"private"}:{},...result,_meta:{...result._meta||{},"io.modelcontextprotocol/serverInfo":SERVER_INFO}}}async function isHostAuthorized(){const hostUrl=(process.env.DIMO_HOST_CALL_URL||"").trim();const hostToken=(process.env.DIMO_HOST_CALL_TOKEN||"").trim();const hasProjectedEnv=Boolean(hostUrl||hostToken||process.env.DIMO_PLUGIN_MCP_TOKEN||process.env.DIMO_PLUGIN_ID);if(!hasProjectedEnv){return Boolean(process.env.NODE_TEST_CONTEXT||process.env.VITEST||process.env.DIMO_COMPUTER_USE_STANDALONE_TEST==="1")}if(!hostUrl||!hostToken){return false}try{const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),1500);const res=await fetch(hostUrl,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${hostToken}`},body:JSON.stringify({capability:"host",operation:"ping",input:{}}),signal:controller.signal});clearTimeout(timer);if(res.status===401||res.status===403){return false}return res.ok||res.status===400}catch{return false}}async function handle(message){if(!message||typeof message!=="object")return;const{id,method,params}=message;if(method==="initialize"){const requested=params&¶ms.protocolVersion;const protocolVersion=["2024-11-05","2025-03-26","2025-06-18","2025-11-25","2026-07-28"].includes(requested)?requested:"2025-11-25";send({jsonrpc:"2.0",id,result:{protocolVersion,capabilities:{tools:{}},serverInfo:SERVER_INFO}});return}if(method==="notifications/initialized"||method==="initialized"){return}if(method==="server/discover"){send({jsonrpc:"2.0",id,result:discoverResult()});return}if(method==="ping"){send({jsonrpc:"2.0",id,result:modernize(params,{})});return}if(method==="tools/list"){if(!await isHostAuthorized()){send({jsonrpc:"2.0",id,result:modernize(params,{tools:[]})});return}try{const res=await callDaemon(null,"mcp.listTools",{});const tools=res&&Array.isArray(res.tools)&&res.tools.length>0?res.tools:FALLBACK_TOOLS;send({jsonrpc:"2.0",id,result:modernize(params,{tools})})}catch{send({jsonrpc:"2.0",id,result:modernize(params,{tools:FALLBACK_TOOLS})})}return}if(method==="tools/call"){if(!await isHostAuthorized()){send({jsonrpc:"2.0",id,result:modernize(params,{content:[{type:"text",text:"computer_use_disabled: Computer Use plugin is not installed or enabled in Dimo."}],isError:true})});return}const toolName=params&&typeof params.name==="string"?params.name:"";const args=params&¶ms.arguments&&typeof params.arguments==="object"?params.arguments:{};try{const result=await callDaemon(null,"mcp.callTool",{name:toolName,arguments:args});send({jsonrpc:"2.0",id,result:modernize(params,result??{content:[{type:"text",text:"Empty tool response"}],isError:true})})}catch(error){send({jsonrpc:"2.0",id,result:modernize(params,{content:[{type:"text",text:error instanceof Error?error.message:String(error)}],isError:true})})}return}if(id!=null){send({jsonrpc:"2.0",id,error:{code:-32601,message:`Method not found: ${String(method||"")}`}})}}var buf=Buffer.alloc(0);process.stdin.on("data",chunk=>{buf=Buffer.concat([buf,chunk]);while(true){const nl=buf.indexOf(10);if(nl<0)break;const line=buf.subarray(0,nl).toString("utf8").trim();buf=buf.subarray(nl+1);if(!line)continue;try{const parsed=JSON.parse(line);void handle(parsed)}catch{}}});process.stdin.resume(); diff --git a/plugins/computer-use/runtime/mcp.mjs b/plugins/computer-use/runtime/mcp.mjs index 69d0fa2c2..2c1b158f6 100644 --- a/plugins/computer-use/runtime/mcp.mjs +++ b/plugins/computer-use/runtime/mcp.mjs @@ -300,6 +300,10 @@ function discoverResult() { resultType: 'complete', supportedVersions: [MODERN_MCP_PROTOCOL], capabilities: { tools: {} }, + // DiscoverResult requires both cache hints; rmcp falls back to another + // result variant and fails the handshake when either is missing. + ttlMs: 0, + cacheScope: 'private', _meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO }, }; } @@ -308,6 +312,8 @@ function modernize(params, result) { if (!isModernRequest(params)) return result; return { resultType: 'complete', + // 2026-07-28 requires both cache hints on a list result; without them a modern client rejects the whole list. + ...(Array.isArray(result.tools) ? { ttlMs: 0, cacheScope: 'private' } : {}), ...result, _meta: { ...(result._meta || {}),