refactor: Extract shared MCP Stdio NDJSON parsing loop into mcp-stdio library
This commit is contained in:
1 parent
f8c0d58415
commit
9009f127a9
8 files changed
+77
-80
No files matched your search
@@ -16,6 +16,7 @@ tracing = "0.1.44"
|
||||
tracing-subscriber = "0.3.23"
|
||||
dirs = "7.0.0"
|
||||
serde_json = "1.0.151"
|
||||
mcp-stdio = { version = "0.1.0", path = "../mcp-stdio" }
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-34
@@ -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(())
|
||||
})
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user