Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/agents/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion crates/agents/src/manager/runner/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<acp::schema::v1::McpServer> {
Expand Down
67 changes: 67 additions & 0 deletions crates/agents/src/mcp_wire.rs
Original file line number Diff line number Diff line change
@@ -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<McpServer>) -> Vec<McpServer> {
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"));
}
}
12 changes: 1 addition & 11 deletions crates/agents/src/omp_mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -244,16 +244,6 @@ fn string_map(value: Option<&Value>) -> BTreeMap<String, String> {
.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::*;
Expand Down
15 changes: 7 additions & 8 deletions crates/agents/src/profiles/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
}

Expand Down
12 changes: 5 additions & 7 deletions crates/agents/tests/built_in_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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()
));
Expand Down
16 changes: 15 additions & 1 deletion crates/dimo-mcp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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) }
})
}
Expand Down
13 changes: 13 additions & 0 deletions crates/dimo-mcp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down
7 changes: 7 additions & 0 deletions crates/server/src/composition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

Expand Down
110 changes: 108 additions & 2 deletions crates/server/src/host/plugin_projections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
Loading