Close MCP stderr readers on client teardown (#43870)

## Why

A descendant outside an MCP server's process group can keep stderr open after the server exits, leaving the reader task and its file descriptor alive.

## What changed

Signal the local stderr reader during explicit shutdown and when the process handle is dropped. Allow up to 250 ms to drain queued diagnostics before closing the reader, even if stderr never reaches EOF.

## Testing

Add a Unix regression test covering explicit shutdown and client drop with a descendant that keeps stderr open. Verify that file descriptor counts return to baseline while the descendant remains alive and that queued diagnostics are logged.

GitOrigin-RevId: 1b544e8dba2b5616db6739d075e7232564c92884
This commit is contained in:
Mitsuhiro Kotake authored and copyberry committed 2026-09-08 17:42:14 +00:00
1 parent ce254df05a
commit 44ab72674e
4 files changed
+280 -17

No files matched your search

@@ -26,7 +26,6 @@ use std::sync::atomic::Ordering;
use std::thread::sleep;
#[cfg(unix)]
use std::thread::spawn;
#[cfg(unix)]
use std::time::Duration;
use anyhow::Result;
@@ -56,6 +55,8 @@ use rmcp::transport::Transport;
use tokio::io::AsyncBufReadExt;
use tokio::io::BufReader;
use tokio::process::Command;
use tokio::sync::watch;
use tokio::time::Instant;
use tracing::info;
use tracing::warn;
@@ -216,6 +217,10 @@ impl StdioServerLauncher for LocalStdioServerLauncher {
#[cfg(unix)]
const PROCESS_GROUP_TERM_GRACE_PERIOD: Duration = Duration::from_secs(2);
// Keep queued stderr diagnostics before closing the reader, even when an
// escaped descendant prevents the pipe from reaching EOF.
const STDERR_READER_DRAIN_GRACE_PERIOD: Duration = Duration::from_millis(250);
#[cfg(unix)]
struct LocalProcessTerminator {
process_group_id: u32,
@@ -239,6 +244,8 @@ struct StdioServerProcessHandleInner {
program_name: String,
kind: StdioServerProcessKind,
terminated: AtomicBool,
// An escaped descendant can keep stderr open after the MCP server exits.
stderr_reader: Option<watch::Sender<()>>,
}
enum StdioServerProcessKind {
@@ -349,25 +356,44 @@ impl LocalStdioServerLauncher {
};
#[cfg(not(windows))]
let terminator = process_id.map(LocalProcessTerminator::new);
let process = StdioServerProcessHandle::local(program_name.clone(), terminator);
if let Some(stderr) = stderr {
tokio::spawn(async move {
let stderr_reader = stderr.map(|stderr| {
let program_name = program_name.clone();
let (stop_tx, mut stop_rx) = watch::channel(());
std::mem::drop(tokio::spawn(async move {
let mut reader = BufReader::new(stderr).lines();
// Give queued diagnostics time to reach the logs without waiting
// indefinitely for a descendant that still has stderr open.
let drain_deadline = tokio::time::sleep(STDERR_READER_DRAIN_GRACE_PERIOD);
tokio::pin!(drain_deadline);
let mut draining = false;
loop {
match reader.next_line().await {
Ok(Some(line)) => {
info!("MCP server stderr ({program_name}): {line}");
}
Ok(None) => break,
Err(error) => {
warn!("Failed to read MCP server stderr ({program_name}): {error}");
break;
tokio::select! {
biased;
_ = &mut drain_deadline, if draining => break,
_ = stop_rx.changed(), if !draining => {
draining = true;
drain_deadline.as_mut().reset(
Instant::now() + STDERR_READER_DRAIN_GRACE_PERIOD
);
}
line = reader.next_line() => {
match line {
Ok(Some(line)) => {
info!("MCP server stderr ({program_name}): {line}");
}
Ok(None) => break,
Err(error) => {
warn!("Failed to read MCP server stderr ({program_name}): {error}");
break;
}
}
},
}
}
});
}
}));
stop_tx
});
let process = StdioServerProcessHandle::local(program_name, terminator, stderr_reader);
Ok(StdioServerTransport {
inner: transport,
@@ -428,12 +454,17 @@ impl LocalProcessTerminator {
}
impl StdioServerProcessHandle {
fn local(program_name: String, terminator: Option<LocalProcessTerminator>) -> Self {
fn local(
program_name: String,
terminator: Option<LocalProcessTerminator>,
stderr_reader: Option<watch::Sender<()>>,
) -> Self {
Self {
inner: Arc::new(StdioServerProcessHandleInner {
program_name,
kind: StdioServerProcessKind::Local(terminator),
terminated: AtomicBool::new(false),
stderr_reader,
}),
}
}
@@ -444,6 +475,7 @@ impl StdioServerProcessHandle {
program_name,
kind: StdioServerProcessKind::Executor(process),
terminated: AtomicBool::new(false),
stderr_reader: None,
}),
}
}
@@ -453,7 +485,7 @@ impl StdioServerProcessHandle {
return Ok(());
}
match &self.inner.kind {
let result = match &self.inner.kind {
StdioServerProcessKind::Local(Some(terminator)) => {
terminator.terminate();
Ok(())
@@ -466,7 +498,11 @@ impl StdioServerProcessHandle {
Err(io::Error::other(error))
}
},
};
if let Some(stderr_reader) = &self.inner.stderr_reader {
stderr_reader.send_replace(());
}
result
}
}
@@ -501,6 +537,9 @@ impl Drop for StdioServerProcessHandleInner {
}));
}
}
if let Some(stderr_reader) = &self.stderr_reader {
stderr_reader.send_replace(());
}
}
}