| 1 | //! MCP newline framing over the broker-owned reviewed stdio process. |
| 2 | use anyhow::Result; |
| 3 | use tokio::process::ChildStdout; |
| 4 | |
| 5 | use super::McpTransport; |
| 6 | use super::process_broker::BrokerSession; |
| 7 | use super::wire::{MAX_MCP_RESPONSE_BYTES, read_line_capped}; |
| 8 | use codewhale_mcp::config::McpServerConfig; |
| 9 | |
| 10 | pub(super) struct StdioTransport { |
| 11 | pub(super) session: BrokerSession, |
| 12 | reader: tokio::io::BufReader<ChildStdout>, |
| 13 | /// Partial frame bytes survive cancellation of the receive future. |
| 14 | pub(super) pending_line: Vec<u8>, |
| 15 | } |
| 16 | |
| 17 | impl StdioTransport { |
| 18 | #[cfg(all(test, unix))] |
| 19 | pub(super) fn spawn( |
| 20 | server_name: &str, |
| 21 | command: &str, |
| 22 | config: &McpServerConfig, |
| 23 | cancel_token: tokio_util::sync::CancellationToken, |
| 24 | ) -> Result<Self> { |
| 25 | Self::spawn_with_auth_context( |
| 26 | server_name, |
| 27 | command, |
| 28 | config, |
| 29 | cancel_token, |
| 30 | super::process_mcp_auth_context(), |
| 31 | ) |
| 32 | } |
| 33 | |
| 34 | pub(super) fn spawn_with_auth_context( |
| 35 | server_name: &str, |
| 36 | command: &str, |
| 37 | config: &McpServerConfig, |
| 38 | cancel_token: tokio_util::sync::CancellationToken, |
| 39 | auth_context: std::sync::Arc<dyn codewhale_runtime::credentials::AuthContext>, |
| 40 | ) -> Result<Self> { |
| 41 | let (session, stdout) = BrokerSession::spawn_with_auth_context( |
| 42 | server_name, |
| 43 | command, |
| 44 | config, |
| 45 | cancel_token, |
| 46 | auth_context, |
| 47 | )?; |
| 48 | Ok(Self { |
| 49 | session, |
| 50 | reader: tokio::io::BufReader::new(stdout), |
| 51 | pending_line: Vec::new(), |
| 52 | }) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | #[async_trait::async_trait] |
| 57 | impl McpTransport for StdioTransport { |
| 58 | async fn last_stderr_line(&self) -> Option<String> { |
| 59 | self.session.last_stderr_line().await |
| 60 | } |
| 61 | |
| 62 | async fn send(&mut self, mut msg: Vec<u8>) -> Result<()> { |
| 63 | msg.push(b'\n'); |
| 64 | self.session.write(&msg).await |
| 65 | } |
| 66 | |
| 67 | /// Non-blocking liveness probe: a reaped child means the transport is |
| 68 | /// dead even though the `Ready` flag is still set (#6187). The sync |
| 69 | /// trait contract forbids awaiting the lock, so a contended lock reads |
| 70 | /// as alive — the read side observes the death on the next call. |
| 71 | fn probe_dead(&self) -> bool { |
| 72 | self.session.probe_dead() |
| 73 | } |
| 74 | |
| 75 | async fn recv(&mut self) -> Result<Vec<u8>> { |
| 76 | loop { |
| 77 | // Bounded read: a server emitting a newline-free multi-GB "line" |
| 78 | // must not OOM us (read_line is unbounded). |
| 79 | let bytes = match read_line_capped( |
| 80 | &mut self.reader, |
| 81 | &mut self.pending_line, |
| 82 | MAX_MCP_RESPONSE_BYTES, |
| 83 | ) |
| 84 | .await |
| 85 | { |
| 86 | Ok(b) => b, |
| 87 | Err(err) => { |
| 88 | if let Some(stderr) = self.session.stderr_context().await { |
| 89 | anyhow::bail!("Stdio transport read error: {err}\n{stderr}"); |
| 90 | } |
| 91 | return Err(err.into()); |
| 92 | } |
| 93 | }; |
| 94 | if bytes == 0 { |
| 95 | // Let the stderr drain task catch up before snapshotting, and |
| 96 | // name the exit status: a reviewed plugin's stderr is never |
| 97 | // retained, so the status is the only reason the operator |
| 98 | // gets when the child dies before the handshake (#5916). |
| 99 | tokio::task::yield_now().await; |
| 100 | let exit = self.session.exit_status().await; |
| 101 | let exit = exit.map_or_else(String::new, |status| format!(" ({status})")); |
| 102 | if let Some(stderr) = self.session.stderr_context().await { |
| 103 | anyhow::bail!("Stdio transport closed{exit}\n{stderr}"); |
| 104 | } |
| 105 | anyhow::bail!("Stdio transport closed{exit}"); |
| 106 | } |
| 107 | |
| 108 | let line_bytes = std::mem::take(&mut self.pending_line); |
| 109 | let line = String::from_utf8_lossy(&line_bytes); |
| 110 | let trimmed = line.trim(); |
| 111 | if trimmed.is_empty() { |
| 112 | continue; |
| 113 | } |
| 114 | |
| 115 | return Ok(trimmed.as_bytes().to_vec()); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// Send SIGTERM and wait up to `STDIO_SHUTDOWN_GRACE` for graceful exit, |
| 120 | /// then force termination and reap the child as the backstop. |
| 121 | async fn shutdown(&mut self) { |
| 122 | self.session.shutdown().await; |
| 123 | } |
| 124 | } |
| 125 |