Skip to main content

agentmux_mcp/
heartbeat.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The heartbeat to srv: every few seconds this process says it is alive, how
5//! old its oldest unanswered call is, and how far behind its async runtime
6//! runs. srv's self-heal (`backend::mcp_health`, #2614) restarts the server
7//! when the beats stop, or the runtime has stopped turning, or a call has
8//! outlived every deadline.
9//!
10//! It runs on a thread of its own, with a runtime of its own: a process
11//! whose main runtime is starved or stuck still beats, and says so, instead
12//! of going quiet in a way no one can tell from a closed pane.
13
14use std::sync::Arc;
15use std::time::Duration;
16
17use serde_json::json;
18
19use crate::serve::Health;
20
21const EVERY: Duration = Duration::from_secs(15);
22const FIRST: Duration = Duration::from_secs(5);
23/// A beat this long after the last one means the machine slept (or this
24/// thread was starved): the clocks the lag and the ages are made from jumped,
25/// so that beat doesn't speak to either.
26const LATE_AFTER: Duration = Duration::from_secs(45);
27
28/// Whether this beat came late, by either clock: `Instant` stops while a machine
29/// is suspended on Linux and macOS, the wall clock doesn't.
30fn is_late(monotonic: Duration, wall: Duration) -> bool {
31    monotonic.max(wall) > LATE_AFTER
32}
33
34/// The beat's body. After a sleep (`late`) the runtime lag and the age of the
35/// oldest call are left out for this one beat: the tick task hasn't had a
36/// chance to run yet, and srv would take the gap for a stuck runtime.
37pub(crate) fn beat_body(health: &Health, slug: &str, late: bool) -> serde_json::Value {
38    let oldest = if late {
39        None
40    } else {
41        health.oldest_unanswered()
42    };
43    json!({
44        "agent": slug,
45        "pid": std::process::id(),
46        "inflight": health.inflight(),
47        "oldest_tool": oldest.as_ref().map(|(t, _)| t.clone()),
48        "oldest_s": oldest.map(|(_, s)| s),
49        "runtime_lag_ms": if late { 0 } else { health.runtime_lag_ms() },
50        "call_threads": health.call_threads(),
51    })
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn a_beat_is_late_by_either_clock() {
60        let ok = Duration::from_secs(15);
61        assert!(!is_late(ok, ok));
62        assert!(is_late(Duration::from_secs(60), ok));
63        assert!(
64            is_late(ok, Duration::from_secs(3600)),
65            "a suspend the monotonic clock didn't count"
66        );
67    }
68
69    #[test]
70    fn a_beat_after_a_sleep_reports_no_lag_and_no_call_age() {
71        let h = Health::new();
72        h.begin("1".into(), "UI".into());
73        std::thread::sleep(Duration::from_millis(1100));
74        let ordinary = beat_body(&h, "a", false);
75        assert!(ordinary["runtime_lag_ms"].as_u64().unwrap() >= 1000);
76        assert_eq!(ordinary["oldest_tool"], "UI");
77        let late = beat_body(&h, "a", true);
78        assert_eq!(late["runtime_lag_ms"], 0);
79        assert!(late["oldest_tool"].is_null() && late["oldest_s"].is_null());
80        assert_eq!(late["inflight"], 1);
81    }
82}
83
84/// Start the beats. Does nothing without the agent's token and slug (a
85/// process started outside AgentMux's own spawn, a test).
86pub(crate) fn start(health: Arc<Health>, local_url: String, auth_key: String) {
87    let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
88    let (Some(token), Some(slug)) = (var("AGENTMUX_AGENT_TOKEN"), var("AGENTMUX_AGENT_SLUG"))
89    else {
90        return;
91    };
92    // The beats feed the health of a persistent controller's long-lived MCP server; a container
93    // agent's turns each start their own, so srv has nothing to record and refuses the route.
94    if crate::self_keys::in_container() {
95        return;
96    }
97    if local_url.is_empty() || auth_key.is_empty() {
98        return;
99    }
100    let spawned = std::thread::Builder::new()
101        .name("mcp-heartbeat".into())
102        .spawn(move || {
103            let Ok(rt) = tokio::runtime::Builder::new_current_thread()
104                .enable_all()
105                .build()
106            else {
107                return;
108            };
109            // Everything, the client included, inside this runtime's own context.
110            rt.block_on(async move {
111                let Ok(client) = agentmux_common::local_http::builder()
112                    .timeout(Duration::from_secs(10))
113                    .build()
114                else {
115                    return;
116                };
117                let url = format!(
118                    "{}/api/v1/agent/self/mcp-beat",
119                    local_url.trim_end_matches('/')
120                );
121                tokio::time::sleep(FIRST).await;
122                let mut last = std::time::Instant::now();
123                let mut last_wall = std::time::SystemTime::now();
124                loop {
125                    let late = is_late(last.elapsed(), last_wall.elapsed().unwrap_or_default());
126                    last = std::time::Instant::now();
127                    last_wall = std::time::SystemTime::now();
128                    let body = beat_body(&health, &slug, late);
129                    // A failure is not news: srv may be restarting, and the next beat tries again.
130                    let _ = client
131                        .post(&url)
132                        .header(agentmux_common::AUTH_KEY_HEADER, &auth_key)
133                        .header("X-Agent-Token", token.trim())
134                        .json(&body)
135                        .send()
136                        .await;
137                    tokio::time::sleep(EVERY).await;
138                }
139            });
140        });
141    if let Err(e) = spawned {
142        eprintln!("agentmux-mcp: couldn't start the heartbeat thread: {e}");
143    }
144}