1use 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
34pub(crate) type CallResult = anyhow::Result<String>;
36pub(crate) type CallFuture = Pin<Box<dyn Future<Output = CallResult>>>;
39
40pub(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
54const MAX_DEADLINE: Duration = Duration::from_secs(29 * 60);
57const DEFAULT_DEADLINE: Duration = Duration::from_secs(5 * 60);
58const UI_DEADLINE: Duration = Duration::from_secs(90);
61
62pub(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 "Terminal" => {
72 secs(150).max(Duration::from_millis(wait_ms("timeout_ms").unwrap_or(0)) + secs(60))
73 }
74 "Browser" | "Vault" | "Widget" => MAX_DEADLINE,
76 "Agents" => secs(400),
78 "Message" => secs(360),
80 "Desktop" => secs(180),
81 _ => DEFAULT_DEADLINE,
82 };
83 d.min(MAX_DEADLINE)
84}
85
86pub(crate) struct Health {
89 started: Instant,
90 inflight: Mutex<HashMap<String, (String, Instant)>>,
91 last_tick_ms: AtomicU64,
93 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 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 pub(crate) fn inflight(&self) -> usize {
134 self.inflight.lock().unwrap().len()
135 }
136
137 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 pub(crate) fn tick(&self) {
148 self.last_tick_ms
149 .store(self.started.elapsed().as_millis() as u64, Ordering::Relaxed);
150 }
151
152 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
167struct 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#[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
193type Running = Arc<Mutex<HashMap<String, tokio::task::AbortHandle>>>;
195
196pub(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 if method == "notifications/cancelled" {
237 session.cancel(¶ms);
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 let _ = tokio::time::timeout(Duration::from_secs(2), writer).await;
264}
265
266async 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
277fn 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
309struct 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 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 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 let mut running_now = self.running.lock().unwrap();
346 let task = tokio::spawn(async move {
347 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
359async 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 let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>();
374 let _cancel = cancel_tx;
375 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
399fn 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;