rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The fake agent's MCP client of the stdio server its session declared,
//! as agy runs rho's stdio bridge ([`super::Script::stdio_mcp`]).

use std::sync::{Arc, Mutex};

use agent_client_protocol::{v1::schema::McpServer, Error};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, Lines};

use super::{fake_error, Record};
use crate::acp_runtime::agent_tools::bridge;

/// The stdio MCP server the agent starts as its session sets up, and what
/// it sends that server before it answers the setup.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct StdioMcpScript {
    /// How the agent reaches the server.
    pub(crate) how: StdioMcp,
    /// JSON-RPC messages sent, in order, before the setup is answered, as
    /// agy discovers and lists a server while it sets the session up; a
    /// request's reply is recorded.
    #[serde(default)]
    pub(crate) setup: Vec<Value>,
}

/// How the agent reaches the stdio MCP server its session declared.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum StdioMcp {
    /// Runs the declared command, with the declared arguments and
    /// environment, as agy does.
    Spawn,
    /// Connects to rho's bridge as the declared relay would, in process,
    /// for tests whose binary is no rho to run.
    Connect,
}

type Writer = Box<dyn AsyncWrite + Send + Unpin>;
type Reader = Box<dyn AsyncRead + Send + Unpin>;

/// The agent's MCP client of the stdio server its session started.
pub(super) struct StdioClient {
    write: Writer,
    read: Lines<BufReader<Reader>>,
    /// The server's process, when the agent ran one; killed as this drops.
    _child: Option<tokio::process::Child>,
}

/// The stdio client the session started, if any, for the turns to use.
pub(super) type SharedStdio = Arc<tokio::sync::Mutex<Option<StdioClient>>>;

impl StdioClient {
    /// Starts the first stdio server of `servers` as `how` says.
    async fn start(servers: &[McpServer], how: StdioMcp) -> Result<Self, Error> {
        let server = servers
            .iter()
            .find_map(|server| match server {
                McpServer::Stdio(server) => Some(server),
                _ => None,
            })
            .ok_or_else(|| fake_error("the session declared no stdio MCP server"))?;
        match how {
            StdioMcp::Spawn => {
                let mut child = tokio::process::Command::new(&server.command)
                    .args(&server.args)
                    .envs(server.env.iter().map(|var| (&var.name, &var.value)))
                    .stdin(std::process::Stdio::piped())
                    .stdout(std::process::Stdio::piped())
                    .kill_on_drop(true)
                    .spawn()
                    .map_err(|error| {
                        fake_error(&format!("could not start the MCP server: {error}"))
                    })?;
                let write: Writer = Box::new(child.stdin.take().expect("piped stdin"));
                let read: Reader = Box::new(child.stdout.take().expect("piped stdout"));
                Ok(Self::of(write, read, Some(child)))
            }
            StdioMcp::Connect => {
                let (address, token) = bridge::relay_target(server)
                    .ok_or_else(|| fake_error("the stdio MCP server is no rho relay"))?;
                let stream = bridge::connect(std::ffi::OsStr::new(address), token)
                    .await
                    .map_err(|error| fake_error(&format!("could not reach the bridge: {error}")))?;
                let (read, write) = tokio::io::split(stream);
                Ok(Self::of(Box::new(write), Box::new(read), None))
            }
        }
    }

    fn of(write: Writer, read: Reader, child: Option<tokio::process::Child>) -> Self {
        Self {
            write,
            read: BufReader::new(read).lines(),
            _child: child,
        }
    }

    /// Sends `message`; for a request, returns the server's reply to it,
    /// or `{"closed": true}` should the server close first.
    async fn exchange(&mut self, message: &Value) -> Value {
        let sent = async {
            self.write
                .write_all(format!("{message}\n").as_bytes())
                .await?;
            self.write.flush().await
        };
        if sent.await.is_err() {
            return json!({"closed": true});
        }
        let Some(id) = message.get("id") else {
            return Value::Null;
        };
        loop {
            match self.read.next_line().await {
                Ok(Some(line)) => {
                    let Ok(reply) = serde_json::from_str::<Value>(&line) else {
                        continue;
                    };
                    // A notification or a request of the server's own.
                    if reply.get("id") == Some(id) && reply.get("method").is_none() {
                        return reply;
                    }
                }
                Ok(None) | Err(_) => return json!({"closed": true}),
            }
        }
    }
}

/// Starts the stdio server of `servers` that a session setup declared, as
/// `script` says, into `stdio`, and sends it the script's setup messages.
pub(super) async fn start(
    stdio: &SharedStdio,
    record: &Mutex<Record>,
    servers: &[McpServer],
    script: StdioMcpScript,
) -> Result<(), Error> {
    *stdio.lock().await = Some(StdioClient::start(servers, script.how).await?);
    send(stdio, record, script.setup).await;
    Ok(())
}

/// Sends `messages` to the session's stdio server in order, recording each
/// request's reply.
pub(super) async fn send(stdio: &SharedStdio, record: &Mutex<Record>, messages: Vec<Value>) {
    let mut stdio = stdio.lock().await;
    for message in messages {
        let reply = match stdio.as_mut() {
            Some(client) => client.exchange(&message).await,
            None => json!({"closed": true}),
        };
        if !reply.is_null() {
            record
                .lock()
                .expect("script record")
                .push_reply(json!({"method": "stdio/mcp", "result": reply}));
        }
    }
}