use std::{
ffi::OsStr,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use agent_client_protocol::v1::schema::{EnvVariable, McpServerStdio, SessionUpdate};
use rmcp::{
model::{
CallToolRequestParams, CallToolResponse, CallToolResult, ListToolsResult,
PaginatedRequestParams, ServerConfig, Tool,
},
service::RequestContext,
ErrorData, RoleServer, ServerHandler, ServiceExt,
};
use tokio::{
io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader},
time::Instant,
};
pub(crate) use super::parked::AWAIT_TOOL;
use super::{
announced::Announced,
parked::{Parked, ANSWER_BY},
ToolCalls, SERVER_NAME,
};
use crate::daemon::{LocalConnected, LocalListener};
pub(crate) const RELAY_COMMAND: &str = "__session-tools";
pub(crate) const TOKEN_ENV: &str = "RHO_SESSION_TOOLS_TOKEN";
const TOKEN_BYTES: usize = 32;
const TOKEN_FRAME_BYTES: usize = TOKEN_BYTES * 2 + 1;
const TOKEN_WAIT: Duration = Duration::from_secs(10);
const ENDPOINT_PREFIX: &str = "rho-tools";
pub(super) struct Bridge {
declaration: McpServerStdio,
calls: Arc<BridgeCalls>,
_listening: AbortOnDrop,
}
impl Bridge {
pub(super) fn open(calls: ToolCalls) -> Result<Self, String> {
let program = relay_program(
crate::daemon::started_path(),
std::env::consts::EXE_SUFFIX,
std::env::current_exe(),
Path::is_file,
)?;
let (listener, address) = LocalListener::bind_private(ENDPOINT_PREFIX)
.map_err(|error| format!("could not listen on a private endpoint: {error}"))?;
let address = address
.into_string()
.map_err(|address| format!("the endpoint {} is not UTF-8", address.display()))?;
let token = crate::secrets::random_hex::<TOKEN_BYTES>();
let declaration = declare(program, address, token.clone());
let calls = Arc::new(BridgeCalls {
calls,
announced: Announced::default(),
parked: Parked::default(),
});
let listening = tokio::spawn(listen(listener, token.into(), Arc::clone(&calls)));
Ok(Self {
declaration,
calls,
_listening: AbortOnDrop(listening),
})
}
pub(super) fn declaration(&self) -> McpServerStdio {
self.declaration.clone()
}
pub(super) fn serves(&self, name: &str) -> bool {
name == AWAIT_TOOL
}
pub(super) fn heard(&self, update: &SessionUpdate, tool: Option<&str>) {
self.calls.announced.hear(update, tool);
}
}
fn declare(program: PathBuf, address: String, token: String) -> McpServerStdio {
McpServerStdio::new(SERVER_NAME, program)
.args(vec![RELAY_COMMAND.to_owned(), address])
.env(vec![EnvVariable::new(TOKEN_ENV, token)])
}
#[cfg(any(test, debug_assertions))]
pub(crate) fn relay_target(server: &McpServerStdio) -> Option<(&str, &str)> {
let [command, address] = server.args.as_slice() else {
return None;
};
let token = server.env.iter().find(|var| var.name == TOKEN_ENV)?;
(command == RELAY_COMMAND).then_some((address.as_str(), token.value.as_str()))
}
fn relay_program(
started: std::io::Result<PathBuf>,
suffix: &str,
current: std::io::Result<PathBuf>,
is_file: impl Fn(&Path) -> bool,
) -> Result<PathBuf, String> {
let mut tried = Vec::new();
if let Ok(started) = &started {
tried.push(started.clone());
if !suffix.is_empty() {
let mut suffixed = started.clone().into_os_string();
suffixed.push(suffix);
tried.push(PathBuf::from(suffixed));
}
}
if let Ok(current) = current {
if !tried.contains(¤t) {
tried.push(current);
}
}
if let Some(program) = tried.iter().find(|path| is_file(path.as_path())) {
return Ok(program.clone());
}
match (started, tried.is_empty()) {
(Err(error), true) => Err(format!("could not find rho's own executable: {error}")),
_ => {
let tried: Vec<_> = tried
.iter()
.map(|path| path.display().to_string())
.collect();
Err(format!(
"rho's executable is at none of {}",
tried.join(", ")
))
}
}
}
struct AbortOnDrop(tokio::task::JoinHandle<()>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
async fn listen(mut listener: LocalListener, token: Arc<str>, calls: Arc<BridgeCalls>) {
let over = calls.calls.over.clone();
loop {
let stream = tokio::select! {
() = over.cancelled() => return,
accepted = listener.accept() => match accepted {
Ok(stream) => stream,
Err(error) => {
tracing::warn!(%error, "rho's tools stopped taking the agent's connections");
return;
}
},
};
let (token, calls, over) = (Arc::clone(&token), Arc::clone(&calls), over.clone());
tokio::spawn(async move {
tokio::select! {
() = over.cancelled() => {}
() = serve(stream, &token, calls) => {}
}
});
}
}
async fn serve<S>(stream: S, token: &str, calls: Arc<BridgeCalls>)
where
S: AsyncRead + AsyncWrite + Send + 'static,
{
let (read, write) = tokio::io::split(stream);
let mut read = BufReader::new(read);
let mut frame = Vec::with_capacity(TOKEN_FRAME_BYTES);
let presented = tokio::time::timeout(
TOKEN_WAIT,
(&mut read)
.take(TOKEN_FRAME_BYTES as u64)
.read_until(b'\n', &mut frame),
)
.await;
if !matches!(presented, Ok(Ok(_))) || !admits(&frame, token) {
tracing::warn!(
"refused a connection to rho's tools that did not present the run's token within \
TOKEN_WAIT ({TOKEN_WAIT:?})"
);
return;
}
let server = BridgeServer { calls };
match server.serve((read, write)).await {
Ok(running) => {
let _ = running.waiting().await;
}
Err(error) => tracing::debug!(%error, "the agent's MCP client left rho's tools"),
}
}
fn admits(frame: &[u8], token: &str) -> bool {
frame
.strip_suffix(b"\n")
.is_some_and(|presented| crate::secrets::constant_time_eq(presented, token.as_bytes()))
}
struct BridgeCalls {
calls: ToolCalls,
announced: Announced,
parked: Parked,
}
impl BridgeCalls {
fn list(&self) -> Vec<Tool> {
let mut tools = self.calls.tools.list();
tools.push(super::parked::await_tool());
tools
}
async fn call(
&self,
name: String,
arguments: serde_json::Map<String, serde_json::Value>,
) -> Result<CallToolResult, ErrorData> {
let deadline = Instant::now() + ANSWER_BY;
self.calls
.serve_blocking(Some(deadline), async {
let key = self.announced.claim(&name, &arguments).await;
if name == AWAIT_TOOL {
if let Some(key) = key {
self.calls.hide(key);
}
return Ok(self.parked.wait(arguments).await);
}
let call = self
.calls
.start(name.clone(), arguments, key)
.map_err(|message| ErrorData::invalid_params(message, None))?;
Ok::<_, ErrorData>(self.parked.run(&name, call).await)
})
.await
}
}
#[derive(Clone)]
struct BridgeServer {
calls: Arc<BridgeCalls>,
}
impl ServerHandler for BridgeServer {
fn get_info(&self) -> ServerConfig {
super::server_config()
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
Ok(ListToolsResult::with_all_items(self.calls.list()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let result = self
.calls
.call(
request.name.into_owned(),
request.arguments.unwrap_or_default(),
)
.await?;
Ok(result.into())
}
}
pub(crate) async fn connect(address: &OsStr, token: &str) -> std::io::Result<LocalConnected> {
let mut stream = crate::daemon::connect_local(address).await?;
stream.write_all(format!("{token}\n").as_bytes()).await?;
Ok(stream)
}
pub(crate) async fn relay(address: &OsStr, token: &str) -> anyhow::Result<()> {
let stream = connect(address, token).await.map_err(|error| {
anyhow::anyhow!(
"could not reach rho's tools at {}: {error}",
address.display()
)
})?;
let (mut from_run, mut to_run) = tokio::io::split(stream);
let mut stdin = stdin_chunks();
let mut stdout = tokio::io::stdout();
let to_run = async {
while let Some(chunk) = stdin.recv().await {
to_run.write_all(&chunk?).await?;
}
to_run.shutdown().await
};
let from_run = async {
tokio::io::copy(&mut from_run, &mut stdout).await?;
stdout.flush().await
};
tokio::select! {
sent = to_run => sent?,
heard = from_run => heard?,
}
Ok(())
}
fn stdin_chunks() -> tokio::sync::mpsc::Receiver<std::io::Result<Vec<u8>>> {
use std::io::Read;
let (chunks, received) = tokio::sync::mpsc::channel(4);
std::thread::spawn(move || {
let mut stdin = std::io::stdin().lock();
let mut buffer = vec![0_u8; 64 * 1024];
loop {
let chunk = match stdin.read(&mut buffer) {
Ok(0) => return,
Ok(read) => Ok(buffer[..read].to_vec()),
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => Err(error),
};
let failed = chunk.is_err();
if chunks.blocking_send(chunk).is_err() || failed {
return;
}
}
});
received
}
#[cfg(test)]
#[path = "bridge_tests.rs"]
mod tests;