D: D1 optional peer argument on the eight tools
Peers resolve through PeerRegistry::get, the same entry point REST uses,
so the hop marker, allowlist and error mapping stay in one place. Log
tools keep the local {entries, truncated, note} shape; tail_journal
consumes the peer SSE stream. Tests cover every tool, path encoding,
error mapping and the integration path through the assembled router.
This commit is contained in:
1 parent
95fac95389
commit
d3285a994b
3 files changed
+1187
-74
No files matched your search
+537
-74
@@ -4,6 +4,7 @@
|
||||
//! Pinned `rmcp` 3.5.1 validates `Host` and `Origin` itself; `service`
|
||||
//! feeds it loopback names, `server.bind` and the configured extras.
|
||||
|
||||
pub mod peers;
|
||||
pub mod prompts;
|
||||
pub mod resources;
|
||||
|
||||
@@ -53,12 +54,16 @@ const TAIL_BACKLOG: usize = 10;
|
||||
pub struct ListUnitsParams {
|
||||
/// Filter on active state: `active`, `inactive`, `failed`, `activating`, `deactivating`, `reloading`. Omit for all units.
|
||||
pub state: Option<String>,
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
pub struct NameParams {
|
||||
/// Unit name (e.g. `nginx.service`) or container name/id.
|
||||
pub name: String,
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -69,6 +74,8 @@ pub struct JournalParams {
|
||||
pub priority: Option<Priority>,
|
||||
/// Number of most recent entries (default 100, capped by the server).
|
||||
pub lines: Option<usize>,
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
@@ -79,6 +86,8 @@ pub struct TailJournalParams {
|
||||
#[serde(default = "default_seconds")]
|
||||
#[schemars(range(min = 0, max = 3600))]
|
||||
pub seconds: u64,
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
fn default_seconds() -> u64 {
|
||||
@@ -91,6 +100,15 @@ pub struct ContainerLogsParams {
|
||||
pub name: String,
|
||||
/// Number of most recent lines (default 100, capped by the server).
|
||||
pub tail: Option<usize>,
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
/// The two list tools take no arguments of their own, only the optional peer.
|
||||
#[derive(Debug, Deserialize, JsonSchema, Default)]
|
||||
pub struct PeerOnlyParams {
|
||||
/// Name of a configured peer; omit for this host.
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
/// Per-session MCP handler. Holds the shared state.
|
||||
@@ -202,6 +220,9 @@ impl TrackerService {
|
||||
&self,
|
||||
Parameters(p): Parameters<ListUnitsParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::units(&self.state, peer, p.state.as_deref()).await;
|
||||
}
|
||||
json_result(self.state.systemd.list_units(p.state.as_deref()).await)
|
||||
}
|
||||
|
||||
@@ -212,13 +233,22 @@ impl TrackerService {
|
||||
&self,
|
||||
Parameters(p): Parameters<NameParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::unit(&self.state, peer, &p.name).await;
|
||||
}
|
||||
json_result(self.state.systemd.unit_status(&p.name).await)
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "List systemd timers with the unit each activates, next_elapse and last_trigger. Use it to explain scheduled jobs and why something ran at a given time."
|
||||
)]
|
||||
async fn list_systemd_timers(&self) -> Result<CallToolResult, ErrorData> {
|
||||
async fn list_systemd_timers(
|
||||
&self,
|
||||
Parameters(p): Parameters<PeerOnlyParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::timers(&self.state, peer).await;
|
||||
}
|
||||
json_result(self.state.systemd.list_timers().await)
|
||||
}
|
||||
|
||||
@@ -230,6 +260,17 @@ impl TrackerService {
|
||||
Parameters(p): Parameters<JournalParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let cap = self.state.config.limits.max_lines;
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::journal(
|
||||
&self.state,
|
||||
peer,
|
||||
p.unit.as_deref(),
|
||||
p.priority,
|
||||
p.lines,
|
||||
cap,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let q = JournalQuery {
|
||||
unit: p.unit,
|
||||
priority: p.priority,
|
||||
@@ -252,6 +293,9 @@ impl TrackerService {
|
||||
&self,
|
||||
Parameters(p): Parameters<TailJournalParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::tail_journal(&self.state, peer, &p.unit, p.seconds).await;
|
||||
}
|
||||
let limits = &self.state.config.limits;
|
||||
let secs = p.seconds.min(limits.max_follow_secs);
|
||||
let entry_cap = limits.max_lines;
|
||||
@@ -300,7 +344,13 @@ impl TrackerService {
|
||||
#[tool(
|
||||
description = "List all Docker containers (running and stopped) with state (`running`, `restarting`, `exited`, `paused`, `dead`, `created`), health (`healthy`, `unhealthy`, `starting`, or none when no health check is defined), uptime and restart_count."
|
||||
)]
|
||||
async fn list_containers(&self) -> Result<CallToolResult, ErrorData> {
|
||||
async fn list_containers(
|
||||
&self,
|
||||
Parameters(p): Parameters<PeerOnlyParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::containers(&self.state, peer).await;
|
||||
}
|
||||
json_result(self.state.docker.ps(true).await)
|
||||
}
|
||||
|
||||
@@ -311,6 +361,9 @@ impl TrackerService {
|
||||
&self,
|
||||
Parameters(p): Parameters<NameParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::container(&self.state, peer, &p.name).await;
|
||||
}
|
||||
json_result(self.state.docker.container_status(&p.name).await)
|
||||
}
|
||||
|
||||
@@ -321,8 +374,12 @@ impl TrackerService {
|
||||
&self,
|
||||
Parameters(p): Parameters<ContainerLogsParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let cap = self.state.config.limits.max_tail;
|
||||
if let Some(peer) = p.peer.as_deref() {
|
||||
return peers::container_logs(&self.state, peer, &p.name, p.tail, cap).await;
|
||||
}
|
||||
let opts = LogOptions {
|
||||
tail: Some(clamp_count(p.tail, self.state.config.limits.max_tail)),
|
||||
tail: Some(clamp_count(p.tail, cap)),
|
||||
since: None,
|
||||
};
|
||||
json_result(
|
||||
@@ -468,7 +525,11 @@ pub fn service(state: AppState) -> StreamableHttpService<TrackerService, LocalSe
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::Config;
|
||||
use crate::peers::testing::{
|
||||
fake_peers_config, fake_state_with_peers, registry_with, FakeTransport,
|
||||
};
|
||||
use crate::sources::fake::fake_state;
|
||||
use rmcp::model::GetPromptResult;
|
||||
|
||||
fn svc() -> TrackerService {
|
||||
TrackerService::new(fake_state(Config::default()))
|
||||
@@ -481,75 +542,58 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn no_peer() -> Parameters<PeerOnlyParams> {
|
||||
Parameters(PeerOnlyParams::default())
|
||||
}
|
||||
|
||||
fn name_param(n: &str) -> Parameters<NameParams> {
|
||||
Parameters(NameParams { name: n.into() })
|
||||
Parameters(NameParams {
|
||||
name: n.into(),
|
||||
peer: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_list_snapshot() {
|
||||
let mut tools = TrackerService::tool_router().list_all();
|
||||
tools.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let names: Vec<&str> = tools.iter().map(|t| &*t.name).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"get_container",
|
||||
"get_container_logs",
|
||||
"get_journal_logs",
|
||||
"get_systemd_unit",
|
||||
"list_containers",
|
||||
"list_systemd_timers",
|
||||
"list_systemd_units",
|
||||
"tail_journal"
|
||||
]
|
||||
);
|
||||
let required: Vec<Vec<String>> = tools
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let mut r: Vec<String> = t
|
||||
.input_schema
|
||||
.get("required")
|
||||
.and_then(|r| r.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
r.sort();
|
||||
r
|
||||
fn tools(svc: &TrackerService) -> Vec<rmcp::model::Tool> {
|
||||
svc.tool_router.list_all()
|
||||
}
|
||||
|
||||
fn prop_names(t: &rmcp::model::Tool) -> Vec<String> {
|
||||
let mut v: Vec<String> = t
|
||||
.input_schema
|
||||
.get("properties")
|
||||
.and_then(|p| p.as_object())
|
||||
.map(|p| p.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
fn required_names(t: &rmcp::model::Tool) -> Vec<String> {
|
||||
let mut v: Vec<String> = t
|
||||
.input_schema
|
||||
.get("required")
|
||||
.and_then(|r| r.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let want: Vec<Vec<&str>> = vec![
|
||||
vec!["name"],
|
||||
vec!["name"],
|
||||
vec![],
|
||||
vec!["name"],
|
||||
vec![],
|
||||
vec![],
|
||||
vec![],
|
||||
vec!["unit"],
|
||||
];
|
||||
assert_eq!(required, want);
|
||||
for t in &tools {
|
||||
assert!(
|
||||
t.description.as_deref().unwrap_or("").len() > 40,
|
||||
"{}",
|
||||
t.name
|
||||
);
|
||||
assert_eq!(t.input_schema["type"], "object", "{}", t.name);
|
||||
}
|
||||
.unwrap_or_default();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_has_capabilities_and_instructions() {
|
||||
let info = svc().get_info();
|
||||
assert!(info.capabilities.tools.is_some());
|
||||
assert!(info.capabilities.prompts.is_some());
|
||||
let res = info.capabilities.resources.as_ref().unwrap();
|
||||
assert!(!res.subscribe.unwrap_or(false));
|
||||
assert!(info.instructions.unwrap().contains("failed"));
|
||||
}
|
||||
/// The eight shared tools with their local-only property sets.
|
||||
const LOCAL_PROPERTIES: [(&str, &[&str], &[&str]); 8] = [
|
||||
("get_container", &["name"], &["name"]),
|
||||
("get_container_logs", &["name", "tail"], &["name"]),
|
||||
("get_journal_logs", &["lines", "priority", "unit"], &[]),
|
||||
("get_systemd_unit", &["name"], &["name"]),
|
||||
("list_containers", &[], &[]),
|
||||
("list_systemd_timers", &[], &[]),
|
||||
("list_systemd_units", &["state"], &[]),
|
||||
("tail_journal", &["seconds", "unit"], &["unit"]),
|
||||
];
|
||||
|
||||
#[tokio::test]
|
||||
async fn happy_paths() {
|
||||
@@ -557,6 +601,7 @@ mod tests {
|
||||
let v = json(
|
||||
s.list_systemd_units(Parameters(ListUnitsParams {
|
||||
state: Some("failed".into()),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -571,7 +616,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(v["n_restarts"], 5);
|
||||
|
||||
let v = json(s.list_systemd_timers().await.unwrap());
|
||||
let v = json(s.list_systemd_timers(no_peer()).await.unwrap());
|
||||
assert_eq!(v[0]["name"], "logrotate.timer");
|
||||
|
||||
let v = json(
|
||||
@@ -579,6 +624,7 @@ mod tests {
|
||||
unit: Some("nginx.service".into()),
|
||||
priority: Some(Priority::Err),
|
||||
lines: Some(5),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -586,7 +632,7 @@ mod tests {
|
||||
assert_eq!(v["entries"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(v["truncated"], false);
|
||||
|
||||
let v = json(s.list_containers().await.unwrap());
|
||||
let v = json(s.list_containers(no_peer()).await.unwrap());
|
||||
let first = v[0]["name"].as_str().unwrap().to_owned();
|
||||
|
||||
let v = json(s.get_container(name_param(&first)).await.unwrap());
|
||||
@@ -596,6 +642,7 @@ mod tests {
|
||||
s.get_container_logs(Parameters(ContainerLogsParams {
|
||||
name: first,
|
||||
tail: Some(2),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -608,12 +655,13 @@ mod tests {
|
||||
let mut cfg = Config::default();
|
||||
cfg.limits.max_tail = 1;
|
||||
let s = TrackerService::new(fake_state(cfg));
|
||||
let v = json(s.list_containers().await.unwrap());
|
||||
let v = json(s.list_containers(no_peer()).await.unwrap());
|
||||
let name = v[0]["name"].as_str().unwrap().to_owned();
|
||||
let v = json(
|
||||
s.get_container_logs(Parameters(ContainerLogsParams {
|
||||
name,
|
||||
tail: Some(500),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -634,6 +682,7 @@ mod tests {
|
||||
unit: None,
|
||||
priority: None,
|
||||
lines: Some(500),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -678,6 +727,7 @@ mod tests {
|
||||
s.tail_journal(Parameters(TailJournalParams {
|
||||
unit: "nginx.service".into(),
|
||||
seconds: 3600,
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -696,6 +746,7 @@ mod tests {
|
||||
.tail_journal(Parameters(TailJournalParams {
|
||||
unit: "nginx.service".into(),
|
||||
seconds: 0,
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -711,6 +762,7 @@ mod tests {
|
||||
s.tail_journal(Parameters(TailJournalParams {
|
||||
unit: "nginx.service".into(),
|
||||
seconds: 60,
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
});
|
||||
@@ -733,6 +785,7 @@ mod tests {
|
||||
s.tail_journal(Parameters(TailJournalParams {
|
||||
unit: "nginx.service".into(),
|
||||
seconds: 30,
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
@@ -740,20 +793,63 @@ mod tests {
|
||||
assert_eq!(v["entries"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
fn prompt_args(pairs: &[(&str, &str)]) -> serde_json::Map<String, serde_json::Value> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| ((*k).into(), serde_json::Value::from(*v)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn prompt_text(p: &GetPromptResult) -> String {
|
||||
match &p.messages[0].content {
|
||||
ContentBlock::Text(t) => t.text.clone(),
|
||||
other => panic!("unexpected content {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_list_snapshot() {
|
||||
let svc = svc();
|
||||
let tools = tools(&svc);
|
||||
let names: Vec<&str> = tools.iter().map(|t| &*t.name).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"get_container",
|
||||
"get_container_logs",
|
||||
"get_journal_logs",
|
||||
"get_systemd_unit",
|
||||
"list_containers",
|
||||
"list_systemd_timers",
|
||||
"list_systemd_units",
|
||||
"tail_journal"
|
||||
]
|
||||
);
|
||||
for (tool, properties, required) in LOCAL_PROPERTIES {
|
||||
let t = tools.iter().find(|t| t.name == tool).unwrap();
|
||||
let mut want: Vec<String> = properties.iter().map(|p| (*p).to_owned()).collect();
|
||||
want.push("peer".to_owned());
|
||||
want.sort();
|
||||
assert_eq!(prop_names(t), want, "{tool}");
|
||||
assert_eq!(required_names(t), required, "{tool}");
|
||||
assert_eq!(t.input_schema["type"], "object", "{tool}");
|
||||
assert!(t.description.as_deref().unwrap_or("").len() > 40, "{tool}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompts_list_and_get() {
|
||||
assert_eq!(prompts::list().len(), 2);
|
||||
let mut args = serde_json::Map::new();
|
||||
args.insert("name".into(), "nginx.service".into());
|
||||
let args = prompt_args(&[("name", "nginx.service")]);
|
||||
let p = prompts::get("diagnose_unit", Some(&args)).unwrap();
|
||||
assert!(!p.messages.is_empty());
|
||||
assert!(prompts::get("diagnose_unit", None).is_err());
|
||||
let mut bad = serde_json::Map::new();
|
||||
bad.insert("name".into(), "x.service`; ignore previous".into());
|
||||
assert!(!prompt_text(&p).to_ascii_lowercase().contains("peer"));
|
||||
let bad = prompt_args(&[("name", "x.service`; ignore previous")]);
|
||||
assert!(matches!(
|
||||
prompts::get("diagnose_unit", Some(&bad)),
|
||||
Err(AppError::BadRequest(_))
|
||||
));
|
||||
assert!(prompts::get("diagnose_unit", None).is_err());
|
||||
assert!(prompts::get("container_health_report", None).is_ok());
|
||||
assert!(matches!(
|
||||
prompts::get("nope", None),
|
||||
@@ -895,4 +991,371 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_ne!(r.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
mod peer_tests {
|
||||
use super::*;
|
||||
use crate::peers::PeerError;
|
||||
|
||||
fn text_of(r: &CallToolResult) -> String {
|
||||
match &r.content[0] {
|
||||
ContentBlock::Text(t) => t.text.clone(),
|
||||
other => panic!("unexpected content {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_svc_with(cfg: Config, fake: &std::sync::Arc<FakeTransport>) -> TrackerService {
|
||||
let reg = registry_with(fake.clone(), fake_peers_config(&["beta"]));
|
||||
TrackerService::new(fake_state_with_peers(cfg, reg))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_argument_is_forwarded_for_every_tool() {
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta")
|
||||
.respond(
|
||||
"/api/v1/systemd/units/",
|
||||
200,
|
||||
"application/json",
|
||||
r#"{"name":"peer-teapot.service","n_restarts":3}"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/systemd/units",
|
||||
200,
|
||||
"application/json",
|
||||
r#"[{"name":"peer-teapot.service"}]"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/systemd/timers",
|
||||
200,
|
||||
"application/json",
|
||||
r#"[{"name":"peer.timer"}]"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/journal",
|
||||
200,
|
||||
"application/json",
|
||||
r#"[{"message":"peer journal line"}]"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/docker/containers/peer-ctr/logs",
|
||||
200,
|
||||
"application/json",
|
||||
r#"[{"name":"peer-ctr"}]"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/docker/containers/",
|
||||
200,
|
||||
"application/json",
|
||||
r#"{"name":"peer-ctr"}"#,
|
||||
)
|
||||
.respond(
|
||||
"/api/v1/docker/ps",
|
||||
200,
|
||||
"application/json",
|
||||
r#"[{"name":"peer-ctr"}]"#,
|
||||
);
|
||||
let s = peer_svc_with(Config::default(), &fake);
|
||||
|
||||
let v = json(
|
||||
s.list_systemd_units(Parameters(ListUnitsParams {
|
||||
state: Some("failed".into()),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v[0]["name"], "peer-teapot.service");
|
||||
|
||||
let v = json(
|
||||
s.get_systemd_unit(Parameters(NameParams {
|
||||
name: "peer-teapot.service".into(),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v["n_restarts"], 3);
|
||||
|
||||
let v = json(
|
||||
s.list_systemd_timers(Parameters(PeerOnlyParams {
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v[0]["name"], "peer.timer");
|
||||
|
||||
// Log-shaped tools keep the local `{entries, truncated, note}` shape.
|
||||
let v = json(
|
||||
s.get_journal_logs(Parameters(JournalParams {
|
||||
unit: Some("nginx.service".into()),
|
||||
priority: Some(Priority::Err),
|
||||
lines: Some(5),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v["entries"][0]["message"], "peer journal line");
|
||||
assert_eq!(v["truncated"], false);
|
||||
|
||||
let v = json(
|
||||
s.list_containers(Parameters(PeerOnlyParams {
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v[0]["name"], "peer-ctr");
|
||||
|
||||
let v = json(
|
||||
s.get_container(Parameters(NameParams {
|
||||
name: "peer-ctr".into(),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v["name"], "peer-ctr");
|
||||
|
||||
let v = json(
|
||||
s.get_container_logs(Parameters(ContainerLogsParams {
|
||||
name: "peer-ctr".into(),
|
||||
tail: Some(2),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v["entries"][0]["name"], "peer-ctr");
|
||||
|
||||
let calls = fake.calls();
|
||||
let paths: Vec<&str> = calls.iter().map(|(_, r)| r.path.as_str()).collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
[
|
||||
"/api/v1/systemd/units",
|
||||
"/api/v1/systemd/units/peer-teapot.service",
|
||||
"/api/v1/systemd/timers",
|
||||
"/api/v1/journal",
|
||||
"/api/v1/docker/ps",
|
||||
"/api/v1/docker/containers/peer-ctr",
|
||||
// Docker logs share the container prefix; the script answers both.
|
||||
"/api/v1/docker/containers/peer-ctr/logs",
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
calls[0].1.query,
|
||||
vec![("state".to_owned(), "failed".to_owned())]
|
||||
);
|
||||
assert_eq!(
|
||||
calls[1].1.query,
|
||||
Vec::<(String, String)>::new(),
|
||||
"no query on a detail path"
|
||||
);
|
||||
let journal = &calls[3].1.query;
|
||||
assert!(journal.contains(&("unit".to_owned(), "nginx.service".to_owned())));
|
||||
assert!(journal.contains(&("priority".to_owned(), "err".to_owned())));
|
||||
assert!(journal.contains(&("lines".to_owned(), "5".to_owned())));
|
||||
assert_eq!(
|
||||
calls[4].1.query,
|
||||
vec![("all".to_owned(), "true".to_owned())]
|
||||
);
|
||||
assert_eq!(calls[6].1.query, vec![("tail".to_owned(), "2".to_owned())]);
|
||||
for (peer, req) in &calls {
|
||||
assert_eq!(peer.as_str(), "beta");
|
||||
let header = |name: &str| {
|
||||
req.headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == name)
|
||||
.map(|(_, v)| v.to_str().unwrap())
|
||||
};
|
||||
assert_eq!(header("x-slinuxm-hop"), Some("1"));
|
||||
assert_eq!(
|
||||
header("authorization"),
|
||||
None,
|
||||
"caller credentials never forwarded"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_tools_do_not_touch_the_peer_transport() {
|
||||
let fake = FakeTransport::new();
|
||||
let s = peer_svc_with(Config::default(), &fake);
|
||||
let v = json(
|
||||
s.list_systemd_units(Parameters(ListUnitsParams {
|
||||
state: Some("failed".into()),
|
||||
peer: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v[0]["name"], "nginx.service");
|
||||
assert!(fake.calls().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_tail_journal_consumes_the_follow_stream() {
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta").stream(
|
||||
"/api/v1/journal/follow",
|
||||
vec![
|
||||
bytes::Bytes::from_static(
|
||||
b"event: journal\ndata: {\"message\":\"one\"}\n\n",
|
||||
),
|
||||
bytes::Bytes::from_static(
|
||||
b"event: journal\ndata: {\"message\":\"two\"}\n\nevent: end\ndata: closed\n\n",
|
||||
),
|
||||
],
|
||||
);
|
||||
let s = peer_svc_with(Config::default(), &fake);
|
||||
let start = tokio::time::Instant::now();
|
||||
let v = json(
|
||||
s.tail_journal(Parameters(TailJournalParams {
|
||||
unit: "nginx.service".into(),
|
||||
seconds: 30,
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_secs(5),
|
||||
"a closed peer stream must return at once"
|
||||
);
|
||||
assert_eq!(v["entries"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(v["entries"][1]["message"], "two");
|
||||
let calls = fake.calls();
|
||||
assert_eq!(calls[0].1.path, "/api/v1/journal/follow");
|
||||
assert_eq!(calls[0].1.accept.as_deref(), Some("text/event-stream"));
|
||||
assert!(v["note"].as_str().unwrap().contains("closed the stream"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_failures_are_tool_errors() {
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta")
|
||||
.respond_err("/api/v1/systemd/units", PeerError::Rejected)
|
||||
.respond("/api/v1/systemd/timers", 503, "application/json", "{}")
|
||||
.respond("/api/v1/journal", 200, "application/json", "not json");
|
||||
let s = peer_svc_with(Config::default(), &fake);
|
||||
|
||||
let r = s
|
||||
.list_systemd_units(Parameters(ListUnitsParams {
|
||||
state: None,
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
let text = text_of(&r);
|
||||
assert!(
|
||||
text.contains("peer beta: peer rejected credentials"),
|
||||
"{text}"
|
||||
);
|
||||
|
||||
let r = s
|
||||
.list_systemd_timers(Parameters(PeerOnlyParams {
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(
|
||||
text_of(&r).contains("peer beta: http_503"),
|
||||
"{}",
|
||||
text_of(&r)
|
||||
);
|
||||
|
||||
let r = s
|
||||
.get_journal_logs(Parameters(JournalParams {
|
||||
unit: None,
|
||||
priority: None,
|
||||
lines: None,
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(
|
||||
text_of(&r).contains("peer beta: malformed response"),
|
||||
"{}",
|
||||
text_of(&r)
|
||||
);
|
||||
|
||||
let r = s
|
||||
.list_systemd_timers(Parameters(PeerOnlyParams {
|
||||
peer: Some("nope".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(text_of(&r).contains("unknown peer"), "{}", text_of(&r));
|
||||
|
||||
// A peer artefact that is not in the registry never reaches the transport.
|
||||
let r = s
|
||||
.get_systemd_unit(Parameters(NameParams {
|
||||
name: "..".into(),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(text_of(&r).contains("invalid unit name"), "{}", text_of(&r));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_argument_without_peers_is_a_tool_error() {
|
||||
let s = svc();
|
||||
let r = s
|
||||
.list_systemd_units(Parameters(ListUnitsParams {
|
||||
state: None,
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(
|
||||
text_of(&r).contains("peer beta: unknown peer"),
|
||||
"{}",
|
||||
text_of(&r)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_paths_encode_and_clamp_like_the_rest_routes() {
|
||||
let fake = FakeTransport::new();
|
||||
fake.peer("beta")
|
||||
.respond("/api/v1/systemd/units/", 200, "application/json", "{}")
|
||||
.respond("/api/v1/docker/containers/", 200, "application/json", "[]");
|
||||
let mut cfg = Config::default();
|
||||
cfg.limits.max_tail = 1;
|
||||
let s = peer_svc_with(cfg, &fake);
|
||||
|
||||
let _ = s
|
||||
.get_systemd_unit(Parameters(NameParams {
|
||||
name: r"dev-disk-by\x2did.device".into(),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = s
|
||||
.get_container_logs(Parameters(ContainerLogsParams {
|
||||
name: "/web-1".into(),
|
||||
tail: Some(500),
|
||||
peer: Some("beta".into()),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = fake.calls();
|
||||
assert_eq!(
|
||||
calls[0].1.path,
|
||||
"/api/v1/systemd/units/dev-disk-by%5Cx2did.device"
|
||||
);
|
||||
assert_eq!(calls[1].1.path, "/api/v1/docker/containers/web-1/logs");
|
||||
assert_eq!(calls[1].1.query, vec![("tail".to_owned(), "1".to_owned())]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
//! Peer-aware MCP surface: argument-to-path mapping, forwarding through the
|
||||
//! shared registry and status summaries.
|
||||
//!
|
||||
//! Every peer request goes through [`PeerRegistry::get`], the same entry point
|
||||
//! REST uses, so allowlists, the hop marker and error mapping stay in one
|
||||
//! place. No URL or header is built here.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::StreamExt;
|
||||
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
|
||||
use rmcp::model::{CallToolResult, ContentBlock};
|
||||
use rmcp::ErrorData;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{capped, json_result, tool_error, MAX_RESULT_BYTES, TAIL_BACKLOG};
|
||||
use crate::error::AppError;
|
||||
use crate::peers::error::{peer_error_to_app, PeerError};
|
||||
use crate::peers::transport::{PeerBody, PeerResponse};
|
||||
use crate::peers::{PeerName, ProxyOpts};
|
||||
use crate::sources::docker::normalize_name;
|
||||
use crate::sources::systemd::validate_unit_name;
|
||||
use crate::sources::{clamp_count, Priority};
|
||||
use crate::state::AppState;
|
||||
|
||||
async fn fetch(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
path: &str,
|
||||
query: Vec<(String, String)>,
|
||||
accept_sse: bool,
|
||||
) -> Result<PeerResponse, AppError> {
|
||||
let reg = state
|
||||
.peers
|
||||
.as_deref()
|
||||
.ok_or_else(|| AppError::NotFound(format!("peer {peer}: unknown peer")))?;
|
||||
let opts = ProxyOpts {
|
||||
traceparent: None,
|
||||
accept_sse,
|
||||
};
|
||||
reg.get(peer, path, &query, opts).await
|
||||
}
|
||||
|
||||
/// The transport turns normal statuses into `PeerError`; this keeps a scripted
|
||||
/// or passthrough 4xx/5xx from rendering as success. The peer's error body is
|
||||
/// not echoed: it is untrusted text and the mapping has fixed wording.
|
||||
fn status_error(peer: &str, status: u16) -> AppError {
|
||||
let Ok(name) = PeerName::parse(peer) else {
|
||||
return AppError::NotFound(format!("peer {peer}: unknown peer"));
|
||||
};
|
||||
let e = match status {
|
||||
401 | 403 => PeerError::Rejected,
|
||||
404 => PeerError::NotFound,
|
||||
400 | 422 => PeerError::BadRequest("bad request".into()),
|
||||
other => PeerError::Http(other),
|
||||
};
|
||||
peer_error_to_app(&name, &e)
|
||||
}
|
||||
|
||||
fn ok_text(text: String) -> CallToolResult {
|
||||
CallToolResult::success(vec![ContentBlock::text(text)])
|
||||
}
|
||||
|
||||
/// Peer JSON is returned verbatim so the shape is the peer's, not a copy.
|
||||
///
|
||||
/// Bodies above the result cap are cut at a char boundary with a marker. List
|
||||
/// sizes are bounded in practice, so this is a guard rather than a path the
|
||||
/// tools normally take.
|
||||
fn json_text(bytes: &Bytes) -> CallToolResult {
|
||||
let text = String::from_utf8_lossy(bytes).into_owned();
|
||||
if text.len() <= MAX_RESULT_BYTES {
|
||||
return ok_text(text);
|
||||
}
|
||||
let mut cut = MAX_RESULT_BYTES;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
ok_text(format!(
|
||||
"{}\n... output truncated to {} KiB (peer response was {} bytes)",
|
||||
&text[..cut],
|
||||
MAX_RESULT_BYTES / 1024,
|
||||
text.len()
|
||||
))
|
||||
}
|
||||
|
||||
fn body_bytes(peer: &str, resp: PeerResponse) -> Result<Bytes, AppError> {
|
||||
match resp.body {
|
||||
PeerBody::Bytes(b) if (200..300).contains(&resp.status) => Ok(b),
|
||||
PeerBody::Bytes(_) => Err(status_error(peer, resp.status)),
|
||||
PeerBody::Stream(_) => Err(AppError::Internal(format!(
|
||||
"peer {peer}: unexpected stream"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
async fn forward_json(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
path: &str,
|
||||
query: Vec<(String, String)>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let body = match fetch(state, peer, path, query, false).await {
|
||||
Ok(resp) => match body_bytes(peer, resp) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
},
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
Ok(json_text(&body))
|
||||
}
|
||||
|
||||
/// Forward a GET whose answer is a flat JSON array of entries and cap it the
|
||||
/// way the local log tools do, so `peer` and local results share one shape.
|
||||
async fn forward_entries(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
path: &str,
|
||||
query: Vec<(String, String)>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let body = match fetch(state, peer, path, query, false).await {
|
||||
Ok(resp) => match body_bytes(peer, resp) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
},
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
let Ok(entries) = serde_json::from_slice::<Vec<Value>>(&body) else {
|
||||
let e = AppError::Internal(format!("peer {peer}: malformed response"));
|
||||
return Ok(tool_error(&e));
|
||||
};
|
||||
json_result(Ok::<_, AppError>(capped(entries, true, None)))
|
||||
}
|
||||
|
||||
/// Percent-encode one path segment. The name validators already reject
|
||||
/// separators; this keeps the few unusual characters unit names may contain
|
||||
/// (such as a backslash) out of the URL structure.
|
||||
fn segment(raw: &str) -> String {
|
||||
const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
|
||||
.remove(b'-')
|
||||
.remove(b'.')
|
||||
.remove(b'_')
|
||||
.remove(b'~')
|
||||
.remove(b'!')
|
||||
.remove(b'$')
|
||||
.remove(b'&')
|
||||
.remove(b'\'')
|
||||
.remove(b'(')
|
||||
.remove(b')')
|
||||
.remove(b'*')
|
||||
.remove(b'+')
|
||||
.remove(b',')
|
||||
.remove(b';')
|
||||
.remove(b'=')
|
||||
.remove(b':')
|
||||
.remove(b'@');
|
||||
utf8_percent_encode(raw, SEGMENT).to_string()
|
||||
}
|
||||
|
||||
pub(crate) async fn units(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
filter: Option<&str>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let query = filter
|
||||
.map(|s| vec![("state".to_owned(), s.to_owned())])
|
||||
.unwrap_or_default();
|
||||
forward_json(state, peer, "/api/v1/systemd/units", query).await
|
||||
}
|
||||
|
||||
pub(crate) async fn unit(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
name: &str,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
if let Err(e) = validate_unit_name(name) {
|
||||
return Ok(tool_error(&e));
|
||||
}
|
||||
let path = format!("/api/v1/systemd/units/{}", segment(name));
|
||||
forward_json(state, peer, &path, Vec::new()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn timers(state: &AppState, peer: &str) -> Result<CallToolResult, ErrorData> {
|
||||
forward_json(state, peer, "/api/v1/systemd/timers", Vec::new()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn containers(state: &AppState, peer: &str) -> Result<CallToolResult, ErrorData> {
|
||||
let query = vec![("all".to_owned(), "true".to_owned())];
|
||||
forward_json(state, peer, "/api/v1/docker/ps", query).await
|
||||
}
|
||||
|
||||
pub(crate) async fn container(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
name: &str,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let name = match normalize_name(name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
let path = format!("/api/v1/docker/containers/{}", segment(&name));
|
||||
forward_json(state, peer, &path, Vec::new()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn container_logs(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
name: &str,
|
||||
tail: Option<usize>,
|
||||
cap: usize,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let name = match normalize_name(name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
let path = format!("/api/v1/docker/containers/{}/logs", segment(&name));
|
||||
let query = vec![("tail".to_owned(), clamp_count(tail, cap).to_string())];
|
||||
forward_entries(state, peer, &path, query).await
|
||||
}
|
||||
|
||||
pub(crate) async fn journal(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
unit: Option<&str>,
|
||||
priority: Option<Priority>,
|
||||
lines: Option<usize>,
|
||||
cap: usize,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let mut query = Vec::new();
|
||||
if let Some(unit) = unit {
|
||||
query.push(("unit".to_owned(), unit.to_owned()));
|
||||
}
|
||||
if let Some(priority) = priority {
|
||||
query.push(("priority".to_owned(), priority.name().to_owned()));
|
||||
}
|
||||
query.push(("lines".to_owned(), clamp_count(lines, cap).to_string()));
|
||||
forward_entries(state, peer, "/api/v1/journal", query).await
|
||||
}
|
||||
|
||||
/// Consume the peer's SSE follow stream for `seconds` and render what arrived
|
||||
/// in the local `{entries, truncated, note}` shape.
|
||||
pub(crate) async fn tail_journal(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
unit: &str,
|
||||
seconds: u64,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let limits = &state.config.limits;
|
||||
let secs = seconds.min(limits.max_follow_secs);
|
||||
let entry_cap = limits.max_lines;
|
||||
let query = vec![
|
||||
("unit".to_owned(), unit.to_owned()),
|
||||
("lines".to_owned(), TAIL_BACKLOG.min(entry_cap).to_string()),
|
||||
];
|
||||
let resp = match fetch(state, peer, "/api/v1/journal/follow", query, true).await {
|
||||
Ok(resp) => resp,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
if !(200..300).contains(&resp.status) {
|
||||
let e = status_error(peer, resp.status);
|
||||
return Ok(tool_error(&e));
|
||||
}
|
||||
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
let mut note = None;
|
||||
match resp.body {
|
||||
PeerBody::Bytes(body) => {
|
||||
let mut buf = body.to_vec();
|
||||
out.extend(take_frames(&mut buf));
|
||||
}
|
||||
PeerBody::Stream(mut stream) => {
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
if out.len() >= entry_cap {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = state.shutdown.cancelled() => {
|
||||
note = Some("server is shutting down; stopped early".to_owned());
|
||||
break;
|
||||
}
|
||||
r = tokio::time::timeout_at(deadline, stream.next()) => match r {
|
||||
Err(_) => break,
|
||||
Ok(None) => {
|
||||
note = Some(format!("peer {peer} closed the stream before the time cap"));
|
||||
break;
|
||||
}
|
||||
Ok(Some(Err(e))) => {
|
||||
note = Some(format!("peer {peer} stream failed: {}", e.class_str()));
|
||||
break;
|
||||
}
|
||||
Ok(Some(Ok(chunk))) => {
|
||||
buf.extend_from_slice(&chunk);
|
||||
out.extend(take_frames(&mut buf));
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if note.is_none() && out.len() >= entry_cap {
|
||||
note = Some(format!("stopped at the {entry_cap} entry cap"));
|
||||
}
|
||||
json_result(Ok::<_, AppError>(capped(out, false, note)))
|
||||
}
|
||||
|
||||
/// Complete SSE frames in `buf` as JSON `data` payloads. The terminal
|
||||
/// `event: end` frame carries a bare reason, not JSON, and is skipped.
|
||||
fn take_frames(buf: &mut Vec<u8>) -> Vec<Value> {
|
||||
let mut out = Vec::new();
|
||||
while let Some((end, skip)) = frame_end(buf) {
|
||||
let frame = String::from_utf8_lossy(&buf[..end]).into_owned();
|
||||
buf.drain(..end + skip);
|
||||
for line in frame.lines() {
|
||||
if let Some(data) = line.strip_prefix("data:") {
|
||||
let data = data.strip_prefix(' ').unwrap_or(data);
|
||||
if let Ok(v) = serde_json::from_str::<Value>(data) {
|
||||
out.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Byte index where an SSE frame ends, and how many newline bytes to drop.
|
||||
fn frame_end(buf: &[u8]) -> Option<(usize, usize)> {
|
||||
(0..buf.len()).find_map(|i| {
|
||||
if buf[i..].starts_with(b"\r\n\r\n") {
|
||||
Some((i, 4))
|
||||
} else if buf[i..].starts_with(b"\n\n") {
|
||||
Some((i, 2))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn segments_keep_readable_names_and_escape_the_rest() {
|
||||
assert_eq!(segment("nginx.service"), "nginx.service");
|
||||
assert_eq!(segment("getty@tty1.service"), "getty@tty1.service");
|
||||
assert_eq!(segment("a_b-c~d"), "a_b-c~d");
|
||||
assert_eq!(segment("a/b"), "a%2Fb");
|
||||
assert_eq!(
|
||||
segment("dev-disk-by\\x2did.device"),
|
||||
"dev-disk-by%5Cx2did.device"
|
||||
);
|
||||
assert_eq!(segment("a b"), "a%20b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_are_parsed_across_chunk_boundaries() {
|
||||
let mut buf = b"event: journal\ndata: {\"a\":1}\n\nda".to_vec();
|
||||
let first = take_frames(&mut buf);
|
||||
assert_eq!(first.len(), 1);
|
||||
assert_eq!(first[0]["a"], 1);
|
||||
assert_eq!(&buf[..], b"da");
|
||||
|
||||
// Second call completes the frame.
|
||||
buf.extend_from_slice(b"ta: {\"b\":2}\n\n");
|
||||
let second = take_frames(&mut buf);
|
||||
assert_eq!(second[0]["b"], 2);
|
||||
assert!(buf.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_skip_non_json_end_frames_and_tolerate_crlf() {
|
||||
let mut buf =
|
||||
b"event: journal\r\ndata: {\"a\":1}\r\n\r\nevent: end\ndata: deadline\n\n".to_vec();
|
||||
let frames = take_frames(&mut buf);
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0]["a"], 1);
|
||||
assert!(buf.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statuses_map_like_peer_errors() {
|
||||
assert_eq!(status_error("beta", 401).code(), "unavailable");
|
||||
assert_eq!(
|
||||
status_error("beta", 401).message(),
|
||||
"peer beta: peer rejected credentials"
|
||||
);
|
||||
assert_eq!(status_error("beta", 404).code(), "not_found");
|
||||
assert_eq!(status_error("beta", 400).code(), "bad_request");
|
||||
assert_eq!(status_error("beta", 503).message(), "peer beta: http_503");
|
||||
// An unparsable name cannot have reached a registry; it is not-found.
|
||||
assert_eq!(status_error("Beta", 500).code(), "not_found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_json_is_cut_with_a_marker() {
|
||||
let body = Bytes::from(vec![b'x'; MAX_RESULT_BYTES + 10]);
|
||||
let r = json_text(&body);
|
||||
let ContentBlock::Text(t) = &r.content[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert!(
|
||||
t.text.contains("output truncated to 256 KiB"),
|
||||
"{}",
|
||||
&t.text[t.text.len() - 80..]
|
||||
);
|
||||
assert!(t.text.len() < MAX_RESULT_BYTES + 200);
|
||||
|
||||
let small = json_text(&Bytes::from_static(br#"{"ok":true}"#));
|
||||
let ContentBlock::Text(t) = &small.content[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(t.text, r#"{"ok":true}"#);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! 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<anyhow::Result<()>>,
|
||||
}
|
||||
|
||||
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<FakeTransport>) -> 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::<serde_json::Value>(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}");
|
||||
}
|
||||
Reference in new issue
Block a user