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()
}
#[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()])
);
}
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,
}
}
#[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,
));
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)),
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;
}