rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{collections::BTreeMap, path::Path, sync::Arc};

use pretty_assertions::assert_eq;
use rho_sdk::{
    model::ToolSpec,
    tool::{Tool, ToolContext, ToolFuture, ToolInvocation},
};
use serde_json::json;

use super::{McpChanges, McpDiscovery, McpHost};
use crate::tools::mcp::{
    config::{McpConfig, McpSamplingPolicy, McpServerConfig, McpToolFilter, McpTransport},
    McpAuthorizationMode, McpBundle, McpReloadChanges, McpRoots, McpSessionOptions,
    McpSessionReport, MCP_CONNECT_TEST_LOCK,
};

struct Named(&'static str);

impl Tool for Named {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: self.0.into(),
            description: String::new(),
            input_schema: json!({"type": "object"}),
        }
    }

    fn call<'a>(&'a self, _invocation: ToolInvocation, _context: ToolContext) -> ToolFuture<'a> {
        unreachable!("never called")
    }
}

fn named(tools: &[Arc<dyn Tool>]) -> Vec<String> {
    tools.iter().map(|tool| tool.spec().name).collect()
}

// Failure mode: two reloads in one turn hand the tool set a tool to remove
// that it never listed (the first reload added it, the second retired it),
// or drop a retirement, so a closed server's tool stays callable.
// Owner layer: MCP host change accumulation.
#[test]
fn a_later_reload_cancels_what_an_earlier_one_added() {
    let listed: Arc<dyn Tool> = Arc::new(Named("listed"));
    let brief: Arc<dyn Tool> = Arc::new(Named("brief"));
    let lasting: Arc<dyn Tool> = Arc::new(Named("lasting"));
    let mut changes = McpChanges {
        report: McpSessionReport::default(),
        retired: vec![Arc::clone(&listed)],
        added: vec![Arc::clone(&brief), Arc::clone(&lasting)],
    };

    changes.merge(McpChanges {
        report: McpSessionReport::default(),
        retired: vec![brief],
        added: Vec::new(),
    });

    assert_eq!(
        (named(&changes.retired), named(&changes.added)),
        (vec!["listed".to_owned()], vec!["lasting".to_owned()])
    );
}

/// A stdio server that appends its tool's name to `log` as it starts, then
/// answers `initialize` only once the file `gate` exists.
const GATED_SERVER: &str = r#"import json, os, sys, time
log, gate, tool = sys.argv[1], sys.argv[2], sys.argv[3]
with open(log, "a") as f:
    f.write(tool + "\n")
for line in sys.stdin:
    message = json.loads(line)
    if "id" not in message:
        continue
    method = message.get("method")
    if method == "initialize":
        while not os.path.exists(gate):
            time.sleep(0.01)
        result = {
            "protocolVersion": message["params"]["protocolVersion"],
            "capabilities": {"tools": {}},
            "serverInfo": {"name": "rho-test", "version": "1"}
        }
    elif method == "tools/list":
        result = {"tools": [{"name": tool, "inputSchema": {"type": "object"}}]}
    else:
        result = {}
    print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True)
"#;

fn gated(directory: &Path, tool: &str, gate: &Path) -> McpServerConfig {
    McpServerConfig {
        enabled: true,
        tools: McpToolFilter::default(),
        log_level: None,
        sampling: McpSamplingPolicy::Deny,
        transport: McpTransport::Stdio {
            command: "python3".into(),
            args: vec![
                directory.join("server.py").display().to_string(),
                directory.join("log").display().to_string(),
                gate.display().to_string(),
                tool.to_owned(),
            ],
            cwd: None,
            env: BTreeMap::new(),
            env_from_env: BTreeMap::new(),
            env_from_secret: Vec::new(),
        },
        filesystem: None,
    }
}

// Failure mode: a turn cancelled while `mcp_reload` waits on a slow server
// drops the running servers the reload took out, so they never close, and
// the next reload starts everything again beside their tools.
// Owner layer: MCP host reload.
#[tokio::test]
async fn a_reload_its_caller_stops_waiting_for_still_puts_the_servers_back() {
    let _guard = MCP_CONNECT_TEST_LOCK.lock().await;
    let directory = tempfile::tempdir().unwrap();
    std::fs::write(directory.path().join("server.py"), GATED_SERVER).unwrap();
    let open = directory.path().join("open");
    std::fs::write(&open, "").unwrap();
    let gate = directory.path().join("gate");
    let running = McpConfig {
        servers: BTreeMap::from([(
            "running".to_owned(),
            gated(directory.path(), "running_tool", &open),
        )]),
        invalid_servers: Vec::new(),
    };
    let mut added = running.clone();
    added.servers.insert(
        "slow".to_owned(),
        gated(directory.path(), "slow_tool", &gate),
    );
    let options = McpSessionOptions::new(
        12_000,
        McpRoots::default(),
        McpAuthorizationMode::NonInteractive,
        crate::session_environment::SessionEnvironment::default(),
    );
    let host = McpHost::default();
    let connected = McpBundle::connect(&running, options.clone()).await;
    host.attach(connected.bundle, connected.catalog);
    host.allow_reload(options, crate::tools::mcp::McpSecretAsks::Unavailable);
    host.set_discovery(McpDiscovery::new(
        directory.path().join("config.toml"),
        Clone::clone,
    ));

    // The caller stops waiting once the slow server has started, as a
    // cancelled turn drops its tool call.
    let log = directory.path().join("log");
    tokio::select! {
        _ = host.reload(&added) => panic!("the slow server answered before its gate opened"),
        () = async {
            while !std::fs::read_to_string(&log).unwrap_or_default().contains("slow_tool") {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        } => {}
    }
    std::fs::write(&gate, "").unwrap();
    let (again, _) = host.reload(&added).await.unwrap();

    assert_eq!(
        (
            again,
            host.take_changes().map(|changes| named(&changes.added)),
            // Lines, since Python writes `\r\n` on Windows.
            std::fs::read_to_string(&log)
                .unwrap()
                .lines()
                .map(str::to_owned)
                .collect::<Vec<_>>(),
        ),
        (
            McpReloadChanges {
                kept: vec!["running".to_owned(), "slow".to_owned()],
                started: Vec::new(),
                stopped: Vec::new(),
            },
            Some(vec!["mcp__slow__slow_tool".to_owned()]),
            vec!["running_tool".to_owned(), "slow_tool".to_owned()],
        )
    );
    host.close().await;
}