mcp-rb/ext/mcp/src/stdio_transport.rs
Joshua Coles 96ae3b2198 Stash
2025-03-17 15:55:55 +00:00

34 lines
1.1 KiB
Rust

use jsonrpsee::core::async_trait;
use jsonrpsee::core::client::{ReceivedMessage, TransportReceiverT, TransportSenderT};
use std::sync::Arc;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWriteExt};
use tokio::sync::Mutex;
pub struct Adapter<T>(pub Arc<Mutex<T>>);
#[async_trait]
impl<T: Unpin + Send + 'static + AsyncWriteExt> TransportSenderT for Adapter<T> {
type Error = tokio::io::Error;
#[tracing::instrument(skip(self), level = "trace")]
async fn send(&mut self, msg: String) -> Result<(), Self::Error> {
let mut guard = self.0.lock().await;
guard.write_all(msg.as_bytes()).await?;
guard.write_all(b"\n").await?;
Ok(())
}
}
#[async_trait]
impl<T: AsyncBufRead + Unpin + Send + 'static> TransportReceiverT for Adapter<T> {
type Error = tokio::io::Error;
#[tracing::instrument(skip(self), level = "trace")]
async fn receive(&mut self) -> Result<ReceivedMessage, Self::Error> {
let mut str = String::new();
self.0.lock().await.read_line(&mut str).await?;
Ok(ReceivedMessage::Text(str))
}
}