diff --git a/TODO.md b/TODO.md index 3edda80..f59563f 100644 --- a/TODO.md +++ b/TODO.md @@ -75,15 +75,15 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) - [ ] **E9** Docker unavailable returns 503 on docker routes only ### WS-F MCP · [card](plan/workstreams/WS-F-mcp.md) -- [ ] **F1** `TrackerService` with `#[tool_router]` and 8 tools -- [ ] **F2** `tail_journal` capped by `limits.max_follow_secs` and an entry cap -- [ ] **F3** `get_container_logs` tail cap -- [ ] **F4** `ServerHandler::get_info`: instructions + capabilities (tools, prompts, resources) -- [ ] **F5** Tool descriptions that explain systemd states, health statuses and priorities -- [ ] **F6** Prompts `diagnose_unit { name }` and `container_health_report {}` -- [ ] **F7** Resources `systemd://units/failed` and `docker://containers`, read live, no subscriptions -- [ ] **F8** `mcp::service(state)` returns `StreamableHttpService` with Origin validation (DEC-8) -- [ ] **F9** Tests: tool list snapshot + each tool against fakes +- [x] **F1** `TrackerService` with `#[tool_router]` and 8 tools +- [x] **F2** `tail_journal` capped by `limits.max_follow_secs` and an entry cap +- [x] **F3** `get_container_logs` tail cap +- [x] **F4** `ServerHandler::get_info`: instructions + capabilities (tools, prompts, resources) +- [x] **F5** Tool descriptions that explain systemd states, health statuses and priorities +- [x] **F6** Prompts `diagnose_unit { name }` and `container_health_report {}` +- [x] **F7** Resources `systemd://units/failed` and `docker://containers`, read live, no subscriptions +- [x] **F8** `mcp::service(state)` returns `StreamableHttpService` with Origin validation (DEC-8) +- [x] **F9** Tests: tool list snapshot + each tool against fakes ### WS-G OTel · [card](plan/workstreams/WS-G-otel.md) - [ ] **G1** `telemetry::init(cfg)`: OTLP grpc/http with headers. Resource has `service.name`, `service.version`, `host.name`. Returns a guard. diff --git a/plan/workstreams/WS-F-mcp.md b/plan/workstreams/WS-F-mcp.md index 15b1c69..d37a4d6 100644 --- a/plan/workstreams/WS-F-mcp.md +++ b/plan/workstreams/WS-F-mcp.md @@ -58,3 +58,4 @@ Tick these in [`TODO.md`](../../TODO.md). ## Log - 2026-10-15: Card created. +- 2026-10-15: Implemented on branch `ws-f/mcp-server`. Prompts and resources are hand-written `ServerHandler` methods (helpers in `prompts.rs`/`resources.rs` are testable without a request context). `tail_journal` follows with a 10-entry backlog, stops at `max_follow_secs` or `max_lines`. Origin validation is enforced (`enforce_origin_validation`) with loopback and bind origins on `server.port` plus configured extras. Tests use real time (1s cap) because tokio `test-util` is not enabled in Cargo.toml. diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 09c8685..3982ac4 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -1,39 +1,580 @@ -//! MCP server (WS-F owns `src/mcp/`). +//! MCP server (WS-F). Tools, prompts and resources are thin projections over +//! the `sources` traits; nothing here talks to D-Bus, journald or Docker. //! -//! STUB: signatures are final. Pinned `rmcp` 3.5.1 validates `Host` and -//! `Origin` itself via `StreamableHttpServerConfig::with_allowed_hosts` and -//! `with_allowed_origins` (DEC-8). Feed it loopback names, `server.bind`, -//! `server.allowed_hosts` and `server.allowed_origins`. +//! Pinned `rmcp` 3.5.1 validates `Host` and `Origin` itself (DEC-8); `service` +//! feeds it loopback names, `server.bind` and the configured extras. pub mod prompts; +pub mod resources; -use rmcp::handler::server::ServerHandler; -use rmcp::model::ServerConfig; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; + +use rmcp::handler::server::router::tool::ToolRouter; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{ + CallToolResult, ContentBlock, GetPromptRequestParams, GetPromptResponse, Implementation, + ListPromptsResult, ListResourcesResult, PaginatedRequestParams, ReadResourceRequestParams, + ReadResourceResponse, ServerCapabilities, ServerConfig, +}; +use rmcp::service::RequestContext; use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use rmcp::transport::streamable_http_server::StreamableHttpService; +use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; +use rmcp::{tool, tool_handler, tool_router, ErrorData, RoleServer, ServerHandler}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use crate::error::AppError; +use crate::sources::{clamp_count, JournalQuery, LogOptions, Priority}; use crate::state::AppState; +const INSTRUCTIONS: &str = "\ +Read-only monitoring for a Linux host: systemd units and timers, the journal, and Docker containers.\n\ +Suggested workflow: (1) start with `list_systemd_units` state=failed and `list_containers` to find \ +failed units or unhealthy/restarting containers; (2) drill into one with `get_systemd_unit` or \ +`get_container`; (3) pull logs for that unit or container with `get_journal_logs` (priority err or \ +more severe first) or `get_container_logs`; (4) use `list_systemd_timers` to explain scheduled jobs \ +and when they last ran. `tail_journal` waits for new entries for a few seconds and returns what it \ +collected. All limits are capped by the server. Resources `systemd://units/failed` and \ +`docker://containers` give the same overview; prompts `diagnose_unit` and `container_health_report` \ +give guided runs."; + +/// Backlog entries included at the start of `tail_journal`. +const TAIL_BACKLOG: usize = 10; + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListUnitsParams { + /// Filter on active state: `active`, `inactive`, `failed`, `activating`, `deactivating`, `reloading`. Omit for all units. + pub state: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct NameParams { + /// Unit name (e.g. `nginx.service`) or container name/id. + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct JournalParams { + /// Restrict to one unit, e.g. `nginx.service`. + pub unit: Option, + /// Minimum severity: entries at this level or more severe. Name or number 0-7. + pub priority: Option, + /// Number of most recent entries (default 100, capped by the server). + pub lines: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct TailJournalParams { + /// Unit to follow, e.g. `nginx.service`. + pub unit: String, + /// How long to listen for new entries, in seconds (capped by the server). + pub seconds: u64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ContainerLogsParams { + /// Container name or id. + pub name: String, + /// Number of most recent lines (default 100, capped by the server). + pub tail: Option, +} + /// Per-session MCP handler. Holds the shared state. #[derive(Clone)] pub struct TrackerService { - #[allow(dead_code)] state: AppState, + tool_router: ToolRouter, } +fn json_result(value: &T) -> Result { + let text = serde_json::to_string(value) + .map_err(|e| ErrorData::from(AppError::Internal(e.to_string())))?; + Ok(CallToolResult::success(vec![ContentBlock::text(text)])) +} + +#[tool_router] impl TrackerService { pub fn new(state: AppState) -> Self { - Self { state } + Self { + state, + tool_router: Self::tool_router(), + } + } + + #[tool( + description = "List systemd units with load_state, active_state and sub_state. active_state: `active` (running), `inactive` (stopped), `failed` (exited abnormally; investigate first), `activating` (starting; sub_state `auto-restart` means waiting to restart after a failure, a crash-loop signal), `deactivating`, `reloading`. Optional `state` filters on active_state." + )] + async fn list_systemd_units( + &self, + Parameters(p): Parameters, + ) -> Result { + let units = self.state.systemd.list_units(p.state.as_deref()).await?; + json_result(&units) + } + + #[tool( + description = "Detailed status of one systemd unit: states, unit file path, enter/exit times and, for services, main_pid, exec_main_status, n_restarts (automatic restarts) and result (`success`, `exit-code`, `signal`, `timeout`). Unknown unit is an error." + )] + async fn get_systemd_unit( + &self, + Parameters(p): Parameters, + ) -> Result { + 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 { + json_result(&self.state.systemd.list_timers().await?) + } + + #[tool( + description = "Snapshot of recent journal entries, oldest first. `priority` is a syslog severity and includes more severe levels: 0 emerg, 1 alert, 2 crit, 3 err, 4 warning, 5 notice, 6 info, 7 debug. Use `err` to see errors only. `lines` defaults to 100 and is capped by the server." + )] + async fn get_journal_logs( + &self, + Parameters(p): Parameters, + ) -> Result { + let cap = self.state.config.limits.max_lines; + let q = JournalQuery { + unit: p.unit, + priority: p.priority, + lines: Some(clamp_count(p.lines, cap)), + since: None, + }; + json_result(&self.state.journal.query(&q).await?) + } + + #[tool( + description = "Listen for new journal entries of one unit for `seconds` (capped by the server, typically 60) and return what arrived, preceded by a few backlog entries. It always terminates: it stops at the time cap or an entry cap and returns whatever was collected, possibly nothing." + )] + async fn tail_journal( + &self, + Parameters(p): Parameters, + ) -> Result { + let limits = &self.state.config.limits; + let secs = p.seconds.min(limits.max_follow_secs); + let entry_cap = limits.max_lines; + let q = JournalQuery { + unit: Some(p.unit), + priority: None, + lines: Some(TAIL_BACKLOG.min(entry_cap)), + since: None, + }; + let mut rx = self.state.journal.follow(&q).await?; + let mut out = Vec::new(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(secs); + while out.len() < entry_cap { + tokio::select! { + () = self.state.shutdown.cancelled() => break, + r = tokio::time::timeout_at(deadline, rx.recv()) => match r { + Ok(Some(e)) => out.push(e), + Ok(None) | Err(_) => break, + }, + } + } + // Dropping the receiver stops the producer. + drop(rx); + json_result(&out) + } + + #[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 { + json_result(&self.state.docker.ps(true).await?) + } + + #[tool( + description = "Detailed status of one container by name or id: state, health and last health check output, exit_code, oom_killed, started/finished times and restart_count. Unknown container is an error." + )] + async fn get_container( + &self, + Parameters(p): Parameters, + ) -> Result { + json_result(&self.state.docker.container_status(&p.name).await?) + } + + #[tool( + description = "Snapshot of the last `tail` log lines of a container (stdout and stderr, oldest first). `tail` defaults to 100 and is capped by the server." + )] + async fn get_container_logs( + &self, + Parameters(p): Parameters, + ) -> Result { + let opts = LogOptions { + tail: Some(clamp_count(p.tail, self.state.config.limits.max_tail)), + since: None, + }; + json_result(&self.state.docker.logs(&p.name, &opts).await?) } } +#[tool_handler(router = self.tool_router)] impl ServerHandler for TrackerService { fn get_info(&self) -> ServerConfig { - todo!("WS-F F4") + ServerConfig::new( + ServerCapabilities::builder() + .enable_tools() + .enable_prompts() + .enable_resources() + .build(), + ) + .with_server_info(Implementation::new( + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION"), + )) + .with_instructions(INSTRUCTIONS) } + + async fn list_prompts( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + Ok(ListPromptsResult { + prompts: prompts::list(), + ..Default::default() + }) + } + + async fn get_prompt( + &self, + request: GetPromptRequestParams, + _context: RequestContext, + ) -> Result { + Ok(prompts::get(&request.name, request.arguments.as_ref())?.into()) + } + + async fn list_resources( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + Ok(ListResourcesResult { + resources: resources::list(), + ..Default::default() + }) + } + + async fn read_resource( + &self, + request: ReadResourceRequestParams, + _context: RequestContext, + ) -> Result { + Ok(resources::read(&self.state, &request.uri).await?.into()) + } +} + +fn authority(ip: IpAddr) -> String { + match ip { + IpAddr::V4(a) => a.to_string(), + IpAddr::V6(a) => format!("[{a}]"), + } +} + +/// Allowed `Host` values: loopback names, `server.bind`, plus configured extras. +fn allowed_hosts(state: &AppState) -> Vec { + let s = &state.config.server; + let mut v: Vec = ["localhost", "127.0.0.1", "::1"] + .into_iter() + .map(String::from) + .collect(); + if !s.bind.is_unspecified() { + v.push(s.bind.to_string()); + } + v.extend(s.allowed_hosts.iter().cloned()); + v +} + +/// Allowed `Origin` values: loopback origins and `server.bind` on the +/// configured port, plus configured extras. +fn allowed_origins(state: &AppState) -> Vec { + let s = &state.config.server; + let mut hosts = vec![ + "localhost".to_owned(), + "127.0.0.1".to_owned(), + "[::1]".to_owned(), + ]; + if !s.bind.is_unspecified() { + hosts.push(authority(s.bind)); + } + let mut v: Vec = hosts + .into_iter() + .map(|h| format!("http://{h}:{}", s.port)) + .collect(); + v.extend(s.allowed_origins.iter().cloned()); + v +} + +/// Streamable HTTP config with Host/Origin validation (DEC-8). +fn http_config(state: &AppState) -> StreamableHttpServerConfig { + StreamableHttpServerConfig::default() + .with_allowed_hosts(allowed_hosts(state)) + .with_allowed_origins(allowed_origins(state)) + .enforce_origin_validation() + .with_cancellation_token(state.shutdown.child_token()) } /// Tower service to mount at `/mcp` with `nest_service`. -pub fn service(_state: AppState) -> StreamableHttpService { - todo!("WS-F F8") +pub fn service(state: AppState) -> StreamableHttpService { + let config = http_config(&state); + StreamableHttpService::new( + move || Ok(TrackerService::new(state.clone())), + Arc::new(LocalSessionManager::default()), + config, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Config; + use crate::sources::fake::fake_state; + + fn svc() -> TrackerService { + TrackerService::new(fake_state(Config::default())) + } + + fn json(r: CallToolResult) -> serde_json::Value { + match &r.content[0] { + ContentBlock::Text(t) => serde_json::from_str(&t.text).unwrap(), + other => panic!("unexpected content {other:?}"), + } + } + + fn name_param(n: &str) -> Parameters { + Parameters(NameParams { name: n.into() }) + } + + #[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> = tools + .iter() + .map(|t| { + let mut r: Vec = 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 + }) + .collect(); + let want: Vec> = vec![ + vec!["name"], + vec!["name"], + vec![], + vec!["name"], + vec![], + vec![], + vec![], + vec!["seconds", "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); + } + } + + #[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(); + // DEC-5: no subscriptions. + assert!(!res.subscribe.unwrap_or(false)); + assert!(info.instructions.unwrap().contains("failed")); + } + + #[tokio::test] + async fn happy_paths() { + let s = svc(); + let v = json( + s.list_systemd_units(Parameters(ListUnitsParams { + state: Some("failed".into()), + })) + .await + .unwrap(), + ); + assert_eq!(v.as_array().unwrap().len(), 1); + assert_eq!(v[0]["name"], "nginx.service"); + + let v = json( + s.get_systemd_unit(name_param("nginx.service")) + .await + .unwrap(), + ); + assert_eq!(v["n_restarts"], 5); + + let v = json(s.list_systemd_timers().await.unwrap()); + assert_eq!(v[0]["name"], "logrotate.timer"); + + let v = json( + s.get_journal_logs(Parameters(JournalParams { + unit: Some("nginx.service".into()), + priority: Some(Priority::Err), + lines: Some(5), + })) + .await + .unwrap(), + ); + assert_eq!(v.as_array().unwrap().len(), 2); + + let v = json(s.list_containers().await.unwrap()); + let first = v[0]["name"].as_str().unwrap().to_owned(); + + let v = json(s.get_container(name_param(&first)).await.unwrap()); + assert_eq!(v["name"], first.as_str()); + + let v = json( + s.get_container_logs(Parameters(ContainerLogsParams { + name: first, + tail: Some(2), + })) + .await + .unwrap(), + ); + assert!(v.as_array().unwrap().len() <= 2); + } + + #[tokio::test] + async fn container_tail_is_clamped() { + 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 name = v[0]["name"].as_str().unwrap().to_owned(); + let v = json( + s.get_container_logs(Parameters(ContainerLogsParams { + name, + tail: Some(500), + })) + .await + .unwrap(), + ); + assert!(v.as_array().unwrap().len() <= 1); + } + + #[tokio::test] + async fn errors_map_to_error_data() { + let s = svc(); + let e = s + .get_systemd_unit(name_param("nope.service")) + .await + .unwrap_err(); + assert_eq!(e.data.unwrap()["code"], "not_found"); + let e = s.get_container(name_param("nope")).await.unwrap_err(); + assert_eq!(e.data.unwrap()["code"], "not_found"); + } + + #[tokio::test] + async fn tail_journal_respects_time_cap() { + let mut cfg = Config::default(); + cfg.limits.max_follow_secs = 1; + let s = TrackerService::new(fake_state(cfg)); + let start = tokio::time::Instant::now(); + let v = json( + s.tail_journal(Parameters(TailJournalParams { + unit: "nginx.service".into(), + seconds: 3600, + })) + .await + .unwrap(), + ); + let elapsed = start.elapsed(); + assert!(elapsed >= Duration::from_secs(1), "{elapsed:?}"); + assert!(elapsed < Duration::from_secs(4), "{elapsed:?}"); + assert_eq!(v.as_array().unwrap().len(), 2); // backlog only + } + + #[tokio::test] + async fn tail_journal_respects_entry_cap() { + let mut cfg = Config::default(); + cfg.limits.max_lines = 1; + let s = TrackerService::new(fake_state(cfg)); + let v = json( + s.tail_journal(Parameters(TailJournalParams { + unit: "nginx.service".into(), + seconds: 30, + })) + .await + .unwrap(), + ); + assert_eq!(v.as_array().unwrap().len(), 1); + } + + #[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 p = prompts::get("diagnose_unit", Some(&args)).unwrap(); + assert!(!p.messages.is_empty()); + assert!(prompts::get("diagnose_unit", None).is_err()); + assert!(prompts::get("container_health_report", None).is_ok()); + assert!(matches!( + prompts::get("nope", None), + Err(AppError::NotFound(_)) + )); + } + + #[tokio::test] + async fn resources_read_live() { + assert_eq!(resources::list().len(), 2); + let st = fake_state(Config::default()); + let r = resources::read(&st, resources::FAILED_UNITS_URI) + .await + .unwrap(); + assert_eq!(r.contents.len(), 1); + assert!(resources::read(&st, resources::CONTAINERS_URI) + .await + .is_ok()); + assert!(matches!( + resources::read(&st, "x://y").await, + Err(AppError::NotFound(_)) + )); + } + + #[test] + fn host_and_origin_allowlists() { + let mut cfg = Config::default(); + cfg.server.allowed_hosts = vec!["mon.example.com".into()]; + cfg.server.allowed_origins = vec!["https://mon.example.com".into()]; + let st = fake_state(cfg); + assert!(allowed_hosts(&st).contains(&"mon.example.com".to_string())); + assert!(allowed_origins(&st).contains(&"http://localhost:9109".to_string())); + assert!(allowed_origins(&st).contains(&"https://mon.example.com".to_string())); + let _svc = service(st); + } } diff --git a/src/mcp/prompts.rs b/src/mcp/prompts.rs index 88b4756..1af08a5 100644 --- a/src/mcp/prompts.rs +++ b/src/mcp/prompts.rs @@ -1,3 +1,75 @@ -//! MCP prompts: diagnose_unit, container_health_report (WS-F) +//! MCP prompts: `diagnose_unit` and `container_health_report` (WS-F). //! -//! Placeholder created in P0 so the owning workstream only edits its own files. +//! Prompts only return instructions that tell the agent which tools to call; +//! they do not read live data themselves. + +use rmcp::model::{GetPromptResult, JsonObject, Prompt, PromptArgument, PromptMessage, Role}; + +use crate::error::AppError; + +pub const DIAGNOSE_UNIT: &str = "diagnose_unit"; +pub const CONTAINER_HEALTH_REPORT: &str = "container_health_report"; + +/// Prompt definitions advertised by `prompts/list`. +pub fn list() -> Vec { + vec![ + Prompt::new( + DIAGNOSE_UNIT, + Some("Diagnose a systemd unit: status, recent error logs, restart count, next step."), + Some(vec![PromptArgument::new("name") + .with_description("Unit name, e.g. nginx.service") + .with_required(true)]), + ), + Prompt::new( + CONTAINER_HEALTH_REPORT, + Some( + "Report on Docker container health: unhealthy and restarting containers with their logs.", + ), + None, + ), + ] +} + +/// Resolve a prompt by name. +pub fn get(name: &str, args: Option<&JsonObject>) -> Result { + match name { + DIAGNOSE_UNIT => { + let unit = args + .and_then(|a| a.get("name")) + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .ok_or_else(|| AppError::BadRequest("missing required argument 'name'".into()))?; + let text = format!( + "Diagnose the systemd unit `{unit}`.\n\ + 1. Call `get_systemd_unit` with name `{unit}` and report its active_state, \ + sub_state, result and exec_main_status.\n\ + 2. Call `get_journal_logs` with unit `{unit}`, priority `err` and lines 50 to \ + see recent errors.\n\ + 3. Check `n_restarts` from the unit status. A high count with state \ + `activating` / `auto-restart` means a crash loop.\n\ + 4. Summarize the most likely cause, then suggest one concrete next look \ + (for example `get_journal_logs` at priority `info` around the failure time, \ + or a dependency unit)." + ); + Ok( + GetPromptResult::new(vec![PromptMessage::new_text(Role::User, text)]) + .with_description(format!("Diagnose unit {unit}")), + ) + } + CONTAINER_HEALTH_REPORT => { + let text = "Produce a Docker container health report.\n\ + 1. Call `list_containers` and note every container whose health is \ + `unhealthy` or `starting`, whose state is `restarting`, `exited` or `dead`, \ + or with a high restart_count.\n\ + 2. For each such container call `get_container` and then `get_container_logs` \ + with tail 100.\n\ + 3. Summarize per container: what is wrong, the evidence from the logs, and a \ + suggested next step. State explicitly if everything is healthy."; + Ok( + GetPromptResult::new(vec![PromptMessage::new_text(Role::User, text)]) + .with_description("Docker container health report"), + ) + } + other => Err(AppError::NotFound(format!("unknown prompt '{other}'"))), + } +} diff --git a/src/mcp/resources.rs b/src/mcp/resources.rs new file mode 100644 index 0000000..3c79950 --- /dev/null +++ b/src/mcp/resources.rs @@ -0,0 +1,47 @@ +//! MCP resources (WS-F). Resolved live on every read; not subscribable (DEC-5). + +use rmcp::model::{ReadResourceResult, Resource, ResourceContents}; + +use crate::error::AppError; +use crate::state::AppState; + +pub const FAILED_UNITS_URI: &str = "systemd://units/failed"; +pub const CONTAINERS_URI: &str = "docker://containers"; + +/// Resources advertised by `resources/list`. +pub fn list() -> Vec { + vec![ + Resource::new(FAILED_UNITS_URI, "failed-units") + .with_title("Failed systemd units") + .with_description("Units currently in the failed active state.") + .with_mime_type("application/json"), + Resource::new(CONTAINERS_URI, "containers") + .with_title("Docker containers") + .with_description("All containers (running and stopped) with state and health.") + .with_mime_type("application/json"), + ] +} + +/// Read a resource by URI, querying the source on each call. +pub async fn read(state: &AppState, uri: &str) -> Result { + let json = match uri { + FAILED_UNITS_URI => { + let units = state.systemd.list_units(Some("failed")).await?; + serde_json::to_string_pretty(&units) + } + CONTAINERS_URI => { + let cs = state.docker.ps(true).await?; + serde_json::to_string_pretty(&cs) + } + other => return Err(AppError::NotFound(format!("unknown resource '{other}'"))), + } + .map_err(|e| AppError::Internal(e.to_string()))?; + Ok(ReadResourceResult::new(vec![ + ResourceContents::TextResourceContents { + uri: uri.to_owned(), + mime_type: Some("application/json".into()), + text: json, + meta: None, + }, + ])) +}