Skip to main content

agentmux_mcp/
main.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! agentmux-mcp — MCP stdio server that exposes AgentMux's MuxAPI tools
5//! (`Terminal`, `Message`, `Memory`, `Pane`, …) to Claude.
6//!
7//! Claude Code launches this binary as an MCP server (via `.mcp.json`'s
8//! `"command": "agentmux-mcp"` entry, auto-injected by agent_config.rs).
9//! Communication is JSON-RPC 2.0 over stdin/stdout.
10//!
11//! The `Terminal` tool's background `run` (formerly `Shell`) starts a
12//! persistent shell on agentmux-srv and returns at once with a `shell_id`;
13//! output streams into the conversation as a `ShellNode` row, unblocking.
14//!
15//! Env vars (inherited from agentmux-srv's agent env injection):
16//!   AGENTMUX_LOCAL_URL    — sidecar HTTP base URL
17//!   AGENTMUX_AUTH_KEY     — X-AuthKey header secret
18//!   AGENTMUX_BLOCKID      — block UUID for shell event scoping (preferred).
19//!                           Injected by agent_handlers/input.rs into every persistent
20//!                           subprocess env; inherited by this MCP subprocess.
21//!   AGENTMUX_AGENT_BUS_ID — MuxBus routing identifier (fallback only).
22//!                           Often set to the agent type string (e.g. "claude")
23//!                           in .mcp.json, NOT the block UUID — do not use it
24//!                           as the shell scope unless AGENTMUX_BLOCKID is absent.
25
26use std::collections::HashMap;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::sync::{Arc, Mutex};
29use std::time::Duration;
30
31use agentmux_common::api_types::{
32    InjectRequest, PaneOpenRequest, PaneOpenResponse, PanePlaceRequest, PlaceArgs, PtyShellCreateRequest, PtyShellCreateResponse,
33    PtyShellInputRequest, PtyShellInputResponse, PtyShellReadRequest, PtyShellReadResponse,
34    PtyShellResizeRequest, PtyShellResizeResponse,
35    PtyShellStatusRequest, PtyShellStatusResponse, PtyShellStopRequest, PtyShellStopResponse,
36    ShellCreateRequest, ShellCreateResponse, ShellInputFailure, ShellInputRequest,
37    ShellInputResponse, ShellStatusRequest, ShellStatusResponse, ShellStopRequest,
38    ShellStopResponse, TabActivateRequest, TabNameRequest, TabNewRequest,
39    UiBrowserDispatchKeyRequest, UiBrowserEvalRequest, UiBrowserFocusElementRequest,
40    UiBrowserFocusInfoRequest, UiBrowserHistoryRequest, UiBrowserNavigateRequest,
41    UiBrowserOpenRequest, UiClickRequest, UiPressKeysRequest, UiQueryRequest, UiResetShortcutsRequest, UiRunCommandRequest, UiSetShortcutRequest,
42    UiRecordRequest, UiRecordResponse, UiScreenshotRequest, UiScreenshotResponse, UiShortcutsListRequest, WindowFocusRequest,
43    WindowNameRequest, WorkspaceNameRequest, PaneTitleRequest, FileRenameRequest, ClosePaneRequest, QuitSelfRequest,
44    RegisterDevServerRequest, RegisterDevServerResponse,
45};
46use agentmux_common::AUTH_KEY_HEADER;
47use anyhow::Result;
48use serde_json::{json, Value};
49use tokio::io::BufReader;
50use tokio::task::JoinHandle;
51
52/// Metadata kept alongside each running loop's task handle.
53struct LoopEntry {
54    handle: JoinHandle<()>,
55    prompt: String,
56    target: String,
57    interval_secs: u64,
58    max_iterations: Option<u64>,
59    fire_count: Arc<AtomicU64>,
60    started_at: u64,
61}
62
63/// In-process registry of running loops, keyed by loop_id. Lives for this MCP
64/// process's lifetime (== the agent session), so loops are reaped automatically
65/// when the agent pane closes.
66type LoopRegistry = Mutex<HashMap<String, LoopEntry>>;
67
68mod desktop_input;
69mod gateway_fwd;
70mod doctor;
71mod heartbeat;
72mod self_keys;
73mod serve;
74mod tool_schemas;
75use tool_schemas::*;
76mod window_blackout;
77mod window_capture;
78use window_capture::*;
79
80#[cfg(test)]
81mod tls_test_init;
82
83fn main() {
84    agentmux_common::tls_provider::install_ring_provider(); // reqwest 0.13 builds no client without it
85    // More workers than cores: a tool call stuck in blocking code (a window
86    // call into an app that stopped answering) holds a worker until it
87    // returns, and a few of those must not starve the rest (#2614).
88    let workers = std::thread::available_parallelism()
89        .map(|n| n.get())
90        .unwrap_or(4)
91        .max(8);
92    tokio::runtime::Builder::new_multi_thread()
93        .worker_threads(workers)
94        .enable_all()
95        .build()
96        .expect("tokio runtime")
97        .block_on(run());
98}
99
100async fn run() {
101    // `agentmux-mcp doctor [--heal]`, from the agent's shell: why its AgentMux
102    // tools aren't connected, with no MCP session (doctor.rs).
103    if std::env::args().nth(1).as_deref() == Some("gateway-fwd") {
104        std::process::exit(gateway_fwd::run().await);
105    }
106    if std::env::args().nth(1).as_deref() == Some("doctor") {
107        std::process::exit(doctor::run(std::env::args().skip(2).collect()).await);
108    }
109    let local_url = std::env::var("AGENTMUX_LOCAL_URL").unwrap_or_default();
110    let auth_key = std::env::var("AGENTMUX_AUTH_KEY").unwrap_or_default();
111    let block_id = scope_block_id();
112    let client = agentmux_common::local_http::builder()
113        .timeout(std::time::Duration::from_secs(10))
114        .default_headers(agent_token_headers(std::env::var("AGENTMUX_AGENT_TOKEN").ok()))
115        .build()
116        .expect("http client");
117
118    // Identity M4d-3: fetch this agent's signing keys from srv now, so the
119    // first signed send doesn't wait on it (self_keys.rs).
120    {
121        let (client, local_url, auth_key) = (client.clone(), local_url.clone(), auth_key.clone());
122        tokio::spawn(async move { self_keys::refresh_if_stale(&client, &local_url, &auth_key).await });
123    }
124
125    // Running loops, keyed by loop_id. Lives for this MCP process's lifetime
126    // (== the agent session), so loops are reaped when the agent pane closes.
127    let loops: Arc<LoopRegistry> = Arc::new(Mutex::new(HashMap::new()));
128    let loop_counter = Arc::new(AtomicU64::new(0));
129
130    let health = serve::Health::new();
131    start_pulse(&health, &local_url, &auth_key);
132    let (granted, tools_changed) = granted_services_kept_fresh(&client, &local_url, &auth_key).await;
133    let runner = tool_runner(client, local_url, auth_key, block_id, loops, loop_counter);
134    serve::serve(
135        BufReader::new(tokio::io::stdin()),
136        tokio::io::stdout(),
137        runner,
138        Arc::new(move || json!(tools_for(&granted.read().unwrap_or_else(|e| e.into_inner())))),
139        tools_changed,
140        health,
141        serve::call_deadline,
142    )
143    .await;
144}
145
146/// The block this process scopes its calls to.
147fn scope_block_id() -> String {
148    // AGENTMUX_BLOCKID is the canonical block UUID injected by agent_handlers/input.rs
149    // into the persistent subprocess env. It is what the frontend subscribes to
150    // for shell_node_create events (`block:<uuid>`), so it MUST be used here.
151    //
152    // AGENTMUX_AGENT_BUS_ID is the MuxBus routing identifier — a different
153    // concept. In existing .mcp.json files it is often set to "claude" (the
154    // agent type, not the block UUID), which was accidentally being used as the
155    // shell scope and caused shell_node_create to publish under `block:claude`
156    // instead of the real pane UUID — making the ActivityDock never receive
157    // shell events. Prefer AGENTMUX_BLOCKID; fall back to AGENTMUX_AGENT_BUS_ID
158    // only for older deployments that pre-date AGENTMUX_BLOCKID injection.
159    let blockid = std::env::var("AGENTMUX_BLOCKID").unwrap_or_default();
160    if blockid.is_empty() {
161        std::env::var("AGENTMUX_AGENT_BUS_ID").unwrap_or_default()
162    } else {
163        blockid
164    }
165}
166
167/// The headers every request to srv carries.
168fn agent_token_headers(token: Option<String>) -> reqwest::header::HeaderMap {
169    // Identity M4a (spec §6.5.3): every request carries this agent's token,
170    // inherited from the spawn environment (never from `.mcp.json`), so srv
171    // can attribute it to the agent's UID. Attribution only — srv never
172    // refuses a request for lacking it. Absent for a tokenless spawn.
173    let mut default_headers = reqwest::header::HeaderMap::new();
174    if let Some(token) = token
175        .filter(|t| !t.trim().is_empty())
176        .and_then(|t| reqwest::header::HeaderValue::from_str(t.trim()).ok())
177    {
178        let mut token = token;
179        token.set_sensitive(true);
180        default_headers.insert("X-Agent-Token", token);
181    }
182    default_headers
183}
184
185/// The runtime's pulse, and the heartbeat to srv from a thread of its
186/// own, so a starved runtime is seen from outside (heartbeat.rs).
187fn start_pulse(health: &Arc<serve::Health>, local_url: &str, auth_key: &str) {
188    let h = Arc::clone(health);
189    tokio::spawn(async move {
190        let mut every = tokio::time::interval(Duration::from_secs(1));
191        loop {
192            every.tick().await;
193            h.tick();
194        }
195    });
196    heartbeat::start(Arc::clone(health), local_url.to_string(), auth_key.to_string());
197}
198
199/// Which Google services this agent has a grant on, for `tools/list`: asked of srv now, again every
200/// minute and right after the agent changes a grant, because `tools/list` is answered at once and
201/// never waits on srv. The `Notify` is woken when the set changes, so the client is told to list
202/// the tools again (it does not on its own).
203async fn granted_services_kept_fresh(
204    client: &reqwest::Client,
205    local_url: &str,
206    auth_key: &str,
207) -> (Arc<std::sync::RwLock<Vec<String>>>, Arc<tokio::sync::Notify>) {
208    let mut first = tools::google_tool::granted_services(client, local_url, auth_key).await;
209    first.sort();
210    let granted = Arc::new(std::sync::RwLock::new(first));
211    let changed = Arc::new(tokio::sync::Notify::new());
212    let (granted_again, changed_again, client, local_url, auth_key) =
213        (Arc::clone(&granted), Arc::clone(&changed), client.clone(), local_url.to_string(), auth_key.to_string());
214    tokio::spawn(async move {
215        loop {
216            tokio::select! {
217                _ = tokio::time::sleep(Duration::from_secs(60)) => {}
218                _ = tools::google_tool::GRANTS_CHANGED.notified() => {}
219            }
220            let fetched = tools::google_tool::fetch_granted(&client, &local_url, &auth_key).await;
221            if tools::google_tool::adopt_granted(&granted_again, fetched) {
222                changed_again.notify_one();
223            }
224        }
225    });
226    (granted, changed)
227}
228
229/// Runs each tool call against srv at `local_url`, scoped to `block_id`.
230fn tool_runner(
231    client: reqwest::Client,
232    local_url: String,
233    auth_key: String,
234    block_id: String,
235    loops: Arc<LoopRegistry>,
236    loop_counter: Arc<AtomicU64>,
237) -> Arc<dyn serve::ToolRunner> {
238    Arc::new(move |params: Value| -> serve::CallFuture {
239        let (client, local_url, auth_key, block_id) =
240            (client.clone(), local_url.clone(), auth_key.clone(), block_id.clone());
241        let (loops, loop_counter) = (Arc::clone(&loops), Arc::clone(&loop_counter));
242        Box::pin(async move {
243            call_tool(
244                &params,
245                &local_url,
246                &auth_key,
247                &block_id,
248                &client,
249                &loops,
250                &loop_counter,
251            )
252            .await
253        })
254    })
255}
256
257mod srv_http;
258mod identity;
259mod tool_helpers;
260mod tools;
261pub(crate) use identity::*;
262use srv_http::*;
263use tool_helpers::*;
264
265async fn call_tool(
266    params: &Value,
267    local_url: &str,
268    auth_key: &str,
269    block_id: &str,
270    client: &reqwest::Client,
271    loops: &LoopRegistry,
272    loop_counter: &AtomicU64,
273) -> Result<String> {
274    let name = params
275        .get("name")
276        .and_then(|v| v.as_str())
277        .unwrap_or("");
278    let arguments = params
279        .get("arguments")
280        .cloned()
281        .unwrap_or(json!({}));
282
283    // Identity M4d-3: every tool may sign (a jekt, a UI-automation proof), so
284    // the fetched keys are checked here, once, before any of them runs.
285    self_keys::refresh_if_stale(client, local_url, auth_key).await;
286    let run = || async {
287        tools::call(
288            name,
289            &arguments,
290            &tools::ToolCtx {
291                local_url,
292                auth_key,
293                block_id,
294                client,
295                loops,
296                loop_counter,
297            },
298        )
299        .await
300    };
301    self_keys::run_healing_a_rejected_signature(client, local_url, auth_key, run).await
302}
303
304#[cfg(test)]
305#[path = "tests/main_tests.rs"]
306mod tests;
307
308// This test binary must hold this checkout's code, not another clone's from
309// a shared target directory (`agentmux_common::checkout`).
310#[cfg(test)]
311agentmux_common::checkout_guard!();