Fix relative MCP server spawning on macOS (#42117)

## Why

Rust falls back to `fork` when a macOS command combines a relative executable
path with a working directory, due to a historical `posix_spawnp` issue. This
can make local MCP server startup less reliable.

## What changed

- Spawn relative macOS MCP executables directly with `posix_spawn`, preserving
  the configured path, `argv[0]`, working directory, environment, stdio, and
  process group.
- Keep the existing launcher for `PATH` lookup and executable text files without
  a shebang.
- Use one local child wrapper for legacy and 2026-07-28 protocol framing, with
  cancellation-safe waiting and cleanup that kills and reaps dropped children.

## Testing

Add macOS regression coverage for relative scripts, argument and descriptor
preservation, launch errors, cancelled waits, and cleanup after runtime shutdown.

GitOrigin-RevId: 1cbc6b90aed6f67e0a38f551964d80496ebc4471
This commit is contained in:
Charlie Marsh authored and copyberry committed 2026-09-01 18:53:06 +00:00
1 parent ef76e6ac30
commit ea7e0714da
11 files changed
+855 -166

No files matched your search

+42 -115
View File
@@ -1,49 +1,46 @@
//! Bounded, compatibility-aware transport for modern locally spawned MCP servers.
//! Protocol framing and child lifetime for locally spawned MCP servers.
//!
//! Process creation is platform-specific; protocol selection and shutdown are shared.
use std::future::Future;
use std::io;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use memchr::memchr;
use futures::FutureExt;
use rmcp::service::RoleClient;
use rmcp::service::RxJsonRpcMessage;
use rmcp::service::TxJsonRpcMessage;
use rmcp::transport::Transport;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::process::Child;
use rmcp::transport::async_rw::AsyncRwTransport;
use tokio::process::ChildStderr;
use tokio::process::ChildStdin;
use tokio::process::ChildStdout;
use tokio::process::Command;
use tokio::sync::Mutex;
use tracing::debug;
use tracing::warn;
/// Match the existing executor stdio transport and the production MCP limit.
pub(crate) const MAX_MCP_STDIO_LINE_BYTES: usize = 8 * 1024 * 1024;
use crate::bounded_stdio_transport::BoundedStdioTransport;
use crate::local_child;
use crate::local_child::LocalChild;
use crate::protocol_mode::McpProtocolMode;
pub(super) struct LocalStdioTransport {
child: Child,
stdin: Arc<Mutex<Option<ChildStdin>>>,
stdout: BufReader<ChildStdout>,
pending_line: Vec<u8>,
program_name: String,
child: LocalChild,
transport: StdioTransport,
}
enum StdioTransport {
/// Preserve rmcp's existing framing for servers using the initialize handshake.
Legacy(AsyncRwTransport<RoleClient, ChildStdout, ChildStdin>),
/// Bound frames and skip messages unknown to the client during 2026-07-28 discovery.
V20260728(BoundedStdioTransport),
}
impl LocalStdioTransport {
pub(super) fn spawn(
mut command: Command,
command: Command,
program_name: String,
protocol_mode: McpProtocolMode,
) -> io::Result<(Self, Option<ChildStderr>)> {
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = command.spawn()?;
let mut child = local_child::spawn(command)?;
let stdin = child
.stdin
.take()
@@ -53,117 +50,47 @@ impl LocalStdioTransport {
.take()
.ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
let stderr = child.stderr.take();
Ok((
Self {
child,
stdin: Arc::new(Mutex::new(Some(stdin))),
stdout: BufReader::new(stdout),
pending_line: Vec::new(),
program_name,
},
stderr,
))
let transport = match protocol_mode {
McpProtocolMode::Legacy => StdioTransport::Legacy(AsyncRwTransport::new(stdout, stdin)),
McpProtocolMode::V20260728 => {
StdioTransport::V20260728(BoundedStdioTransport::new(stdin, stdout, program_name))
}
};
Ok((Self { child, transport }, stderr))
}
pub(super) fn id(&self) -> Option<u32> {
self.child.id()
}
async fn receive_message(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
loop {
let bytes = match self.stdout.fill_buf().await {
Ok(bytes) => bytes,
Err(error) => {
warn!(
"Failed to read MCP server stdout ({}): {error}",
self.program_name
);
return None;
}
};
if bytes.is_empty() {
if self.pending_line.is_empty() {
return None;
}
return self.decode_pending_message();
}
let newline = memchr(b'\n', bytes);
let content_len = newline.unwrap_or(bytes.len());
if content_len > MAX_MCP_STDIO_LINE_BYTES.saturating_sub(self.pending_line.len()) {
warn!(
"MCP stdio line exceeds {MAX_MCP_STDIO_LINE_BYTES} bytes ({}); closing transport",
self.program_name
);
self.pending_line.clear();
return None;
}
self.pending_line.extend_from_slice(&bytes[..content_len]);
let consumed = content_len + usize::from(newline.is_some());
self.stdout.consume(consumed);
if newline.is_some()
&& let Some(message) = self.decode_pending_message()
{
return Some(message);
}
}
}
fn decode_pending_message(&mut self) -> Option<RxJsonRpcMessage<RoleClient>> {
let line = std::mem::take(&mut self.pending_line);
let line = line.strip_suffix(b"\r").unwrap_or(&line);
match serde_json::from_slice(line) {
Ok(message) => Some(message),
Err(error) => {
debug!(
"Failed to parse local MCP server message ({}): {error}",
self.program_name
);
None
}
}
}
}
impl Transport<RoleClient> for LocalStdioTransport {
type Error = io::Error;
#[expect(
clippy::await_holding_invalid_type,
reason = "complete JSON-RPC frames must hold the stdin lock across writes"
)]
fn send(
&mut self,
item: TxJsonRpcMessage<RoleClient>,
) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
let stdin = Arc::clone(&self.stdin);
async move {
let mut message = serde_json::to_vec(&item).map_err(io::Error::other)?;
message.push(b'\n');
let mut guard = stdin.lock().await;
let stdin = guard
.as_mut()
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "MCP stdin closed"))?;
stdin.write_all(&message).await?;
stdin.flush().await
) -> impl Future<Output = io::Result<()>> + Send + 'static {
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.send(item).boxed(),
StdioTransport::V20260728(transport) => transport.send(item).boxed(),
}
}
fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<RoleClient>>> + Send {
self.receive_message()
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.receive().boxed(),
StdioTransport::V20260728(transport) => transport.receive().boxed(),
}
}
async fn close(&mut self) -> Result<(), Self::Error> {
self.stdin.lock().await.take();
async fn close(&mut self) -> io::Result<()> {
match &mut self.transport {
StdioTransport::Legacy(transport) => transport.close().await?,
StdioTransport::V20260728(transport) => transport.close().await?,
}
match tokio::time::timeout(Duration::from_secs(3), self.child.wait()).await {
Ok(status) => {
status?;
Ok(())
}
Ok(status) => status.map(|_| ()),
Err(_) => self.child.kill().await,
}
}