From 9cd4ba8b1addefd0c5f8f18b1bb003bc7f328942 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 16:21:46 +0200 Subject: [PATCH] feat(mcp): contract tools for targets, scans, SBOM, CVEs and the control mapping (#273) breakpilot's document service pulls a target's evidence over MCP. It had no way to find the targets, and no SBOM document or CVE list to pull. - list_targets: id, name, type, artifact kinds and detected type (no credential leaves: the record is redacted first). - get_scan_results: a target's scan runs, newest first. - get_sbom: the whole SBOM as one CycloneDX 1.5 or SPDX 2.3 document, built by the same code as the agent's export (moved to compliance_core::sbom_docs). - list_cves: the target's CVE alerts, highest CVSS first. - get_control_mapping: the CRA Annex I mapping (OSCAL assessment results); oscal_assessment stays for existing clients. - Shared cursor/JSON helpers for the tools; the server's instructions say to start with list_targets. Not in this change (remaining in #273): run_scan (the MCP process cannot start scans), token expiry, per-call audit and entitlement checks, and hiding runtime-only tools in source-only deployments. Tests: the summary never carries a credential; parameters; and the four tools against a real tenant database (skips without MongoDB). Docs: the MCP tool tables. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/api/handlers/sbom.rs | 4 +- compliance-agent/src/evidence/mod.rs | 3 +- compliance-core/src/lib.rs | 1 + .../src}/sbom_docs.rs | 5 +- compliance-mcp/src/database.rs | 12 + compliance-mcp/src/server.rs | 61 +++- compliance-mcp/src/tools/mod.rs | 43 +++ compliance-mcp/src/tools/sbom.rs | 52 ++++ compliance-mcp/src/tools/targets.rs | 266 ++++++++++++++++++ docs/features/mcp-server.md | 22 ++ 10 files changed, 461 insertions(+), 8 deletions(-) rename {compliance-agent/src/evidence => compliance-core/src}/sbom_docs.rs (96%) create mode 100644 compliance-mcp/src/tools/targets.rs diff --git a/compliance-agent/src/api/handlers/sbom.rs b/compliance-agent/src/api/handlers/sbom.rs index f3f2b04..4c8ff18 100644 --- a/compliance-agent/src/api/handlers/sbom.rs +++ b/compliance-agent/src/api/handlers/sbom.rs @@ -167,9 +167,9 @@ pub async fn export_sbom( let subject = format!("repo-{}", params.repo_id); let body = if params.format == "spdx" { - crate::evidence::sbom_docs::spdx(&entries, ¶ms.repo_id) + compliance_core::sbom_docs::spdx(&entries, ¶ms.repo_id) } else { - crate::evidence::sbom_docs::cyclonedx(&entries, &subject) + compliance_core::sbom_docs::cyclonedx(&entries, &subject) }; let json_str = diff --git a/compliance-agent/src/evidence/mod.rs b/compliance-agent/src/evidence/mod.rs index a673409..8ff6f61 100644 --- a/compliance-agent/src/evidence/mod.rs +++ b/compliance-agent/src/evidence/mod.rs @@ -7,8 +7,6 @@ //! hash of the control catalog that produced the CRA mapping, so a report //! built from the pack can say exactly what it rests on. -pub mod sbom_docs; - use std::io::Write; use chrono::{DateTime, Utc}; @@ -17,6 +15,7 @@ use sha2::{Digest, Sha256}; use compliance_core::models::oscal_assessment::assess; use compliance_core::models::{CveAlert, Finding, OnboardedTarget, SbomEntry, ScanRun}; +use compliance_core::sbom_docs; use crate::error::AgentError; diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 63b8bf9..0b4b83a 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -7,6 +7,7 @@ pub mod exec_policy; pub mod guarded_net; pub mod models; pub mod net_guard; +pub mod sbom_docs; pub mod scan_matrix; #[cfg(feature = "telemetry")] pub mod telemetry; diff --git a/compliance-agent/src/evidence/sbom_docs.rs b/compliance-core/src/sbom_docs.rs similarity index 96% rename from compliance-agent/src/evidence/sbom_docs.rs rename to compliance-core/src/sbom_docs.rs index 0f526ea..299e76d 100644 --- a/compliance-agent/src/evidence/sbom_docs.rs +++ b/compliance-core/src/sbom_docs.rs @@ -1,7 +1,8 @@ //! SBOM documents in the two exchange formats: CycloneDX 1.5 and SPDX 2.3. -//! Shared by the SBOM export and the evidence pack, so both say the same. +//! Shared by the agent's SBOM export and evidence pack and by the MCP server, +//! so all of them say the same. -use compliance_core::models::SbomEntry; +use crate::models::SbomEntry; /// A CycloneDX 1.5 document for `entries`, named after `subject`. pub fn cyclonedx(entries: &[SbomEntry], subject: &str) -> serde_json::Value { diff --git a/compliance-mcp/src/database.rs b/compliance-mcp/src/database.rs index 670e1e2..bccb2b5 100644 --- a/compliance-mcp/src/database.rs +++ b/compliance-mcp/src/database.rs @@ -151,4 +151,16 @@ impl Database { pub fn pentest_messages(&self) -> Collection { self.inner.collection("pentest_messages") } + + pub fn onboarded_targets(&self) -> Collection { + self.inner.collection("onboarded_targets") + } + + pub fn scan_runs(&self) -> Collection { + self.inner.collection("scan_runs") + } + + pub fn cve_alerts(&self) -> Collection { + self.inner.collection("cve_alerts") + } } diff --git a/compliance-mcp/src/server.rs b/compliance-mcp/src/server.rs index 2306877..6582f15 100644 --- a/compliance-mcp/src/server.rs +++ b/compliance-mcp/src/server.rs @@ -3,7 +3,7 @@ use rmcp::{ }; use crate::database::{Database, DatabasePool}; -use crate::tools::{dast, findings, oscal, pentest, sbom}; +use crate::tools::{dast, findings, oscal, pentest, sbom, targets}; pub struct ComplianceMcpServer { pool: DatabasePool, @@ -75,6 +75,52 @@ impl ComplianceMcpServer { oscal::oscal_assessment(&db, params).await } + #[tool( + description = "CRA Annex I control mapping of a target as an OSCAL 1.1 assessment-results document (same as oscal_assessment; repo_id is the target id)" + )] + async fn get_control_mapping( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + oscal::oscal_assessment(&db, params).await + } + + // ── Targets and scans ───────────────────────────────── + + #[tool( + description = "List the tenant's targets (products under test) with their id, name, type and artifact kinds; the id is the repo_id/target_id the other tools take" + )] + async fn list_targets( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + targets::list_targets(&db, params).await + } + + #[tool( + description = "Get a target's scan runs, newest first: status, start and finish, new findings, error, and the stages that were not run with their reasons" + )] + async fn get_scan_results( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + targets::get_scan_results(&db, params).await + } + + #[tool( + description = "List the CVE alerts of a target's dependencies and firmware libraries, highest CVSS first" + )] + async fn list_cves( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + targets::list_cves(&db, params).await + } + // ── SBOM ────────────────────────────────────────────── #[tool( @@ -88,6 +134,17 @@ impl ComplianceMcpServer { sbom::list_sbom_packages(&db, params).await } + #[tool( + description = "Get a target's whole SBOM as one CycloneDX 1.5 (default) or SPDX 2.3 document" + )] + async fn get_sbom( + &self, + Parameters(params): Parameters, + ) -> Result { + let db = self.tenant_db()?; + sbom::get_sbom(&db, params).await + } + #[tool( description = "Generate a vulnerability report for a repository showing all packages with known CVEs" )] @@ -185,7 +242,7 @@ impl ServerHandler for ComplianceMcpServer { .build(), server_info: Implementation::from_build_env(), instructions: Some( - "Compliance Scanner MCP server. Query security findings, SBOM data, DAST results, and AI pentest sessions for your tenant." + "Prüfwerk MCP server. Start with list_targets; each target's id is the repo_id/target_id the other tools take. Query findings, the CRA control mapping (OSCAL), SBOMs (CycloneDX, SPDX), CVE alerts, scan runs, DAST results and pentest sessions of your tenant." .to_string(), ), } diff --git a/compliance-mcp/src/tools/mod.rs b/compliance-mcp/src/tools/mod.rs index 2a3751c..9877de3 100644 --- a/compliance-mcp/src/tools/mod.rs +++ b/compliance-mcp/src/tools/mod.rs @@ -3,3 +3,46 @@ pub mod findings; pub mod oscal; pub mod pentest; pub mod sbom; +pub mod targets; + +use rmcp::{model::*, ErrorData as McpError}; + +/// Every document a cursor yields. +/// +/// # Errors +/// +/// A database or decoding error, as an internal MCP error. +pub async fn collect(mut cursor: mongodb::Cursor) -> Result, McpError> +where + T: serde::de::DeserializeOwned + Send + Sync, +{ + let mut items = Vec::new(); + while cursor + .advance() + .await + .map_err(|e| McpError::internal_error(format!("cursor error: {e}"), None))? + { + items.push( + cursor + .deserialize_current() + .map_err(|e| McpError::internal_error(format!("deserialize error: {e}"), None))?, + ); + } + Ok(items) +} + +/// A tool result holding `value` as pretty JSON. +/// +/// # Errors +/// +/// When `value` does not serialise. +pub fn json_result(value: &T) -> Result { + let json = serde_json::to_string_pretty(value) + .map_err(|e| McpError::internal_error(format!("json error: {e}"), None))?; + Ok(CallToolResult::success(vec![Content::text(json)])) +} + +/// A database error as an internal MCP error. +pub fn db_error(e: mongodb::error::Error) -> McpError { + McpError::internal_error(format!("DB error: {e}"), None) +} diff --git a/compliance-mcp/src/tools/sbom.rs b/compliance-mcp/src/tools/sbom.rs index 86806f0..dac11fc 100644 --- a/compliance-mcp/src/tools/sbom.rs +++ b/compliance-mcp/src/tools/sbom.rs @@ -187,3 +187,55 @@ pub async fn sbom_vuln_report( Ok(CallToolResult::success(vec![Content::text(json)])) } + +/// The SBOM exchange formats `get_sbom` writes. +#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum SbomFormat { + /// CycloneDX 1.5 (the default). + #[default] + Cyclonedx, + /// SPDX 2.3. + Spdx, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct GetSbomParams { + /// The target id (as `list_targets` returns it). + pub target_id: String, + /// `cyclonedx` (default) or `spdx`. + #[serde(default)] + pub format: SbomFormat, +} + +/// Components one SBOM document is built from, as for the agent's export. +const MAX_SBOM_COMPONENTS: u64 = 100_000; + +/// `get_sbom`: a target's whole SBOM as one CycloneDX or SPDX document, the +/// same document the agent's export and evidence pack hold. +pub async fn get_sbom(db: &Database, params: GetSbomParams) -> Result { + let filter = doc! { "repo_id": ¶ms.target_id }; + let count = db + .sbom_entries() + .count_documents(filter.clone()) + .await + .map_err(super::db_error)?; + if count > MAX_SBOM_COMPONENTS { + return Err(McpError::invalid_request( + format!("the SBOM has {count} components, more than one document holds"), + None, + )); + } + let entries = super::collect( + db.sbom_entries() + .find(filter) + .await + .map_err(super::db_error)?, + ) + .await?; + let document = match params.format { + SbomFormat::Cyclonedx => compliance_core::sbom_docs::cyclonedx(&entries, ¶ms.target_id), + SbomFormat::Spdx => compliance_core::sbom_docs::spdx(&entries, ¶ms.target_id), + }; + super::json_result(&document) +} diff --git a/compliance-mcp/src/tools/targets.rs b/compliance-mcp/src/tools/targets.rs new file mode 100644 index 0000000..62e313a --- /dev/null +++ b/compliance-mcp/src/tools/targets.rs @@ -0,0 +1,266 @@ +//! Targets, their scan runs and their CVE alerts: the contract tools (#273) +//! a client needs to find what to ask the other tools about. + +use mongodb::bson::doc; +use rmcp::{model::*, ErrorData as McpError}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use compliance_core::models::{Credentials, OnboardedTarget}; + +use super::{collect, db_error, json_result}; +use crate::database::Database; + +/// Most scan runs one call returns. +const MAX_RUNS: i64 = 50; +/// Scan runs returned when the caller does not say. +const DEFAULT_RUNS: i64 = 10; + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListTargetsParams {} + +/// A target as the tools name it: its id is the `repo_id` the finding, SBOM +/// and OSCAL tools take. +#[derive(Debug, Serialize, PartialEq)] +pub struct TargetSummary { + pub id: String, + pub name: String, + pub target_type: String, + /// The artifact kinds attached (`git_repo`, `source_archive`, ...). + pub artifacts: Vec, + /// The type detection suggested, when it ran. + pub detected_type: Option, +} + +impl From for TargetSummary { + fn from(target: OnboardedTarget) -> Self { + // Nothing of a credential leaves the service, even by accident. + let target = target.redacted(); + Self { + id: target.id.map(|id| id.to_hex()).unwrap_or_default(), + name: target.name, + target_type: target.target_type.to_string(), + artifacts: target + .artifacts + .iter() + .map(|a| { + serde_json::to_value(a.kind) + .ok() + .and_then(|v| v.as_str().map(String::from)) + .unwrap_or_default() + }) + .collect(), + detected_type: target.classification.map(|c| c.suggested.to_string()), + } + } +} + +/// `list_targets`: every target of the tenant. +pub async fn list_targets( + db: &Database, + _params: ListTargetsParams, +) -> Result { + let targets = collect( + db.onboarded_targets() + .find(doc! {}) + .sort(doc! { "name": 1 }) + .await + .map_err(db_error)?, + ) + .await?; + let summaries: Vec = targets.into_iter().map(TargetSummary::from).collect(); + json_result(&summaries) +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct GetScanResultsParams { + /// The target id (as `list_targets` returns it). + pub target_id: String, + /// How many runs, newest first (default 10, max 50). + pub limit: Option, +} + +/// `get_scan_results`: a target's scan runs, newest first, with their status, +/// new-finding count, error and the stages they did not run. +pub async fn get_scan_results( + db: &Database, + params: GetScanResultsParams, +) -> Result { + let limit = params.limit.unwrap_or(DEFAULT_RUNS).clamp(1, MAX_RUNS); + let runs = collect( + db.scan_runs() + .find(doc! { "repo_id": ¶ms.target_id }) + .sort(doc! { "started_at": -1 }) + .limit(limit) + .await + .map_err(db_error)?, + ) + .await?; + json_result(&runs) +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListCvesParams { + /// The target id (as `list_targets` returns it). + pub target_id: String, +} + +/// `list_cves`: the CVE alerts of a target's dependencies and firmware +/// libraries, highest CVSS first. +pub async fn list_cves(db: &Database, params: ListCvesParams) -> Result { + let alerts = collect( + db.cve_alerts() + .find(doc! { "repo_id": ¶ms.target_id }) + .sort(doc! { "cvss_score": -1 }) + .await + .map_err(db_error)?, + ) + .await?; + json_result(&alerts) +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::{Artifact, ArtifactAuth, TargetType}; + + #[test] + fn a_summary_names_the_target_and_never_carries_a_credential() { + let mut target = OnboardedTarget::new("gateway".into(), TargetType::FirmwareRtos); + target.id = Some(mongodb::bson::oid::ObjectId::new()); + let mut repo = Artifact::git_repo("https://git.example.com/a.git", "main"); + repo.auth = Some(ArtifactAuth { + method: "token".into(), + secret: Some("enc:v1:secret".into()), + ..Default::default() + }); + target.artifacts = vec![repo]; + + let summary = TargetSummary::from(target); + assert_eq!(summary.name, "gateway"); + assert_eq!(summary.target_type, "firmware_rtos"); + assert_eq!(summary.artifacts, ["git_repo"]); + assert!(!serde_json::to_string(&summary) + .unwrap_or_default() + .contains("enc:v1")); + } + + #[test] + fn params_read_as_documented() { + let p: GetScanResultsParams = + serde_json::from_value(serde_json::json!({ "target_id": "t" })) + .unwrap_or_else(|e| panic!("params: {e}")); + assert_eq!(p.limit, None); + assert!(serde_json::from_value::(serde_json::json!({})).is_err()); + } + + /// The text of a successful tool result. + fn text(result: CallToolResult) -> String { + result + .content + .iter() + .filter_map(|c| c.as_text().map(|t| t.text.clone())) + .collect() + } + + /// The contract tools against a real tenant database: what a client sees + /// for a target with an SBOM entry and a CVE alert. Skips without Mongo. + #[tokio::test] + async fn the_contract_tools_answer_for_a_target() { + use compliance_core::models::{CveAlert, CveSource, SbomEntry}; + + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + // A fresh prefix per run: the tail of a new ObjectId is unique enough. + let prefix = format!( + "mcp_{}", + &mongodb::bson::oid::ObjectId::new().to_hex()[14..] + ); + let Ok(pool) = crate::database::DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP: no MongoDB at {uri}"); + return; + }; + let db = pool.for_tenant_id("t1"); + let mut target = OnboardedTarget::new("gateway".into(), TargetType::FirmwareRtos); + let id = mongodb::bson::oid::ObjectId::new(); + target.id = Some(id); + let target_id = id.to_hex(); + db.onboarded_targets() + .insert_one(&target) + .await + .unwrap_or_else(|e| panic!("{e}")); + let entry = SbomEntry::new( + target_id.clone(), + "lwIP".into(), + "2.1.2".into(), + "embedded".into(), + ); + db.sbom_entries() + .insert_one(&entry) + .await + .unwrap_or_else(|e| panic!("{e}")); + let alert = CveAlert::new( + "CVE-2020-22283".into(), + target_id.clone(), + "lwIP".into(), + "2.1.2".into(), + CveSource::Nvd, + ); + db.cve_alerts() + .insert_one(&alert) + .await + .unwrap_or_else(|e| panic!("{e}")); + + let listed = text( + list_targets(&db, ListTargetsParams {}) + .await + .unwrap_or_else(|e| panic!("{e:?}")), + ); + let sbom = text( + super::super::sbom::get_sbom( + &db, + super::super::sbom::GetSbomParams { + target_id: target_id.clone(), + format: super::super::sbom::SbomFormat::Spdx, + }, + ) + .await + .unwrap_or_else(|e| panic!("{e:?}")), + ); + let cves = text( + list_cves( + &db, + ListCvesParams { + target_id: target_id.clone(), + }, + ) + .await + .unwrap_or_else(|e| panic!("{e:?}")), + ); + let runs = text( + get_scan_results( + &db, + GetScanResultsParams { + target_id, + limit: None, + }, + ) + .await + .unwrap_or_else(|e| panic!("{e:?}")), + ); + + assert!( + listed.contains("gateway") && listed.contains(&id.to_hex()), + "{listed}" + ); + assert!(sbom.contains("SPDX-2.3") && sbom.contains("lwIP"), "{sbom}"); + assert!(cves.contains("CVE-2020-22283"), "{cves}"); + assert_eq!(runs.trim(), "[]"); + let _ = pool + .admin_db() + .client() + .database(&pool.tenant_db_name("t1")) + .drop() + .await; + } +} diff --git a/docs/features/mcp-server.md b/docs/features/mcp-server.md index 6c09159..c8cb7d5 100644 --- a/docs/features/mcp-server.md +++ b/docs/features/mcp-server.md @@ -47,6 +47,27 @@ endpoint itself is reachable from your client. The MCP server exposes seven tools that LLM clients can discover and call: +### Targets and Scans + +Start here: each target's id is the `repo_id` / `target_id` the other tools take. + +| Tool | Description | +|------|-------------| +| `list_targets` | The tenant's targets with id, name, type, artifact kinds and the detected type. No credentials are returned. | +| `get_scan_results` | A target's scan runs, newest first (default 10, max 50): status, times, new findings, error, and the stages not run with their reasons. | +| `list_cves` | The CVE alerts of a target's dependencies and firmware libraries, highest CVSS first. | + +### Compliance Tools + +| Tool | Description | +|------|-------------| +| `get_control_mapping` | The target's CRA Annex I control mapping as an OSCAL 1.1 assessment-results document. | +| `oscal_assessment` | The same document (kept for existing clients). | + +The whole evidence set (OSCAL, both SBOM formats, findings, CVE alerts and a +manifest of sha256 checksums) is also served as one ZIP at +`GET /api/v1/targets/{id}/evidence-pack`. + ### Findings Tools | Tool | Description | @@ -59,6 +80,7 @@ The MCP server exposes seven tools that LLM clients can discover and call: | Tool | Description | |------|-------------| +| `get_sbom` | A target's whole SBOM as one CycloneDX 1.5 (default) or SPDX 2.3 document, the same the API exports. | | `list_sbom_packages` | List SBOM packages with filters for repository, vulnerabilities, package manager, and license. | | `sbom_vuln_report` | Generate a vulnerability report for a repository showing all packages with known CVEs. | -- 2.54.1