返回 CodeWhale
process_broker.rs
根目录 / crates / engine / src / mcp / process_broker.rs
1 //! Reviewed stdio process ownership, extracted from `mcp/stdio.rs`.
2 //!
3 //! Both the Rust MCP transport and the selected SDK broker use this lifetime
4 //! owner. This session owns spawn,
5 //! scrubbed environment, reviewed executable handles, stdin, bounded stderr,
6 //! authority cancellation, process-tree containment and graceful teardown.
7 //! `StdioTransport` owns only stdout framing and its cancellation-safe buffer.
8 //!
9 //! It accepts only the existing Rust MCP configuration. The SDK broker checks
10 //! Rust-issued launch and exact-operation authority before exposing its pipe
11 //! operations to the pinned builtin; plugins cannot use this process surface.
12 //! Protocol negotiation, catalog admission, tool approvals and call replay
13 //! policy remain in their owners.
14
15 use crate::mcp::McpServerConfigExt;
16 use std::collections::VecDeque;
17 use std::sync::Arc;
18 use std::time::Duration;
19
20 use anyhow::{Context, Result};
21 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
22 use tokio::process::{Child, ChildStdin, ChildStdout};
23 use tokio::sync::Mutex as TokioMutex;
24
25 use super::McpServerConfig;
26 use codewhale_runtime::child_env;
27
28 pub struct BrokerSession {
29 child: Arc<TokioMutex<Child>>,
30 stdin: ChildStdin,
31 stderr_tail: Arc<StderrTail>,
32 /// Idle reviewed children die when their connection authority is revoked.
33 authority_cancel_watch: Option<tokio::task::JoinHandle<()>>,
34 /// Keep the reviewed executable/script descriptors alive through cleanup.
35 _reviewed_launch: Option<super::ReviewedStdioLaunch>,
36 /// Owned until Drop transfers it to the bounded asynchronous cleanup.
37 process_tree: Option<Arc<codewhale_runtime::process_tree::ProcessTree>>,
38 }
39
40 /// How long `BrokerSession::shutdown` waits for the child to exit on SIGTERM
41 /// before `kill_on_drop` fires SIGKILL. Tuned short so a hung MCP server
42 /// can't stall TUI exit; well-behaved servers almost always exit within
43 /// a few hundred ms.
44 pub(super) const STDIO_SHUTDOWN_GRACE: Duration = Duration::from_millis(2_000);
45
46 /// How many lines of MCP-server stderr to keep around for crash diagnostics.
47 /// Bounded so a chatty server can't grow this without limit; large enough to
48 /// catch typical Node/Python startup or panic output.
49 const STDERR_TAIL_CAPACITY: usize = 64;
50
51 /// Bounded ring buffer for the most recent stderr lines from a spawned MCP
52 /// server. Owned by `BrokerSession` to surface server-side context when the
53 /// transport read side fails (server crashed, exited early, etc).
54 #[derive(Default)]
55 struct StderrTail {
56 lines: TokioMutex<VecDeque<String>>,
57 }
58
59 impl StderrTail {
60 fn new() -> Arc<Self> {
61 Arc::new(Self {
62 lines: TokioMutex::new(VecDeque::with_capacity(STDERR_TAIL_CAPACITY)),
63 })
64 }
65
66 async fn push(&self, line: String) {
67 let mut buf = self.lines.lock().await;
68 if buf.len() >= STDERR_TAIL_CAPACITY {
69 buf.pop_front();
70 }
71 buf.push_back(line);
72 }
73
74 async fn snapshot(&self) -> Vec<String> {
75 self.lines.lock().await.iter().cloned().collect()
76 }
77
78 async fn last_line(&self) -> Option<String> {
79 self.lines
80 .lock()
81 .await
82 .iter()
83 .rev()
84 .map(|line| line.trim())
85 .find(|line| !line.is_empty())
86 .map(str::to_string)
87 }
88 }
89
90 impl BrokerSession {
91 pub fn spawn(
92 server_name: &str,
93 command: &str,
94 config: &McpServerConfig,
95 cancel_token: tokio_util::sync::CancellationToken,
96 ) -> Result<(Self, ChildStdout)> {
97 Self::spawn_with_auth_context(
98 server_name,
99 command,
100 config,
101 cancel_token,
102 super::process_mcp_auth_context(),
103 )
104 }
105
106 pub fn spawn_with_auth_context(
107 server_name: &str,
108 command: &str,
109 config: &McpServerConfig,
110 cancel_token: tokio_util::sync::CancellationToken,
111 auth_context: Arc<dyn codewhale_runtime::credentials::AuthContext>,
112 ) -> Result<(Self, ChildStdout)> {
113 let reviewed_launch = if let Some(reviewed_plugin) = config.reviewed_plugin_source() {
114 // This is deliberately the last trust check before constructing
115 // and spawning the lazy stdio child. It re-reads only the
116 // Codewhale-owned plugin bundle, never user MCP/provider config or
117 // credential files, and fails closed on any content/capability
118 // drift after pool construction.
119 Some(reviewed_plugin.prepare_stdio_launch(
120 server_name,
121 command,
122 &config.args,
123 config.cwd.as_deref(),
124 )?)
125 } else {
126 None
127 };
128 // Windows: Path::canonicalize yields a verbatim prefix. Node's ESM loader
129 // (and several other Windows tools) refuse that spelling for ordinary
130 // paths under MAX_PATH, so the reviewed peer exits 1 before handshake.
131 // Strip only at the child boundary; containment kept the prefixed form.
132 let mut cmd = reviewed_launch.as_ref().map_or_else(
133 || {
134 let mut command_process =
135 tokio::process::Command::new(super::strip_windows_verbatim_for_child(command));
136 for arg in &config.args {
137 command_process.arg(super::strip_windows_verbatim_for_child(arg.as_str()));
138 }
139 command_process
140 },
141 |launch| {
142 let mut command_process = tokio::process::Command::new(
143 super::strip_windows_verbatim_for_child(&launch.command),
144 );
145 for arg in &launch.args {
146 command_process.arg(super::strip_windows_verbatim_for_child(arg));
147 }
148 command_process
149 },
150 );
151 codewhale_util::utils::suppress_tokio_console_window(&mut cmd);
152 cmd.stdin(std::process::Stdio::piped())
153 .stdout(std::process::Stdio::piped())
154 .stderr(std::process::Stdio::piped())
155 .kill_on_drop(true);
156 let launch_cwd = reviewed_launch
157 .as_ref()
158 .and_then(|launch| launch.cwd.as_ref())
159 .or(config.cwd.as_ref().filter(|_| reviewed_launch.is_none()));
160 if let Some(cwd) = launch_cwd {
161 cmd.current_dir(super::strip_windows_verbatim_for_child(cwd.as_os_str()));
162 }
163 #[cfg(unix)]
164 if let Some(cwd_fd) = reviewed_launch
165 .as_ref()
166 .and_then(|launch| launch.cwd_fd.as_ref())
167 {
168 use std::os::fd::AsRawFd as _;
169 let fd = cwd_fd.as_raw_fd();
170 // SAFETY: the closure calls only async-signal-safe `fchdir` on an
171 // inherited directory descriptor before exec.
172 unsafe {
173 cmd.pre_exec(move || {
174 if libc::fchdir(fd) == 0 {
175 Ok(())
176 } else {
177 Err(std::io::Error::last_os_error())
178 }
179 });
180 }
181 }
182
183 // Expand `${NAME}` placeholders so secret env values can be sourced
184 // from the owning credential context instead of being stored in cleartext
185 // in the MCP config. The child env is allowlist-sanitized below, so
186 // these vars would not otherwise be inherited by the child.
187 let expanded_env =
188 super::expanded_mcp_stdio_env_with_auth_context(config, auth_context.as_ref())
189 .with_context(|| format!("MCP server '{server_name}' env expansion failed"))?;
190
191 // User-configured MCP keeps the compatibility-oriented Node/Python
192 // bootstrap allowlist (#1244). Reviewed plugins receive only the base
193 // secret-scrubbed child environment plus their explicitly reviewed
194 // mappings, so namespaces such as NPM_CONFIG_* are never inherited
195 // ambiently across the consent boundary.
196 if let Some(reviewed_plugin) = config.reviewed_plugin_source() {
197 cmd.env_clear();
198 for (key, value) in child_env::sanitized_plugin_mcp_env_from(
199 reviewed_plugin.host_environment.entries().iter().cloned(),
200 child_env::string_map_env(&expanded_env),
201 ) {
202 cmd.env(key, value);
203 }
204 } else {
205 child_env::apply_to_tokio_command_mcp(
206 &mut cmd,
207 child_env::string_map_env(&expanded_env),
208 );
209 }
210 // Lead a process group of its own so teardown can reach descendants.
211 #[cfg(unix)]
212 cmd.process_group(0);
213
214 let mut child = cmd.spawn().map_err(|error| {
215 let message = if error.kind() == std::io::ErrorKind::NotFound
216 && super::is_node_command(command)
217 && launch_cwd.is_none_or(|directory| directory.is_dir())
218 {
219 format!("MCP server {server_name} could not start because Node.js was not found. Install Node.js from https://nodejs.org/ and restart Codewhale with node on PATH. Computer Use requires Node.js 20 or newer.")
220 } else if config.reviewed_plugin.is_some() {
221 format!(
222 "MCP stdio spawn failed (transport=stdio server={server_name} reviewed-plugin argv_count={} env_count={})",
223 config.args.len(),
224 expanded_env.len(),
225 )
226 } else {
227 let env_keys: Vec<&str> = expanded_env.keys().map(String::as_str).collect();
228 format!(
229 "MCP stdio spawn failed (transport=stdio server={server_name} cmd={command:?} args={:?} env_keys={env_keys:?})",
230 config.args,
231 )
232 };
233 anyhow::Error::new(error).context(message)
234 })?;
235
236 let process_tree = match codewhale_runtime::process_tree::ProcessTree::attach_tokio(&child)
237 {
238 Ok(tree) => Arc::new(tree),
239 Err(error) => {
240 let _ = child.start_kill();
241 return Err(anyhow::Error::new(error).context(format!(
242 "MCP server {server_name} could not be contained with its child processes"
243 )));
244 }
245 };
246
247 let stdin = child.stdin.take().context("Failed to get MCP stdin")?;
248 let stdout = child.stdout.take().context("Failed to get MCP stdout")?;
249 let stderr = child.stderr.take().context("Failed to get MCP stderr")?;
250
251 // Drain stderr into a bounded ring buffer so a crash mid-run leaves
252 // diagnostic breadcrumbs instead of disappearing into `Stdio::null`.
253 // The task exits naturally when the child closes its stderr
254 // (kill_on_drop / exit / explicit shutdown).
255 let stderr_tail = StderrTail::new();
256 {
257 let tail = Arc::clone(&stderr_tail);
258 // A reviewed plugin child receives environment-backed values that
259 // are intentionally absent from its manifest. Still drain its
260 // stderr to avoid blocking, but do not retain or surface arbitrary
261 // child output that could echo those credentials into a chat or
262 // persisted transcript.
263 let capture = config.reviewed_plugin.is_none().then_some(tail);
264 tokio::spawn(drain_stderr(stderr, capture));
265 }
266
267 let child = Arc::new(TokioMutex::new(child));
268 let authority_cancel_watch = config.reviewed_plugin_source().map(|_| {
269 let watched_child = Arc::clone(&child);
270 let watched_tree = Arc::clone(&process_tree);
271 tokio::spawn(async move {
272 cancel_token.cancelled().await;
273 terminate_child_for_authority_change(&watched_child, &watched_tree).await;
274 })
275 });
276
277 Ok((
278 Self {
279 child,
280 stdin,
281 stderr_tail,
282 authority_cancel_watch,
283 _reviewed_launch: reviewed_launch,
284 process_tree: Some(process_tree),
285 },
286 stdout,
287 ))
288 }
289 }
290
291 impl BrokerSession {
292 /// Write already-framed bytes; the transport owns the framing policy.
293 pub async fn write(&mut self, bytes: &[u8]) -> Result<()> {
294 self.stdin.write_all(bytes).await?;
295 self.stdin.flush().await?;
296 Ok(())
297 }
298
299 pub async fn last_stderr_line(&self) -> Option<String> {
300 // The child can write its reason immediately before the error reply.
301 tokio::task::yield_now().await;
302 if let Some(line) = self.stderr_tail.last_line().await {
303 return Some(line);
304 }
305 tokio::time::sleep(Duration::from_millis(100)).await;
306 self.stderr_tail.last_line().await
307 }
308
309 pub async fn stderr_context(&self) -> Option<String> {
310 format_stderr_context(&self.stderr_tail).await
311 }
312
313 pub async fn exit_status(&self) -> Option<std::process::ExitStatus> {
314 let mut child = self.child.lock().await;
315 observe_exit(&mut child, self.process_tree.as_deref())
316 }
317
318 /// Never await or spawn for readiness; a contended child still reads live.
319 pub fn probe_dead(&self) -> bool {
320 match self.child.try_lock() {
321 Ok(mut child) => observe_exit(&mut child, self.process_tree.as_deref()).is_some(),
322 Err(_) => false,
323 }
324 }
325
326 /// Reap the direct child and contain descendants through the same grace.
327 pub async fn shutdown(&mut self) {
328 let mut child = self.child.lock().await;
329 terminate_child(&mut child, self.process_tree.as_deref()).await;
330 }
331
332 #[cfg(all(test, unix))]
333 pub(super) fn child_for_tests(&self) -> Arc<TokioMutex<Child>> {
334 Arc::clone(&self.child)
335 }
336 }
337
338 /// Longest stderr line retained in the tail, in bytes after decoding. An
339 /// overlong line keeps its end, where the error usually is, and the start is
340 /// drained and discarded so a newline-free progress stream cannot grow memory.
341 const STDERR_LINE_CAP: usize = 4 * 1024;
342
343 /// Drain a child's stderr until EOF, retaining lossily decoded, length-capped
344 /// lines in `tail` when given. Stderr is not a protocol channel: a non-UTF-8
345 /// byte or an endless line must never stop the drain, because dropping the
346 /// pipe makes the child's next stderr write fail (EPIPE/SIGPIPE) and hides
347 /// the context this tail exists to keep.
348 async fn drain_stderr<R>(stderr: R, tail: Option<Arc<StderrTail>>)
349 where
350 R: tokio::io::AsyncRead + Unpin,
351 {
352 let mut reader = tokio::io::BufReader::new(stderr);
353 let mut line = Vec::new();
354 loop {
355 let (consumed, line_ended) = {
356 let available = match reader.fill_buf().await {
357 Ok(available) => available,
358 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
359 Err(_) => break,
360 };
361 if available.is_empty() {
362 break;
363 }
364 let (consumed, line_ended) = match available.iter().position(|&b| b == b'\n') {
365 Some(pos) => (pos + 1, true),
366 None => (available.len(), false),
367 };
368 if tail.is_some() {
369 let content = &available[..consumed - usize::from(line_ended)];
370 let keep = content.len().min(STDERR_LINE_CAP);
371 let overflow = (line.len() + keep).saturating_sub(STDERR_LINE_CAP);
372 line.drain(..overflow);
373 line.extend_from_slice(&content[content.len() - keep..]);
374 }
375 (consumed, line_ended)
376 };
377 reader.consume(consumed);
378 if line_ended {
379 push_stderr_line(tail.as_deref(), &mut line).await;
380 }
381 }
382 if !line.is_empty() {
383 push_stderr_line(tail.as_deref(), &mut line).await;
384 }
385 }
386
387 async fn push_stderr_line(tail: Option<&StderrTail>, line: &mut Vec<u8>) {
388 if let Some(tail) = tail {
389 let bytes: &[u8] = line;
390 let text = String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes));
391 // Lossy decoding can triple invalid bytes; hold the retained size to
392 // the cap too, again keeping the end.
393 let mut start = text.len().saturating_sub(STDERR_LINE_CAP);
394 while !text.is_char_boundary(start) {
395 start += 1;
396 }
397 tail.push(text[start..].to_owned()).await;
398 }
399 line.clear();
400 }
401
402 /// Format the captured stderr tail for inclusion in an error message. Empty
403 /// tails return `None` so the caller can fall back to its original message.
404 async fn format_stderr_context(tail: &StderrTail) -> Option<String> {
405 let lines = tail.snapshot().await;
406 if lines.is_empty() {
407 return None;
408 }
409 Some(format!(
410 "MCP server stderr (last {} line{}):\n{}",
411 lines.len(),
412 if lines.len() == 1 { "" } else { "s" },
413 lines.join("\n"),
414 ))
415 }
416
417 /// Best-effort SIGTERM. On Unix uses `libc::kill`, addressed to the child's
418 /// whole process group when it leads one (`contained`); on Windows there's no
419 /// equivalent so we let `kill_on_drop` (TerminateProcess) and the Job Object
420 /// handle it. Returns whether a signal was actually sent.
421 fn send_sigterm(child: &Child, contained: bool) -> bool {
422 #[cfg(unix)]
423 {
424 if let Some(pid) = child.id() {
425 let pid = pid as i32;
426 let target = if contained { -pid } else { pid };
427 // SAFETY: pid was just obtained from `child.id()` of an unreaped
428 // child, so neither it nor the group it leads can have been
429 // recycled. `libc::kill` with `SIGTERM` is async-signal-safe and
430 // never observes invalid memory. ESRCH is deliberately ignored.
431 unsafe {
432 let _ = libc::kill(target, libc::SIGTERM);
433 }
434 return true;
435 }
436 false
437 }
438 #[cfg(not(unix))]
439 {
440 let _ = (child, contained);
441 false
442 }
443 }
444
445 async fn terminate_child_for_authority_change(
446 child: &Arc<TokioMutex<Child>>,
447 tree: &codewhale_runtime::process_tree::ProcessTree,
448 ) {
449 let mut child = child.lock().await;
450 terminate_child(&mut child, Some(tree)).await;
451 }
452
453 /// Non-blocking exit probe that keeps the kill ahead of the reap. On Unix an
454 /// exited server's group is SIGKILLed while the unreaped leader still pins
455 /// the group id, then the leader is reaped and the tree disarmed, so nothing
456 /// signals that id afterwards. Elsewhere the Job is terminated once the exit
457 /// is seen.
458 fn observe_exit(
459 child: &mut Child,
460 tree: Option<&codewhale_runtime::process_tree::ProcessTree>,
461 ) -> Option<std::process::ExitStatus> {
462 #[cfg(unix)]
463 if let Some(tree) = tree
464 && !tree.kill_if_leader_exited()
465 {
466 return None;
467 }
468 let status = child.try_wait().ok().flatten();
469 if status.is_some()
470 && let Some(tree) = tree
471 {
472 let _ = tree.kill();
473 tree.disarm();
474 }
475 status
476 }
477
478 async fn terminate_child(
479 child: &mut Child,
480 tree: Option<&codewhale_runtime::process_tree::ProcessTree>,
481 ) {
482 // An already-exited server is reaped here after its group was killed, so
483 // the PID resolved below always belongs to an unreaped child.
484 if observe_exit(child, tree).is_some() {
485 return;
486 }
487
488 #[cfg(unix)]
489 send_sigterm(child, tree.is_some());
490
491 #[cfg(not(unix))]
492 let _ = child.start_kill();
493
494 let exited = tokio::time::timeout(STDIO_SHUTDOWN_GRACE, async {
495 match tree {
496 Some(tree) => tree.wait_then_kill(child).await,
497 None => child.wait().await,
498 }
499 })
500 .await;
501 if !matches!(exited, Ok(Ok(_))) {
502 if let Some(tree) = tree {
503 let _ = tree.kill();
504 }
505 let _ = child.start_kill();
506 let _ = child.wait().await;
507 if let Some(tree) = tree {
508 tree.disarm();
509 }
510 }
511 }
512
513 /// Session changes can drop a pool without explicitly awaiting shutdown.
514 /// Keep the owned child alive for the same bounded cleanup as explicit
515 /// shutdown, so servers can release input and recording resources. Runtime
516 /// teardown still drops the cleanup future and invokes `kill_on_drop`.
517 impl Drop for BrokerSession {
518 fn drop(&mut self) {
519 if let Some(watch) = self.authority_cancel_watch.take() {
520 watch.abort();
521 }
522 if let Ok(runtime) = tokio::runtime::Handle::try_current() {
523 let child = Arc::clone(&self.child);
524 let reviewed_launch = self._reviewed_launch.take();
525 // The task owns the tree so it is not killed before the grace.
526 let tree = self.process_tree.take();
527 runtime.spawn(async move {
528 let _reviewed_launch = reviewed_launch;
529 let mut child = child.lock().await;
530 terminate_child(&mut child, tree.as_deref()).await;
531 });
532 return;
533 }
534 if let Ok(mut child) = self.child.try_lock()
535 && observe_exit(&mut child, self.process_tree.as_deref()).is_none()
536 {
537 send_sigterm(&child, self.process_tree.is_some());
538 }
539 // No runtime: dropping the tree below SIGKILLs the group / closes the
540 // job, the same backstop `kill_on_drop` gives the direct child.
541 }
542 }
543
544 #[cfg(test)]
545 mod stderr_drain_tests {
546 use super::{STDERR_LINE_CAP, StderrTail, drain_stderr};
547 use tokio::io::AsyncWriteExt;
548
549 #[tokio::test]
550 async fn invalid_utf8_and_long_lines_do_not_stop_the_drain() {
551 let (mut writer, reader) = tokio::io::duplex(64);
552 let tail = StderrTail::new();
553 let drain = tokio::spawn(drain_stderr(reader, Some(tail.clone())));
554 writer.write_all(b"starting\r\n").await.unwrap();
555 writer.write_all(b"caf\xe9 \xff\xfe\n").await.unwrap();
556 writer
557 .write_all(&vec![b'#'; STDERR_LINE_CAP * 3])
558 .await
559 .unwrap();
560 writer.write_all(b"\npanic: boom").await.unwrap();
561 drop(writer);
562 drain.await.unwrap();
563 let lines = tail.snapshot().await;
564 assert_eq!(lines.len(), 4, "{lines:?}");
565 assert_eq!(lines[0], "starting");
566 assert_eq!(lines[1], "caf\u{fffd} \u{fffd}\u{fffd}");
567 assert_eq!(lines[2].len(), STDERR_LINE_CAP);
568 assert_eq!(lines[3], "panic: boom");
569 }
570
571 #[tokio::test]
572 async fn overlong_lines_keep_their_end_within_the_cap() {
573 let (mut writer, reader) = tokio::io::duplex(64);
574 let tail = StderrTail::new();
575 let drain = tokio::spawn(drain_stderr(reader, Some(tail.clone())));
576 // A long prefix, then the actual failure at the end of the line.
577 writer
578 .write_all(&vec![b'.'; STDERR_LINE_CAP * 3])
579 .await
580 .unwrap();
581 writer.write_all(b"error: config missing\n").await.unwrap();
582 // Invalid bytes decode to three-byte U+FFFD each.
583 writer
584 .write_all(&vec![0xff; STDERR_LINE_CAP])
585 .await
586 .unwrap();
587 writer.write_all(b"\n").await.unwrap();
588 drop(writer);
589 drain.await.unwrap();
590 let lines = tail.snapshot().await;
591 assert_eq!(lines.len(), 2, "{lines:?}");
592 assert!(
593 lines[0].ends_with("error: config missing"),
594 "{:?}",
595 &lines[0][lines[0].len() - 40..]
596 );
597 assert_eq!(lines[0].len(), STDERR_LINE_CAP);
598 assert!(lines[1].len() <= STDERR_LINE_CAP, "{}", lines[1].len());
599 assert!(lines[1].chars().all(|c| c == '\u{fffd}'));
600 }
601
602 #[tokio::test]
603 async fn uncaptured_stderr_is_still_drained_to_eof() {
604 let (mut writer, reader) = tokio::io::duplex(16);
605 let drain = tokio::spawn(drain_stderr(reader, None));
606 // A non-UTF-8 line, then far more than the pipe buffer: a drain that
607 // stopped at the bad line would fail this write with a broken pipe.
608 writer.write_all(b"\xff\n").await.unwrap();
609 writer.write_all(&[b'x'; 4096]).await.unwrap();
610 drop(writer);
611 drain.await.unwrap();
612 }
613 }
614
614 lines RUST