//! 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 s = TcpStream::connect(("127.0.0.1", self.port)).await.unwrap(); let host = format!("127.0.0.1:{}", self.port); let mut headers: Vec<(&str, &str)> = MCP_HEADERS.to_vec(); if let Some(sid) = sid { headers.push(("Mcp-Session-Id", sid)); } let req = common::request("POST", "/mcp", &host, &headers, Some(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 { 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 } 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}}}}}"# ); let (status, head, text) = self.post(&body, Some(sid)).await; assert_eq!(status, 200, "{head}\n{text}"); rpc(&text) } } /// 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() } #[tokio::test] async fn peer_argument_reads_through_the_consolidator() { let fake = FakeTransport::new(); fake.peer("beta").respond( "/api/v1/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, "/api/v1/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"); } #[tokio::test] async fn peer_failures_are_visible_tool_errors() { let fake = FakeTransport::new(); fake.peer("beta").respond_err( "/api/v1/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}"); }