Files
leleka/control-plane/tests/mcp_hub/stdio_servers.rs
T

267 lines
8.6 KiB
Rust

//! MCP stdio servers: list, call, failure and restart.
use crate::harness::{hub, names, python, stdio};
use serde_json::{Value, json};
use leleka_control_plane::mcp::{Hub, McpError, Settings};
use tokio::sync::watch;
const TOOLS: [&str; 6] = ["echo", "fail", "sleep", "big", "die", "add"];
fn by_name(status: &Value, n: &str) -> Value {
status["servers"]
.as_array()
.unwrap()
.iter()
.find(|s| s["name"] == n)
.unwrap()
.clone()
}
/// initialize + tools/list over every page
fn assert_ready_servers_list_their_tools(status: &Value) {
assert_eq!(by_name(status, "fake")["status"], "ready");
assert_eq!(by_name(status, "fake")["transport"], "stdio");
assert_eq!(by_name(status, "fake")["info"]["name"], "fake");
assert_eq!(by_name(status, "fake")["info"]["protocol"], "2025-06-18");
let want: Vec<String> = TOOLS.iter().map(|t| format!("fake__{t}")).collect();
assert_eq!(names(status, "fake"), want);
assert_eq!(
names(status, "paged"),
TOOLS
.iter()
.map(|t| format!("paged__{t}"))
.collect::<Vec<_>>()
);
assert_eq!(status["tools"], 12);
assert_eq!(status["settings"]["max_result_chars"], 1000);
}
/// servers that do not start are left out, with the reason
fn assert_failed_servers_give_the_reason(status: &Value) {
assert_eq!(by_name(status, "broken")["status"], "failed");
assert!(
by_name(status, "broken")["error"]
.as_str()
.unwrap()
.contains("missing configuration"),
"{}",
by_name(status, "broken")
);
assert_eq!(by_name(status, "missing")["status"], "failed");
assert!(
by_name(status, "missing")["error"]
.as_str()
.unwrap()
.contains("could not start")
);
}
/// the tools in the chat template's form
async fn assert_template_tools(hub: &Hub) {
let tools = hub.template_tools(&["paged__echo".to_owned()]).await;
let echo = tools.iter().find(|t| t["name"] == "fake__echo").unwrap();
assert_eq!(echo["parameters"]["properties"]["text"]["type"], "string");
assert_eq!(echo["description"], "Returns the text it is given.");
assert!(tools.iter().all(|t| t["name"] != "paged__echo"));
assert_eq!(tools.len(), 11);
}
/// calls that answer, fail in text, or carry arguments that are not an object
async fn assert_calls_answer_or_fail_in_text(hub: &Hub) {
let r = hub
.call("fake__echo", json!({"text": "hello wörld"}), None)
.await
.unwrap();
assert_eq!(
(r.ok, r.text.as_str(), r.server.as_deref(), r.tool.as_str()),
(true, "hello wörld", Some("fake"), "echo")
);
assert_eq!(
hub.call("fake__add", json!({"a": 2, "b": 40}), None)
.await
.unwrap()
.text,
"42"
);
let r = hub.call("fake__fail", json!({}), None).await.unwrap();
assert!(!r.ok);
assert_eq!(r.text, "error: it failed on purpose");
assert_unknown_tool_is_refused(hub).await;
assert_non_object_arguments_become_empty(hub).await;
}
async fn assert_unknown_tool_is_refused(hub: &Hub) {
let r = hub.call("nobody__nothing", json!({}), None).await.unwrap();
assert!(
!r.ok && r.text.starts_with("error: there is no tool"),
"{}",
r.text
);
}
async fn assert_non_object_arguments_become_empty(hub: &Hub) {
// arguments that are not an object are sent as {}
assert_eq!(
hub.call("fake__echo", json!("x"), None).await.unwrap().text,
""
);
}
/// a JSON-RPC error from the server
async fn assert_a_json_rpc_error_is_reported(hub: &Hub) {
let fake = hub.servers.iter().find(|s| s.name == "fake").unwrap();
let error = fake
.call(
"no-such-tool",
json!({}),
std::time::Duration::from_secs(5),
None,
)
.await
.unwrap_err();
assert!(error.to_string().contains("unknown tool"), "{error}");
}
/// a call that outlasts the timeout, then the server still answers
async fn assert_a_slow_call_times_out(hub: &Hub) {
let started = std::time::Instant::now();
let r = hub
.call("fake__sleep", json!({"seconds": 5}), None)
.await
.unwrap();
assert!(started.elapsed().as_secs_f64() < 4.0);
assert!(!r.ok);
assert!(r.text.contains("timed out after 1.5 s"), "{}", r.text);
}
async fn assert_the_server_answers_after_a_timeout(hub: &Hub) {
assert_eq!(
hub.call("fake__echo", json!({"text": "still here"}), None)
.await
.unwrap()
.text,
"still here"
);
}
/// the result cap
async fn assert_a_big_result_is_capped(hub: &Hub) {
let r = hub
.call("fake__big", json!({"n": 50000}), None)
.await
.unwrap();
assert!(r.ok && r.truncated);
assert_eq!(r.chars, 50000);
assert!(
r.text
.starts_with(&format!("{}\n\n[... truncated", "y".repeat(1000)))
);
assert!(r.text.contains("50,000 characters"));
assert!(r.text.chars().count() < 1200);
}
/// cancellation reaches the server as notifications/cancelled
async fn assert_cancellation_reaches_the_server(hub: &Hub, log: &std::path::Path) {
let (stop, cancel) = watch::channel(false);
let canceller = tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let _ = stop.send(true);
});
let started = std::time::Instant::now();
let outcome = hub
.call("fake__sleep", json!({"seconds": 1.2}), Some(cancel))
.await;
assert_eq!(outcome.unwrap_err(), McpError::Cancelled);
assert!(started.elapsed().as_secs_f64() < 1.0);
canceller.await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
let seen = std::fs::read_to_string(log).unwrap();
assert!(seen.contains("\"cancelled\""), "{seen}");
}
/// The four servers of the first scenario: working, paged, crashing at start, missing.
fn scenario_hub(log: &std::path::PathBuf) -> Hub {
let settings = Settings {
timeout_s: 1.5,
max_result_chars: 1000,
..Settings::default()
};
hub(
vec![
("fake", stdio(&[], Some(log))),
("paged", stdio(&["--page", "4"], None)),
("broken", stdio(&["--crash-at-start"], None)),
(
"missing",
json!({"command": "strata-no-such-program"})
.as_object()
.unwrap()
.clone(),
),
],
settings,
)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn stdio_servers_list_call_and_fail_like_the_python_hub() {
if python().is_none() {
eprintln!("python3 not found: skipped");
return;
}
let log = std::env::temp_dir().join(format!("strata-mcp-{}.jsonl", std::process::id()));
let _ = std::fs::remove_file(&log);
let hub = scenario_hub(&log);
hub.start().await;
let status = hub.status().await;
assert_ready_servers_list_their_tools(&status);
assert_failed_servers_give_the_reason(&status);
assert_template_tools(&hub).await;
assert_calls_answer_or_fail_in_text(&hub).await;
assert_a_json_rpc_error_is_reported(&hub).await;
assert_a_slow_call_times_out(&hub).await;
assert_the_server_answers_after_a_timeout(&hub).await;
assert_a_big_result_is_capped(&hub).await;
assert_cancellation_reaches_the_server(&hub, &log).await;
hub.close().await;
let _ = std::fs::remove_file(&log);
}
async fn assert_dying_call_reports_the_stop(hub: &Hub) {
let r = hub.call("solo__die", json!({}), None).await.unwrap();
assert!(!r.ok);
assert!(r.text.contains("the server stopped"), "{}", r.text);
assert!(r.text.contains("dying on purpose"), "{}", r.text);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_server_that_dies_mid_call_is_started_again_by_the_next_call() {
if python().is_none() {
eprintln!("python3 not found: skipped");
return;
}
let hub = hub(
vec![("solo", stdio(&[], None))],
Settings {
timeout_s: 5.0,
..Settings::default()
},
);
hub.start().await;
assert_dying_call_reports_the_stop(&hub).await;
let status = hub.status().await;
assert_eq!(status["servers"][0]["status"], "stopped");
assert_eq!(
status["tools"], 6,
"its tools stay: the next call restarts it"
);
let r = hub
.call("solo__echo", json!({"text": "back"}), None)
.await
.unwrap();
assert_eq!(r.text, "back");
assert_eq!(hub.status().await["servers"][0]["status"], "ready");
hub.close().await;
}