1use std::io::{BufRead, BufReader, Write};
14use std::path::{Path, PathBuf};
15use std::process::{Command, Stdio};
16use std::time::Duration;
17
18use serde_json::{json, Value};
19
20const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
21const INITIALIZE: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"agentmux-mcp-doctor","version":"0"}}}"#;
22
23#[derive(Default)]
24struct Report {
25 lines: Vec<(&'static str, String)>,
26}
27
28impl Report {
29 fn ok(&mut self, text: impl Into<String>) {
30 self.lines.push(("ok ", text.into()));
31 }
32 fn fail(&mut self, text: impl Into<String>) {
33 self.lines.push(("FAIL", text.into()));
34 }
35 fn info(&mut self, text: impl Into<String>) {
36 self.lines.push(("info", text.into()));
37 }
38 fn failed(&self) -> bool {
39 self.lines.iter().any(|(k, _)| *k == "FAIL")
40 }
41}
42
43pub async fn run(args: Vec<String>) -> i32 {
46 let heal = args.iter().any(|a| a == "--heal");
47 let mut report = Report::default();
48 let workdir = std::env::var("AGENTMUX_AGENT_WORKDIR")
49 .ok()
50 .filter(|w| !w.is_empty())
51 .map(PathBuf::from)
52 .or_else(|| std::env::current_dir().ok())
53 .unwrap_or_default();
54
55 report.ok(format!(
56 "agentmux-mcp {} ({})",
57 env!("CARGO_PKG_VERSION"),
58 std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default()
59 ));
60 let config = config_path(&workdir);
63 let config_folder = config.parent().map(|dir| dir.to_string_lossy().into_owned()).unwrap_or_default();
64 let srv = Srv::from_env();
65 let health = match &srv {
66 Some(srv) => Some(srv.post("/api/v1/agent/self/mcp-health", Some(&config_folder)).await),
67 None => None,
68 };
69 let rule = match &health {
70 Some(Ok((200, body))) => body.get("folder_rule").and_then(Value::as_bool),
71 _ => None,
72 };
73 let entry = check_config(&mut report, &config);
74 let may_start = may_start_entry(&config, in_container(), rule);
75 let entry = match &may_start {
76 Ok(()) => entry,
77 Err(why) => {
78 if entry.is_some() {
79 report.fail(why.clone());
80 }
81 None
82 }
83 };
84 check_handshakes(&mut report, entry.as_ref(), &config, may_start.is_ok());
85 match (&srv, health) {
86 (Some(srv), Some(answer)) => report_srv(&mut report, srv, answer),
87 _ => report.fail("AGENTMUX_LOCAL_URL, AGENTMUX_AUTH_KEY, AGENTMUX_AGENT_TOKEN or AGENTMUX_AGENT_SLUG is not set: run this from the agent's own shell"),
88 }
89 check_cli_log(&mut report, &workdir);
90 if heal {
91 match &srv {
92 Some(srv) => request_heal(&mut report, srv).await,
93 None => report.fail("--heal needs srv (see above)"),
94 }
95 }
96
97 for (kind, text) in &report.lines {
98 println!("{kind} {text}");
99 }
100 if !heal && report.failed() {
101 println!("\nRun `agentmux-mcp doctor --heal` to ask AgentMux to repair it, and tell the operator.");
102 }
103 i32::from(report.failed())
104}
105
106struct Entry {
108 command: String,
109 args: Vec<String>,
110}
111
112fn config_path(workdir: &Path) -> PathBuf {
115 let configured = std::env::var_os("AGENTMUX_MCP_CONFIG")
118 .map(PathBuf::from)
119 .filter(|p| !p.as_os_str().is_empty());
120 resolve_config_path(workdir, configured.as_deref(), in_container())
121}
122
123fn in_container() -> bool {
127 is_in_container(crate::self_keys::in_container(), cfg!(target_os = "linux"), || {
128 Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists()
129 })
130}
131
132fn is_in_container(hint: bool, linux: bool, runtime_marker: impl FnOnce() -> bool) -> bool {
133 hint && linux && runtime_marker()
134}
135
136fn resolve_config_path(workdir: &Path, configured: Option<&Path>, in_container: bool) -> PathBuf {
138 if let Some(configured) = configured {
139 return configured.to_path_buf();
140 }
141 if in_container {
142 let mounted = agentmux_common::mcp_config_path::container_config_path();
143 if mounted.is_file() {
144 return mounted;
145 }
146 }
147 let expanded = agentmux_common::mcp_config_path::expand_home(workdir);
148 agentmux_common::mcp_config_path::config_path_for(&expanded)
149}
150
151fn may_start_entry(config: &Path, in_container: bool, rule: Option<bool>) -> Result<(), String> {
157 if in_container {
158 return Ok(());
159 }
160 let folder = config.parent().unwrap_or(config).display();
161 match rule {
162 Some(false) => Ok(()),
163 Some(true) => Err(format!(
164 "a container agent can write in {folder} (or has run in it), so no command from {} is started on this computer: run doctor inside the container, or from a host agent's own pane",
165 config.display()
166 )),
167 None => Err(format!(
168 "AgentMux did not say whether a container agent can write in {folder}, so no command from {} is started: run doctor from the agent's own pane",
169 config.display()
170 )),
171 }
172}
173
174fn check_config(report: &mut Report, path: &Path) -> Option<Entry> {
175 let parsed = match std::fs::read_to_string(&path).map(|t| serde_json::from_str::<Value>(&t)) {
176 Ok(Ok(v)) => v,
177 Ok(Err(e)) => {
178 report.fail(format!("{} is not valid JSON: {e}", path.display()));
179 return None;
180 }
181 Err(e) => {
182 report.fail(format!("can't read {}: {e}", path.display()));
183 return None;
184 }
185 };
186 let Some(server) = parsed.pointer("/mcpServers/agentmux") else {
187 report.fail(format!("{} has no mcpServers.agentmux entry", path.display()));
188 return None;
189 };
190 let command = server.get("command").and_then(Value::as_str).unwrap_or_default().to_string();
191 if command.is_empty() {
192 report.fail(format!("the agentmux entry in {} has no command", path.display()));
193 return None;
194 }
195 let args: Vec<String> = server
196 .get("args")
197 .and_then(Value::as_array)
198 .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())
199 .unwrap_or_default();
200 let has_value = |k: &str| server.pointer(&format!("/env/{k}")).and_then(Value::as_str).is_some_and(|v| !v.is_empty());
203 if has_value("AGENTMUX_JEKT_KEY") || has_value("AGENTMUX_LAN_KEY") {
204 report.ok(format!("{} has the agentmux entry ({command}); it still holds a signing value an older version wrote, replaced when the agent next starts", path.display()));
205 } else {
206 report.ok(format!("{} has the agentmux entry ({command}); its signing keys come from srv", path.display()));
207 }
208 Some(Entry { command, args })
209}
210
211fn check_handshakes(report: &mut Report, entry: Option<&Entry>, config: &Path, from_the_environment: bool) {
218 let (command, args) = match entry {
219 Some(e) => (e.command.clone(), e.args.clone()),
220 None => match std::env::current_exe() {
221 Ok(own) => (own.to_string_lossy().into_owned(), Vec::new()),
222 Err(e) => {
223 report.fail(format!("can't tell where this agentmux-mcp is, so it is not started: {e}"));
224 return;
225 }
226 },
227 };
228 if entry.is_some() {
230 let line = std::iter::once(command.as_str()).chain(args.iter().map(String::as_str)).collect::<Vec<_>>().join(" ");
231 println!("info about to start `{line}`, the agentmux entry of {}", config.display());
232 let _ = std::io::stdout().flush();
233 }
234 match handshake(Command::new(&command).args(&args)) {
235 Ok(version) => report.ok(format!("`{command}` starts and answers MCP (server {version})")),
236 Err(e) => report.fail(format!("`{command}` doesn't answer MCP: {e}")),
237 }
238 if !from_the_environment {
239 report.info("the shell prefix is not started here either");
240 return;
241 }
242 let Some(prefix) = std::env::var("CLAUDE_CODE_SHELL_PREFIX").ok().filter(|p| !p.is_empty()) else {
243 report.info("no CLAUDE_CODE_SHELL_PREFIX: the CLI starts the server directly");
244 return;
245 };
246 let joined = prefix_line(&command, &args);
248 let name = Path::new(&prefix).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or(prefix.clone());
249 match handshake(Command::new(&prefix).arg(&joined)) {
250 Ok(_) => report.ok(format!("it starts through the shell prefix ({name}), as the CLI starts it")),
251 Err(e) => report.fail(format!(
252 "it does NOT start through the shell prefix ({name}), which is how the CLI starts it: {e}"
253 )),
254 }
255}
256
257fn prefix_line(command: &str, args: &[String]) -> String {
260 let word = |w: &str| {
261 if w.is_empty() || w.contains(['\\', ' ', '\'', '"']) {
262 format!("'{}'", w.replace('\'', "'\\''"))
263 } else {
264 w.to_string()
265 }
266 };
267 std::iter::once(command).chain(args.iter().map(String::as_str)).map(word).collect::<Vec<_>>().join(" ")
268}
269
270fn handshake(cmd: &mut Command) -> Result<String, String> {
272 cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
273 #[cfg(windows)]
274 {
275 use agentmux_common::win32::NoWindow;
276 cmd.no_window();
277 }
278 let mut child = cmd.spawn().map_err(|e| format!("can't start it: {e}"))?;
279 let mut stdin = child.stdin.take().ok_or("no stdin")?;
280 let stdout = child.stdout.take().ok_or("no stdout")?;
281 let stderr = child.stderr.take().ok_or("no stderr")?;
282 let _ = writeln!(stdin, "{INITIALIZE}");
283 let (tx, rx) = std::sync::mpsc::channel();
284 std::thread::spawn(move || {
285 let mut line = String::new();
286 let _ = BufReader::new(stdout).read_line(&mut line);
287 let _ = tx.send(line);
288 });
289 let answer = rx.recv_timeout(HANDSHAKE_TIMEOUT);
290 drop(stdin);
291 let _ = child.kill();
292 let _ = child.wait();
293 let first_stderr_line = || {
294 let mut text = String::new();
295 let _ = BufReader::new(stderr).read_line(&mut text);
296 text.trim().to_string()
297 };
298 match answer {
299 Ok(line) if !line.trim().is_empty() => match serde_json::from_str::<Value>(&line) {
300 Ok(v) => v
301 .pointer("/result/serverInfo/version")
302 .and_then(Value::as_str)
303 .map(str::to_string)
304 .ok_or_else(|| format!("unexpected answer: {}", line.trim())),
305 Err(_) => Err(format!("not JSON-RPC on stdout: {}", line.trim())),
306 },
307 Ok(_) => {
308 let err = first_stderr_line();
309 Err(if err.is_empty() { "it exited without answering".to_string() } else { format!("it exited: {err}") })
310 }
311 Err(_) => Err(format!("no answer in {} s", HANDSHAKE_TIMEOUT.as_secs())),
312 }
313}
314
315struct Srv {
316 client: reqwest::Client,
317 url: String,
318 auth_key: String,
319 token: String,
320 slug: String,
321}
322
323impl Srv {
324 fn from_env() -> Option<Self> {
325 let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
326 Some(Self {
327 client: agentmux_common::local_http::builder().timeout(Duration::from_secs(10)).build().ok()?,
328 url: var("AGENTMUX_LOCAL_URL")?,
329 auth_key: var("AGENTMUX_AUTH_KEY")?,
330 token: var("AGENTMUX_AGENT_TOKEN")?,
331 slug: var("AGENTMUX_AGENT_SLUG")?,
332 })
333 }
334
335 async fn post(&self, path: &str, folder: Option<&str>) -> Result<(u16, Value), String> {
337 let mut body = json!({ "agent": self.slug });
338 if let Some(folder) = folder {
339 body["folder"] = json!(folder);
340 }
341 let resp = self
342 .client
343 .post(format!("{}{path}", self.url.trim_end_matches('/')))
344 .header(agentmux_common::AUTH_KEY_HEADER, &self.auth_key)
345 .header("X-Agent-Token", self.token.trim())
346 .json(&body)
347 .send()
348 .await
349 .map_err(|e| e.to_string())?;
350 let status = resp.status().as_u16();
351 Ok((status, resp.json().await.unwrap_or(Value::Null)))
352 }
353}
354
355fn report_srv(report: &mut Report, srv: &Srv, answer: Result<(u16, Value), String>) {
356 match answer {
357 Ok((200, body)) => {
358 report.ok(format!("AgentMux (srv) answers at {}", srv.url));
359 report.info(srv_health_line(&body));
360 }
361 Ok((404, _)) => report.info("this AgentMux is older than this doctor: it can't say what it saw, or repair"),
362 Ok((code, body)) => report.fail(format!("srv refused ({code}): {}", body.get("error").and_then(Value::as_str).unwrap_or(""))),
363 Err(e) => report.fail(format!("can't reach srv at {}: {e}", srv.url)),
364 }
365}
366
367fn srv_health_line(body: &Value) -> String {
369 let auto = if body.get("auto").and_then(Value::as_bool) == Some(false) { " (automatic repair is off)" } else { "" };
370 let Some(h) = body.get("health").filter(|h| !h.is_null()) else {
371 return format!("srv hasn't seen this agent's MCP status yet{auto}");
372 };
373 let get = |k: &str| h.get(k).and_then(Value::as_str).unwrap_or("?");
374 let mut line = format!("srv saw the server {}; repair: {}", get("status"), get("phase"));
375 if h.get("safe_profile").and_then(Value::as_bool) == Some(true) {
376 line.push_str("; running in the safe profile (no shell prefix)");
377 }
378 if let Some(e) = h.get("last_error").and_then(Value::as_str) {
379 line.push_str(&format!("; last error: {e}"));
380 }
381 match h.get("rung").and_then(Value::as_u64) {
382 Some(3) => line.push_str("; repair rewrote the agentmux entry of .mcp.json"),
383 Some(4) => line.push_str("; repair rewrote the agentmux entry of .mcp.json, then with the absolute path of agentmux-mcp"),
384 _ => {}
385 }
386 line.push_str(match (h.get("status").and_then(Value::as_str), h.get("hello_ms").and_then(Value::as_u64)) {
387 (_, Some(_)) => "; the server has contacted AgentMux",
388 (Some("failed"), None) => "; the server has never contacted AgentMux, so the process did not run",
389 (Some("connected"), None) => "; the server has not contacted AgentMux (the CLI started it; it may not reach AgentMux, or it predates the heartbeat)",
390 _ => "",
391 });
392 match h.get("selftest").and_then(Value::as_str) {
393 Some("ok") => line.push_str("; the launch self-test started it through the shell prefix and it answered"),
394 Some(failed) => line.push_str(&format!("; the launch self-test failed: {failed}")),
395 None => {}
396 }
397 line + auto
398}
399
400async fn request_heal(report: &mut Report, srv: &Srv) {
401 match srv.post("/api/v1/agent/self/mcp-heal", None).await {
402 Ok((202, _)) => report.ok("repair started: AgentMux is reconnecting the server; the pane shows how it goes"),
403 Ok((404, _)) => report.fail("this AgentMux is older than this doctor and can't repair: ask the operator to restart the agent"),
404 Ok((200, body)) => {
405 let status = body.get("status").and_then(Value::as_str).unwrap_or("?");
406 report.info(match status {
407 "connected" => "nothing to repair: srv saw the server connected".to_string(),
408 "already_healing" => "a repair is already under way".to_string(),
409 "no_status_yet" => "srv hasn't seen the server's status yet; try again once the agent has started".to_string(),
410 "no_process" => "the agent's CLI isn't running".to_string(),
411 other => format!("srv: {other}"),
412 });
413 }
414 Ok((code, body)) => report.fail(format!("srv refused the repair ({code}): {}", body.get("error").and_then(Value::as_str).unwrap_or(""))),
415 Err(e) => report.fail(format!("can't reach srv: {e}")),
416 }
417}
418
419fn project_key(dir: &Path) -> String {
422 dir.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
423}
424
425fn cli_cache_dir() -> Option<PathBuf> {
429 let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
430 if cfg!(windows) {
431 Some(var("LOCALAPPDATA")?.join("claude-cli-nodejs").join("Cache"))
432 } else if cfg!(target_os = "macos") {
433 Some(var("HOME")?.join("Library").join("Caches").join("claude-cli-nodejs"))
434 } else {
435 let base = var("XDG_CACHE_HOME").or_else(|| var("HOME").map(|h| h.join(".cache")))?;
436 Some(base.join("claude-cli-nodejs"))
437 }
438}
439
440fn check_cli_log(report: &mut Report, workdir: &Path) {
441 let Some(dir) = cli_cache_dir().map(|c| c.join(project_key(workdir)).join("mcp-logs-agentmux")) else {
442 return;
443 };
444 let newest = std::fs::read_dir(&dir).ok().and_then(|entries| {
445 entries
446 .flatten()
447 .filter(|e| e.path().extension().is_some_and(|x| x == "jsonl"))
448 .max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())
449 });
450 let Some(file) = newest else {
451 report.info(format!("no Claude Code MCP log for the server in {}", dir.display()));
452 return;
453 };
454 let text = std::fs::read_to_string(file.path()).unwrap_or_default();
455 let name = file.file_name().to_string_lossy().into_owned();
456 report.info(format!("Claude Code's latest log for the server ({name}): {}", log_outcome(&text)));
457}
458
459fn log_outcome(text: &str) -> String {
462 let flat = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
463 let mut outcome = "no connection attempt recorded".to_string();
464 let mut stderr: Option<String> = None;
465 for line in text.lines() {
466 let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
467 let debug = v.get("debug").and_then(Value::as_str).unwrap_or_default();
468 if debug.starts_with("Starting connection") {
469 stderr = None;
470 } else if debug.starts_with("Successfully connected") {
471 outcome = "connected".to_string();
472 } else if let Some(e) = v.get("error").and_then(Value::as_str) {
473 match e.strip_prefix("Server stderr:") {
474 Some(rest) => stderr = Some(flat(rest)),
475 None => {
476 outcome = match &stderr {
477 Some(s) => format!("error: {} (server stderr: {s})", flat(e)),
478 None => format!("error: {}", flat(e)),
479 }
480 }
481 }
482 }
483 }
484 outcome
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490
491 #[test]
492 fn the_prefix_is_handed_the_line_as_the_cli_joins_it() {
493 let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
494 assert_eq!(prefix_line("agentmux-mcp", &args(&["serve", "--stdio"])), "agentmux-mcp serve --stdio", "a bare name is as it was");
495 assert_eq!(prefix_line(r"C:\Users\a\agentmux-mcp.exe", &[]), r"'C:\Users\a\agentmux-mcp.exe'", "a Windows path is quoted");
496 assert_eq!(
497 prefix_line(r"C:\Users\a\agentmux-mcp.exe", &args(&["--config", r"C:\x\mcp.json", "serve"])),
498 r"'C:\Users\a\agentmux-mcp.exe' --config 'C:\x\mcp.json' serve",
499 "with arguments, each unsafe word is quoted and the rest are not"
500 );
501 assert_eq!(prefix_line("/opt/my tools/mcp", &args(&["a"])), "'/opt/my tools/mcp' a", "a space is quoted");
502 assert_eq!(prefix_line("mcp", &args(&["it's"])), r"mcp 'it'\''s'", "a quote inside is closed, escaped and opened");
503 assert_eq!(prefix_line("mcp", &args(&[""])), "mcp ''", "an empty word is kept");
504 }
505
506 #[test]
509 fn the_config_checked_follows_the_agent_where_its_config_lives() {
510 let project = Path::new("/agentmux-test-project");
513 let path = resolve_config_path(project, None, false);
514 assert!(!path.starts_with(project), "the project file is not the agent's: {}", path.display());
515 assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("mcp.json"));
516
517 let owned = dirs_home().join(".agentmux").join("agents").join("aria");
518 assert_eq!(resolve_config_path(&owned, None, false), owned.join(".mcp.json"));
519 }
520
521 fn dirs_home() -> PathBuf {
522 std::env::var_os("USERPROFILE")
523 .or_else(|| std::env::var_os("HOME"))
524 .map(PathBuf::from)
525 .unwrap_or_default()
526 }
527
528 #[test]
531 fn the_config_is_the_path_srv_resolved_when_it_is_given() {
532 let dir = tempfile::tempdir().unwrap();
533 let configured = dir.path().join("mcp.json");
534 assert_eq!(resolve_config_path(Path::new("/agentmux-test-project"), Some(&configured), false), configured);
535 let fallback = resolve_config_path(Path::new("/agentmux-test-project"), None, false);
536 assert!(!fallback.starts_with("/agentmux-test-project"), "{}", fallback.display());
537 }
538
539 #[test]
540 fn the_project_key_is_claude_codes_folder_name() {
541 assert_eq!(
542 project_key(Path::new(r"C:\Users\u\.agentmux\agents\agenty-0629j")),
543 "C--Users-u--agentmux-agents-agenty-0629j"
544 );
545 assert_eq!(project_key(Path::new("/home/u/work")), "-home-u-work");
546 }
547
548 #[test]
549 fn the_log_outcome_is_the_last_thing_that_happened() {
550 let failed = r#"{"debug":"Starting connection with timeout of 30000ms"}
551{"error":"Server stderr: error: unrecognized subcommand 'agentmux-mcp'\n\nUsage: agentmux-bashwrap.exe <COMMAND>\n"}
552{"error":"Connection failed (CONNECTION_CLOSED): Connection closed"}"#;
553 assert_eq!(
554 log_outcome(failed),
555 "error: Connection failed (CONNECTION_CLOSED): Connection closed (server stderr: error: unrecognized \
556 subcommand 'agentmux-mcp' Usage: agentmux-bashwrap.exe <COMMAND>)"
557 );
558 let ok = r#"{"debug":"Starting connection with timeout of 30000ms"}
559{"debug":"Successfully connected (transport: stdio) in 39ms"}"#;
560 assert_eq!(log_outcome(ok), "connected");
561 assert_eq!(log_outcome(""), "no connection attempt recorded");
562 }
563
564 #[test]
565 fn the_srv_line_says_what_srv_saw() {
566 assert_eq!(srv_health_line(&json!({ "health": null, "auto": true })), "srv hasn't seen this agent's MCP status yet");
567 let body = json!({ "auto": false, "health": {
568 "status": "failed", "phase": "gave_up", "safe_profile": true, "last_error": "Connection closed" } });
569 assert_eq!(
570 srv_health_line(&body),
571 "srv saw the server failed; repair: gave_up; running in the safe profile (no shell prefix); \
572 last error: Connection closed; the server has never contacted AgentMux, so the process did not run \
573 (automatic repair is off)"
574 );
575 let heard = json!({ "health": { "status": "connected", "phase": "ok", "hello_ms": 5 } });
576 assert_eq!(srv_health_line(&heard), "srv saw the server connected; repair: ok; the server has contacted AgentMux");
577 let tested = json!({ "health": { "status": "failed", "phase": "ok", "selftest": "no response within 10s" } });
578 assert!(srv_health_line(&tested).ends_with("; the launch self-test failed: no response within 10s"));
579 let passed = json!({ "health": { "status": "connected", "phase": "ok", "hello_ms": 5, "selftest": "ok" } });
580 assert!(srv_health_line(&passed).contains("the launch self-test started it through the shell prefix and it answered"));
581 let rewrote = json!({ "health": { "status": "failed", "phase": "healing", "rung": 4, "hello_ms": 5 } });
582 assert!(srv_health_line(&rewrote).contains("rewrote the agentmux entry of .mcp.json, then with the absolute path"));
583 let silent = json!({ "health": { "status": "connected", "phase": "ok" } });
584 assert!(srv_health_line(&silent).contains("has not contacted AgentMux"));
585 }
586
587 #[test]
588 fn a_failed_check_fails_the_run() {
589 let mut r = Report::default();
590 r.ok("a");
591 r.info("b");
592 assert!(!r.failed());
593 r.fail("c");
594 assert!(r.failed());
595 }
596
597 #[test]
598 fn a_command_from_a_file_is_started_only_when_srv_says_no_container_agent_can_write_its_folder() {
599 let (folder, data) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
600 for config in [folder.path().join(".mcp.json"), data.path().join("mcp").join("abc").join("mcp.json")] {
602 assert_eq!(may_start_entry(&config, false, Some(false)), Ok(()), "srv said no container agent can");
603 let refused = may_start_entry(&config, false, Some(true)).unwrap_err();
604 assert!(refused.contains("a container agent can write in") && refused.contains("no command from") && refused.contains("is started on this computer"), "{refused}");
605 let untold = may_start_entry(&config, false, None).unwrap_err();
606 assert!(untold.contains("did not say") && untold.contains("no command from"), "{untold}");
607 assert_eq!(may_start_entry(&config, true, Some(true)), Ok(()), "inside the container nothing runs on the host");
608 }
609 }
610
611 #[test]
613 fn only_a_linux_system_with_the_runtimes_marker_is_a_container() {
614 assert!(is_in_container(true, true, || true));
615 assert!(!is_in_container(true, true, || false), "the hint with no marker of the runtime");
616 assert!(!is_in_container(true, false, || true), "the hint on a system that is not Linux");
617 assert!(!is_in_container(false, true, || true), "no hint: srv did not start it as a container agent's");
618 #[cfg(not(target_os = "linux"))]
619 {
620 std::env::set_var("AGENTMUX_IN_CONTAINER", "1");
621 let said = in_container();
622 std::env::remove_var("AGENTMUX_IN_CONTAINER");
623 assert!(!said, "set in the environment on this computer, and still not a container");
624 }
625 }
626
627 #[test]
630 fn with_no_entry_to_start_doctor_names_its_own_executable_by_path() {
631 let folder = tempfile::tempdir().unwrap();
632 let planted = folder.path().join(if cfg!(windows) { "agentmux-mcp.exe" } else { "agentmux-mcp" });
633 std::fs::write(&planted, b"not the real one").unwrap();
634 let mut report = Report::default();
635 check_handshakes(&mut report, None, &folder.path().join(".mcp.json"), false);
636 let own = std::env::current_exe().unwrap();
637 let lines: Vec<&String> = report.lines.iter().map(|(_, text)| text).collect();
638 assert!(lines.iter().any(|text| text.contains(&*own.to_string_lossy())), "{lines:?}");
639 assert!(!lines.iter().any(|text| text.contains(&*planted.to_string_lossy())), "{lines:?}");
640 assert!(lines.iter().any(|text| text.contains("shell prefix is not started")), "{lines:?}");
641 }
642}