use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use serde_json::Value;
use crate::mcp::client::McpTransport;
use crate::mcp::protocol::{
JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, McpError, JSONRPC_VERSION,
};
const MAX_STDERR_BYTES: usize = 64 * 1024;
const SHUTDOWN_GRACE: Duration = Duration::from_millis(500);
const SHUTDOWN_POLL: Duration = Duration::from_millis(10);
const EOF_STDERR_WAIT: Duration = Duration::from_millis(50);
enum StdoutEvent {
Line(String),
Eof,
IoError(String),
}
pub struct StdioTransport {
child: Child,
stdin: Option<ChildStdin>,
stdout_rx: Receiver<StdoutEvent>,
stderr_buf: Arc<Mutex<String>>,
_stdout_thread: Option<JoinHandle<()>>,
_stderr_thread: Option<JoinHandle<()>>,
}
impl StdioTransport {
pub fn spawn(
command: &str,
args: &[String],
env: &BTreeMap<String, String>,
) -> Result<Self, McpError> {
let mut cmd = Command::new(command);
cmd.args(args)
.envs(env)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| McpError::Transport {
message: format!("failed to spawn MCP server command '{command}': {e}"),
stderr: None,
})?;
let stdin = child.stdin.take().ok_or_else(|| McpError::Transport {
message: format!("failed to open stdin pipe for MCP server '{command}'"),
stderr: None,
})?;
let stdout = child.stdout.take().ok_or_else(|| McpError::Transport {
message: format!("failed to open stdout pipe for MCP server '{command}'"),
stderr: None,
})?;
let stderr = child.stderr.take().ok_or_else(|| McpError::Transport {
message: format!("failed to open stderr pipe for MCP server '{command}'"),
stderr: None,
})?;
let (tx, rx) = mpsc::channel();
let stdout_thread = thread::spawn(move || {
let mut reader = BufReader::new(stdout);
let mut line = String::new();
loop {
line.clear();
match reader.read_line(&mut line) {
Ok(0) => {
let _ = tx.send(StdoutEvent::Eof);
break;
}
Ok(_) => {
if tx.send(StdoutEvent::Line(line.clone())).is_err() {
break;
}
}
Err(e) => {
let _ = tx.send(StdoutEvent::IoError(e.to_string()));
break;
}
}
}
});
let stderr_buf = Arc::new(Mutex::new(String::new()));
let stderr_capture = Arc::clone(&stderr_buf);
let stderr_thread = thread::spawn(move || {
let mut reader = BufReader::new(stderr);
let mut chunk = [0u8; 4096];
loop {
match reader.read(&mut chunk) {
Ok(0) => break,
Ok(n) => {
let text = String::from_utf8_lossy(&chunk[..n]);
if let Ok(mut guard) = stderr_capture.lock() {
guard.push_str(&text);
if guard.len() > MAX_STDERR_BYTES {
let excess = guard.len() - MAX_STDERR_BYTES;
let mut cut = excess;
while cut < guard.len() && !guard.is_char_boundary(cut) {
cut += 1;
}
guard.drain(..cut);
}
}
}
Err(_) => break,
}
}
});
Ok(Self {
child,
stdin: Some(stdin),
stdout_rx: rx,
stderr_buf,
_stdout_thread: Some(stdout_thread),
_stderr_thread: Some(stderr_thread),
})
}
pub fn stderr_output(&self) -> Option<String> {
self.stderr_buf
.lock()
.ok()
.map(|s| s.clone())
.filter(|s| !s.trim().is_empty())
}
fn write_line(&mut self, payload: &str) -> Result<(), McpError> {
let Some(stdin) = self.stdin.as_mut() else {
return Err(McpError::Transport {
message: "MCP server stdin is closed".to_string(),
stderr: self.stderr_output(),
});
};
if let Err(e) = stdin
.write_all(payload.as_bytes())
.and_then(|()| stdin.write_all(b"\n"))
.and_then(|()| stdin.flush())
{
thread::sleep(EOF_STDERR_WAIT);
return Err(McpError::Transport {
message: format!("failed writing to MCP server stdin: {e}"),
stderr: self.stderr_output(),
});
}
Ok(())
}
}
impl McpTransport for StdioTransport {
fn send_request(
&mut self,
request_id: u64,
method: &str,
params: Option<Value>,
timeout: Duration,
) -> Result<Value, McpError> {
let req = JsonRpcRequest {
jsonrpc: JSONRPC_VERSION,
id: request_id,
method,
params,
};
let encoded = serde_json::to_string(&req)
.map_err(|e| McpError::Protocol(format!("failed to serialize request: {e}")))?;
self.write_line(&encoded)?;
let deadline = Instant::now() + timeout;
loop {
let now = Instant::now();
if now >= deadline {
return Err(McpError::Timeout {
operation: method.to_string(),
timeout,
});
}
let remaining = deadline - now;
match self.stdout_rx.recv_timeout(remaining) {
Ok(StdoutEvent::Line(line)) => {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let raw: Value = serde_json::from_str(trimmed).map_err(|e| {
let stderr = self.stderr_output();
match stderr {
Some(s) => McpError::Protocol(format!(
"invalid JSON from stdio MCP server: {e} (line: {trimmed}; stderr: {})",
s.trim()
)),
None => McpError::Protocol(format!(
"invalid JSON from stdio MCP server: {e} (line: {trimmed})"
)),
}
})?;
let has_method = raw.get("method").is_some();
let has_result_or_error =
raw.get("result").is_some() || raw.get("error").is_some();
if has_method && !has_result_or_error {
continue;
}
let resp: JsonRpcResponse = serde_json::from_value(raw).map_err(|e| {
McpError::Protocol(format!("malformed JSON-RPC response: {e}"))
})?;
if resp.matches_id(request_id) {
return resp.into_result();
}
if resp.id.is_none() && resp.error.is_some() {
return resp.into_result();
}
}
Ok(StdoutEvent::Eof) | Err(RecvTimeoutError::Disconnected) => {
thread::sleep(EOF_STDERR_WAIT);
let exit_detail = match self.child.try_wait() {
Ok(Some(status)) => format!(" (exit status: {status})"),
_ => String::new(),
};
return Err(McpError::Transport {
message: format!(
"stdio MCP server closed stdout before replying to '{method}'{exit_detail}"
),
stderr: self.stderr_output(),
});
}
Ok(StdoutEvent::IoError(msg)) => {
thread::sleep(EOF_STDERR_WAIT);
return Err(McpError::Transport {
message: format!("failed reading stdio MCP server stdout: {msg}"),
stderr: self.stderr_output(),
});
}
Err(RecvTimeoutError::Timeout) => {
return Err(McpError::Timeout {
operation: method.to_string(),
timeout,
});
}
}
}
}
fn send_notification(
&mut self,
method: &str,
params: Option<Value>,
_timeout: Duration,
) -> Result<(), McpError> {
let notif = JsonRpcNotification {
jsonrpc: JSONRPC_VERSION,
method,
params,
};
let encoded = serde_json::to_string(¬if)
.map_err(|e| McpError::Protocol(format!("failed to serialize notification: {e}")))?;
self.write_line(&encoded)
}
}
impl Drop for StdioTransport {
fn drop(&mut self) {
self.stdin.take();
let deadline = Instant::now() + SHUTDOWN_GRACE;
while Instant::now() < deadline {
match self.child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => thread::sleep(SHUTDOWN_POLL),
Err(_) => break,
}
}
let _ = self.child.kill();
let _ = self.child.wait();
}
}