From 36a64e43495a9780f372fc76987eedb3f96c3eae Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:48:40 +0200 Subject: [PATCH] fix(mcp): MCP server cards per tenant, not shared by all The dashboard kept its MCP server cards in its own database, read with find({}): every tenant saw, deleted and re-keyed the same cards, and a card added by one tenant (with its mongodb_uri) showed to all (#432). The cards now live in each tenant's database at the agent, behind /api/v1/mcp-servers (list, create, delete, regenerate token), like the MCP tokens. Tenant resolution, the role gate and support access apply as for every agent route; the access tokens go only to roles that may change things. A tenant without cards gets the three default cards on its first listing (by name, so two listings at once do not create them twice), for the dashboard's MCP_ENDPOINT_URL. The dashboard's server functions call the agent; the health status is probed live on each listing (concurrently, 3 s) instead of being written back, so a read-only role no longer writes. At start the dashboard drops its old shared collection, whose cards cannot be attributed to a tenant. Closes #432. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- .../src/api/handlers/mcp_servers.rs | 241 +++++++++++++ compliance-agent/src/api/handlers/mod.rs | 1 + compliance-agent/src/api/routes.rs | 13 + compliance-agent/src/database.rs | 5 + compliance-agent/tests/mcp_servers.rs | 158 +++++++++ .../src/infrastructure/database.rs | 4 - .../src/infrastructure/mcp.rs | 321 ++++++------------ .../src/infrastructure/server.rs | 87 +---- compliance-dashboard/src/pages/mcp_servers.rs | 3 +- compliance-dashboard/src/pages/overview.rs | 11 +- 10 files changed, 549 insertions(+), 295 deletions(-) create mode 100644 compliance-agent/src/api/handlers/mcp_servers.rs create mode 100644 compliance-agent/tests/mcp_servers.rs diff --git a/compliance-agent/src/api/handlers/mcp_servers.rs b/compliance-agent/src/api/handlers/mcp_servers.rs new file mode 100644 index 0000000..9db9a4a --- /dev/null +++ b/compliance-agent/src/api/handlers/mcp_servers.rs @@ -0,0 +1,241 @@ +//! `/api/v1/mcp-servers` — the MCP server cards of the caller's tenant. +//! +//! The dashboard's MCP page lists the servers an LLM client can connect to. +//! The cards live in the tenant's own database, so one tenant never sees or +//! changes another's (#432). Every tenant starts with the three default cards +//! (Findings, SBOM, DAST), created on its first listing. A card's access token +//! is display data (the MCP server authenticates with the tenant's MCP tokens); +//! it is shown only to roles that may change things. + +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; +use chrono::Utc; +use mongodb::bson::{doc, oid::ObjectId}; + +use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport}; +use compliance_core::tenant_ctx::TenantCtx; + +use super::dto::{tenant_db, AgentExt}; +use crate::database::Database; + +/// The default cards: name, description and the tools each exposes. +const DEFAULT_SERVERS: [(&str, &str, &[&str]); 3] = [ + ( + "Findings MCP", + "Exposes security findings, triage data, and finding summaries to LLM agents", + &["list_findings", "get_finding", "findings_summary"], + ), + ( + "SBOM MCP", + "Exposes software bill of materials and vulnerability reports to LLM agents", + &["list_sbom_packages", "sbom_vuln_report"], + ), + ( + "DAST MCP", + "Exposes DAST scan findings and scan summaries to LLM agents", + &["list_dast_findings", "dast_scan_summary"], + ), +]; + +/// Every tool a card created by hand exposes. +const ALL_TOOLS: [&str; 7] = [ + "list_findings", + "get_finding", + "findings_summary", + "list_sbom_packages", + "sbom_vuln_report", + "list_dast_findings", + "dast_scan_summary", +]; + +#[derive(Debug, serde::Deserialize)] +pub struct ListQuery { + /// Where the deployment's MCP server answers (the dashboard's + /// `MCP_ENDPOINT_URL`), for the default cards of a tenant that has none. + #[serde(default)] + pub default_endpoint: Option, +} + +#[derive(Debug, serde::Deserialize)] +pub struct CreateRequest { + pub name: String, + pub endpoint_url: String, + #[serde(default)] + pub transport: String, + #[serde(default)] + pub port: Option, + #[serde(default)] + pub description: Option, + #[serde(default)] + pub mongodb_uri: Option, + #[serde(default)] + pub mongodb_database: Option, +} + +/// A fresh display token for a card. +fn new_token() -> String { + format!("mcp_{}", uuid::Uuid::new_v4().simple()) +} + +/// `value` trimmed, `None` when blank. +fn non_blank(value: Option) -> Option { + value + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) +} + +/// Create the default cards for a tenant that has no cards yet. `endpoint` +/// must be an http(s) URL; anything else creates nothing. +async fn seed_defaults(db: &Database, endpoint: &str) -> Result<(), mongodb::error::Error> { + let endpoint = endpoint.trim().trim_end_matches('/'); + if !(endpoint.starts_with("https://") || endpoint.starts_with("http://")) { + return Ok(()); + } + if db.mcp_servers().count_documents(doc! {}).await? > 0 { + return Ok(()); + } + let now = Utc::now(); + let cards = DEFAULT_SERVERS + .iter() + .map(|(name, description, tools)| McpServerConfig { + id: None, + name: (*name).to_string(), + endpoint_url: format!("{endpoint}/mcp"), + transport: McpTransport::Http, + port: Some(8090), + status: McpServerStatus::Stopped, + access_token: new_token(), + tools_enabled: tools.iter().map(|t| (*t).to_string()).collect(), + description: Some((*description).to_string()), + mongodb_uri: None, + mongodb_database: None, + created_at: now, + updated_at: now, + }); + // By name, so two first listings at once do not create them twice. + for card in cards { + let Ok(fields) = mongodb::bson::to_document(&card) else { + continue; + }; + db.mcp_servers() + .update_one(doc! { "name": &card.name }, doc! { "$setOnInsert": fields }) + .upsert(true) + .await?; + } + Ok(()) +} + +/// `GET /api/v1/mcp-servers` — the tenant's cards, newest first; the access +/// tokens only for roles that may change things. +#[tracing::instrument(skip_all)] +pub async fn list_mcp_servers( + Extension(agent): AgentExt, + tenant: TenantCtx, + Query(query): Query, +) -> Result, StatusCode> { + let db = tenant_db(&agent, &tenant).await?; + if let Some(endpoint) = query.default_endpoint.as_deref() { + if let Err(e) = seed_defaults(&db, endpoint).await { + tracing::warn!("could not create the default MCP server cards: {e}"); + } + } + let cursor = db + .mcp_servers() + .find(doc! {}) + .sort(doc! { "created_at": -1 }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mut servers: Vec = super::dto::collect_cursor_async(cursor).await; + if !tenant.0.product_access().can_write() { + for server in &mut servers { + server.access_token = String::new(); + } + } + Ok(Json(serde_json::json!({ "data": servers }))) +} + +/// `POST /api/v1/mcp-servers` — add a card to the tenant. +#[tracing::instrument(skip_all)] +pub async fn create_mcp_server( + Extension(agent): AgentExt, + tenant: TenantCtx, + Json(req): Json, +) -> Result, StatusCode> { + if req.name.trim().is_empty() || req.endpoint_url.trim().is_empty() { + return Err(StatusCode::BAD_REQUEST); + } + let db = tenant_db(&agent, &tenant).await?; + let now = Utc::now(); + let server = McpServerConfig { + id: None, + name: req.name.trim().to_string(), + endpoint_url: req.endpoint_url.trim().to_string(), + transport: if req.transport == "http" { + McpTransport::Http + } else { + McpTransport::Stdio + }, + port: req.port, + status: McpServerStatus::Stopped, + access_token: new_token(), + tools_enabled: ALL_TOOLS.iter().map(|t| (*t).to_string()).collect(), + description: non_blank(req.description), + mongodb_uri: non_blank(req.mongodb_uri), + mongodb_database: non_blank(req.mongodb_database), + created_at: now, + updated_at: now, + }; + let inserted = db + .mcp_servers() + .insert_one(&server) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(serde_json::json!({ "id": inserted.inserted_id }))) +} + +/// `DELETE /api/v1/mcp-servers/{id}` — remove one of the tenant's cards; 404 +/// for an id the tenant has not. +#[tracing::instrument(skip_all, fields(server_id = %id))] +pub async fn delete_mcp_server( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result { + let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; + let db = tenant_db(&agent, &tenant).await?; + let deleted = db + .mcp_servers() + .delete_one(doc! { "_id": oid }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if deleted.deleted_count == 0 { + return Err(StatusCode::NOT_FOUND); + } + Ok(StatusCode::NO_CONTENT) +} + +/// `POST /api/v1/mcp-servers/{id}/token` — give one of the tenant's cards a +/// new access token; 404 for an id the tenant has not. +#[tracing::instrument(skip_all, fields(server_id = %id))] +pub async fn regenerate_mcp_server_token( + Extension(agent): AgentExt, + tenant: TenantCtx, + Path(id): Path, +) -> Result, StatusCode> { + let oid = ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?; + let db = tenant_db(&agent, &tenant).await?; + let token = new_token(); + let updated = db + .mcp_servers() + .update_one( + doc! { "_id": oid }, + doc! { "$set": { "access_token": &token, "updated_at": mongodb::bson::DateTime::now() } }, + ) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if updated.matched_count == 0 { + return Err(StatusCode::NOT_FOUND); + } + Ok(Json(serde_json::json!({ "token": token }))) +} diff --git a/compliance-agent/src/api/handlers/mod.rs b/compliance-agent/src/api/handlers/mod.rs index 40591a9..c98ba96 100644 --- a/compliance-agent/src/api/handlers/mod.rs +++ b/compliance-agent/src/api/handlers/mod.rs @@ -11,6 +11,7 @@ pub mod health; pub mod help_chat; pub mod issues; pub mod manual_findings; +pub mod mcp_servers; pub mod mcp_tokens; pub mod notifications; pub mod onboarding; diff --git a/compliance-agent/src/api/routes.rs b/compliance-agent/src/api/routes.rs index e6885aa..2a6219f 100644 --- a/compliance-agent/src/api/routes.rs +++ b/compliance-agent/src/api/routes.rs @@ -125,6 +125,19 @@ pub fn build_router() -> Router { .route("/api/v1/issues", get(handlers::list_issues)) .route("/api/v1/scan-runs", get(handlers::list_scan_runs)) // MCP token management (per-tenant API tokens for the MCP server) + .route( + "/api/v1/mcp-servers", + get(handlers::mcp_servers::list_mcp_servers) + .post(handlers::mcp_servers::create_mcp_server), + ) + .route( + "/api/v1/mcp-servers/{id}", + delete(handlers::mcp_servers::delete_mcp_server), + ) + .route( + "/api/v1/mcp-servers/{id}/token", + post(handlers::mcp_servers::regenerate_mcp_server_token), + ) .route( "/api/v1/mcp-tokens", get(handlers::mcp_tokens::list_mcp_tokens).post(handlers::mcp_tokens::create_mcp_token), diff --git a/compliance-agent/src/database.rs b/compliance-agent/src/database.rs index 8b154c3..173e7e8 100644 --- a/compliance-agent/src/database.rs +++ b/compliance-agent/src/database.rs @@ -578,6 +578,11 @@ impl Database { self.inner.collection("cve_notifications") } + /// The MCP server cards the dashboard shows (#432). + pub fn mcp_servers(&self) -> Collection { + self.inner.collection("mcp_servers") + } + pub fn tracker_issues(&self) -> Collection { self.inner.collection("tracker_issues") } diff --git a/compliance-agent/tests/mcp_servers.rs b/compliance-agent/tests/mcp_servers.rs new file mode 100644 index 0000000..e4865e4 --- /dev/null +++ b/compliance-agent/tests/mcp_servers.rs @@ -0,0 +1,158 @@ +//! MCP server cards per tenant (#432): one tenant's cards are invisible and +//! untouchable for another, every tenant gets the default cards once, and a +//! read-only role sees no access tokens. Runs against a live Mongo and skips +//! cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::Arc; + +use axum::extract::{Extension, Path, Query}; +use axum::http::StatusCode; +use axum::Json; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::api::handlers::mcp_servers::{ + create_mcp_server, delete_mcp_server, list_mcp_servers, regenerate_mcp_server_token, + CreateRequest, ListQuery, +}; +use compliance_agent::database::DatabasePool; +use compliance_core::tenant_ctx::TenantCtx; +use compliance_core::{OrgRole, TenantContext, TenantStatus}; + +use common::dev_config; + +fn tenant(id: &str, role: OrgRole) -> TenantCtx { + TenantCtx(TenantContext { + tenant_id: id.to_string(), + tenant_slug: id.to_string(), + org_roles: vec![role], + products: vec!["compliance-scanner".to_string()], + plan: "starter".to_string(), + status: TenantStatus::Active, + user_id: "u-1".to_string(), + user_name: None, + staff: None, + }) +} + +async fn names(agent: &Arc, who: TenantCtx) -> Vec<(String, String, String)> { + let Json(body) = list_mcp_servers( + Extension(agent.clone()), + who, + Query(ListQuery { + default_endpoint: Some("https://pruefwerk.example".into()), + }), + ) + .await + .unwrap(); + body["data"] + .as_array() + .unwrap() + .iter() + .map(|s| { + ( + s["name"].as_str().unwrap().to_string(), + s["_id"]["$oid"].as_str().unwrap_or_default().to_string(), + s["access_token"].as_str().unwrap_or_default().to_string(), + ) + }) + .collect() +} + +#[tokio::test] +async fn mcp_server_cards_are_per_tenant() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("mcps_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]); + let Ok(pool) = DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP mcp_servers: no MongoDB reachable at {uri}"); + return; + }; + let agent = Arc::new(ComplianceAgent::new(dev_config(uri, db_name), pool.clone())); + let (a, b) = ("tenant-a", "tenant-b"); + + // Every tenant starts with the three default cards, once. + let first = names(&agent, tenant(a, OrgRole::ItAdmin)).await; + assert_eq!(first.len(), 3); + assert_eq!(names(&agent, tenant(a, OrgRole::ItAdmin)).await.len(), 3); + + // Tenant A adds a card. + let _created = create_mcp_server( + Extension(agent.clone()), + tenant(a, OrgRole::ItAdmin), + Json(CreateRequest { + name: "A's own".into(), + endpoint_url: "https://mcp.a.example/mcp".into(), + transport: "http".into(), + port: None, + description: None, + mongodb_uri: Some("mongodb://secret-a".into()), + mongodb_database: None, + }), + ) + .await + .unwrap(); + let a_cards = names(&agent, tenant(a, OrgRole::ItAdmin)).await; + let (_, a_id, a_token) = a_cards + .iter() + .find(|(name, _, _)| name == "A's own") + .cloned() + .expect("A sees its card"); + assert!(a_token.starts_with("mcp_")); + + // Tenant B sees only its own defaults, and cannot touch A's card. + let b_cards = names(&agent, tenant(b, OrgRole::ItAdmin)).await; + assert_eq!(b_cards.len(), 3); + assert!(!b_cards + .iter() + .any(|(name, id, _)| name == "A's own" || *id == a_id)); + assert_eq!( + delete_mcp_server( + Extension(agent.clone()), + tenant(b, OrgRole::ItAdmin), + Path(a_id.clone()) + ) + .await + .unwrap_err(), + StatusCode::NOT_FOUND + ); + assert_eq!( + regenerate_mcp_server_token( + Extension(agent.clone()), + tenant(b, OrgRole::ItAdmin), + Path(a_id.clone()) + ) + .await + .unwrap_err(), + StatusCode::NOT_FOUND + ); + assert!(names(&agent, tenant(a, OrgRole::ItAdmin)) + .await + .iter() + .any(|(_, id, token)| *id == a_id && *token == a_token)); + + // A read-only role sees the cards without their tokens. + let read_only = names(&agent, tenant(a, OrgRole::Cxo)).await; + assert_eq!(read_only.len(), 4); + assert!(read_only.iter().all(|(_, _, token)| token.is_empty())); + + // A deletes its own card. + assert_eq!( + delete_mcp_server( + Extension(agent.clone()), + tenant(a, OrgRole::ItAdmin), + Path(a_id) + ) + .await + .unwrap(), + StatusCode::NO_CONTENT + ); + assert_eq!(names(&agent, tenant(a, OrgRole::ItAdmin)).await.len(), 3); + + for t in [a, b] { + pool.drop_tenant(t).await.ok(); + } +} diff --git a/compliance-dashboard/src/infrastructure/database.rs b/compliance-dashboard/src/infrastructure/database.rs index d9963f8..d823c87 100644 --- a/compliance-dashboard/src/infrastructure/database.rs +++ b/compliance-dashboard/src/infrastructure/database.rs @@ -43,8 +43,4 @@ impl Database { pub fn tracker_issues(&self) -> Collection { self.inner.collection("tracker_issues") } - - pub fn mcp_servers(&self) -> Collection { - self.inner.collection("mcp_servers") - } } diff --git a/compliance-dashboard/src/infrastructure/mcp.rs b/compliance-dashboard/src/infrastructure/mcp.rs index 29d8bfd..61f7dfd 100644 --- a/compliance-dashboard/src/infrastructure/mcp.rs +++ b/compliance-dashboard/src/infrastructure/mcp.rs @@ -8,42 +8,85 @@ pub struct McpServersResponse { pub data: Vec, } +/// The tenant's MCP server cards, with each server's health probed now. +/// +/// The cards live in the tenant's database at the agent (#432), so a tenant +/// sees only its own. A tenant without cards gets the default ones for this +/// deployment's `MCP_ENDPOINT_URL`. Access tokens come only to roles that may +/// change things. #[server] pub async fn fetch_mcp_servers() -> Result { - use mongodb::bson::doc; - let state: super::server_state::ServerState = dioxus_fullstack::FullstackContext::extract().await?; - - let mut cursor = state - .db - .mcp_servers() - .find(doc! {}) - .sort(doc! { "created_at": -1 }) + let mut path = "/api/v1/mcp-servers".to_string(); + if let Some(endpoint) = state.config.mcp_endpoint_url.as_deref() { + path.push_str(&format!( + "?default_endpoint={}", + url::form_urlencoded::byte_serialize(endpoint.as_bytes()).collect::() + )); + } + let resp = super::agent_client::agent_get(&path) + .await? + .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - - // A server's access token is a key: only a role that may change things - // sees it. - let show_tokens = super::agent_client::current_access().await?.can_write(); - let mut data = Vec::new(); - while cursor - .advance() - .await - .map_err(|e| ServerFnError::new(e.to_string()))? - { - let mut server: McpServerConfig = cursor - .deserialize_current() - .map_err(|e| ServerFnError::new(e.to_string()))?; - if !show_tokens { - server.access_token = String::new(); - } - data.push(server); - } - - Ok(McpServersResponse { data }) + let mut servers: McpServersResponse = super::agent_client::json_or_error(resp).await?; + probe_health(&state, &mut servers.data).await; + Ok(servers) } +/// Set each server's status from its health endpoint, probed concurrently. +#[cfg(feature = "server")] +async fn probe_health(state: &super::server_state::ServerState, servers: &mut [McpServerConfig]) { + use compliance_core::models::McpServerStatus; + + let Ok(client) = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(3)) + .build() + else { + return; + }; + // The endpoint the default cards point at; the `MCP_HEALTH_URL` + // override applies to exactly those. + let seeded = state + .config + .mcp_endpoint_url + .as_deref() + .map(seeded_mcp_endpoint); + let mut probes = tokio::task::JoinSet::new(); + for (index, server) in servers.iter().enumerate() { + let candidates = mcp_health_url_candidates( + &server.endpoint_url, + seeded.as_deref(), + state.mcp_health_url.as_deref(), + ); + let client = client.clone(); + probes.spawn(async move { + for url in candidates { + if client + .get(&url) + .send() + .await + .is_ok_and(|r| r.status().is_success()) + { + return (index, McpServerStatus::Running); + } + } + (index, McpServerStatus::Stopped) + }); + } + let mut statuses = vec![McpServerStatus::Stopped; servers.len()]; + while let Some(Ok((index, status))) = probes.join_next().await { + if let Some(slot) = statuses.get_mut(index) { + *slot = status; + } + } + for (server, status) in servers.iter_mut().zip(statuses) { + server.status = status; + } +} + +/// Add an MCP server card to the tenant. #[server] pub async fn add_mcp_server( name: String, @@ -54,70 +97,22 @@ pub async fn add_mcp_server( mongodb_uri: String, mongodb_database: String, ) -> Result<(), ServerFnError> { - use chrono::Utc; - use compliance_core::models::{McpServerStatus, McpTransport}; super::agent_client::require_write_access().await?; - - let state: super::server_state::ServerState = - dioxus_fullstack::FullstackContext::extract().await?; - - let transport = match transport.as_str() { - "http" => McpTransport::Http, - _ => McpTransport::Stdio, - }; - - let port_num: Option = port.parse().ok(); - - // Generate a random access token - let token = format!("mcp_{}", uuid::Uuid::new_v4().to_string().replace('-', "")); - - let all_tools = vec![ - "list_findings".to_string(), - "get_finding".to_string(), - "findings_summary".to_string(), - "list_sbom_packages".to_string(), - "sbom_vuln_report".to_string(), - "list_dast_findings".to_string(), - "dast_scan_summary".to_string(), - ]; - - let now = Utc::now(); - let server = McpServerConfig { - id: None, - name, - endpoint_url, - transport, - port: port_num, - status: McpServerStatus::Stopped, - access_token: token, - tools_enabled: all_tools, - description: if description.is_empty() { - None - } else { - Some(description) - }, - mongodb_uri: if mongodb_uri.is_empty() { - None - } else { - Some(mongodb_uri) - }, - mongodb_database: if mongodb_database.is_empty() { - None - } else { - Some(mongodb_database) - }, - created_at: now, - updated_at: now, - }; - - state - .db - .mcp_servers() - .insert_one(server) + let resp = super::agent_client::agent_request(reqwest::Method::POST, "/api/v1/mcp-servers") + .await? + .json(&serde_json::json!({ + "name": name, + "endpoint_url": endpoint_url, + "transport": transport, + "port": port.parse::().ok(), + "description": description, + "mongodb_uri": mongodb_uri, + "mongodb_database": mongodb_database, + })) + .send() .await .map_err(|e| ServerFnError::new(e.to_string()))?; - - Ok(()) + super::agent_client::ok_or_error(resp).await } /// The `endpoint_url` the seeded default MCP server cards carry for a @@ -156,137 +151,39 @@ pub fn mcp_health_url_candidates( } } -/// Probe each MCP server's health endpoint and update status in MongoDB. -#[server] -pub async fn refresh_mcp_status() -> Result<(), ServerFnError> { - // Not a change a role is refused: it only records what the health probe - // saw, and every reader's overview runs it. - use chrono::Utc; - use compliance_core::models::McpServerStatus; - use mongodb::bson::doc; - - let state: super::server_state::ServerState = - dioxus_fullstack::FullstackContext::extract().await?; - - let mut cursor = state - .db - .mcp_servers() - .find(doc! {}) - .await - .map_err(|e| ServerFnError::new(e.to_string()))?; - - let client = reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(5)) - .build() - .map_err(|e| ServerFnError::new(e.to_string()))?; - - // The endpoint the default (seeded) MCP server cards point at — the - // explicit `MCP_HEALTH_URL` override applies to exactly those. - let seeded_endpoint = state - .config - .mcp_endpoint_url - .as_deref() - .map(seeded_mcp_endpoint); - - while cursor - .advance() - .await - .map_err(|e| ServerFnError::new(e.to_string()))? - { - let server: compliance_core::models::McpServerConfig = cursor - .deserialize_current() - .map_err(|e| ServerFnError::new(e.to_string()))?; - - let Some(oid) = server.id else { continue }; - - let candidates = mcp_health_url_candidates( - &server.endpoint_url, - seeded_endpoint.as_deref(), - state.mcp_health_url.as_deref(), - ); - - let mut new_status = McpServerStatus::Stopped; - for health_url in &candidates { - match client.get(health_url).send().await { - Ok(resp) if resp.status().is_success() => { - new_status = McpServerStatus::Running; - break; - } - Ok(resp) => tracing::debug!( - "MCP probe {health_url} for '{}' returned {}", - server.name, - resp.status() - ), - Err(e) => { - tracing::debug!("MCP probe {health_url} for '{}' failed: {e}", server.name) - } - } - } - - let status_bson = match bson::to_bson(&new_status) { - Ok(b) => b, - Err(_) => continue, - }; - - let _ = state - .db - .mcp_servers() - .update_one( - doc! { "_id": oid }, - doc! { "$set": { "status": status_bson, "updated_at": Utc::now().to_rfc3339() } }, - ) - .await; - } - - Ok(()) -} - +/// Remove one of the tenant's MCP server cards. #[server] pub async fn delete_mcp_server(server_id: String) -> Result<(), ServerFnError> { super::agent_client::require_write_access().await?; - use mongodb::bson::doc; - - let state: super::server_state::ServerState = - dioxus_fullstack::FullstackContext::extract().await?; - - let oid = bson::oid::ObjectId::parse_str(&server_id) - .map_err(|e| ServerFnError::new(e.to_string()))?; - - state - .db - .mcp_servers() - .delete_one(doc! { "_id": oid }) - .await - .map_err(|e| ServerFnError::new(e.to_string()))?; - - Ok(()) + let resp = super::agent_client::agent_request( + reqwest::Method::DELETE, + &format!("/api/v1/mcp-servers/{server_id}"), + ) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + super::agent_client::ok_or_error(resp).await } +/// Give one of the tenant's MCP server cards a new access token. #[server] pub async fn regenerate_mcp_token(server_id: String) -> Result { super::agent_client::require_write_access().await?; - use chrono::Utc; - use mongodb::bson::doc; - - let state: super::server_state::ServerState = - dioxus_fullstack::FullstackContext::extract().await?; - - let oid = bson::oid::ObjectId::parse_str(&server_id) - .map_err(|e| ServerFnError::new(e.to_string()))?; - - let new_token = format!("mcp_{}", uuid::Uuid::new_v4().to_string().replace('-', "")); - - state - .db - .mcp_servers() - .update_one( - doc! { "_id": oid }, - doc! { "$set": { "access_token": &new_token, "updated_at": Utc::now().to_rfc3339() } }, - ) - .await - .map_err(|e| ServerFnError::new(e.to_string()))?; - - Ok(new_token) + #[derive(serde::Deserialize)] + struct Regenerated { + token: String, + } + let resp = super::agent_client::agent_request( + reqwest::Method::POST, + &format!("/api/v1/mcp-servers/{server_id}/token"), + ) + .await? + .send() + .await + .map_err(|e| ServerFnError::new(e.to_string()))?; + let regenerated: Regenerated = super::agent_client::json_or_error(resp).await?; + Ok(regenerated.token) } #[cfg(test)] diff --git a/compliance-dashboard/src/infrastructure/server.rs b/compliance-dashboard/src/infrastructure/server.rs index 2c2ec70..7aa1db7 100644 --- a/compliance-dashboard/src/infrastructure/server.rs +++ b/compliance-dashboard/src/infrastructure/server.rs @@ -6,7 +6,6 @@ use tower_http::set_header::SetResponseHeaderLayer; use tower_sessions::SessionManagerLayer; use compliance_core::config::AppEnv; -use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport}; use mongodb::bson::doc; use super::config; @@ -45,8 +44,7 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> { KeycloakConfig::from_env().map(|kc| &*Box::leak(Box::new(kc))); let db = Database::connect(&config.mongodb_uri, &config.mongodb_database).await?; - // Seed default MCP server configs - seed_default_mcp_servers(&db, config.mcp_endpoint_url.as_deref()).await; + retire_global_mcp_servers(&db).await; let app_env = AppEnv::parse(&std::env::var("APP_ENV").unwrap_or_default()) .map_err(DashboardError::Other)?; @@ -150,73 +148,22 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> { }) } -/// Seed three default MCP server configs (Findings, SBOM, DAST) if they don't already exist. -async fn seed_default_mcp_servers(db: &Database, mcp_endpoint_url: Option<&str>) { - let endpoint = mcp_endpoint_url.unwrap_or("http://localhost:8090"); - - let defaults = [ - ( - "Findings MCP", - "Exposes security findings, triage data, and finding summaries to LLM agents", - vec!["list_findings", "get_finding", "findings_summary"], - ), - ( - "SBOM MCP", - "Exposes software bill of materials and vulnerability reports to LLM agents", - vec!["list_sbom_packages", "sbom_vuln_report"], - ), - ( - "DAST MCP", - "Exposes DAST scan findings and scan summaries to LLM agents", - vec!["list_dast_findings", "dast_scan_summary"], - ), - ]; - - let collection = db.mcp_servers(); - - let expected_url = format!("{endpoint}/mcp"); - - for (name, description, tools) in defaults { - // If it already exists, update the endpoint URL if it changed - if let Ok(Some(existing)) = collection.find_one(doc! { "name": name }).await { - if existing.endpoint_url != expected_url { - let _ = collection - .update_one( - doc! { "name": name }, - doc! { "$set": { "endpoint_url": &expected_url } }, - ) - .await; - tracing::info!( - "Updated MCP server '{name}' endpoint: {} -> {expected_url}", - existing.endpoint_url - ); - } - continue; - } - - let now = chrono::Utc::now(); - let token = format!("mcp_{}", uuid::Uuid::new_v4().to_string().replace('-', "")); - - let server = McpServerConfig { - id: None, - name: name.to_string(), - endpoint_url: format!("{endpoint}/mcp"), - transport: McpTransport::Http, - port: Some(8090), - status: McpServerStatus::Stopped, - access_token: token, - tools_enabled: tools.into_iter().map(|s| s.to_string()).collect(), - description: Some(description.to_string()), - mongodb_uri: None, - mongodb_database: None, - created_at: now, - updated_at: now, - }; - - match collection.insert_one(server).await { - Ok(_) => tracing::info!("Seeded default MCP server: {name}"), - Err(e) => tracing::warn!("Failed to seed MCP server '{name}': {e}"), - } +/// Remove the MCP server cards the dashboard used to keep for every tenant +/// at once (#432). They now live in each tenant's database at the agent, which +/// creates the default cards per tenant; the old shared ones cannot be told +/// apart by tenant, so they are dropped. +async fn retire_global_mcp_servers(db: &Database) { + let old = db + .inner() + .collection::("mcp_servers"); + match old.count_documents(doc! {}).await { + Ok(0) | Err(_) => {} + Ok(count) => match old.drop().await { + Ok(()) => tracing::info!( + "Removed {count} MCP server cards shared by all tenants; each tenant now has its own" + ), + Err(e) => tracing::warn!("Could not remove the shared MCP server cards: {e}"), + }, } } diff --git a/compliance-dashboard/src/pages/mcp_servers.rs b/compliance-dashboard/src/pages/mcp_servers.rs index e8333fe..d913de1 100644 --- a/compliance-dashboard/src/pages/mcp_servers.rs +++ b/compliance-dashboard/src/pages/mcp_servers.rs @@ -5,7 +5,7 @@ use dioxus_free_icons::Icon; use crate::components::page_header::PageHeader; use crate::components::toast::{ToastType, Toasts}; use crate::infrastructure::mcp::{ - add_mcp_server, delete_mcp_server, fetch_mcp_servers, refresh_mcp_status, regenerate_mcp_token, + add_mcp_server, delete_mcp_server, fetch_mcp_servers, regenerate_mcp_token, }; #[component] @@ -28,7 +28,6 @@ pub fn McpServersPage() -> Element { use_effect(move || { spawn(async move { refreshing.set(true); - let _ = refresh_mcp_status().await; servers.restart(); refreshing.set(false); }); diff --git a/compliance-dashboard/src/pages/overview.rs b/compliance-dashboard/src/pages/overview.rs index 7532fc5..22f4619 100644 --- a/compliance-dashboard/src/pages/overview.rs +++ b/compliance-dashboard/src/pages/overview.rs @@ -10,7 +10,7 @@ use crate::i18n::texts::{common, overview, scans as scan_texts}; use crate::i18n::{format_ago, use_lang, Lang}; use crate::infrastructure::evidence::{fetch_compliance_summary, ComplianceSummaryRow}; use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery}; -use crate::infrastructure::mcp::{fetch_mcp_servers, refresh_mcp_status}; +use crate::infrastructure::mcp::fetch_mcp_servers; use crate::infrastructure::onboarding::fetch_targets; use crate::infrastructure::platform::use_source_only; use crate::infrastructure::stats::fetch_overview_stats; @@ -295,12 +295,9 @@ fn TargetRow(line: TargetLine, lang: Lang) -> Element { fn RuntimeSections() -> Element { let lang = use_lang()(); let repos = use_resource(|| async { fetch_targets().await.ok() }); - // Probe the MCP health endpoints first so the seeded cards reflect the - // live status (running / stopped) instead of the stored default. - let mcp_servers = use_resource(|| async { - let _ = refresh_mcp_status().await; - fetch_mcp_servers().await.ok() - }); + // The listing probes each server's health, so the cards show the live + // status (running / stopped). + let mcp_servers = use_resource(|| async { fetch_mcp_servers().await.ok() }); rsx! { // AI Chat section div { class: "card",