Skip to main content

agentmux_mcp/
serve.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MCP request loop: JSON-RPC lines in, JSON-RPC lines out, with every
5//! `tools/call` running as its own task under its own deadline, so one call
6//! that never returns can't hold up the others
7//! (docs/reports/ on #2614: a window call hung for 1800 s and every later call,
8//! to any tool, hung behind it, for ten hours, until the agent restarted).
9//!
10//! Each call runs on a thread of its own (driving the same async runtime), so a
11//! call stuck in blocking code, such as an OS window call into an app that has
12//! stopped answering, holds that thread and nothing else.
13//!
14//! Calls to the same tool still run in the order they arrived (a `type` and a
15//! `read` of the same shell mean something in order); calls to different tools
16//! don't wait for each other. A call that outlives its deadline is answered
17//! with an error and given up on (and so is a call that is cancelled): its
18//! future is dropped, which stops async work at its next await. A call stuck in
19//! blocking code can't be stopped, so its thread stays stuck, but the loop
20//! doesn't, and its tool's queue moves on without it: the order holds among
21//! the calls still being waited for.
22
23use std::collections::HashMap;
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30use serde_json::{json, Value};
31use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
32use tokio::sync::mpsc;
33
34/// What a tool call returns: the text for the model, or the error to show it.
35pub(crate) type CallResult = anyhow::Result<String>;
36/// Not `Send`: a tool may hold an OS window handle across an await. The
37/// future is made and run on one thread (see [`serve`]).
38pub(crate) type CallFuture = Pin<Box<dyn Future<Output = CallResult>>>;
39
40/// Runs one `tools/call`'s `params` (`{name, arguments}`).
41pub(crate) trait ToolRunner: Send + Sync + 'static {
42    fn run(&self, params: Value) -> CallFuture;
43}
44
45impl<F> ToolRunner for F
46where
47    F: Fn(Value) -> CallFuture + Send + Sync + 'static,
48{
49    fn run(&self, params: Value) -> CallFuture {
50        self(params)
51    }
52}
53
54/// Claude Code gives up on a call that is silent for 1800 s. A tool is
55/// answered well before that.
56const MAX_DEADLINE: Duration = Duration::from_secs(29 * 60);
57const DEFAULT_DEADLINE: Duration = Duration::from_secs(5 * 60);
58/// A window call (capture, look, click) takes seconds; a hung target window
59/// makes the OS call wait for it forever.
60const UI_DEADLINE: Duration = Duration::from_secs(90);
61
62/// How long `tool` may run with `arguments` before the loop answers for it.
63/// The tools that wait on purpose (a shell, the user, a spawned agent) get
64/// their own wait, plus a margin; the rest get a few minutes.
65pub(crate) fn call_deadline(tool: &str, arguments: &Value) -> Duration {
66    let secs = |n: u64| Duration::from_secs(n);
67    let wait_ms = |key: &str| arguments.get(key).and_then(Value::as_u64);
68    let d = match tool {
69        "UI" => UI_DEADLINE,
70        // Waits on a pattern, the exit of a command or quiet, for `timeout_ms`.
71        "Terminal" => {
72            secs(150).max(Duration::from_millis(wait_ms("timeout_ms").unwrap_or(0)) + secs(60))
73        }
74        // A fill or click can wait for a page or the user to sign in.
75        "Browser" | "Vault" | "Widget" => MAX_DEADLINE,
76        // `spawn` waits for the new agent to start (360 s).
77        "Agents" => secs(400),
78        // File uploads (300 s).
79        "Message" => secs(360),
80        "Desktop" => secs(180),
81        _ => DEFAULT_DEADLINE,
82    };
83    d.min(MAX_DEADLINE)
84}
85
86/// What the loop is doing, for the heartbeat to srv (`mcp_health`): the calls
87/// not yet answered, and whether the async runtime is still turning.
88pub(crate) struct Health {
89    started: Instant,
90    inflight: Mutex<HashMap<String, (String, Instant)>>,
91    /// Milliseconds after `started` when the runtime last ran its tick task.
92    last_tick_ms: AtomicU64,
93    /// Call threads started and not yet back: a call given up on that is stuck
94    /// in blocking code stays counted here.
95    threads: AtomicU64,
96}
97
98impl Health {
99    pub(crate) fn new() -> Arc<Self> {
100        Arc::new(Self {
101            started: Instant::now(),
102            inflight: Mutex::new(HashMap::new()),
103            last_tick_ms: AtomicU64::new(0),
104            threads: AtomicU64::new(0),
105        })
106    }
107
108    fn threads_start(&self) {
109        self.threads.fetch_add(1, Ordering::Relaxed);
110    }
111
112    fn threads_end(&self) {
113        self.threads.fetch_sub(1, Ordering::Relaxed);
114    }
115
116    /// Call threads still running, answered for or not.
117    pub(crate) fn call_threads(&self) -> u64 {
118        self.threads.load(Ordering::Relaxed)
119    }
120
121    pub(crate) fn begin(&self, key: String, tool: String) {
122        self.inflight
123            .lock()
124            .unwrap()
125            .insert(key, (tool, Instant::now()));
126    }
127
128    fn end(&self, key: &str) {
129        self.inflight.lock().unwrap().remove(key);
130    }
131
132    /// Calls received and not yet answered.
133    pub(crate) fn inflight(&self) -> usize {
134        self.inflight.lock().unwrap().len()
135    }
136
137    /// The age in seconds of the oldest call not yet answered, and its tool.
138    pub(crate) fn oldest_unanswered(&self) -> Option<(String, u64)> {
139        let map = self.inflight.lock().unwrap();
140        map.values()
141            .min_by_key(|(_, at)| *at)
142            .map(|(tool, at)| (tool.clone(), at.elapsed().as_secs()))
143    }
144
145    /// Run on the runtime once a second: if it stops running, the runtime is
146    /// starved or stuck, which [`Health::runtime_lag_ms`] shows from outside.
147    pub(crate) fn tick(&self) {
148        self.last_tick_ms
149            .store(self.started.elapsed().as_millis() as u64, Ordering::Relaxed);
150    }
151
152    /// How long ago the runtime last ran [`Health::tick`], read from another thread.
153    pub(crate) fn runtime_lag_ms(&self) -> u64 {
154        (self.started.elapsed().as_millis() as u64)
155            .saturating_sub(self.last_tick_ms.load(Ordering::Relaxed))
156    }
157}
158
159fn error_result(id: &Value, text: String) -> Value {
160    json!({ "jsonrpc": "2.0", "id": id, "result": { "content": [{"type": "text", "text": text}], "isError": true } })
161}
162
163fn text_result(id: &Value, text: String) -> Value {
164    json!({ "jsonrpc": "2.0", "id": id, "result": { "content": [{"type": "text", "text": text}], "isError": false } })
165}
166
167/// One call thread in [`Health`]'s count, until it ends.
168struct ThreadCount(Arc<Health>);
169
170impl ThreadCount {
171    fn start(health: Arc<Health>) -> Self {
172        health.threads_start();
173        Self(health)
174    }
175}
176
177impl Drop for ThreadCount {
178    fn drop(&mut self) {
179        self.0.threads_end();
180    }
181}
182
183/// The per-tool queues: calls to one tool run in arrival order.
184#[derive(Default)]
185struct ToolQueues(Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>);
186
187impl ToolQueues {
188    fn of(&self, tool: &str) -> Arc<tokio::sync::Mutex<()>> {
189        Arc::clone(self.0.lock().unwrap().entry(tool.to_string()).or_default())
190    }
191}
192
193/// The calls running now, by request id, so a cancel can stop the one it names.
194type Running = Arc<Mutex<HashMap<String, tokio::task::AbortHandle>>>;
195
196/// Reads requests from `input` until it closes, answering each on `output`.
197/// `deadline_of` says how long each call may run ([`call_deadline`] in production).
198/// `initialize` and `tools/list` are answered at once; `tools/call` runs
199/// through `runner` as a task. `notifications/cancelled` stops the call it names.
200/// Each `tools_changed` wake-up tells the client the tool list changed, so it asks for it
201/// again: a client lists the tools once, when it connects, and never again unless told.
202pub(crate) async fn serve<R, W>(
203    mut input: R,
204    output: W,
205    runner: Arc<dyn ToolRunner>,
206    tools: Arc<dyn Fn() -> Value + Send + Sync>,
207    tools_changed: Arc<tokio::sync::Notify>,
208    health: Arc<Health>,
209    deadline_of: fn(&str, &Value) -> Duration,
210) where
211    R: AsyncBufReadExt + Unpin,
212    W: AsyncWrite + Unpin + Send + 'static,
213{
214    let (out_tx, writer) = spawn_writer(output);
215    let session = Session { runner, health, out_tx, queues: Arc::default(), running: Arc::default() };
216    let tells_client = tokio::spawn(tell_tools_changed(tools_changed, session.out_tx.clone()));
217    let mut line = String::new();
218    loop {
219        line.clear();
220        match input.read_line(&mut line).await {
221            Ok(0) | Err(_) => break,
222            Ok(_) => {}
223        }
224        let trimmed = line.trim();
225        if trimmed.is_empty() {
226            continue;
227        }
228        let Ok(msg) = serde_json::from_str::<Value>(trimmed) else {
229            continue;
230        };
231        let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
232        let id = msg.get("id").cloned().unwrap_or(Value::Null);
233        let params = msg.get("params").cloned().unwrap_or(Value::Null);
234        if id.is_null() {
235            // A notification: no answer. Only a cancel does anything.
236            if method == "notifications/cancelled" {
237                session.cancel(&params);
238            }
239            continue;
240        }
241        match method {
242            "initialize" => {
243                let _ = session.out_tx.send(initialize_answer(&id));
244            }
245            "tools/list" => {
246                let _ = session
247                    .out_tx
248                    .send(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": tools() } }));
249            }
250            "tools/call" => {
251                let tool = params.get("name").and_then(Value::as_str).unwrap_or("");
252                let deadline = deadline_of(tool, params.get("arguments").unwrap_or(&Value::Null));
253                session.start_call(id, params, deadline);
254            }
255            _ => {
256                let _ = session.out_tx.send(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "method not found" } }));
257            }
258        }
259    }
260    tells_client.abort();
261    drop(session);
262    // Answers already queued still go out.
263    let _ = tokio::time::timeout(Duration::from_secs(2), writer).await;
264}
265
266/// Sends `notifications/tools/list_changed` each time `changed` is woken (MCP's way to say the
267/// tools differ now; announced as `listChanged` in `initialize`).
268async fn tell_tools_changed(changed: Arc<tokio::sync::Notify>, out_tx: mpsc::UnboundedSender<Value>) {
269    loop {
270        changed.notified().await;
271        if out_tx.send(json!({ "jsonrpc": "2.0", "method": "notifications/tools/list_changed" })).is_err() {
272            return;
273        }
274    }
275}
276
277/// One writer, so two answers never interleave on the pipe.
278fn spawn_writer<W>(output: W) -> (mpsc::UnboundedSender<Value>, tokio::task::JoinHandle<()>)
279where
280    W: AsyncWrite + Unpin + Send + 'static,
281{
282    let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Value>();
283    let writer = tokio::spawn(async move {
284        let mut output = output;
285        while let Some(v) = out_rx.recv().await {
286            let line = serde_json::to_string(&v).unwrap_or_default();
287            if output.write_all(line.as_bytes()).await.is_err()
288                || output.write_all(b"\n").await.is_err()
289                || output.flush().await.is_err()
290            {
291                break;
292            }
293        }
294    });
295    (out_tx, writer)
296}
297
298fn initialize_answer(id: &Value) -> Value {
299    json!({
300        "jsonrpc": "2.0", "id": id,
301        "result": {
302            "protocolVersion": "2024-11-05",
303            "capabilities": { "tools": { "listChanged": true } },
304            "serverInfo": { "name": "agentmux-mcp", "version": env!("CARGO_PKG_VERSION") }
305        }
306    })
307}
308
309/// What the loop shares with the calls it starts.
310struct Session {
311    runner: Arc<dyn ToolRunner>,
312    health: Arc<Health>,
313    out_tx: mpsc::UnboundedSender<Value>,
314    queues: Arc<ToolQueues>,
315    running: Running,
316}
317
318impl Session {
319    /// Stops the call a `notifications/cancelled` names, if it is still running.
320    fn cancel(&self, params: &Value) {
321        if let Some(request) = params.get("requestId") {
322            if let Some(handle) = self.running.lock().unwrap().remove(&request.to_string()) {
323                handle.abort();
324                self.health.end(&request.to_string());
325            }
326        }
327    }
328
329    /// Runs a `tools/call` as a task of its own, under its deadline, and answers it on the writer.
330    fn start_call(&self, id: Value, params: Value, deadline: Duration) {
331        let tool = params.get("name").and_then(Value::as_str).unwrap_or("").to_string();
332        let key = id.to_string();
333        self.health.begin(key.clone(), tool.clone());
334        let (runner, queue, out_tx, health, running_map) = (
335            Arc::clone(&self.runner),
336            self.queues.of(&tool),
337            self.out_tx.clone(),
338            Arc::clone(&self.health),
339            Arc::clone(&self.running),
340        );
341        let key_for_task = key.clone();
342        let handle = tokio::runtime::Handle::current();
343        // Held until the handle is in the map: the task removes its own
344        // entry when it ends, and a fast call must not do that first.
345        let mut running_now = self.running.lock().unwrap();
346        let task = tokio::spawn(async move {
347            // The deadline covers the wait for the tool's earlier calls too.
348            let work = run_in_turn(runner, queue, params, &tool, Arc::clone(&health), handle);
349            let outcome = tokio::time::timeout(deadline, work).await.ok();
350            let answer = answer_for(&id, &tool, deadline, outcome);
351            health.end(&key_for_task);
352            running_map.lock().unwrap().remove(&key_for_task);
353            let _ = out_tx.send(answer);
354        });
355        running_now.insert(key, task.abort_handle());
356    }
357}
358
359/// Waits for the tool's turn, then runs the call on a thread of its own.
360/// The outer error is why there was no answer from the call itself.
361async fn run_in_turn(
362    runner: Arc<dyn ToolRunner>,
363    queue: Arc<tokio::sync::Mutex<()>>,
364    params: Value,
365    tool: &str,
366    health: Arc<Health>,
367    handle: tokio::runtime::Handle,
368) -> Result<CallResult, String> {
369    let _turn = queue.lock().await;
370    let (done_tx, done_rx) = tokio::sync::oneshot::channel();
371    // Dropped with this future (the deadline, a cancel): the thread
372    // then drops the call's future instead of running it on.
373    let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>();
374    let _cancel = cancel_tx;
375    // Counts the thread until it ends, a panic included (or
376    // until the spawn fails and drops this with the closure).
377    let counted = ThreadCount::start(health);
378    let spawned = std::thread::Builder::new()
379        .name(format!("mcp-call-{tool}"))
380        .stack_size(4 << 20)
381        .spawn(move || {
382            let _counted = counted;
383            let result = handle.block_on(async {
384                tokio::select! {
385                    result = runner.run(params) => Some(result),
386                    _ = cancel_rx => None,
387                }
388            });
389            if let Some(result) = result {
390                let _ = done_tx.send(result);
391            }
392        });
393    match spawned {
394        Ok(_) => done_rx.await.map_err(|_| "the call stopped without an answer".to_string()),
395        Err(e) => Err(format!("couldn't start a thread for the call: {e}")),
396    }
397}
398
399/// The answer to a call: its text, its error, why it gave none, or that it outlived
400/// `deadline` (`outcome` is `None`).
401fn answer_for(id: &Value, tool: &str, deadline: Duration, outcome: Option<Result<CallResult, String>>) -> Value {
402    match outcome {
403        Some(Ok(Ok(text))) => text_result(id, text),
404        Some(Ok(Err(e))) => error_result(id, e.to_string()),
405        Some(Err(why)) => error_result(id, format!("{tool}: {why}")),
406        None => {
407            eprintln!("agentmux-mcp: {tool} did not finish within {} s; answered for it", deadline.as_secs());
408            error_result(
409                id,
410                format!(
411                    "{tool} didn't finish within {} s, so it was given up on and your other tools keep working. The work may still be running: check before you repeat it.",
412                    deadline.as_secs()
413                ),
414            )
415        }
416    }
417}
418
419#[cfg(test)]
420#[path = "tests/serve_tests.rs"]
421mod tests;