335 lines
11 KiB
Rust
335 lines
11 KiB
Rust
use super::*;
|
|
use std::path::PathBuf;
|
|
|
|
fn fake() -> PathBuf {
|
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_mcp.py")
|
|
}
|
|
|
|
fn stdio(extra: &str) -> Server {
|
|
let mut s: Server = serde_json::from_str(&format!(
|
|
r#"{{"command":"python3","args":["{}"]{extra}}}"#,
|
|
fake().display()
|
|
))
|
|
.unwrap();
|
|
s.timeout_secs.get_or_insert(10);
|
|
s
|
|
}
|
|
|
|
async fn hub(extra: &str) -> Arc<Hub> {
|
|
Arc::new(Hub::start(BTreeMap::from([("f".to_string(), stdio(extra))])).await)
|
|
}
|
|
|
|
fn cx() -> ToolCtx {
|
|
ToolCtx {
|
|
cwd: ".".into(),
|
|
state: Default::default(),
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn stdio_lazy_index_describe_call() {
|
|
let h = hub(r#","eager":false"#).await;
|
|
let s = &h.servers["f"];
|
|
assert_eq!(s.st().error, None);
|
|
assert_eq!(s.st().tools.len(), 5, "pagination followed");
|
|
assert!(!h.is_eager("f"));
|
|
let sp = h.system_prompt();
|
|
assert!(sp.contains("- f.echo: Echo a message back\n"), "{sp}");
|
|
assert!(!sp.contains("second line"));
|
|
assert!(sp.contains("mem://notes") && sp.contains("Use echo for tests."));
|
|
let st = h.status();
|
|
assert!(
|
|
st[0].contains("5 tools") && st[0].contains("lazy") && st[0].contains("index ~"),
|
|
"{st:?}"
|
|
);
|
|
|
|
let mut reg = hx_core::tool::Registry::default();
|
|
h.register(&mut reg);
|
|
let names: Vec<String> = reg.specs().into_iter().map(|s| s.name).collect();
|
|
assert_eq!(names, ["mcp_call", "mcp_describe", "mcp_read"]);
|
|
let d = reg
|
|
.call("mcp_describe", json!({"server":"f","tool":"add"}), &cx())
|
|
.await;
|
|
assert!(d.content.contains("\"required\":[\"a\",\"b\"]"), "{d:?}");
|
|
let r = reg
|
|
.call(
|
|
"mcp_call",
|
|
json!({"server":"f","tool":"add","arguments":{"a":2,"b":3}}),
|
|
&cx(),
|
|
)
|
|
.await;
|
|
assert_eq!(r, ToolResult::ok("5"));
|
|
// validation against cached schema: missing + wrong type, no server round trip
|
|
let r = reg
|
|
.call(
|
|
"mcp_call",
|
|
json!({"server":"f","tool":"add","arguments":{"a":"x"}}),
|
|
&cx(),
|
|
)
|
|
.await;
|
|
assert!(
|
|
r.is_error && r.content.contains("missing required argument `b`"),
|
|
"{r:?}"
|
|
);
|
|
let r = reg
|
|
.call("mcp_call", json!({"server":"f","tool":"nope"}), &cx())
|
|
.await;
|
|
assert!(r.is_error && r.content.contains("unknown tool"));
|
|
let r = reg
|
|
.call("mcp_read", json!({"server":"f","uri":"mem://notes"}), &cx())
|
|
.await;
|
|
assert_eq!(r, ToolResult::ok("note body"));
|
|
assert_eq!(
|
|
h.prompt("f", "review", "src/a.rs").await.unwrap(),
|
|
"Please review src/a.rs"
|
|
);
|
|
assert_eq!(
|
|
h.prompt("f", "review", "path=b.rs").await.unwrap(),
|
|
"Please review b.rs"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn eager_and_allowlist() {
|
|
// small schemas -> native tools, no mcp_call
|
|
assert!(spec_tokens(&hub("").await.servers["f"].st().tools) <= EAGER_MAX_TOKENS);
|
|
let h = hub(r#","allow":["echo","add"]"#).await;
|
|
assert!(h.is_eager("f"));
|
|
let mut reg = hx_core::tool::Registry::default();
|
|
h.register(&mut reg);
|
|
let names: Vec<String> = reg.specs().into_iter().map(|s| s.name).collect();
|
|
assert_eq!(names, ["f__add", "f__echo", "mcp_read"]);
|
|
assert!(!h.system_prompt().contains("# MCP tools"));
|
|
let r = reg.call("f__echo", json!({"message":"hi"}), &cx()).await;
|
|
assert_eq!(r, ToolResult::ok("echo: hi"));
|
|
// disallowed tool is not callable
|
|
assert!(h.call("f", "crash", json!({})).await.is_error);
|
|
// explicit eager=false wins over size
|
|
let h = hub(r#","allow":["echo"],"eager":false"#).await;
|
|
assert!(!h.is_eager("f"));
|
|
// explicit eager=true / size rule with a tiny budget
|
|
assert!(hub(r#","eager":true"#).await.is_eager("f"));
|
|
assert_eq!(native_name("my.srv", "a/b"), "my_srv__a_b");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn safety_cap_timeout_restart() {
|
|
let h = hub(r#","timeoutSecs":1"#).await;
|
|
let r = h.call("f", "big", json!({})).await;
|
|
assert!(
|
|
r.content.len() < OUTPUT_CAP + 100 && r.content.contains("[truncated"),
|
|
"{}",
|
|
r.content.len()
|
|
);
|
|
// stdio servers answer in order, so the timeout test gets its own process
|
|
let r = hub(r#","timeoutSecs":1"#)
|
|
.await
|
|
.call("f", "slow", json!({}))
|
|
.await;
|
|
assert!(r.is_error && r.content.contains("timed out"), "{r:?}");
|
|
// kill the server; next call reconnects
|
|
let r = h.call("f", "crash", json!({})).await;
|
|
assert!(r.is_error && r.content.contains("server exited"), "{r:?}");
|
|
let r = h.call("f", "echo", json!({"message":"back"})).await;
|
|
assert_eq!(r, ToolResult::ok("echo: back"));
|
|
// bounded restarts
|
|
for _ in 0..MAX_RESTARTS {
|
|
h.call("f", "crash", json!({})).await;
|
|
}
|
|
let r = h.call("f", "echo", json!({"message":"x"})).await;
|
|
assert!(r.content.contains("gave up"), "{r:?}");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn http_transport() {
|
|
let port = 30000 + std::process::id() % 20000;
|
|
let mut srv = tokio::process::Command::new("python3")
|
|
.arg(fake())
|
|
.args(["http", &port.to_string()])
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.unwrap();
|
|
let cfg: Server = serde_json::from_value(json!({
|
|
"type": "http", "url": format!("http://127.0.0.1:{port}/mcp"),
|
|
"headers": {"Authorization": "Bearer t0k"}
|
|
}))
|
|
.unwrap();
|
|
let mut h = Hub::default();
|
|
for _ in 0..50 {
|
|
h = Hub::start(BTreeMap::from([("w".to_string(), cfg.clone())])).await;
|
|
if h.servers["w"].st().error.is_none() {
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
}
|
|
assert_eq!(h.servers["w"].st().error, None);
|
|
assert_eq!(h.servers["w"].st().tools.len(), 5);
|
|
assert_eq!(
|
|
h.call("w", "echo", json!({"message":"sse"})).await,
|
|
ToolResult::ok("echo: sse")
|
|
);
|
|
// wrong token -> clear error
|
|
let mut bad = cfg.clone();
|
|
bad.headers
|
|
.insert("Authorization".into(), "Bearer no".into());
|
|
let h = Hub::start(BTreeMap::from([("w".to_string(), bad)])).await;
|
|
assert!(
|
|
h.servers["w"]
|
|
.st()
|
|
.error
|
|
.as_deref()
|
|
.unwrap_or("")
|
|
.contains("401"),
|
|
"{:?}",
|
|
h.servers["w"].st().error
|
|
);
|
|
let _ = srv.kill().await;
|
|
}
|
|
|
|
/// Reference server (@modelcontextprotocol/server-everything), only when npx has it cached.
|
|
#[tokio::test]
|
|
async fn reference_server_everything() {
|
|
let home = std::env::var("HOME").unwrap_or_default();
|
|
let cached = std::fs::read_dir(format!("{home}/.npm/_npx"))
|
|
.into_iter()
|
|
.flatten()
|
|
.flatten()
|
|
.any(|d| {
|
|
d.path()
|
|
.join("node_modules/@modelcontextprotocol/server-everything")
|
|
.exists()
|
|
});
|
|
if !cached {
|
|
eprintln!("skip: server-everything not cached");
|
|
return;
|
|
}
|
|
let cfg: Server = serde_json::from_value(json!({
|
|
"command": "npx", "args": ["-y", "--offline", "@modelcontextprotocol/server-everything"]
|
|
}))
|
|
.unwrap();
|
|
let h = Hub::start(BTreeMap::from([("e".to_string(), cfg)])).await;
|
|
assert_eq!(h.servers["e"].st().error, None);
|
|
assert!(h.tool("e", "echo").is_some() && h.tool("e", "get-sum").is_some());
|
|
assert_eq!(
|
|
h.call("e", "echo", json!({"message":"ref"})).await,
|
|
ToolResult::ok("Echo: ref")
|
|
);
|
|
assert!(
|
|
h.call("e", "get-sum", json!({"a":2,"b":3}))
|
|
.await
|
|
.content
|
|
.contains('5')
|
|
);
|
|
assert!(!h.servers["e"].st().prompts.is_empty() && !h.servers["e"].st().resources.is_empty());
|
|
assert!(
|
|
h.prompt("e", "simple-prompt", "")
|
|
.await
|
|
.unwrap()
|
|
.contains("simple prompt")
|
|
);
|
|
let uri = h.servers["e"].st().resources[0]["uri"]
|
|
.as_str()
|
|
.unwrap()
|
|
.to_string();
|
|
assert!(!h.read("e", &uri).await.is_error);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn http_oauth_login_and_refresh() {
|
|
let port = 20000 + std::process::id() % 20000;
|
|
let mut srv = tokio::process::Command::new("python3")
|
|
.arg(fake())
|
|
.args(["http", &port.to_string(), "oauth"])
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.unwrap();
|
|
let store = tempfile::tempdir().unwrap().keep().join("mcp-auth.json");
|
|
let mut cfg: Server = serde_json::from_value(json!({
|
|
"type": "http", "url": format!("http://127.0.0.1:{port}/mcp")
|
|
}))
|
|
.unwrap();
|
|
cfg.oauth.store = Some(store.clone());
|
|
let start = || async { Hub::start(BTreeMap::from([("o".to_string(), cfg.clone())])).await };
|
|
let mut h = Hub::default();
|
|
for _ in 0..50 {
|
|
h = start().await;
|
|
// server up once the error is the 401 (not a connection error)
|
|
if h.servers["o"]
|
|
.st()
|
|
.error
|
|
.as_deref()
|
|
.is_some_and(|e| e.contains("401"))
|
|
{
|
|
break;
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
}
|
|
let st = h.status().join("\n");
|
|
assert!(st.contains("hx mcp login o"), "{st}");
|
|
// login: the "browser" hits the redirect with the right state
|
|
oauth::login(&cfg, |u| {
|
|
let q: BTreeMap<String, String> = u
|
|
.split_once('?')
|
|
.unwrap()
|
|
.1
|
|
.split('&')
|
|
.filter_map(|kv| kv.split_once('='))
|
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
|
.collect();
|
|
assert_eq!(q["code_challenge_method"], "S256");
|
|
assert!(q["resource"].contains("%2Fmcp"), "{u}");
|
|
let redirect = q["redirect_uri"].replace("%3A", ":").replace("%2F", "/");
|
|
let url = format!("{redirect}?code=abc&state={}", q["state"]);
|
|
tokio::spawn(async move { reqwest::get(url).await });
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert!(oauth::logged_in(&cfg));
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
assert_eq!(
|
|
std::fs::metadata(&store).unwrap().permissions().mode() & 0o777,
|
|
0o600
|
|
);
|
|
}
|
|
// a1 is rejected by the server -> 401 -> forced refresh -> a2
|
|
let h = start().await;
|
|
assert_eq!(h.servers["o"].st().error, None);
|
|
assert_eq!(h.servers["o"].st().tools.len(), 5);
|
|
assert_eq!(
|
|
h.call("o", "echo", json!({"message":"auth"})).await,
|
|
ToolResult::ok("echo: auth")
|
|
);
|
|
oauth::logout(&cfg).unwrap();
|
|
assert!(!oauth::logged_in(&cfg));
|
|
let _ = srv.kill().await;
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn spawn_does_not_block_on_slow_server() {
|
|
let slow = stdio(r#","env":{"FAKE_INIT_DELAY":"2"}"#);
|
|
let t0 = std::time::Instant::now();
|
|
let h = Hub::spawn(BTreeMap::from([
|
|
("fast".to_string(), stdio("")),
|
|
("slow".to_string(), slow),
|
|
]));
|
|
assert!(t0.elapsed() < Duration::from_millis(200), "spawn blocked");
|
|
assert_eq!(h.pending().len(), 2);
|
|
// pending: status says connecting, describe/call wait for the slot instead of failing
|
|
assert!(h.status().iter().all(|l| l.contains("connecting")));
|
|
let r = h.call("fast", "echo", json!({"message":"hi"})).await;
|
|
assert_eq!(r, ToolResult::ok("echo: hi"));
|
|
assert_eq!(
|
|
h.pending(),
|
|
vec!["slow".to_string()],
|
|
"fast ready, slow still pending"
|
|
);
|
|
assert!(h.system_prompt().contains("still connecting: slow"));
|
|
h.wait_all(Duration::from_secs(10)).await;
|
|
assert!(h.pending().is_empty());
|
|
assert_eq!(h.servers["slow"].st().tools.len(), 5);
|
|
let r = h.call("slow", "echo", json!({"message":"late"})).await;
|
|
assert_eq!(r, ToolResult::ok("echo: late"));
|
|
}
|