feat(mcp): contract tools for targets, scans, SBOM, CVEs and the control mapping (#273) #353

Merged
sharang merged 1 commits from feat/mcp-contract-tools into main 2026-09-23 15:54:40 +00:00
10 changed files with 461 additions and 8 deletions

No files matched your search

+2 -2
View File
@@ -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, &params.repo_id)
compliance_core::sbom_docs::spdx(&entries, &params.repo_id)
} else {
crate::evidence::sbom_docs::cyclonedx(&entries, &subject)
compliance_core::sbom_docs::cyclonedx(&entries, &subject)
};
let json_str =
+1 -2
View File
@@ -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;
+1
View File
@@ -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;
@@ -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 {
+12
View File
@@ -151,4 +151,16 @@ impl Database {
pub fn pentest_messages(&self) -> Collection<PentestMessage> {
self.inner.collection("pentest_messages")
}
pub fn onboarded_targets(&self) -> Collection<OnboardedTarget> {
self.inner.collection("onboarded_targets")
}
pub fn scan_runs(&self) -> Collection<ScanRun> {
self.inner.collection("scan_runs")
}
pub fn cve_alerts(&self) -> Collection<CveAlert> {
self.inner.collection("cve_alerts")
}
}
+59 -2
View File
@@ -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<oscal::OscalAssessmentParams>,
) -> Result<CallToolResult, rmcp::ErrorData> {
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<targets::ListTargetsParams>,
) -> Result<CallToolResult, rmcp::ErrorData> {
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<targets::GetScanResultsParams>,
) -> Result<CallToolResult, rmcp::ErrorData> {
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<targets::ListCvesParams>,
) -> Result<CallToolResult, rmcp::ErrorData> {
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<sbom::GetSbomParams>,
) -> Result<CallToolResult, rmcp::ErrorData> {
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(),
),
}
+43
View File
@@ -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<T>(mut cursor: mongodb::Cursor<T>) -> Result<Vec<T>, 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<T: serde::Serialize>(value: &T) -> Result<CallToolResult, McpError> {
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)
}
+52
View File
@@ -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<CallToolResult, McpError> {
let filter = doc! { "repo_id": &params.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, &params.target_id),
SbomFormat::Spdx => compliance_core::sbom_docs::spdx(&entries, &params.target_id),
};
super::json_result(&document)
}
+266
View File
@@ -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<String>,
/// The type detection suggested, when it ran.
pub detected_type: Option<String>,
}
impl From<OnboardedTarget> 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<CallToolResult, McpError> {
let targets = collect(
db.onboarded_targets()
.find(doc! {})
.sort(doc! { "name": 1 })
.await
.map_err(db_error)?,
)
.await?;
let summaries: Vec<TargetSummary> = 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<i64>,
}
/// `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<CallToolResult, McpError> {
let limit = params.limit.unwrap_or(DEFAULT_RUNS).clamp(1, MAX_RUNS);
let runs = collect(
db.scan_runs()
.find(doc! { "repo_id": &params.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<CallToolResult, McpError> {
let alerts = collect(
db.cve_alerts()
.find(doc! { "repo_id": &params.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::<ListCvesParams>(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;
}
}
+22
View File
@@ -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. |