//! MCP surface with a peer registry: the assembled router on an ephemeral //! port, fake sources and a fake peer transport. No sockets to peers. mod common; use std::time::Duration; use skyg_linux_tracker::config::Config; use skyg_linux_tracker::peers::testing::{fake_peers_config, registry_with, FakeTransport}; use skyg_linux_tracker::server; use skyg_linux_tracker::sources::fake::fake_state; use skyg_linux_tracker::state::AppState; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio_util::sync::CancellationToken; const WAIT: Duration = Duration::from_secs(2); struct Harness { port: u16, shutdown: CancellationToken, join: tokio::task::JoinHandle>, } impl Drop for Harness { fn drop(&mut self) { self.shutdown.cancel(); self.join.abort(); } } async fn start(state: AppState) -> Harness { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); let shutdown = state.shutdown.clone(); let app = server::build_router(state); let join = tokio::spawn(server::serve_listener( listener, None, app, shutdown.clone(), server::Limits::default(), )); Harness { port, shutdown, join, } } fn peers_state(fake: &std::sync::Arc) -> AppState { let mut config = Config::default(); config.auth.enabled = false; let reg = registry_with(fake.clone(), fake_peers_config(&["beta", "gamma"])); skyg_linux_tracker::peers::testing::fake_state_with_peers(config, reg) } fn local_state() -> AppState { let mut config = Config::default(); config.auth.enabled = false; fake_state(config) } const MCP_HEADERS: [(&str, &str); 2] = [ ("Content-Type", "application/json"), ("Accept", "application/json, text/event-stream"), ]; fn init_body() -> &'static str { r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"it","version":"0"}}}"# } impl Harness { async fn post(&self, body: &str, sid: Option<&str>) -> (u16, String, String) { let mut headers: Vec<(&str, &str)> = MCP_HEADERS.to_vec(); if let Some(sid) = sid { headers.push(("Mcp-Session-Id", sid)); } self.send("/mcp", &headers, Some(body)).await } async fn get(&self, path: &str) -> (u16, String, String) { self.send(path, &[], None).await } /// One request on a fresh connection, read to close. async fn send( &self, path: &str, headers: &[(&str, &str)], body: Option<&str>, ) -> (u16, String, String) { let method = if body.is_some() { "POST" } else { "GET" }; let mut s = TcpStream::connect(("127.0.0.1", self.port)).await.unwrap(); let host = format!("127.0.0.1:{}", self.port); let req = common::request(method, path, &host, headers, body); s.write_all(req.as_bytes()).await.unwrap(); let mut buf = Vec::new(); let _ = tokio::time::timeout(WAIT, async { let mut chunk = [0u8; 4096]; loop { match s.read(&mut chunk).await { Ok(0) | Err(_) => break, Ok(n) => buf.extend_from_slice(&chunk[..n]), } } }) .await; common::parse_response(&buf) } async fn open(&self) -> String { self.init().await.0 } async fn init(&self) -> (String, serde_json::Value) { let (status, head, body) = self.post(init_body(), None).await; assert_eq!(status, 200, "{head}\n{body}"); let sid = head .lines() .find_map(|l| l.strip_prefix("mcp-session-id: ")) .expect("session id") .trim() .to_owned(); let (status, _, _) = self .post( r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, Some(&sid), ) .await; assert_eq!(status, 202); (sid, rpc(&body)) } async fn rpc(&self, sid: &str, body: &str) -> serde_json::Value { let (status, head, text) = self.post(body, Some(sid)).await; assert_eq!(status, 200, "{head}\n{text}"); rpc(&text) } async fn call(&self, sid: &str, id: u32, tool: &str, arguments: &str) -> serde_json::Value { let body = format!( r#"{{"jsonrpc":"2.0","id":{id},"method":"tools/call","params":{{"name":"{tool}","arguments":{arguments}}}}}"# ); self.rpc(sid, &body).await } async fn resource_uris(&self, sid: &str) -> Vec { let v = self .rpc(sid, r#"{"jsonrpc":"2.0","id":2,"method":"resources/list"}"#) .await; v["result"]["resources"] .as_array() .unwrap() .iter() .map(|r| r["uri"].as_str().unwrap().to_owned()) .collect() } async fn tools(&self, sid: &str) -> Vec { let v = self .rpc(sid, r#"{"jsonrpc":"2.0","id":9,"method":"tools/list"}"#) .await; v["result"]["tools"].as_array().expect("tools").clone() } } /// First JSON-RPC message in the body, whether it came as JSON or SSE. fn rpc(text: &str) -> serde_json::Value { let mut candidates = Vec::new(); if let Ok(v) = serde_json::from_str::(text.trim()) { candidates.push(v); } for line in text.lines() { if let Some(data) = line.strip_prefix("data: ") { if let Ok(v) = serde_json::from_str(data) { candidates.push(v); } } } candidates .into_iter() .find(|v| v.get("result").is_some() || v.get("error").is_some()) .unwrap_or_else(|| panic!("no JSON-RPC response in {text:?}")) } fn result_text(v: &serde_json::Value) -> String { v["result"]["content"][0]["text"] .as_str() .unwrap_or_else(|| panic!("no text content in {v}")) .to_owned() } fn tool<'a>(tools: &'a [serde_json::Value], name: &str) -> &'a serde_json::Value { tools .iter() .find(|t| t["name"] == name) .unwrap_or_else(|| panic!("tool {name} missing from {tools:?}")) } #[tokio::test] async fn tool_list_is_ten_with_peers_and_eight_without() { let fake = FakeTransport::new(); let h = start(peers_state(&fake)).await; let sid = h.open().await; let tools = h.tools(&sid).await; let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); names.sort(); // A fixture, not read back from the router: renaming or dropping a tool // has to be an explicit edit here too. assert_eq!( names.join(","), "get_container,get_container_logs,get_journal_logs,get_peer,get_systemd_unit,\ list_containers,list_peers,list_systemd_timers,list_systemd_units,tail_journal" ); let units = tool(&tools, "list_systemd_units"); assert!( units["inputSchema"]["properties"]["peer"].is_object(), "{units}" ); assert!( units["inputSchema"]["required"] .as_array() .is_none_or(|r| r.is_empty()), "peer and state are optional: {units}" ); let h = start(local_state()).await; let sid = h.open().await; let tools = h.tools(&sid).await; let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); names.sort(); assert_eq!(names.len(), 8, "{names:?}"); assert!(!names.contains(&"list_peers")); assert!(!names.contains(&"get_peer")); for t in &tools { let props = &t["inputSchema"]["properties"]; assert!( props.get("peer").is_none(), "{} must not advertise peer when peers are off: {t}", t["name"] ); assert!( !t["description"].as_str().unwrap_or("").contains("peer"), "{}", t["name"] ); } } #[tokio::test] async fn list_peers_and_get_peer_tools() { let fake = FakeTransport::new(); let h = start(peers_state(&fake)).await; let sid = h.open().await; let v = h.call(&sid, 2, "list_peers", "{}").await; assert_eq!(v["result"]["isError"], false, "{v}"); let body: serde_json::Value = serde_json::from_str(&result_text(&v)).unwrap(); let mut names: Vec<&str> = body["peers"] .as_array() .unwrap() .iter() .map(|p| p["name"].as_str().unwrap()) .collect(); names.sort(); assert_eq!(names, ["beta", "gamma"]); assert!(body["peers"][0].get("server").is_some()); let v = h.call(&sid, 3, "get_peer", r#"{"name":"beta"}"#).await; assert_eq!(v["result"]["isError"], false, "{v}"); let v = h.call(&sid, 4, "get_peer", r#"{"name":"nope"}"#).await; assert_eq!(v["result"]["isError"], true, "{v}"); assert!(result_text(&v).contains("not_found"), "{v}"); } #[tokio::test] async fn peer_tools_are_absent_without_configuration() { let h = start(local_state()).await; let sid = h.open().await; let v = h.call(&sid, 2, "list_peers", "{}").await; let error = &v["error"]; assert!(error.is_object(), "{v}"); assert!( error["message"] .as_str() .unwrap_or("") .contains("tool not found"), "{v}" ); } #[tokio::test] async fn peer_argument_reads_through_the_consolidator() { let fake = FakeTransport::new(); fake.peer("beta").respond( "/systemd/units", 200, "application/json", r#"[{"name":"peer-only.service","active_state":"failed"}]"#, ); let h = start(peers_state(&fake)).await; let sid = h.open().await; let v = h .call( &sid, 2, "list_systemd_units", r#"{"state":"failed","peer":"beta"}"#, ) .await; assert_eq!(v["result"]["isError"], false, "{v}"); let units: serde_json::Value = serde_json::from_str(&result_text(&v)).unwrap(); assert_eq!(units[0]["name"], "peer-only.service"); let calls = fake.calls(); assert_eq!(calls.len(), 1); assert_eq!(calls[0].1.path, "/systemd/units"); assert_eq!( calls[0].1.query, vec![("state".to_owned(), "failed".to_owned())] ); assert!(calls[0] .1 .headers .iter() .all(|(k, _)| k.as_str() != "authorization")); // Without `peer` the same instance still reads its own host. let v = h .call(&sid, 3, "list_systemd_units", r#"{"state":"failed"}"#) .await; let units: serde_json::Value = serde_json::from_str(&result_text(&v)).unwrap(); assert_eq!(units[0]["name"], "nginx.service"); assert_eq!(fake.calls().len(), 1, "local calls never reach a peer"); } /// Both surfaces classify a peer status with the same table, so a client /// sees one error per peer answer whichever it uses. #[tokio::test] async fn rest_and_mcp_report_the_same_peer_status_errors() { let rows = [ (400, 503, "unavailable", "peer beta: http_400"), (404, 404, "not_found", "peer beta: not found on peer"), ( 401, 503, "unavailable", "peer beta: peer rejected credentials", ), (500, 503, "unavailable", "peer beta: http_500"), ]; for (peer_status, http_status, code, message) in rows { let fake = FakeTransport::new(); fake.peer("beta") .respond("/systemd/units", peer_status, "application/json", "{}"); let h = start(peers_state(&fake)).await; let (status, head, body) = h.get("/api/v1/peers/beta/systemd/units").await; assert_eq!(status, http_status, "peer {peer_status}: {head}\n{body}"); let rest: serde_json::Value = serde_json::from_str(&body).unwrap(); assert_eq!(rest["error"]["code"], code, "peer {peer_status}: {rest}"); assert_eq!( rest["error"]["message"], message, "peer {peer_status}: {rest}" ); assert_eq!( head.lines() .find_map(|l| l.strip_prefix("x-slinuxm-peer: ")) .map(str::trim), Some("beta"), "{head}" ); let sid = h.open().await; let v = h .call(&sid, 2, "list_systemd_units", r#"{"peer":"beta"}"#) .await; assert_eq!(v["result"]["isError"], true, "peer {peer_status}: {v}"); let text = result_text(&v); assert!( text.starts_with(&format!("{code}: {message}.")), "peer {peer_status} over MCP: {text}" ); } } #[tokio::test] async fn peer_failures_are_visible_tool_errors() { let fake = FakeTransport::new(); fake.peer("beta").respond_err( "/systemd/units", skyg_linux_tracker::peers::PeerError::Rejected, ); let h = start(peers_state(&fake)).await; let sid = h.open().await; let v = h .call(&sid, 2, "list_systemd_units", r#"{"peer":"beta"}"#) .await; assert_eq!(v["result"]["isError"], true, "{v}"); assert!( result_text(&v).contains("peer beta: peer rejected credentials"), "{v}" ); let v = h .call(&sid, 3, "list_systemd_units", r#"{"peer":"nope"}"#) .await; assert_eq!(v["result"]["isError"], true, "{v}"); assert!(result_text(&v).contains("unknown peer"), "{v}"); } #[tokio::test] async fn peer_argument_without_configuration_is_a_tool_error() { let h = start(local_state()).await; let sid = h.open().await; let v = h .call(&sid, 2, "list_systemd_units", r#"{"peer":"beta"}"#) .await; assert_eq!(v["result"]["isError"], true, "{v}"); assert!(result_text(&v).contains("peer beta: unknown peer"), "{v}"); } #[tokio::test] async fn instructions_and_prompts_mention_peers_only_when_enabled() { let fake = FakeTransport::new(); let h = start(peers_state(&fake)).await; let (sid, init) = h.init().await; let instructions = init["result"]["instructions"].as_str().unwrap(); assert!(instructions.contains("list_peers"), "{instructions}"); assert!(instructions.contains("untrusted data"), "{instructions}"); let v = h .rpc(&sid, r#"{"jsonrpc":"2.0","id":2,"method":"prompts/list"}"#) .await; for prompt in v["result"]["prompts"].as_array().unwrap() { let args = prompt["arguments"].as_array().cloned().unwrap_or_default(); let peer = args.iter().find(|a| a["name"] == "peer"); assert!( peer.is_some(), "{} must advertise the peer argument: {prompt}", prompt["name"] ); assert_ne!(peer.unwrap()["required"], true); } let v = h .rpc( &sid, r#"{"jsonrpc":"2.0","id":3,"method":"prompts/get","params":{"name":"diagnose_unit","arguments":{"name":"nginx.service","peer":"beta"}}}"#, ) .await; let text = v["result"]["messages"][0]["content"]["text"] .as_str() .unwrap(); assert!(text.contains("peer `beta`"), "{text}"); assert!(text.contains("untrusted data"), "{text}"); // Peers off: no peer arguments, no peer wording. let h = start(local_state()).await; let (sid, init) = h.init().await; let instructions = init["result"]["instructions"].as_str().unwrap(); assert!( !instructions.to_ascii_lowercase().contains("peer"), "{instructions}" ); let v = h .rpc(&sid, r#"{"jsonrpc":"2.0","id":2,"method":"prompts/list"}"#) .await; for prompt in v["result"]["prompts"].as_array().unwrap() { for arg in prompt["arguments"].as_array().cloned().unwrap_or_default() { assert_ne!(arg["name"], "peer", "{}", prompt["name"]); } } } #[tokio::test] async fn peers_status_resource() { let fake = FakeTransport::new(); let h = start(peers_state(&fake)).await; let sid = h.open().await; let uris = h.resource_uris(&sid).await; assert!(uris.iter().any(|u| u == "peers://status"), "{uris:?}"); let v = h .rpc( &sid, r#"{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"peers://status"}}"#, ) .await; let text = v["result"]["contents"][0]["text"].as_str().unwrap(); let status: serde_json::Value = serde_json::from_str(text).unwrap(); assert_eq!(status["peers"].as_array().unwrap().len(), 2, "{status}"); // Absent entirely when peers are off: not listed, not readable. let h = start(local_state()).await; let sid = h.open().await; let uris = h.resource_uris(&sid).await; assert!(!uris.iter().any(|u| u == "peers://status"), "{uris:?}"); let v = h .rpc( &sid, r#"{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"peers://status"}}"#, ) .await; assert!(v["error"].is_object(), "{v}"); }