refactor: Extract shared MCP Stdio NDJSON parsing loop into mcp-stdio library

This commit is contained in:
Riz Ashraf committed 2026-09-19 07:06:14 +01:00
1 parent f8c0d58415
commit 9009f127a9
8 files changed
+77 -80

No files matched your search

+2 -34
View File
@@ -12,40 +12,7 @@ struct Cli {
target: String,
}
async fn read_mcp_message(stdin: &mut tokio::io::BufReader<tokio::io::Stdin>) -> Option<String> {
use tokio::io::AsyncReadExt;
let mut length = 0;
loop {
let mut line = String::new();
let bytes_read = stdin.read_line(&mut line).await.unwrap_or(0);
if bytes_read == 0 {
tracing::info!("stdin EOF reached");
return None;
}
tracing::info!("Read {} bytes from stdin: {:?}", bytes_read, line);
if line.starts_with('{') {
return Some(line.trim_end().to_string());
}
let line = line.trim_end();
if line.is_empty() {
break;
}
let lower_line = line.to_lowercase();
if let Some(len_str) = lower_line.strip_prefix("content-length:") {
length = len_str.trim().parse().unwrap_or(0);
}
}
if length == 0 {
return None;
}
let mut buffer = vec![0; length];
if stdin.read_exact(&mut buffer).await.is_err() {
return None;
}
String::from_utf8(buffer).ok()
}
fn init_logging(app_name: &str) -> Option<tracing_appender::non_blocking::WorkerGuard> {
let mut base_dir = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
@@ -74,7 +41,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(async move {
let mut stdin = tokio::io::BufReader::new(tokio::io::stdin());
while let Some(msg) = read_mcp_message(&mut stdin).await {
while let Some(msg) = mcp_stdio::read_mcp_message(&mut stdin).await {
let _ = msg_tx.send(msg).await;
}
let _ = shutdown_tx.send(()).await;
@@ -190,3 +157,4 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
})
}