Skip to main content

agentmux_srv_core/backend/
mcp_selftest.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The launch self-test of an agent's `agentmux` MCP server (`SPEC_AGENT_MCP_SELF_HEAL_2026_10_10.md`
5//! §2 and §4.1, signal C): once per agent per AgentMux build, start the server the way Claude Code will,
6//! through the shell prefix and from the entry in the agent's `.mcp.json`, and speak the MCP handshake
7//! to it (`mcp_probe`). The bug this is for (v0.59.19) started fine directly and not through the
8//! prefix, so a probe of the bare entry would have said it was healthy.
9//!
10//! It runs in the background while the agent launches and changes nothing about the launch. A failure
11//! is logged and kept for `agentmux-mcp doctor` (`mcp_health::Snapshot::selftest`).
12
13use std::collections::{HashMap, HashSet};
14use std::path::Path;
15use std::sync::{Mutex, OnceLock};
16
17use serde_json::{json, Value};
18
19/// The env var Claude Code reads for its shell prefix.
20const PREFIX_ENV: &str = "CLAUDE_CODE_SHELL_PREFIX";
21
22/// Agents already tested by this build: `<agent>@<version>`.
23fn tested() -> &'static Mutex<HashSet<String>> {
24    static SET: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
25    SET.get_or_init(Default::default)
26}
27
28/// The variables of the launch environment the server's start depends on: where its command is found
29/// and which shell the wrapper runs it in. The rest of the environment is the CLI's, not the server's.
30const FORWARDED: [&str; 3] = ["PATH", "AGENTMUX_BASH", "BASH"];
31
32/// The `agentmux` entry of a `.mcp.json`.
33fn entry_of(mcp_json: &str) -> Option<Value> {
34    let doc: Value = serde_json::from_str(mcp_json).ok()?;
35    doc.pointer("/mcpServers/agentmux").cloned()
36}
37
38/// The probe's config for `entry` started through `prefix` the way the CLI starts a stdio server: the
39/// prefix is the program and the server's command line, joined unquoted, is its one argument. The
40/// server gets the entry's `env` and the variables of the agent's launch environment that decide how it
41/// starts (`launch_env`, see `FORWARDED`): its `PATH` has the AgentMux tools directory the bare
42/// `agentmux-mcp` command is found in, and its `AGENTMUX_BASH` the shell; srv's own may differ. An `env` of the entry wins. It
43/// starts in `cwd`, the agent's workspace, as the CLI starts it, so a workspace-relative command resolves.
44fn through_prefix(entry: &Value, prefix: &str, launch_env: &HashMap<String, String>, cwd: Option<&Path>) -> Option<Value> {
45    let command = entry.get("command")?.as_str()?;
46    let mut line = command.to_string();
47    for arg in entry.get("args").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
48        line.push(' ');
49        line.push_str(arg);
50    }
51    let mut env = entry.get("env").and_then(Value::as_object).cloned().unwrap_or_default();
52    for (name, value) in launch_env {
53        env.entry(name.as_str()).or_insert_with(|| json!(value));
54    }
55    let mut config = json!({ "command": prefix, "args": [line], "env": env });
56    if let Some(cwd) = cwd {
57        config["cwd"] = json!(cwd.to_string_lossy());
58    }
59    Some(config)
60}
61
62/// Test the `agentmux` server of the agent about to launch, once per agent per build, in the
63/// background. Called with the environment the CLI will get; without a shell prefix there is nothing
64/// to test that the server's own start would not show.
65pub fn launch(env: &HashMap<String, String>, block_id: &str, block_meta: &crate::backend::obj::MetaMapType) {
66    // A container agent has the prefix stripped (`agent_env_scope`) and starts its server inside the image.
67    if super::runtime_adapter::RuntimeKind::of_block_meta(block_meta).is_container() {
68        return;
69    }
70    let Some(prefix) = env.get(PREFIX_ENV).filter(|p| !p.is_empty()).cloned() else { return };
71    // Only AgentMux's own wrapper: an agent's own prefix is its script, not run by srv.
72    if !is_bundled(&prefix, crate::backend::tool_store::bashwrap_path().as_deref()) {
73        return;
74    }
75    let agent = env.get("AGENTMUX_AGENT_ID").cloned().unwrap_or_default();
76    let cwd = crate::backend::obj::meta_get_string(block_meta, "cmd:cwd", "");
77    if agent.is_empty() || cwd.is_empty() {
78        return;
79    }
80    let key = format!("{agent}@{}", env!("CARGO_PKG_VERSION"));
81    if !tested().lock().unwrap().insert(key.clone()) {
82        return;
83    }
84    let Ok(runtime) = tokio::runtime::Handle::try_current() else {
85        tested().lock().unwrap().remove(&key);
86        return;
87    };
88    let launch_env: HashMap<String, String> = FORWARDED.iter().filter_map(|k| env.get(*k).map(|v| (k.to_string(), v.clone()))).collect();
89    let (block_id, path) = (block_id.to_string(), mcp_json_path(&cwd));
90    runtime.spawn(async move {
91        let result = run(&path, &prefix, &launch_env).await;
92        match &result {
93            Ok(()) => tracing::info!(block_id = %block_id, "mcp launch self-test: the agentmux server answers through the shell prefix"),
94            Err(e) => {
95                tracing::warn!(block_id = %block_id, "mcp launch self-test failed: {e}");
96                // Not final: the agent's next launch tests it again.
97                tested().lock().unwrap().remove(&key);
98            }
99        }
100        crate::backend::mcp_health::on_selftest(&block_id, result);
101    });
102}
103
104/// Whether `prefix` is the bundled wrapper (`bundled`, when there is one).
105fn is_bundled(prefix: &str, bundled: Option<&Path>) -> bool {
106    bundled.is_some_and(|b| b == Path::new(prefix))
107}
108
109/// The agent's MCP config: `cmd:cwd` may be a default folder stored as `~/.agentmux/agents/<slug>`
110/// (the file is in it), or a user's project (the config is AgentMux's relocated one, #3680). In a folder a
111/// container agent can write it is AgentMux's own file outside the folder, never the folder's.
112fn mcp_json_path(cwd: &str) -> std::path::PathBuf {
113    crate::backend::mcp_config_file::host_config_path(cwd)
114}
115
116/// Probe the `agentmux` entry of the `.mcp.json` at `path` through `prefix`.
117async fn run(path: &Path, prefix: &str, launch_env: &HashMap<String, String>) -> Result<(), String> {
118    let text = tokio::fs::read_to_string(path).await.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
119    let entry = entry_of(&text).ok_or_else(|| ".mcp.json has no agentmux entry".to_string())?;
120    let config = through_prefix(&entry, prefix, launch_env, path.parent()).ok_or_else(|| "the agentmux entry has no command".to_string())?;
121    let probed = crate::backend::mcp_probe::probe("stdio", &config.to_string()).await;
122    match probed.status {
123        crate::backend::mcp_probe::ProbeStatus::Connected => Ok(()),
124        _ => Err(probed.error.unwrap_or_else(|| format!("{:?}", probed.status))),
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn the_entry_is_started_the_way_the_cli_starts_it() {
134        let entry = json!({ "command": "agentmux-mcp", "args": ["--stdio", "x"], "env": { "AGENTMUX_AGENT_ID": "manoz" } });
135        let config = through_prefix(&entry, "/t/agentmux-bashwrap", &HashMap::new(), Some(Path::new("/work/a"))).unwrap();
136        assert_eq!(config["cwd"], "/work/a", "it starts in the agent's workspace");
137        assert_eq!(config["command"], "/t/agentmux-bashwrap");
138        assert_eq!(config["args"], json!(["agentmux-mcp --stdio x"]), "one argument: the command line");
139        assert_eq!(config["env"]["AGENTMUX_AGENT_ID"], "manoz");
140        assert_eq!(through_prefix(&json!({ "command": "agentmux-mcp" }), "p", &HashMap::new(), None).unwrap()["args"], json!(["agentmux-mcp"]));
141        assert!(through_prefix(&json!({ "args": [] }), "p", &HashMap::new(), None).is_none(), "no command, nothing to start");
142    }
143
144    #[test]
145    fn the_server_gets_the_agents_path_unless_its_entry_sets_one() {
146        let bare = json!({ "command": "agentmux-mcp", "env": { "AGENTMUX_AGENT_ID": "manoz" } });
147        let launch = HashMap::from([("PATH".to_string(), "/agent/tools:/usr/bin".to_string()), ("AGENTMUX_BASH".to_string(), "/opt/bash".to_string())]);
148        let config = through_prefix(&bare, "p", &launch, None).unwrap();
149        assert_eq!(config["env"]["AGENTMUX_BASH"], "/opt/bash", "the shell override reaches the wrapper");
150        assert_eq!(config["env"]["PATH"], "/agent/tools:/usr/bin", "the bare command is found where the CLI finds it");
151        assert_eq!(config["env"]["AGENTMUX_AGENT_ID"], "manoz");
152        let own = json!({ "command": "x", "env": { "PATH": "/entry/own" } });
153        assert_eq!(through_prefix(&own, "p", &HashMap::from([("PATH".to_string(), "/agent/tools".to_string())]), None).unwrap()["env"]["PATH"], "/entry/own");
154    }
155
156    #[test]
157    fn a_container_agent_is_not_tested() {
158        let env = HashMap::from([("CLAUDE_CODE_SHELL_PREFIX".to_string(), "/w".to_string()), ("AGENTMUX_AGENT_ID".to_string(), "a-container-agent".to_string())]);
159        let meta: crate::backend::obj::MetaMapType = HashMap::from([("agentMode".to_string(), json!("container")), ("cmd:cwd".to_string(), json!("/work"))]);
160        launch(&env, "b", &meta);
161        assert!(!tested().lock().unwrap().iter().any(|k| k.starts_with("a-container-agent@")), "no test was started for it");
162    }
163
164    #[test]
165    fn only_the_bundled_wrapper_is_tested_not_an_agents_own_prefix() {
166        let wrapper = Path::new("/t/agentmux-bashwrap");
167        assert!(is_bundled("/t/agentmux-bashwrap", Some(wrapper)));
168        assert!(!is_bundled("/home/me/log-commands.sh", Some(wrapper)), "the agent's own script");
169        assert!(!is_bundled("/t/agentmux-bashwrap", None), "no wrapper installed");
170    }
171
172    #[test]
173    fn a_default_workspace_stored_with_a_tilde_is_found() {
174        let path = mcp_json_path("~/.agentmux/agents/x-0930a");
175        assert!(!path.starts_with("~"), "{}", path.display());
176        assert_eq!(path.file_name().unwrap(), ".mcp.json");
177        assert!(path.parent().unwrap().ends_with("x-0930a"), "{}", path.display());
178        // A user's project gets the config outside it, under AgentMux's data root (#3680).
179        let relocated = mcp_json_path("/work/a");
180        assert!(!relocated.starts_with("/work/a"), "{}", relocated.display());
181    }
182
183    #[test]
184    fn only_the_agentmux_entry_is_tested() {
185        let doc = r#"{"mcpServers":{"github":{"command":"gh-mcp"},"agentmux":{"command":"agentmux-mcp"}}}"#;
186        assert_eq!(entry_of(doc).unwrap()["command"], "agentmux-mcp");
187        assert!(entry_of(r#"{"mcpServers":{"github":{"command":"x"}}}"#).is_none());
188        assert!(entry_of("not json").is_none());
189    }
190
191    #[tokio::test]
192    async fn a_file_that_is_missing_or_has_no_entry_is_an_error_not_a_panic() {
193        let dir = std::env::temp_dir().join(format!("agentmux-selftest-{}", uuid::Uuid::new_v4()));
194        std::fs::create_dir_all(&dir).unwrap();
195        let path = dir.join(".mcp.json");
196        assert!(run(&path, "p", &HashMap::new()).await.unwrap_err().contains("cannot read"));
197        std::fs::write(&path, r#"{"mcpServers":{}}"#).unwrap();
198        assert!(run(&path, "p", &HashMap::new()).await.unwrap_err().contains("no agentmux entry"));
199        let _ = std::fs::remove_dir_all(dir);
200    }
201
202    /// The real wrapper as the prefix and a stub server behind it: the handshake goes through, and a
203    /// server that cannot start is an error. Skipped when `agentmux-bashwrap` is not built next to srv.
204    #[tokio::test]
205    async fn a_server_behind_the_real_prefix_answers_and_one_that_cannot_start_does_not() {
206        let exe = if cfg!(windows) { "agentmux-bashwrap.exe" } else { "agentmux-bashwrap" };
207        let wrapper = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/debug").join(exe);
208        let has_node = std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join("node").is_file() || d.join("node.exe").is_file()));
209        if !wrapper.is_file() || !has_node {
210            eprintln!("selftest wrapper test: agentmux-bashwrap or node missing: skipping");
211            return;
212        }
213        let dir = std::env::temp_dir().join(format!("agentmux-selftest-{}", uuid::Uuid::new_v4()));
214        std::fs::create_dir_all(&dir).unwrap();
215        let stub = dir.join("stub.js");
216        std::fs::write(
217            &stub,
218            r#"const rl = require("readline").createInterface({ input: process.stdin });
219rl.on("line", (l) => { let m; try { m = JSON.parse(l); } catch { return; }
220  if (m.method === "initialize") console.log(JSON.stringify({ jsonrpc: "2.0", id: m.id, result: { protocolVersion: "2024-11-05", capabilities: {}, serverInfo: { name: "stub", version: "1" } } }));
221  if (m.method === "tools/list") console.log(JSON.stringify({ jsonrpc: "2.0", id: m.id, result: { tools: [] } })); });"#,
222        )
223        .unwrap();
224        let write = |command: &str| {
225            let doc = json!({ "mcpServers": { "agentmux": { "command": command, "args": [] } } });
226            std::fs::write(dir.join(".mcp.json"), doc.to_string()).unwrap();
227        };
228        let prefix = wrapper.to_string_lossy().to_string();
229        // Relative to the workspace, as an entry can be: it resolves only if the server starts there.
230        write("node stub.js");
231        assert_eq!(run(&dir.join(".mcp.json"), &prefix, &HashMap::new()).await, Ok(()));
232        write("agentmux-mcp-that-does-not-exist-anywhere");
233        assert!(run(&dir.join(".mcp.json"), &prefix, &HashMap::new()).await.is_err());
234        let _ = std::fs::remove_dir_all(dir);
235    }
236
237    /// The launch self-test reads a host agent's config. For a container agent it does not run at all, in a
238    /// marked folder as in any other.
239    #[test]
240    fn a_container_agents_launch_is_not_tested_on_the_host() {
241        let meta: crate::backend::obj::MetaMapType = [("agentMode", json!("container")), ("cmd:cwd", json!("/work/a"))].into_iter().map(|(k, v)| (k.to_string(), v)).collect();
242        let prefix = crate::backend::tool_store::bashwrap_path().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|| "/t/agentmux-bashwrap".to_string());
243        let env = HashMap::from([(PREFIX_ENV.to_string(), prefix), ("AGENTMUX_AGENT_ID".to_string(), "selftest-container-agent".to_string())]);
244        launch(&env, "block-selftest-container", &meta);
245        assert!(!tested().lock().unwrap().iter().any(|key| key.starts_with("selftest-container-agent@")), "it returned before anything was read");
246    }
247}