Skip to content

Scanners

Vulnerability scanners that query OSV, NVD, and other databases.

agent_bom.scanners

Vulnerability scanning — re-exports for agent_bom.scanners public surface.

The package_scan re-exports resolve on first use: importing any agent_bom.scanners.* submodule (the CLI does this for --help) must not pay for the vulnerability-matching stack.

ScannerExecutionState

Bases: str, Enum

Whether a driver is executable today or declared as a roadmap slot.

Source code in src/agent_bom/scanners/base.py
class ScannerExecutionState(str, Enum):
    """Whether a driver is executable today or declared as a roadmap slot."""

    ACTIVE = "active"
    PASSIVE = "passive"
    PLANNED = "planned"

ScannerFailureMode

Bases: str, Enum

How the orchestrator should treat driver failures.

Source code in src/agent_bom/scanners/base.py
class ScannerFailureMode(str, Enum):
    """How the orchestrator should treat driver failures."""

    FAIL_CLOSED = "fail_closed"
    WARN_AND_CONTINUE = "warn_and_continue"
    SKIP_WHEN_UNAVAILABLE = "skip_when_unavailable"

ScannerPhase

Bases: str, Enum

Pipeline phase where a scanner driver contributes evidence.

Source code in src/agent_bom/scanners/base.py
class ScannerPhase(str, Enum):
    """Pipeline phase where a scanner driver contributes evidence."""

    DISCOVERY = "discovery"
    EXTRACTION = "extraction"
    SCANNING = "scanning"
    ENRICHMENT = "enrichment"
    ANALYSIS = "analysis"
    OUTPUT = "output"

ScannerRegistration dataclass

Bases: RegistryEntry

Registry metadata for a scanner driver implementation.

Source code in src/agent_bom/scanners/base.py
@dataclass(frozen=True)
class ScannerRegistration(RegistryEntry):
    """Registry metadata for a scanner driver implementation."""

    phase: ScannerPhase = ScannerPhase.SCANNING
    execution_state: ScannerExecutionState = ScannerExecutionState.ACTIVE
    failure_mode: ScannerFailureMode = ScannerFailureMode.WARN_AND_CONTINUE
    enabled_by_default: bool = True
    run_attr: str = ""
    input_types: tuple[str, ...] = ()
    output_types: tuple[str, ...] = ()
    finding_types: tuple[str, ...] = ()
    skip_when: tuple[str, ...] = ()
    telemetry_keys: tuple[str, ...] = ()
    standards: tuple[str, ...] = ()
    summary: str = ""

    def to_dict(self) -> dict[str, Any]:
        """Return a stable API/CLI-safe representation."""

        return {
            "name": self.name,
            "module": self.module,
            "source": self.source,
            "phase": self.phase.value,
            "execution_state": self.execution_state.value,
            "failure_mode": self.failure_mode.value,
            "enabled_by_default": self.enabled_by_default,
            "run_attr": self.run_attr,
            "input_types": list(self.input_types),
            "output_types": list(self.output_types),
            "finding_types": list(self.finding_types),
            "skip_when": list(self.skip_when),
            "telemetry_keys": list(self.telemetry_keys),
            "standards": list(self.standards),
            "summary": self.summary,
            "capabilities": {
                "scan_modes": list(self.capabilities.scan_modes),
                "required_scopes": list(self.capabilities.required_scopes),
                "permissions_used": list(self.capabilities.permissions_used),
                "outbound_destinations": list(self.capabilities.outbound_destinations),
                "data_boundary": self.capabilities.data_boundary,
                "writes": self.capabilities.writes,
                "network_access": self.capabilities.network_access,
                "guarantees": list(self.capabilities.guarantees),
            },
        }

to_dict

to_dict() -> dict[str, Any]

Return a stable API/CLI-safe representation.

Source code in src/agent_bom/scanners/base.py
def to_dict(self) -> dict[str, Any]:
    """Return a stable API/CLI-safe representation."""

    return {
        "name": self.name,
        "module": self.module,
        "source": self.source,
        "phase": self.phase.value,
        "execution_state": self.execution_state.value,
        "failure_mode": self.failure_mode.value,
        "enabled_by_default": self.enabled_by_default,
        "run_attr": self.run_attr,
        "input_types": list(self.input_types),
        "output_types": list(self.output_types),
        "finding_types": list(self.finding_types),
        "skip_when": list(self.skip_when),
        "telemetry_keys": list(self.telemetry_keys),
        "standards": list(self.standards),
        "summary": self.summary,
        "capabilities": {
            "scan_modes": list(self.capabilities.scan_modes),
            "required_scopes": list(self.capabilities.required_scopes),
            "permissions_used": list(self.capabilities.permissions_used),
            "outbound_destinations": list(self.capabilities.outbound_destinations),
            "data_boundary": self.capabilities.data_boundary,
            "writes": self.capabilities.writes,
            "network_access": self.capabilities.network_access,
            "guarantees": list(self.capabilities.guarantees),
        },
    }

IncompleteScanError

Bases: RuntimeError

Raised when a scan cannot produce a trustworthy verdict.

Source code in src/agent_bom/scanners/scan_options.py
class IncompleteScanError(RuntimeError):
    """Raised when a scan cannot produce a trustworthy verdict."""

ScanOptions dataclass

Immutable per-scan scanner controls.

The legacy module-level setters remain for CLI compatibility, but request handlers and concurrent scan callers should pass explicit options so tenant policy cannot bleed through shared module state.

Source code in src/agent_bom/scanners/scan_options.py
@dataclass(frozen=True)
class ScanOptions:
    """Immutable per-scan scanner controls.

    The legacy module-level setters remain for CLI compatibility, but request
    handlers and concurrent scan callers should pass explicit options so tenant
    policy cannot bleed through shared module state.
    """

    offline: bool = False
    compliance_enabled: bool = False
    resolve_transitive: bool = False
    prefer_local_db: bool = False
    demo_advisories: bool = False
    # Target project directory (the ``-p`` path) for local install resolution.
    # When set, bare/floating versions are resolved against the target — its
    # virtualenv for pip, the dir itself for npm/go — never the scanner host.
    project_dir: Optional[str] = None
    # Advisories on a registry-selected (range/unpinned) version become
    # possibly-affected candidates; ``check`` of a named target turns this off.
    registry_selected_as_candidates: bool = True

expand_blast_radius_hops

expand_blast_radius_hops(blast_radii: list[BlastRadius], agents: list[Agent], max_depth: int = 1) -> None

Preserve direct findings without inventing cross-agent delegation.

These inputs describe configured inventory, not directed delegation or credential-use receipts. Even an identical remote endpoint does not prove that one client can reach another client or its credentials. The retired shared-name traversal therefore cannot qualify additional hops or risk.

Keep the callable for existing scanner integrations. Historical fields already supplied by a caller remain intact; this function does not rewrite stored evidence. Typed graph queries own evidence-backed path analysis.

Source code in src/agent_bom/scanners/blast_radius.py
def expand_blast_radius_hops(
    blast_radii: list[BlastRadius],
    agents: list[Agent],
    max_depth: int = 1,
) -> None:
    """Preserve direct findings without inventing cross-agent delegation.

    These inputs describe configured inventory, not directed delegation or
    credential-use receipts. Even an identical remote endpoint does not prove
    that one client can reach another client or its credentials. The retired
    shared-name traversal therefore cannot qualify additional hops or risk.

    Keep the callable for existing scanner integrations. Historical fields
    already supplied by a caller remain intact; this function does not rewrite
    stored evidence. Typed graph queries own evidence-backed path analysis.
    """
    return None

builtin_scanner_registrations

builtin_scanner_registrations() -> list[ScannerRegistration]

Return built-in scanner registrations with capability metadata.

Source code in src/agent_bom/scanners/builtin_registrations.py
def builtin_scanner_registrations() -> list[ScannerRegistration]:
    """Return built-in scanner registrations with capability metadata."""

    local_read = _local_read_capabilities()
    return [
        *_code_registrations(local_read),
        *_sast_and_ingest_registrations(local_read),
        *_container_and_sbom_registrations(local_read),
        *_infrastructure_registrations(local_read),
        *_pipeline_and_dataset_registrations(local_read),
        *_content_and_policy_registrations(local_read),
        *_advisory_and_runtime_registrations(local_read),
        *_heuristic_registrations(local_read),
    ]

get_scanner_registration

get_scanner_registration(name: str) -> ScannerRegistration

Return one scanner registration or raise KeyError.

Source code in src/agent_bom/scanners/registry.py
def get_scanner_registration(name: str) -> ScannerRegistration:
    """Return one scanner registration or raise ``KeyError``."""

    _ensure_scanner_registry_loaded()
    return _SCANNER_REGISTRY[name]

list_registered_scanners

list_registered_scanners(*, include_planned: bool = True) -> list[ScannerRegistration]

Return registered scanner drivers sorted by name.

Source code in src/agent_bom/scanners/registry.py
def list_registered_scanners(*, include_planned: bool = True) -> list[ScannerRegistration]:
    """Return registered scanner drivers sorted by name."""

    _ensure_scanner_registry_loaded()
    registrations = [_SCANNER_REGISTRY[name] for name in sorted(_SCANNER_REGISTRY)]
    if include_planned:
        return registrations
    return [registration for registration in registrations if registration.execution_state != ScannerExecutionState.PLANNED]

register_scanner

register_scanner(registration: ScannerRegistration) -> None

Register a scanner driver with capability and execution metadata.

Source code in src/agent_bom/scanners/registry.py
def register_scanner(registration: ScannerRegistration) -> None:
    """Register a scanner driver with capability and execution metadata."""

    if not registration.name:
        raise ValueError("scanner registration must declare a name")
    if registration.name in _SCANNER_REGISTRY:
        raise ValueError(f"duplicate scanner registration: {registration.name}")
    _SCANNER_REGISTRY[registration.name] = registration

scanner_registry_summary

scanner_registry_summary() -> dict[str, object]

Return a compact scanner registry summary for API/UI surfaces.

Source code in src/agent_bom/scanners/registry.py
def scanner_registry_summary() -> dict[str, object]:
    """Return a compact scanner registry summary for API/UI surfaces."""

    registrations = list_registered_scanners(include_planned=True)
    by_phase: dict[str, int] = {}
    by_state: dict[str, int] = {}
    for registration in registrations:
        by_phase[registration.phase.value] = by_phase.get(registration.phase.value, 0) + 1
        by_state[registration.execution_state.value] = by_state.get(registration.execution_state.value, 0) + 1
    return {
        "total": len(registrations),
        "active": by_state.get(ScannerExecutionState.ACTIVE.value, 0),
        "passive": by_state.get(ScannerExecutionState.PASSIVE.value, 0),
        "planned": by_state.get(ScannerExecutionState.PLANNED.value, 0),
        "by_phase": by_phase,
        "by_state": by_state,
    }

scanner_registry_warnings

scanner_registry_warnings() -> list[str]

Return sanitized non-fatal registry loading warnings.

Source code in src/agent_bom/scanners/registry.py
def scanner_registry_warnings() -> list[str]:
    """Return sanitized non-fatal registry loading warnings."""

    _ensure_scanner_registry_loaded()
    return list(_SCANNER_REGISTRY_WARNINGS)

advisory_id_severity_fallback

advisory_id_severity_fallback(advisory_id: str) -> tuple[Severity, Optional[str]]

Return conservative triage severity for advisory-only IDs.

Some advisory ecosystems publish IDs before CVSS/vendor severity arrives. These should not stay invisible as unknown findings in operator views, but only known advisory namespaces get this fallback. Arbitrary missing severity still remains UNKNOWN.

Source code in src/agent_bom/scanners/risk.py
def advisory_id_severity_fallback(advisory_id: str) -> tuple[Severity, Optional[str]]:
    """Return conservative triage severity for advisory-only IDs.

    Some advisory ecosystems publish IDs before CVSS/vendor severity arrives.
    These should not stay invisible as ``unknown`` findings in operator views,
    but only known advisory namespaces get this fallback. Arbitrary missing
    severity still remains ``UNKNOWN``.
    """
    normalized = advisory_id.upper()
    if normalized.startswith("GHSA-"):
        return Severity.MEDIUM, "ghsa_heuristic"
    if normalized.startswith(_OSV_MEDIUM_FALLBACK_PREFIXES):
        return Severity.MEDIUM, "osv_heuristic"
    if normalized.startswith(_DISTRO_MEDIUM_FALLBACK_PREFIXES):
        return Severity.MEDIUM, "distro_advisory_heuristic"
    return Severity.UNKNOWN, None

parse_cvss_vector

parse_cvss_vector(vector: str) -> Optional[float]

Compute CVSS base score from a vector string (v3.x and v4.0).

Source code in src/agent_bom/core/cvss.py
def parse_cvss_vector(vector: str) -> Optional[float]:
    """Compute CVSS base score from a vector string (v3.x and v4.0)."""
    try:
        vector = vector.strip()
        if vector.startswith("CVSS:4"):
            return parse_cvss4_vector(vector)
        if not vector.startswith("CVSS:3"):
            return None

        parts = vector.split("/")[1:]
        metrics = dict(p.split(":") for p in parts)

        av = _CVSS3_AV.get(metrics.get("AV", ""), None)
        ac = _CVSS3_AC.get(metrics.get("AC", ""), None)
        scope = metrics.get("S", "U")
        pr_map = _CVSS3_PR_C if scope == "C" else _CVSS3_PR_U
        pr = pr_map.get(metrics.get("PR", ""), None)
        ui = _CVSS3_UI.get(metrics.get("UI", ""), None)
        c = _CVSS3_CIA.get(metrics.get("C", ""), None)
        i = _CVSS3_CIA.get(metrics.get("I", ""), None)
        a = _CVSS3_CIA.get(metrics.get("A", ""), None)

        if any(value is None for value in (av, ac, pr, ui, c, i, a)):
            return None

        av, ac, pr, ui = float(av), float(ac), float(pr), float(ui)  # type: ignore[arg-type]
        c, i, a = float(c), float(i), float(a)  # type: ignore[arg-type]

        isc_base = 1.0 - (1.0 - c) * (1.0 - i) * (1.0 - a)
        if scope == "C":
            isc = 7.52 * (isc_base - 0.029) - 3.25 * ((isc_base - 0.02) ** 15)
        else:
            isc = 6.42 * isc_base

        if isc <= 0:
            return 0.0

        exploitability = 8.22 * av * ac * pr * ui
        raw = min(1.08 * (isc + exploitability), 10.0) if scope == "C" else min(isc + exploitability, 10.0)
        return math.ceil(raw * 10) / 10.0
    except Exception:  # noqa: BLE001
        _logger.debug("CVSS vector parse failed")
        return None

parse_osv_severity

parse_osv_severity(vuln_data: dict) -> tuple[Severity, Optional[float], Optional[str]]

Extract severity, CVSS score, and severity source from OSV data.

Source code in src/agent_bom/scanners/risk.py
def parse_osv_severity(vuln_data: dict) -> tuple[Severity, Optional[float], Optional[str]]:
    """Extract severity, CVSS score, and severity source from OSV data."""
    basis = osv_severity_basis(vuln_data)
    return basis.severity, basis.cvss_score, basis.severity_source

severity_from_label

severity_from_label(raw: Any) -> Severity

Normalize vendor labels into the scanner's supported severity enum.

Source code in src/agent_bom/core/severity.py
def severity_from_label(raw: Any) -> Severity:
    """Normalize vendor labels into the scanner's supported severity enum."""
    label = normalize_severity(str(raw) if raw is not None else None)
    return Severity(label) if label != "info" else Severity.UNKNOWN

peek_coverage_warnings

peek_coverage_warnings() -> list[dict]

Read the structured coverage warnings without draining them.

The scanner needs to see what a sub-step recorded (e.g. an OSV lookup failure) while leaving the channel intact for the command boundary that actually consumes it.

Source code in src/agent_bom/scanners/state.py
def peek_coverage_warnings() -> list[dict]:
    """Read the structured coverage warnings without draining them.

    The scanner needs to see what a sub-step recorded (e.g. an OSV lookup
    failure) while leaving the channel intact for the command boundary that
    actually consumes it.
    """
    return list(_coverage_warnings_state())

record_coverage_warning

record_coverage_warning(warning: dict, *, replace: bool = False) -> None

Record a structured per-release coverage-gap warning (deduped by release).

replace swaps an earlier entry for the same release instead of keeping it, for receipts whose detail accumulates across scanner batches.

Source code in src/agent_bom/scanners/state.py
def record_coverage_warning(warning: dict, *, replace: bool = False) -> None:
    """Record a structured per-release coverage-gap warning (deduped by release).

    ``replace`` swaps an earlier entry for the same release instead of keeping
    it, for receipts whose detail accumulates across scanner batches.
    """
    captured = _coverage_capture.get()
    if captured is not None:
        captured.append(dict(warning))
    warnings = _coverage_warnings_state()
    release = warning.get("release")
    if any(existing.get("release") == release for existing in warnings):
        if not replace:
            return
        warnings[:] = [existing for existing in warnings if existing.get("release") != release]
    warnings.append(warning)

reset_scan_warnings

reset_scan_warnings() -> None

Reset all scan warning channels at a command/request boundary.

Source code in src/agent_bom/scanners/state.py
def reset_scan_warnings() -> None:
    """Reset all scan warning channels at a command/request boundary."""
    _scan_state_local.warnings = []
    _scan_state_local.coverage_warnings = []
    _scan_state_local.resolution_deadline = None
    _scan_state_local.epss_outcome = None
    _scan_state_local.epss_summary = None

reset_scan_warnings_only

reset_scan_warnings_only() -> None

Reset transient scanner warnings without discarding parser coverage gaps.

Project manifest parsers can run before vulnerability scanning and record a structured coverage warning. The package scanner must clear warnings from a prior scan, but must preserve those parser warnings for the final report.

Source code in src/agent_bom/scanners/state.py
def reset_scan_warnings_only() -> None:
    """Reset transient scanner warnings without discarding parser coverage gaps.

    Project manifest parsers can run before vulnerability scanning and record a
    structured coverage warning. The package scanner must clear warnings from a
    prior scan, but must preserve those parser warnings for the final report.
    """
    _scan_state_local.warnings = []

build_vulnerabilities

build_vulnerabilities(vuln_data_list: list[dict], package: Package) -> list[Vulnerability]

Convert OSV response data to Vulnerability objects.

Filters out false positives by verifying the package version falls within OSV affected ranges. Deduplicates by canonical CVE ID.

Source code in src/agent_bom/scanners/package_scan.py
def build_vulnerabilities(vuln_data_list: list[dict], package: Package) -> list[Vulnerability]:
    """Convert OSV response data to Vulnerability objects.

    Filters out false positives by verifying the package version falls
    within OSV affected ranges.  Deduplicates by canonical CVE ID.
    """
    vulns = []

    for raw_vuln_data in eligible_advisories(vuln_data_list, package, _emit_scan_warning):
        vuln_data = _scope_advisory_to_package_release(raw_vuln_data, package)
        if vuln_data is None:
            continue
        vuln_id = vuln_data.get("id", "unknown")

        # Version-range filter: skip vulns that don't affect our version
        if package.version and package.version not in ("unknown", "latest"):
            if not _is_version_affected(
                vuln_data,
                package.name,
                package.version,
                package.ecosystem,
                source_package=package.source_package,
                aliases=tuple(package.lookup_names),
            ):
                _logger.debug("Filtered %s: version %s not in affected range for %s", vuln_id, package.version, package.name)
                continue

        from agent_bom.advisory_ids import canonical_vulnerability_id, match_confidence_tier

        aliases = vuln_data.get("aliases", [])
        canonical_id, all_aliases = canonical_vulnerability_id(vuln_id, aliases)

        severity, cvss_score, sev_source = parse_osv_severity(vuln_data)
        cvss_vector = osv_cvss_vector(vuln_data) if cvss_score is not None else None
        fixed = parse_fixed_version(
            vuln_data,
            package.name,
            package.ecosystem,
            current_version=package.version or "",
            source_package=package.source_package,
            aliases=tuple(package.lookup_names),
        )

        references = [ref.get("url", "") for ref in vuln_data.get("references", []) if ref.get("url")]

        summary = vuln_data.get("summary", vuln_data.get("details", "No description available"))[:200]

        # Extract CWE IDs from database_specific (GHSA entries store them here)
        cwe_ids: list[str] = []
        db_specific = vuln_data.get("database_specific", {})
        if isinstance(db_specific, dict):
            raw_cwes = db_specific.get("cwe_ids", [])
            if isinstance(raw_cwes, list):
                cwe_ids = [c for c in raw_cwes if isinstance(c, str) and c.startswith("CWE-")]

        affected_symbols = advisory_affected_symbols_list(vuln_data)
        affected_symbols_by_path = advisory_affected_symbols_by_path(vuln_data)

        vulns.append(
            Vulnerability(
                id=canonical_id,
                summary=summary,
                severity=severity,
                severity_source=sev_source,
                cvss_score=cvss_score,
                cvss_vector=cvss_vector,
                fixed_version=fixed,
                fix_is_prerelease=fix_is_prerelease(fixed, package.ecosystem),
                references=references,
                published_at=vuln_data.get("published"),
                modified_at=vuln_data.get("modified"),
                upstream_ids=upstream_advisory_ids(vuln_data.get("upstream")),
                aliases=all_aliases,
                cwe_ids=cwe_ids,
                affected_symbols=affected_symbols,
                affected_symbols_by_path=affected_symbols_by_path,
                advisory_sources=["osv"],
                match_confidence_tier=match_confidence_tier(
                    advisory_source="osv",
                    db_ecosystem=None,
                    package_ecosystem=package.ecosystem,
                    fixed_version=fixed,
                ),
            )
        )

    from agent_bom.scanners.advisory_merge import fix_fallback_allowed, merge_advisory_clusters

    vulns = merge_advisory_clusters(vulns, fix_fallback=fix_fallback_allowed(package))
    _apply_distro_release_ambiguity(package, vulns)
    return vulns

create_client

create_client(timeout: float | None = None, max_redirects: int = 0, *, cert: str | tuple[str, str] | None = None, verify: bool | str = True) -> httpx.AsyncClient

Create an httpx.AsyncClient with connection-level retries.

Uses httpx's built-in transport retry for connection failures (DNS, TCP reset). Application-level retries (429, 5xx) are handled by request_with_retry.

Parameters:

Name Type Description Default
timeout float | None

Per-request timeout in seconds.

None
max_redirects int

Maximum redirects available if a caller explicitly enables redirects on a request. Redirect following is disabled by default so SSRF validation cannot be bypassed by a Location header.

0
Source code in src/agent_bom/http_client.py
def create_client(
    timeout: float | None = None,
    max_redirects: int = 0,
    *,
    cert: str | tuple[str, str] | None = None,
    verify: bool | str = True,
) -> httpx.AsyncClient:
    """Create an httpx.AsyncClient with connection-level retries.

    Uses httpx's built-in transport retry for connection failures (DNS, TCP reset).
    Application-level retries (429, 5xx) are handled by ``request_with_retry``.

    Args:
        timeout: Per-request timeout in seconds.
        max_redirects: Maximum redirects available if a caller explicitly
            enables redirects on a request. Redirect following is disabled by
            default so SSRF validation cannot be bypassed by a Location header.
    """
    check_offline()
    from agent_bom.config import HTTP_DEFAULT_TIMEOUT

    if timeout is None:
        timeout = HTTP_DEFAULT_TIMEOUT
    tls_context = _verified_tls_context(verify, cert)
    transport = None if _env_proxy_configured() else httpx.AsyncHTTPTransport(retries=2, verify=tls_context)
    return httpx.AsyncClient(
        timeout=timeout,
        transport=transport,
        follow_redirects=False,
        max_redirects=max_redirects,
        verify=tls_context,
    )

deduplicate_packages

deduplicate_packages(packages: list) -> list

Remove duplicate packages across discovery sources.

Deduplicates by (ecosystem, normalized_name, version) fingerprint. When duplicates exist, the first occurrence is kept (preserves source ordering).

This prevents redundant OSV API calls and duplicate vulnerability findings when the same package is discovered from multiple sources (local, K8s, cloud).

Parameters:

Name Type Description Default
packages list

List of Package objects from one or more discovery sources.

required

Returns:

Type Description
list

Deduplicated list, preserving first-seen order.

Source code in src/agent_bom/scanners/package_preparation.py
def deduplicate_packages(packages: list) -> list:
    """Remove duplicate packages across discovery sources.

    Deduplicates by (ecosystem, normalized_name, version) fingerprint.
    When duplicates exist, the first occurrence is kept (preserves source ordering).

    This prevents redundant OSV API calls and duplicate vulnerability findings
    when the same package is discovered from multiple sources (local, K8s, cloud).

    Args:
        packages: List of Package objects from one or more discovery sources.

    Returns:
        Deduplicated list, preserving first-seen order.
    """
    seen: set[tuple[str, ...]] = set()
    result = []
    for pkg in packages:
        # Use normalized name for dedup (PEP 503: torch == Torch == pytorch)
        name = getattr(pkg, "name", "") or ""
        ecosystem = getattr(pkg, "ecosystem", "") or ""
        version = getattr(pkg, "version", "") or ""
        key = (*canonical_package_identity(name, version, ecosystem, getattr(pkg, "purl", None)), runtime_cve.runtime_assessment_key(pkg))
        if key not in seen:
            seen.add(key)
            result.append(pkg)
    return result

default_scan_options

default_scan_options(*, compliance_enabled: bool = False, resolve_transitive: bool = False, prefer_local_db: bool | None = None, offline: bool | None = None, demo_advisories: bool = False, project_dir: str | None = None) -> ScanOptions

Build per-scan options while preserving legacy offline defaults.

Source code in src/agent_bom/scanners/package_scan.py
def default_scan_options(
    *,
    compliance_enabled: bool = False,
    resolve_transitive: bool = False,
    prefer_local_db: bool | None = None,
    offline: bool | None = None,
    demo_advisories: bool = False,
    project_dir: str | None = None,
) -> ScanOptions:
    """Build per-scan options while preserving legacy offline defaults."""

    return ScanOptions(
        offline=_scanners_patchable("offline_mode") if offline is None else offline,
        compliance_enabled=compliance_enabled,
        resolve_transitive=resolve_transitive,
        prefer_local_db=(prefer_local_db if prefer_local_db is not None else _scanners_patchable("prefer_local_db")),
        demo_advisories=demo_advisories,
        project_dir=project_dir,
    )

parse_fixed_version

parse_fixed_version(vuln_data: dict, package_name: str, ecosystem: str = '', current_version: str = '', source_package: str | None = None, allow_prerelease: bool = True, aliases: tuple[str, ...] = ()) -> Optional[str]

Smallest fix for the installed version's window; stable preferred, pre-release otherwise.

Source code in src/agent_bom/scanners/osv.py
def parse_fixed_version(
    vuln_data: dict,
    package_name: str,
    ecosystem: str = "",
    current_version: str = "",
    source_package: str | None = None,
    allow_prerelease: bool = True,
    aliases: tuple[str, ...] = (),
) -> Optional[str]:
    """Smallest fix for the installed version's window; stable preferred, pre-release otherwise."""
    from agent_bom.version_utils import compare_version_order, is_prerelease_version

    names = candidate_package_names(package_name, ecosystem, source_package, aliases)
    has_current = bool(current_version and current_version not in ("unknown", "latest"))
    stable: list[str] = []
    prereleases: list[str] = []
    windows: list[tuple[object, object, object, list]] = []
    for affected in vuln_data.get("affected", []):
        pkg = affected.get("package", {})
        osv_eco = pkg.get("ecosystem", ecosystem)
        if not pkg.get("name") or not ecosystem_matches(osv_eco, ecosystem):
            continue
        if normalize_package_name(pkg["name"], osv_eco) not in names:
            continue
        for rng in filter(is_release_range, affected.get("ranges", [])):
            events = rng.get("events", [])
            for introduced, fixed, last in range_windows(events, ecosystem):
                windows.append((introduced, fixed, last, events))
                if not isinstance(fixed, str) or not is_valid_fix_version(fixed):
                    continue
                # An explicit version pin can establish membership independently
                # of a range, but cannot borrow that range's remediation. Unknown
                # comparisons and lost/invalid limits cannot support a fix either.
                if has_current and not any(
                    range_match_state(current_version, introduced, fixed, last, ecosystem, limit) == "affected"
                    for limit in range_limits(events)
                ):
                    continue
                (prereleases if is_prerelease_version(fixed, ecosystem) else stable).append(fixed)
    candidates = stable or (prereleases if allow_prerelease else [])
    if not candidates and has_current:
        candidates = _next_unaffected_fixes(windows, current_version, ecosystem, allow_prerelease)
    chosen = None
    for candidate in candidates:
        order = compare_version_order(candidate, chosen, ecosystem) if chosen is not None else None
        if chosen is None or (order is not None and order < 0):
            chosen = candidate
    return chosen

query_osv_batch async

query_osv_batch(packages: list[Package]) -> dict[str, list[dict]]

Query OSV API for vulnerabilities in batch.

Source code in src/agent_bom/scanners/package_scan.py
async def query_osv_batch(packages: list[Package]) -> dict[str, list[dict]]:
    """Query OSV API for vulnerabilities in batch."""
    return await query_osv_batch_impl(
        packages,
        console=console,
        get_scan_cache=_scanners_patchable("_get_scan_cache"),
        get_api_semaphore=_get_api_semaphore,
        bump_scan_perf=_bump_scan_perf,
        enrich_results_if_needed_fn=_scanners_patchable("_enrich_results_if_needed"),
        record_scan_warning=_scanners_patchable("record_scan_warning"),
        osv_ecosystems_for_package=_osv_ecosystems_for_package,
        non_osv_ecosystems=_NON_OSV_ECOSYSTEMS,
        create_client_fn=_scanners_patchable("create_client"),
        request_with_retry_fn=_scanners_patchable("request_with_retry"),
    )

scan_agents async

scan_agents(agents: list[Agent], *, compliance_enabled: bool = False, resolve_transitive: bool = False, show_scan_banner: bool = True, options: ScanOptions | None = None) -> list[BlastRadius]

Scan all agents' MCP server packages for vulnerabilities.

Source code in src/agent_bom/scanners/package_scan.py
async def scan_agents(
    agents: list[Agent],
    *,
    compliance_enabled: bool = False,
    resolve_transitive: bool = False,
    show_scan_banner: bool = True,
    options: ScanOptions | None = None,
) -> list[BlastRadius]:
    """Scan all agents' MCP server packages for vulnerabilities."""
    scan_options = options or default_scan_options(
        compliance_enabled=compliance_enabled,
        resolve_transitive=resolve_transitive,
    )
    if show_scan_banner:
        from agent_bom.output.brand_tokens import PRODUCT_NAME

        console.print(f"\n[bold cyan]{PRODUCT_NAME}[/bold cyan]  [bold]Scanning for vulnerabilities…[/bold]\n")

    _pkg_key = runtime_cve.advisory_instance_key

    # Collect all unique packages
    all_packages = []
    pkg_to_servers: dict[str, list[MCPServer]] = {}
    pkg_to_agents: dict[str, list[Agent]] = {}

    for agent in agents:
        for server in agent.mcp_servers:
            for pkg in server.packages:
                key = _pkg_key(pkg)
                all_packages.append(pkg)

                pkg_to_servers.setdefault(key, []).append(server)

                if key not in pkg_to_agents:
                    pkg_to_agents[key] = []
                if agent not in pkg_to_agents[key]:
                    pkg_to_agents[key].append(agent)

    # Deduplicate packages for scanning — uses canonical deduplicate_packages()
    # which normalizes by (ecosystem, normalized_name, version) fingerprint.
    unique_packages = deduplicate_packages(all_packages)

    if show_scan_banner:
        console.print(f"  Scanning {len(unique_packages)} unique packages across {len(agents)} agent(s)...")

    total_vulns = await _scanners_patchable("scan_packages")(unique_packages, options=scan_options)
    runtime_cve.propagate_runtime_assessments(all_packages, unique_packages)
    propagate_possibly_affected(all_packages, unique_packages, _pkg_key)

    # Propagate vulnerabilities back to all instances
    vuln_map = {}
    for pkg in unique_packages:
        if pkg.vulnerabilities:
            vuln_map[_pkg_key(pkg)] = pkg.vulnerabilities

    for agent in agents:
        for server in agent.mcp_servers:
            for pkg in server.packages:
                if _pkg_key(pkg) in vuln_map:
                    pkg.vulnerabilities = vuln_map[_pkg_key(pkg)]

    # Build blast radius analysis. Registry enrichment is keyed by MCP server,
    # not by vulnerable package. Keep one cache for the whole scan: a server can
    # expose many packages, and matching the same registry catalog once per
    # package turns a linear build into an avoidable package×catalog walk.
    from agent_bom.parsers import get_registry_entry

    _registry_cache: dict[tuple[str, str, tuple[str, ...], str], dict | None] = {}

    def _registry_key(server: MCPServer) -> tuple[str, str, tuple[str, ...], str]:
        return (
            server.name,
            server.command,
            tuple(server.args),
            server.url or "",
        )

    blast_radii = []
    for pkg in unique_packages:
        if not pkg.vulnerabilities:
            continue

        key = _pkg_key(pkg)
        affected_servers = pkg_to_servers.get(key, [])
        affected_agents = pkg_to_agents.get(key, [])

        # Collect exposed credentials and tools — enrich from registry when server
        # config doesn't have explicit tool/credential data.
        # Cache registry lookups per server to avoid duplicate tool creation.
        #
        # IMPORTANT: Registry-sourced tools are "phantom" — they reflect what
        # the registry CLAIMS the server has, not what was introspected.
        # We include them for visibility but mark them so blast radius
        # consumers can distinguish confirmed vs phantom tools.
        exposed_creds: list[str] = []
        exposed_tools: list = []
        phantom_tools: list = []
        for server in affected_servers:
            server_creds = server.credential_names
            server_tools = list(server.tools)  # copy — don't mutate server

            # Registry enrichment: if no tools/creds known from config, use registry
            if not server_tools or not server_creds:
                registry_key = _registry_key(server)
                if registry_key not in _registry_cache:
                    _registry_cache[registry_key] = get_registry_entry(server)
                reg = _registry_cache[registry_key]
                if reg:
                    if not server_tools and reg.get("tools"):
                        from agent_bom.models import MCPTool

                        server_tools = [
                            MCPTool(
                                name=t,
                                description="(registry — unverified)",
                                discovery_source="registry",
                                discovery_confidence="unverified",
                            )
                            for t in reg["tools"]
                        ]
                    if not server_creds and reg.get("credential_env_vars"):
                        server_creds = reg["credential_env_vars"]

            exposed_creds.extend(server_creds)
            for tool in server_tools:
                if getattr(tool, "discovery_source", None) == "registry" and getattr(tool, "discovery_confidence", None) == "unverified":
                    phantom_tools.append(tool)
                else:
                    exposed_tools.append(tool)

        # Deduplicate credentials and tools to prevent inflation
        exposed_creds_deduped = sorted(set(exposed_creds))
        seen_tool_names: set[str] = set()
        deduped_tools = []
        for t in exposed_tools:
            if t.name not in seen_tool_names:
                seen_tool_names.add(t.name)
                deduped_tools.append(t)
        exposed_tools = deduped_tools
        seen_phantom: set[str] = set()
        deduped_phantom = []
        for t in phantom_tools:
            if t.name not in seen_phantom:
                seen_phantom.add(t.name)
                deduped_phantom.append(t)
        phantom_tools = deduped_phantom

        package_ai_context = _package_ai_risk_context(pkg, exposed_creds_deduped, exposed_tools, phantom_tools)

        for vuln in pkg.vulnerabilities:
            if not vuln.compliance_tags:
                vuln.compliance_tags = _tag_vuln(vuln, pkg)

            # CWE-aware filtering: only expose credentials/tools the vuln
            # type can realistically reach. A DoS (CWE-400) doesn't steal
            # DATABASE_URL. An RCE (CWE-94) does.
            from agent_bom.cwe_impact import (
                build_attack_vector_summary,
                classify_cwe_impact,
                filter_credentials_by_impact,
                filter_tools_by_impact,
            )

            impact_cat = classify_cwe_impact(vuln.cwe_ids)
            filtered_creds = filter_credentials_by_impact(
                impact_cat,
                exposed_creds_deduped,
            )
            filtered_tools = filter_tools_by_impact(
                impact_cat,
                exposed_tools,
            )
            filtered_phantom = filter_tools_by_impact(
                impact_cat,
                phantom_tools,
            )
            attack_summary = build_attack_vector_summary(
                cwe_ids=vuln.cwe_ids,
                category=impact_cat,
                filtered_creds=filtered_creds,
                filtered_tools=filtered_tools,
                severity=vuln.severity.value if vuln.severity else None,
                is_kev=vuln.is_kev,
            )
            ai_risk_context = " ".join(part for part in (package_ai_context, attack_summary) if part) or None

            br = BlastRadius(
                vulnerability=vuln,
                package=pkg,
                affected_servers=affected_servers,
                affected_agents=affected_agents,
                exposed_credentials=filtered_creds,
                exposed_tools=filtered_tools,
                phantom_tools=filtered_phantom,
                ai_risk_context=ai_risk_context,
                impact_category=impact_cat,
                all_server_credentials=list(exposed_creds_deduped),
                all_server_tools=list(exposed_tools) + list(phantom_tools),
                attack_vector_summary=attack_summary,
            )
            br.calculate_risk_score()
            # Context-aware tagging remains opt-in for explicit compliance
            # views, but effective framework tags are always materialized.
            if scan_options.compliance_enabled:
                apply_framework_tags(br)
            apply_effective_blast_radius_tags(br)
            blast_radii.append(br)

    # Sort by risk score descending
    blast_radii.sort(key=risk_rank_key)

    _print_vulnerability_summary(total_vulns, len(blast_radii), agents=agents, blast_radii=blast_radii)

    _logger.info(
        "Scan summary: %d packages scanned, %d vulnerabilities, %d blast radius findings across %d agent(s)",
        len(unique_packages),
        total_vulns,
        len(blast_radii),
        len(agents),
    )

    return blast_radii

scan_agents_sync

scan_agents_sync(agents: list[Agent], enable_enrichment: bool = False, nvd_api_key: Optional[str] = None, blast_radius_depth: int = 1, compliance_enabled: bool = False, resolve_transitive: bool = False, show_scan_banner: bool = True, offline: bool | None = None, prefer_local_db: bool | None = None, demo_advisories: bool = False, project_dir: str | None = None, options: ScanOptions | None = None) -> list[BlastRadius]

Synchronous wrapper for scan_agents.

Source code in src/agent_bom/scanners/package_scan.py
def scan_agents_sync(
    agents: list[Agent],
    enable_enrichment: bool = False,
    nvd_api_key: Optional[str] = None,
    blast_radius_depth: int = 1,
    compliance_enabled: bool = False,
    resolve_transitive: bool = False,
    show_scan_banner: bool = True,
    offline: bool | None = None,
    prefer_local_db: bool | None = None,
    demo_advisories: bool = False,
    project_dir: str | None = None,
    options: ScanOptions | None = None,
) -> list[BlastRadius]:
    """Synchronous wrapper for scan_agents."""
    scan_options = options or default_scan_options(
        compliance_enabled=compliance_enabled,
        resolve_transitive=resolve_transitive,
        prefer_local_db=prefer_local_db,
        offline=offline,
        demo_advisories=demo_advisories,
        project_dir=project_dir,
    )
    if enable_enrichment:
        blast_radii = asyncio.run(
            scan_agents_with_enrichment(
                agents,
                nvd_api_key,
                enable_enrichment,
                compliance_enabled=scan_options.compliance_enabled,
                show_scan_banner=show_scan_banner,
                options=scan_options,
            )
        )
    else:
        kev_prefetch = start_default_kev_prefetch(offline=bool(scan_options.offline))
        blast_radii = asyncio.run(
            scan_agents(
                agents,
                compliance_enabled=scan_options.compliance_enabled,
                resolve_transitive=scan_options.resolve_transitive,
                show_scan_banner=show_scan_banner,
                options=scan_options,
            )
        )
        join_default_kev_catalog(blast_radii, offline=scan_options.offline, prefetch=kev_prefetch)
    if blast_radius_depth > 1:
        if show_scan_banner:
            console.print(
                "[yellow]--blast-radius-depth retains direct scanner scope: shared configuration does not prove delegation. "
                "Use typed graph paths to inspect recorded relationships.[/yellow]"
            )
        expand_blast_radius_hops(blast_radii, agents, max_depth=blast_radius_depth)
    return blast_radii

scan_agents_with_enrichment async

scan_agents_with_enrichment(agents: list[Agent], nvd_api_key: Optional[str] = None, enable_enrichment: bool = True, compliance_enabled: bool = False, show_scan_banner: bool = True, options: ScanOptions | None = None) -> list[BlastRadius]

Scan agents and enrich vulnerabilities with NVD/EPSS/KEV data.

Source code in src/agent_bom/scanners/package_scan.py
async def scan_agents_with_enrichment(
    agents: list[Agent],
    nvd_api_key: Optional[str] = None,
    enable_enrichment: bool = True,
    compliance_enabled: bool = False,
    show_scan_banner: bool = True,
    options: ScanOptions | None = None,
) -> list[BlastRadius]:
    """Scan agents and enrich vulnerabilities with NVD/EPSS/KEV data."""
    scan_options = options or default_scan_options(compliance_enabled=compliance_enabled)
    # First, do normal OSV scan
    blast_radii = await scan_agents(
        agents,
        compliance_enabled=scan_options.compliance_enabled,
        show_scan_banner=show_scan_banner,
        options=scan_options,
    )

    # Then enrich with external data
    if enable_enrichment and blast_radii:
        from agent_bom.enrichment import enrich_vulnerabilities
        from agent_bom.resolver import enrich_supply_chain_metadata

        # Collect all vulnerabilities
        all_vulns = []
        all_pkgs: list[Package] = []
        for agent in agents:
            for server in agent.mcp_servers:
                for pkg in server.packages:
                    all_pkgs.append(pkg)
                    all_vulns.extend(pkg.vulnerabilities)

        if all_vulns:
            await enrich_vulnerabilities(
                all_vulns,
                nvd_api_key=nvd_api_key,
                enable_nvd=True,
                enable_epss=True,
                enable_kev=True,
                offline=offline_mode,
            )

            # Refresh CVE-level compliance tags now that CWE/KEV/EPSS data is populated
            for agent in agents:
                for server in agent.mcp_servers:
                    for pkg in server.packages:
                        for v in pkg.vulnerabilities:
                            v.compliance_tags = _tag_vuln(v, pkg)

        # Supply-chain metadata enrichment — feeds Scorecard repo resolution
        try:
            async with create_client(timeout=10.0) as client:
                await enrich_supply_chain_metadata(all_pkgs, client)
        except Exception as exc:  # noqa: BLE001
            _logger.warning("Supply chain metadata enrichment failed (scorecard coverage may be incomplete): %s", exc)
            _emit_scan_warning("supply-chain metadata enrichment failed")

        # Scorecard enrichment — adds supply-chain quality signal
        try:
            from agent_bom.scorecard import enrich_packages_with_scorecard

            if all_pkgs:
                await enrich_packages_with_scorecard(all_pkgs)
        except Exception as exc:  # noqa: BLE001
            _logger.warning("Scorecard auto-enrichment failed (risk scores may be understated): %s", exc)
            _emit_scan_warning("OpenSSF Scorecard enrichment failed")

        # Recalculate blast radius with all enriched data
        for br in blast_radii:
            br.calculate_risk_score()
            apply_effective_blast_radius_tags(br)

        # Re-sort by updated risk scores
        blast_radii.sort(key=risk_rank_key)

    return blast_radii

scan_packages async

scan_packages(packages: list[Package], *, resolve_transitive: bool = False, options: ScanOptions | None = None) -> int

Scan a list of packages for vulnerabilities. Returns count of vulns found.

Source code in src/agent_bom/scanners/package_scan.py
async def scan_packages(
    packages: list[Package],
    *,
    resolve_transitive: bool = False,
    options: ScanOptions | None = None,
) -> int:
    """Scan a list of packages for vulnerabilities. Returns count of vulns found."""
    scan_options = options or default_scan_options(resolve_transitive=resolve_transitive)
    scan_offline = scan_options.offline
    packages = _prepare_packages(packages)
    packages, runtime_count = await _scan_runtime_packages(packages, scan_offline)

    # Installed versions reflect what's actually on disk, so they are tried before the registry fallback.
    unresolved = [p for p in packages if _is_unresolved_package(p) and p.ecosystem.lower() in ("npm", "pypi", "go")]
    if unresolved:
        _resolve_local_versions(unresolved, scan_options.project_dir)
    await _resolve_registry_versions(packages, scan_offline)

    # Only the version-resolved direct demo inventory is closed evidence;
    # packages found by transitive expansion still require a real advisory lookup.
    demo_inventory_keys = {_package_db_key(package) for package in packages} if scan_options.demo_advisories else set()
    if scan_options.resolve_transitive and not scan_offline:
        packages = await _expand_transitive_packages(packages)

    scannable = _select_scannable_packages(packages)
    if not scannable:
        return runtime_count

    local_count, db_covered, local_db_targets = _scan_local_advisories(scannable, scan_options, demo_inventory_keys)
    coverage_gaps = _detect_coverage_gaps(scannable)
    osv_targets, covered_ecos = _select_osv_targets(scannable, scan_offline, local_db_targets, db_covered, coverage_gaps)
    if not scan_offline:
        # A local row without a range receipt is only a candidate; let live OSV decide it.
        osv_targets.extend(pkg for pkg in unverified_packages(scannable) if pkg not in osv_targets)
    results = await _query_osv_results(scannable, osv_targets, covered_ecos, scan_options)

    total_vulns = local_count + runtime_count
    total_vulns += _apply_osv_results(scannable, osv_targets, results)
    demoted = sum(demote_to_candidates(pkg) for pkg in scannable)
    total_vulns -= demoted
    if unconfirmed := unconfirmed_matches_line(demoted):
        console.print(unconfirmed)
    retire_stale_receipt_warnings_if_decided(scannable)
    total_vulns += await _scan_supplemental_advisories(scannable, scan_offline)
    _record_runtime_coverage_gaps(scannable, scan_offline)
    await resolve_distro_advisory_severity(scannable, offline=scan_offline)
    _flag_suspicious_packages(scannable)
    total_vulns -= _suppress_unfixed_findings(scannable)
    total_vulns -= demote_ambiguous_distro_matches(scannable)
    if scan_options.registry_selected_as_candidates:
        total_vulns -= demote_registry_selected(scannable)

    # Apply ignores once after BlastRadius construction so outputs can record why findings were accepted.
    return total_vulns

set_include_unfixed

set_include_unfixed(value: bool) -> None

Toggle surfacing of unfixed (no-dsa/won't-fix) OS-package advisories.

Source code in src/agent_bom/scanners/package_scan.py
def set_include_unfixed(value: bool) -> None:
    """Toggle surfacing of unfixed (no-dsa/won't-fix) OS-package advisories."""
    global include_unfixed  # noqa: PLW0603
    include_unfixed = value

set_offline_mode

set_offline_mode(value: bool) -> None

Set offline mode in both scanner and http_client transport layer.

Source code in src/agent_bom/scanners/package_scan.py
def set_offline_mode(value: bool) -> None:
    """Set offline mode in both scanner and http_client transport layer."""
    global offline_mode  # noqa: PLW0603
    offline_mode = value
    from agent_bom.http_client import set_offline

    set_offline(value)