Skip to main content

agentmux_srv_core/backend/
mcp_health_meta.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agent MCP self-heal's state on the pane's block (`agent:mcp_health`), for the surfaces that
5//! show a row per agent without opening its pane: the Swarm
6//! (`docs/specs/SPEC_AGENT_MCP_SELF_HEAL_2026_10_10.md` ยง4.2). `{ "state": "healing" | "restarting" |
7//! "gave_up", "step", "at" }` while the agent's AgentMux tools are down or being repaired; the key is
8//! removed when they are back. The CLI's error text is not stored here: it is untrusted and the pane
9//! row already shows it.
10
11use std::sync::Arc;
12
13use serde_json::{json, Value};
14
15use crate::backend::eventbus::EventBus;
16use crate::backend::mcp_health::Notice;
17use crate::backend::storage::store::Store;
18
19/// The block meta key.
20pub const META_KEY: &str = "agent:mcp_health";
21
22/// What `notice` puts under [`META_KEY`]: the state while the tools are down, `Null` (the key removed)
23/// once they are back. `at` is when this state began.
24pub fn meta_value(notice: &Notice, now_ms: u64) -> Value {
25    match notice.state {
26        "healing" | "restarting" | "gave_up" => json!({ "state": notice.state, "step": notice.step, "at": now_ms }),
27        _ => Value::Null,
28    }
29}
30
31/// The tools are connected: remove the key if it is set. Called when a process reports the server
32/// connected, which for a process started fresh produces no notice (nothing was being repaired for it),
33/// so a key left by an earlier process, a stopped agent or an srv restart is not left to show.
34pub fn clear(block_id: &str, store: &Arc<Store>, event_bus: &Option<Arc<EventBus>>) {
35    let ok = Notice { episode: String::new(), state: "ok", step: 0, error: None, safe_profile: false };
36    persist(block_id, &ok, store, event_bus);
37}
38
39/// Store `notice`'s state on `block_id` and tell the open windows. Nothing when it would change nothing
40/// (a retry of the same state, or `ok` with no key to remove).
41pub fn persist(block_id: &str, notice: &Notice, store: &Arc<Store>, event_bus: &Option<Arc<EventBus>>) {
42    let current = store
43        .must_get::<crate::backend::obj::Block>(block_id)
44        .ok()
45        .and_then(|b| b.meta.get(META_KEY).cloned())
46        .filter(|v| !v.is_null());
47    let mut next = meta_value(notice, agentmux_common::time::now_ms_u64());
48    match (&current, &next) {
49        (None, Value::Null) => return,
50        // The same state again keeps when it began.
51        (Some(old), Value::Object(new)) if old.get("state") == new.get("state") && old.get("step") == new.get("step") => return,
52        (Some(old), Value::Object(new)) if old.get("state") == new.get("state") => {
53            if let (Some(at), Some(obj)) = (old.get("at"), next.as_object_mut()) {
54                obj.insert("at".to_string(), at.clone());
55            }
56        }
57        _ => {}
58    }
59    let mut update = crate::backend::obj::MetaMapType::new();
60    update.insert(META_KEY.to_string(), next);
61    // One transaction for the read, the merge and the write, as every meta writer does, so a
62    // concurrent writer of another key is not reverted.
63    let written = store.with_tx(|tx| {
64        let mut block = tx.must_get::<crate::backend::obj::Block>(block_id)?;
65        block.meta = crate::backend::obj::merge_meta(&block.meta, &update, true);
66        tx.update(&mut block)
67    });
68    match written {
69        Ok(_) => {
70            if let Some(bus) = event_bus {
71                crate::backend::blockcontroller::core::broadcast_block_update(store, bus, block_id);
72            }
73        }
74        Err(e) => tracing::warn!(block_id = %block_id, error = %e, "could not store agent:mcp_health"),
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    fn notice(state: &'static str, step: u8) -> Notice {
83        Notice { episode: "e".into(), state, step, error: Some("boom".into()), safe_profile: false }
84    }
85
86    #[test]
87    fn the_tools_being_down_is_stored_without_the_error_and_being_back_removes_it() {
88        assert_eq!(meta_value(&notice("healing", 3), 7), json!({ "state": "healing", "step": 3, "at": 7 }));
89        assert_eq!(meta_value(&notice("restarting", 0), 7)["state"], "restarting");
90        assert_eq!(meta_value(&notice("gave_up", 0), 7)["state"], "gave_up");
91        assert_eq!(meta_value(&notice("ok", 0), 7), Value::Null);
92    }
93
94    #[test]
95    fn a_state_is_stored_once_keeps_when_it_began_and_is_removed_when_the_tools_are_back() {
96        let store = Arc::new(Store::open_in_memory().unwrap());
97        let mut block = crate::backend::obj::Block {
98            oid: "77777777-7777-7777-7777-777777777777".into(),
99            parentoref: String::new(),
100            version: 1,
101            runtimeopts: None,
102            stickers: None,
103            meta: crate::backend::obj::MetaMapType::new(),
104            subblockids: None,
105        };
106        store.insert(&mut block).unwrap();
107        let read = || store.must_get::<crate::backend::obj::Block>("77777777-7777-7777-7777-777777777777").unwrap().meta.get(META_KEY).cloned();
108
109        persist("77777777-7777-7777-7777-777777777777", &notice("healing", 1), &store, &None);
110        let first = read().unwrap();
111        assert_eq!(first["state"], "healing");
112        persist("77777777-7777-7777-7777-777777777777", &notice("healing", 2), &store, &None);
113        let second = read().unwrap();
114        assert_eq!(second["step"], 2);
115        assert_eq!(second["at"], first["at"], "still the same episode state: it began when it first did");
116        persist("77777777-7777-7777-7777-777777777777", &notice("gave_up", 0), &store, &None);
117        assert_eq!(read().unwrap()["state"], "gave_up");
118
119        persist("77777777-7777-7777-7777-777777777777", &notice("ok", 0), &store, &None);
120        assert!(read().is_none_or(|v| v.is_null()), "the tools are back: nothing to show");
121        persist("77777777-7777-7777-7777-777777777777", &notice("ok", 0), &store, &None);
122
123        // A key left behind by an earlier process goes when a new one reports the tools connected.
124        persist("77777777-7777-7777-7777-777777777777", &notice("gave_up", 0), &store, &None);
125        assert!(read().is_some());
126        clear("77777777-7777-7777-7777-777777777777", &store, &None);
127        assert!(read().is_none_or(|v| v.is_null()));
128        clear("77777777-7777-7777-7777-777777777777", &store, &None);
129    }
130}