Skip to main content

agentmux_srv/server/app_api/
mcp_health.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agentmux-mcp doctor`'s two calls (docs/specs/SPEC_AGENT_MCP_SELF_HEAL_2026_10_10.md
5//! ยง7): what srv knows about the caller's own `agentmux` MCP server, and
6//! "repair it now".
7//!
8//! `doctor` runs in the agent's shell, which has no MCP signing key (only the
9//! MCP process does), so the caller's pane comes from its agent token
10//! (`actor::own_pane_by_token`). There is no target: an agent can only look
11//! at, and heal, its own pane.
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::server::caller::Caller;
21use crate::server::state::AppState;
22
23#[derive(Debug, Deserialize)]
24pub(crate) struct SelfRequest {
25    /// The caller's slug (`AGENTMUX_AGENT_SLUG`), which its token must name.
26    agent: String,
27    /// The folder `doctor` asks about, the one its config file is in: whether it may start a command read
28    /// from a file there (`folder_rule` in the answer). Absent: the pane's own folder.
29    #[serde(default)]
30    folder: Option<String>,
31}
32
33/// Whether a host agent in `folder` (else the folder of the pane `block_id`) gets only the MCP servers
34/// AgentMux writes: a container agent can write it, or has run in it (`backend::mcp_folder_rule`). Yes when
35/// that can't be told, and when there is no folder to ask about.
36async fn folder_rule(state: &AppState, block_id: &str, folder: Option<String>) -> bool {
37    let folder = folder.filter(|f| !f.trim().is_empty()).or_else(|| {
38        let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten()?;
39        Some(crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "")).filter(|cwd| !cwd.trim().is_empty())
40    });
41    rule_for(folder).await
42}
43
44/// [`folder_rule`] for the folder that was found, if one was.
45async fn rule_for(folder: Option<String>) -> bool {
46    let Some(folder) = folder else { return true };
47    tokio::task::spawn_blocking(move || crate::backend::mcp_folder_rule::holds_in(&folder)).await.unwrap_or(true)
48}
49
50fn own_pane(state: &AppState, caller: Option<&Caller>, agent: &str) -> Option<String> {
51    crate::server::actor::own_pane_by_token(&state.mstore, caller, agent.trim())
52}
53
54fn no_pane() -> Response {
55    let error = "no pane for this agent token: run this from the agent's own shell \
56                 (it needs AGENTMUX_AGENT_TOKEN and AGENTMUX_AGENT_SLUG)";
57    (StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))).into_response()
58}
59
60/// `POST /api/v1/agent/self/mcp-health`
61pub(crate) async fn handle_mcp_health(
62    State(state): State<AppState>,
63    caller: Option<Extension<Caller>>,
64    Json(req): Json<SelfRequest>,
65) -> Response {
66    let Some(block_id) = own_pane(&state, caller.as_deref(), &req.agent) else {
67        return no_pane();
68    };
69    let health = crate::backend::mcp_health::snapshot(&block_id);
70    Json(json!({
71        "block_id": block_id,
72        "folder_rule": folder_rule(&state, &block_id, req.folder.clone()).await,
73        "health": health,
74        "safe_profile": crate::backend::mcp_health::is_safe_profile(&block_id),
75        "auto": crate::backend::mcp_health::auto_enabled(),
76    }))
77    .into_response()
78}
79
80/// `POST /api/v1/agent/self/mcp-heal`: 202 `healing` when a repair started,
81/// else 200 with why not (`connected`, `already_healing`, `no_status_yet`,
82/// `no_process`).
83pub(crate) async fn handle_mcp_heal(
84    State(state): State<AppState>,
85    caller: Option<Extension<Caller>>,
86    Json(req): Json<SelfRequest>,
87) -> Response {
88    use crate::backend::blockcontroller::persistent::PersistentSubprocessController;
89    let Some(block_id) = own_pane(&state, caller.as_deref(), &req.agent) else {
90        return no_pane();
91    };
92    let Some(ctrl) = crate::backend::blockcontroller::get_controller(&block_id) else {
93        return Json(json!({ "status": "no_process" })).into_response();
94    };
95    let Some(ctrl) = ctrl.as_any().downcast_ref::<PersistentSubprocessController>() else {
96        return Json(json!({ "status": "no_process" })).into_response();
97    };
98    let outcome = ctrl.mcp_heal_now();
99    tracing::info!(block_id = %block_id, agent = %req.agent, outcome = ?outcome, "agentmux-mcp doctor --heal");
100    match outcome {
101        Ok(()) => (StatusCode::ACCEPTED, Json(json!({ "status": "healing" }))).into_response(),
102        Err(why) => Json(json!({ "status": why })).into_response(),
103    }
104}
105
106#[derive(Debug, Deserialize)]
107pub(crate) struct BeatRequest {
108    agent: String,
109    #[serde(flatten)]
110    beat: crate::backend::mcp_health::Beat,
111}
112
113/// `POST /api/v1/agent/self/mcp-beat`: the MCP process says it is alive and
114/// how it is doing (`agentmux-mcp`'s heartbeat.rs). 204 always for a known
115/// pane: a beat is never worth an error in the MCP process.
116pub(crate) async fn handle_mcp_beat(
117    State(state): State<AppState>,
118    caller: Option<Extension<Caller>>,
119    Json(req): Json<BeatRequest>,
120) -> Response {
121    use crate::backend::blockcontroller::persistent::PersistentSubprocessController;
122    let Some(block_id) = own_pane(&state, caller.as_deref(), &req.agent) else {
123        return no_pane();
124    };
125    if let Some(ctrl) = crate::backend::blockcontroller::get_controller(&block_id) {
126        if let Some(ctrl) = ctrl
127            .as_any()
128            .downcast_ref::<PersistentSubprocessController>()
129        {
130            ctrl.mcp_beat(&req.beat);
131        }
132    }
133    StatusCode::NO_CONTENT.into_response()
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    /// `doctor` starts a command from a file only on a plain no, so no folder to ask about is a yes.
141    #[tokio::test]
142    async fn the_rule_holds_when_there_is_no_folder_to_ask_about() {
143        assert!(rule_for(None).await);
144    }
145}