Skip to main content

blyte_cli/mcp/
stdio.rs

1//! Stdio JSON-RPC 2.0 transport for local MCP servers.
2
3use std::collections::BTreeMap;
4use std::io::{BufRead, BufReader, Read, Write};
5use std::process::{Child, ChildStdin, Command, Stdio};
6use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
7use std::sync::{Arc, Mutex};
8use std::thread::{self, JoinHandle};
9use std::time::{Duration, Instant};
10
11use serde_json::Value;
12
13use crate::mcp::client::McpTransport;
14use crate::mcp::protocol::{
15    JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, McpError, JSONRPC_VERSION,
16};
17
18const MAX_STDERR_BYTES: usize = 64 * 1024;
19const SHUTDOWN_GRACE: Duration = Duration::from_millis(500);
20const SHUTDOWN_POLL: Duration = Duration::from_millis(10);
21const EOF_STDERR_WAIT: Duration = Duration::from_millis(50);
22
23enum StdoutEvent {
24    Line(String),
25    Eof,
26    IoError(String),
27}
28
29/// JSON-RPC 2.0 transport communicating over a child process's stdin and stdout.
30pub struct StdioTransport {
31    child: Child,
32    stdin: Option<ChildStdin>,
33    stdout_rx: Receiver<StdoutEvent>,
34    stderr_buf: Arc<Mutex<String>>,
35    _stdout_thread: Option<JoinHandle<()>>,
36    _stderr_thread: Option<JoinHandle<()>>,
37}
38
39impl StdioTransport {
40    /// Spawns the configured command with `args` and extra `env` variables.
41    pub fn spawn(
42        command: &str,
43        args: &[String],
44        env: &BTreeMap<String, String>,
45    ) -> Result<Self, McpError> {
46        let mut cmd = Command::new(command);
47        cmd.args(args)
48            .envs(env)
49            .stdin(Stdio::piped())
50            .stdout(Stdio::piped())
51            .stderr(Stdio::piped());
52
53        let mut child = cmd.spawn().map_err(|e| McpError::Transport {
54            message: format!("failed to spawn MCP server command '{command}': {e}"),
55            stderr: None,
56        })?;
57
58        let stdin = child.stdin.take().ok_or_else(|| McpError::Transport {
59            message: format!("failed to open stdin pipe for MCP server '{command}'"),
60            stderr: None,
61        })?;
62        let stdout = child.stdout.take().ok_or_else(|| McpError::Transport {
63            message: format!("failed to open stdout pipe for MCP server '{command}'"),
64            stderr: None,
65        })?;
66        let stderr = child.stderr.take().ok_or_else(|| McpError::Transport {
67            message: format!("failed to open stderr pipe for MCP server '{command}'"),
68            stderr: None,
69        })?;
70
71        let (tx, rx) = mpsc::channel();
72        let stdout_thread = thread::spawn(move || {
73            let mut reader = BufReader::new(stdout);
74            let mut line = String::new();
75            loop {
76                line.clear();
77                match reader.read_line(&mut line) {
78                    Ok(0) => {
79                        let _ = tx.send(StdoutEvent::Eof);
80                        break;
81                    }
82                    Ok(_) => {
83                        if tx.send(StdoutEvent::Line(line.clone())).is_err() {
84                            break;
85                        }
86                    }
87                    Err(e) => {
88                        let _ = tx.send(StdoutEvent::IoError(e.to_string()));
89                        break;
90                    }
91                }
92            }
93        });
94
95        let stderr_buf = Arc::new(Mutex::new(String::new()));
96        let stderr_capture = Arc::clone(&stderr_buf);
97        let stderr_thread = thread::spawn(move || {
98            let mut reader = BufReader::new(stderr);
99            let mut chunk = [0u8; 4096];
100            loop {
101                match reader.read(&mut chunk) {
102                    Ok(0) => break,
103                    Ok(n) => {
104                        let text = String::from_utf8_lossy(&chunk[..n]);
105                        if let Ok(mut guard) = stderr_capture.lock() {
106                            guard.push_str(&text);
107                            if guard.len() > MAX_STDERR_BYTES {
108                                let excess = guard.len() - MAX_STDERR_BYTES;
109                                let mut cut = excess;
110                                while cut < guard.len() && !guard.is_char_boundary(cut) {
111                                    cut += 1;
112                                }
113                                guard.drain(..cut);
114                            }
115                        }
116                    }
117                    Err(_) => break,
118                }
119            }
120        });
121
122        Ok(Self {
123            child,
124            stdin: Some(stdin),
125            stdout_rx: rx,
126            stderr_buf,
127            _stdout_thread: Some(stdout_thread),
128            _stderr_thread: Some(stderr_thread),
129        })
130    }
131
132    /// Returns a snapshot of captured stderr output, if non-empty.
133    pub fn stderr_output(&self) -> Option<String> {
134        self.stderr_buf
135            .lock()
136            .ok()
137            .map(|s| s.clone())
138            .filter(|s| !s.trim().is_empty())
139    }
140
141    fn write_line(&mut self, payload: &str) -> Result<(), McpError> {
142        let Some(stdin) = self.stdin.as_mut() else {
143            return Err(McpError::Transport {
144                message: "MCP server stdin is closed".to_string(),
145                stderr: self.stderr_output(),
146            });
147        };
148        if let Err(e) = stdin
149            .write_all(payload.as_bytes())
150            .and_then(|()| stdin.write_all(b"\n"))
151            .and_then(|()| stdin.flush())
152        {
153            thread::sleep(EOF_STDERR_WAIT);
154            return Err(McpError::Transport {
155                message: format!("failed writing to MCP server stdin: {e}"),
156                stderr: self.stderr_output(),
157            });
158        }
159        Ok(())
160    }
161}
162
163impl McpTransport for StdioTransport {
164    fn send_request(
165        &mut self,
166        request_id: u64,
167        method: &str,
168        params: Option<Value>,
169        timeout: Duration,
170    ) -> Result<Value, McpError> {
171        let req = JsonRpcRequest {
172            jsonrpc: JSONRPC_VERSION,
173            id: request_id,
174            method,
175            params,
176        };
177        let encoded = serde_json::to_string(&req)
178            .map_err(|e| McpError::Protocol(format!("failed to serialize request: {e}")))?;
179        self.write_line(&encoded)?;
180
181        let deadline = Instant::now() + timeout;
182        loop {
183            let now = Instant::now();
184            if now >= deadline {
185                return Err(McpError::Timeout {
186                    operation: method.to_string(),
187                    timeout,
188                });
189            }
190            let remaining = deadline - now;
191            match self.stdout_rx.recv_timeout(remaining) {
192                Ok(StdoutEvent::Line(line)) => {
193                    let trimmed = line.trim();
194                    if trimmed.is_empty() {
195                        continue;
196                    }
197                    let raw: Value = serde_json::from_str(trimmed).map_err(|e| {
198                        let stderr = self.stderr_output();
199                        match stderr {
200                            Some(s) => McpError::Protocol(format!(
201                                "invalid JSON from stdio MCP server: {e} (line: {trimmed}; stderr: {})",
202                                s.trim()
203                            )),
204                            None => McpError::Protocol(format!(
205                                "invalid JSON from stdio MCP server: {e} (line: {trimmed})"
206                            )),
207                        }
208                    })?;
209                    let has_method = raw.get("method").is_some();
210                    let has_result_or_error =
211                        raw.get("result").is_some() || raw.get("error").is_some();
212                    if has_method && !has_result_or_error {
213                        continue;
214                    }
215                    let resp: JsonRpcResponse = serde_json::from_value(raw).map_err(|e| {
216                        McpError::Protocol(format!("malformed JSON-RPC response: {e}"))
217                    })?;
218                    if resp.matches_id(request_id) {
219                        return resp.into_result();
220                    }
221                    if resp.id.is_none() && resp.error.is_some() {
222                        return resp.into_result();
223                    }
224                }
225                Ok(StdoutEvent::Eof) | Err(RecvTimeoutError::Disconnected) => {
226                    thread::sleep(EOF_STDERR_WAIT);
227                    let exit_detail = match self.child.try_wait() {
228                        Ok(Some(status)) => format!(" (exit status: {status})"),
229                        _ => String::new(),
230                    };
231                    return Err(McpError::Transport {
232                        message: format!(
233                            "stdio MCP server closed stdout before replying to '{method}'{exit_detail}"
234                        ),
235                        stderr: self.stderr_output(),
236                    });
237                }
238                Ok(StdoutEvent::IoError(msg)) => {
239                    thread::sleep(EOF_STDERR_WAIT);
240                    return Err(McpError::Transport {
241                        message: format!("failed reading stdio MCP server stdout: {msg}"),
242                        stderr: self.stderr_output(),
243                    });
244                }
245                Err(RecvTimeoutError::Timeout) => {
246                    return Err(McpError::Timeout {
247                        operation: method.to_string(),
248                        timeout,
249                    });
250                }
251            }
252        }
253    }
254
255    fn send_notification(
256        &mut self,
257        method: &str,
258        params: Option<Value>,
259        _timeout: Duration,
260    ) -> Result<(), McpError> {
261        let notif = JsonRpcNotification {
262            jsonrpc: JSONRPC_VERSION,
263            method,
264            params,
265        };
266        let encoded = serde_json::to_string(&notif)
267            .map_err(|e| McpError::Protocol(format!("failed to serialize notification: {e}")))?;
268        self.write_line(&encoded)
269    }
270}
271
272impl Drop for StdioTransport {
273    fn drop(&mut self) {
274        self.stdin.take();
275        let deadline = Instant::now() + SHUTDOWN_GRACE;
276        while Instant::now() < deadline {
277            match self.child.try_wait() {
278                Ok(Some(_)) => return,
279                Ok(None) => thread::sleep(SHUTDOWN_POLL),
280                Err(_) => break,
281            }
282        }
283        let _ = self.child.kill();
284        let _ = self.child.wait();
285    }
286}