//! 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::time::Duration; use futures::FutureExt; use rmcp::service::RoleClient; use rmcp::service::RxJsonRpcMessage; use rmcp::service::TxJsonRpcMessage; use rmcp::transport::Transport; use rmcp::transport::async_rw::AsyncRwTransport; use tokio::process::ChildStderr; use tokio::process::ChildStdin; use tokio::process::ChildStdout; use tokio::process::Command; 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: LocalChild, transport: StdioTransport, } enum StdioTransport { /// Preserve rmcp's existing framing for servers using the initialize handshake. Legacy(AsyncRwTransport), /// Bound frames and skip messages unknown to the client during 2026-07-28 discovery. V20260728(BoundedStdioTransport), } impl LocalStdioTransport { pub(super) fn spawn( command: Command, program_name: String, protocol_mode: McpProtocolMode, ) -> io::Result<(Self, Option)> { let mut child = local_child::spawn(command)?; let stdin = child .stdin .take() .ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?; let stdout = child .stdout .take() .ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?; let stderr = child.stderr.take(); 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 { self.child.id() } } impl Transport for LocalStdioTransport { type Error = io::Error; fn send( &mut self, item: TxJsonRpcMessage, ) -> impl Future> + 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>> + Send { match &mut self.transport { StdioTransport::Legacy(transport) => transport.receive().boxed(), StdioTransport::V20260728(transport) => transport.receive().boxed(), } } 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.map(|_| ()), Err(_) => self.child.kill().await, } } }