1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//! A stdio server's process as a probe runs it: the end of its standard
//! error kept and its exit status read, so a server that fails to start can
//! say why. A session's servers run unwatched, with their standard error
//! discarded, since nothing reads it there.
use std::{
collections::VecDeque,
process::ExitStatus,
sync::{Arc, Mutex, PoisonError},
time::Duration,
};
use tokio::{
io::AsyncReadExt,
process::{Child, ChildStderr},
task::JoinHandle,
};
/// The most of a server's standard error a probe keeps: its end, which is
/// where a crash's reason is. Measured: a Python import error is 156 bytes,
/// and a traceback through four frames 1,033; this keeps one eight times
/// that size whole.
const STDERR_TAIL_BYTES: usize = 8 * 1024;
/// How long a probe waits for the process to report its exit once it is
/// done with it, and again for its standard error to close once it exited
/// or was killed. Measured: a process's exit is reaped 0.02 ms (at most
/// 0.04 ms in 50 runs) after its output closes, so this only separates a
/// process that exited from one that closed its output and kept running, or
/// one whose child holds its standard error open.
const EXIT_REPORT_GRACE: Duration = Duration::from_secs(1);
/// How a connect runs a stdio server's process.
pub(crate) enum McpStdio {
/// Its standard error discarded, as a session's servers run.
Unwatched,
/// Watched by an `McpStdioWatch`, as a probe runs one.
Watched(McpStdioWatch),
}
/// The process a probe started, once it started one. Clones share it.
#[derive(Clone, Default)]
pub(crate) struct McpStdioWatch {
process: Arc<Mutex<Option<WatchedProcess>>>,
}
/// Spawned with `kill_on_drop`, so dropping it stops it.
struct WatchedProcess {
child: Child,
stderr: Arc<Mutex<Tail>>,
/// Ends once its standard error closes.
stderr_closed: JoinHandle<()>,
}
/// What a watched process left behind.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct McpStdioReport {
/// Its exit status, when it exited on its own.
pub(crate) exit: Option<ExitStatus>,
/// The end of its standard error, empty when it wrote none.
pub(crate) stderr: Vec<u8>,
/// Whether `stderr` was cut from a longer output.
pub(crate) stderr_cut: bool,
}
/// The end of a process's standard error.
#[derive(Default)]
struct Tail {
bytes: VecDeque<u8>,
cut: bool,
}
impl McpStdioWatch {
/// Watches `child`, whose standard error is `stderr`, keeping the end of
/// what it writes there.
pub(crate) fn attach(&self, child: Child, stderr: ChildStderr) {
let tail = Arc::new(Mutex::new(Tail::default()));
let stderr_closed = tokio::spawn(keep_tail(stderr, Arc::clone(&tail)));
*self.lock() = Some(WatchedProcess {
child,
stderr: tail,
stderr_closed,
});
}
/// What the process left: its exit status if it exits within
/// [`EXIT_REPORT_GRACE`], else it is killed, and its standard error.
pub(crate) async fn finish(&self) -> McpStdioReport {
let Some(WatchedProcess {
mut child,
stderr,
mut stderr_closed,
}) = self.lock().take()
else {
return McpStdioReport::default();
};
let exit = tokio::time::timeout(EXIT_REPORT_GRACE, child.wait())
.await
.ok()
.and_then(Result::ok);
drop(child);
if tokio::time::timeout(EXIT_REPORT_GRACE, &mut stderr_closed)
.await
.is_err()
{
stderr_closed.abort();
}
let tail = std::mem::take(&mut *stderr.lock().unwrap_or_else(PoisonError::into_inner));
McpStdioReport {
exit,
stderr: tail.bytes.into(),
stderr_cut: tail.cut,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Option<WatchedProcess>> {
self.process.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// Reads `stderr` until it closes, keeping its last [`STDERR_TAIL_BYTES`]
/// in `tail`, so a chatty server never blocks on a full pipe.
async fn keep_tail(mut stderr: ChildStderr, tail: Arc<Mutex<Tail>>) {
let mut buffer = [0u8; 4096];
while let Ok(read) = stderr.read(&mut buffer).await {
if read == 0 {
break;
}
let mut tail = tail.lock().unwrap_or_else(PoisonError::into_inner);
tail.bytes.extend(&buffer[..read]);
let excess = tail.bytes.len().saturating_sub(STDERR_TAIL_BYTES);
if excess > 0 {
tail.bytes.drain(..excess);
tail.cut = true;
}
}
}