use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
use tokio::io::{AsyncWriteExt, BufReader, BufWriter};
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, warn};
use super::capped_line::{CappedLine, read_capped_line};
use super::{
CALL_TIMEOUT, MAX_LINE_BYTES, MCP_PROTOCOL_VERSION, McpTool, ServerInfo, StdioMcpClient,
build_initialize_request, extract_result, plugin_stderr_stdio,
};
impl StdioMcpClient {
pub async fn spawn(
binary: &str,
args: &[&str],
client_name: impl Into<String>,
) -> Result<Self> {
Self::spawn_with_env(binary, args, client_name, &std::collections::HashMap::new()).await
}
pub async fn spawn_with_env(
binary: &str,
args: &[&str],
client_name: impl Into<String>,
envs: &std::collections::HashMap<String, String>,
) -> Result<Self> {
Self::spawn_inner(binary, args, client_name, envs, false).await
}
pub async fn spawn_grouped_with_env(
binary: &str,
args: &[&str],
client_name: impl Into<String>,
envs: &std::collections::HashMap<String, String>,
) -> Result<Self> {
Self::spawn_inner(binary, args, client_name, envs, true).await
}
async fn spawn_inner(
binary: &str,
args: &[&str],
client_name: impl Into<String>,
envs: &std::collections::HashMap<String, String>,
own_group: bool,
) -> Result<Self> {
let mut command = server_command(binary, args, own_group);
let mut child = command
.envs(envs.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.spawn()
.with_context(|| format!("failed to spawn MCP binary {binary}"))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| anyhow!("child stdin not captured"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow!("child stdout not captured"))?;
Ok(Self {
child,
stdin: BufWriter::new(stdin),
stdout: BufReader::new(stdout),
line_buf: Vec::new(),
discard_line: false,
next_id: AtomicU64::new(1),
binary: binary.to_string(),
args: args.iter().map(|s| s.to_string()).collect(),
client_name: client_name.into(),
own_group,
})
}
pub fn is_alive(&mut self) -> bool {
matches!(self.child.try_wait(), Ok(None))
}
async fn respawn(&mut self) -> Result<()> {
let args_ref: Vec<&str> = self.args.iter().map(String::as_str).collect();
let mut new_child = server_command(&self.binary, &args_ref, self.own_group)
.spawn()
.with_context(|| format!("failed to respawn MCP binary {}", self.binary))?;
let stdin = new_child
.stdin
.take()
.ok_or_else(|| anyhow!("child stdin not captured on respawn"))?;
let stdout = new_child
.stdout
.take()
.ok_or_else(|| anyhow!("child stdout not captured on respawn"))?;
self.kill_group();
let _ = self.child.start_kill();
self.child = new_child;
self.stdin = BufWriter::new(stdin);
self.stdout = BufReader::new(stdout);
self.line_buf = Vec::new();
self.discard_line = false;
self.initialize()
.await
.context("MCP initialize failed after respawn")?;
Ok(())
}
async fn ensure_alive(&mut self) -> Result<()> {
if !self.is_alive() {
warn!("StdioMcpClient: child process exited, attempting respawn");
self.respawn().await?;
}
Ok(())
}
pub(super) fn alloc_id(&self) -> u64 {
self.next_id.fetch_add(1, Ordering::Relaxed)
}
pub async fn initialize(&mut self) -> Result<ServerInfo> {
let id = self.alloc_id();
let req = build_initialize_request(id, &self.client_name);
let resp = self.request(&req, CALL_TIMEOUT).await?;
let result = extract_result(resp)?;
let server_info = result
.get("serverInfo")
.ok_or_else(|| anyhow!("initialize response missing serverInfo"))?;
let name = server_info
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let version = server_info
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let protocol_version = result
.get("protocolVersion")
.and_then(|v| v.as_str())
.unwrap_or(MCP_PROTOCOL_VERSION)
.to_string();
let notif = json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
});
self.write_line(¬if).await?;
Ok(ServerInfo {
name,
version,
protocol_version,
})
}
pub async fn list_tools(&mut self) -> Result<Vec<McpTool>> {
self.ensure_alive().await?;
let id = self.alloc_id();
let req = json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/list",
});
let resp = self.request(&req, CALL_TIMEOUT).await?;
let result = extract_result(resp)?;
let tools = result
.get("tools")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("tools/list response missing tools array"))?;
let mut out = Vec::with_capacity(tools.len());
for t in tools {
let name = t
.get("name")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow!("tool entry missing name"))?
.to_string();
let description = t
.get("description")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let input_schema = t.get("inputSchema").cloned().unwrap_or_else(|| json!({}));
out.push(McpTool {
name,
description,
input_schema,
});
}
Ok(out)
}
pub async fn call_tool(&mut self, name: &str, params: Value) -> Result<Value> {
self.call_tool_with_timeout(name, params, CALL_TIMEOUT)
.await
}
pub async fn call_tool_with_timeout(
&mut self,
name: &str,
params: Value,
call_timeout: Duration,
) -> Result<Value> {
self.ensure_alive().await?;
let id = self.alloc_id();
let req = json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": { "name": name, "arguments": params },
});
let resp = self.request(&req, call_timeout).await?;
extract_result(resp)
}
pub async fn ping(&mut self) -> Result<()> {
self.ensure_alive().await?;
let id = self.alloc_id();
let req = json!({
"jsonrpc": "2.0",
"id": id,
"method": "ping",
});
let _ = self.request(&req, CALL_TIMEOUT).await?;
Ok(())
}
async fn write_line(&mut self, value: &Value) -> Result<()> {
let bytes = serde_json::to_vec(value).context("serializing JSON-RPC frame")?;
self.stdin.write_all(&bytes).await?;
self.stdin.write_all(b"\n").await?;
self.stdin.flush().await?;
Ok(())
}
pub(super) async fn read_line(&mut self) -> Result<Value> {
loop {
let bytes = self.read_line_bytes().await?;
let line = String::from_utf8_lossy(&bytes);
let trimmed = line.trim_start();
if !trimmed.starts_with('{') {
debug!(
"StdioMcpClient: skipping non-JSON line from child stdout: {:?}",
log_field(line.trim_end())
);
continue;
}
let value: Value = serde_json::from_str(line.trim_end()).with_context(|| {
format!("parsing JSON-RPC frame: {:?}", log_field(line.trim_end()))
})?;
return Ok(value);
}
}
async fn read_line_bytes(&mut self) -> Result<Vec<u8>> {
let read = read_capped_line(
&mut self.stdout,
&mut self.line_buf,
&mut self.discard_line,
MAX_LINE_BYTES,
)
.await?;
match read {
CappedLine::Line(bytes) => Ok(bytes),
CappedLine::Eof => bail!("MCP server closed stdout before responding"),
CappedLine::TooLong => {
bail!("MCP server line exceeded the {MAX_LINE_BYTES}-byte cap; line discarded")
}
}
}
async fn request(&mut self, req: &Value, bound: Duration) -> Result<Value> {
let expected_id = req
.get("id")
.cloned()
.ok_or_else(|| anyhow!("request must carry an id"))?;
timeout(bound, async {
self.write_line(req).await?;
loop {
let frame = self.read_line().await?;
if is_response_to(&frame, &expected_id) {
return Ok::<Value, anyhow::Error>(frame);
}
log_skipped_frame(&frame, &expected_id);
}
})
.await
.map_err(|_| anyhow!("MCP request timed out after {bound:?}"))?
}
}
fn log_skipped_frame(frame: &Value, expected_id: &Value) {
let id = log_field(&frame.get("id").map(Value::to_string).unwrap_or_default());
let method = log_field(frame.get("method").and_then(Value::as_str).unwrap_or(""));
if frame.get("id") == Some(expected_id) {
warn!(expected = %expected_id, %method, "StdioMcpClient: skipping non-response frame with the awaited id");
} else {
debug!(expected = %expected_id, %id, %method, "StdioMcpClient: skipping non-matching frame");
}
}
const LOG_FIELD_CHARS: usize = 64;
pub fn log_field(s: &str) -> String {
match s.char_indices().nth(LOG_FIELD_CHARS) {
None => s.to_string(),
Some((cut, _)) => {
let rest = s[cut..].chars().count();
format!("{}…(+{rest})", &s[..cut])
}
}
}
pub fn is_response_to(frame: &Value, id: &Value) -> bool {
frame.get("id") == Some(id)
&& frame.get("method").is_none()
&& (frame.get("result").is_some() || frame.get("error").is_some())
}
fn server_command(binary: &str, args: &[&str], own_group: bool) -> Command {
let mut command = Command::new(binary);
command
.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(plugin_stderr_stdio(binary))
.kill_on_drop(true);
#[cfg(unix)]
if own_group {
command.process_group(0);
}
#[cfg(not(unix))]
let _ = own_group;
command
}