bomscout 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bomscout/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """bomscout: an MCP server for OWASP Dependency-Track.
2
+
3
+ Ask an AI assistant about your software portfolio: which projects a CVE affects and how far
4
+ remediation got, the riskiest projects, findings by severity, licenses, policy violations,
5
+ and where a package is used.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from .client import DependencyTrack # noqa: E402
11
+ from .errors import DTError # noqa: E402
12
+ from .scout import Scout # noqa: E402
13
+
14
+ __all__ = ["DependencyTrack", "DTError", "Scout", "__version__"]
bomscout/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .server import main
4
+
5
+ sys.exit(main())
bomscout/client.py ADDED
@@ -0,0 +1,295 @@
1
+ """A small, dependency-free client for the Dependency-Track REST API (v4.x).
2
+
3
+ Only the read endpoints bomscout needs, plus the one write (``PUT /api/v1/analysis``).
4
+ Every error is turned into a :class:`DTError` whose text tells the model, and the person
5
+ behind it, what went wrong and how to fix it (wrong URL, bad API key, a missing team
6
+ permission, an unknown project).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import ssl
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
19
+
20
+ from .errors import DTError
21
+
22
+ #: A transport takes (method, url, headers, body) and returns (status, headers, body).
23
+ #: Tests pass a fake one; the default uses urllib.
24
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes]], Tuple[int, Dict[str, str], bytes]]
25
+
26
+ UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
27
+
28
+ # The team permission each endpoint needs (from the @PermissionRequired annotations of the
29
+ # Dependency-Track 4.x API server), so a 403 can say exactly what to grant.
30
+ _PERMISSIONS = [
31
+ ("/v1/finding", "VIEW_VULNERABILITY"),
32
+ ("/v1/analysis", "VULNERABILITY_ANALYSIS"),
33
+ ("/v1/violation", "VIEW_POLICY_VIOLATION"),
34
+ ("/v1/vulnerability", "VIEW_PORTFOLIO"),
35
+ ("/v1/", "VIEW_PORTFOLIO"),
36
+ ]
37
+
38
+ # Ordered guesses for the source of a vulnerability id when none is given.
39
+ _SOURCE_BY_PREFIX = [
40
+ ("CVE-", "NVD"),
41
+ ("GHSA-", "GITHUB"),
42
+ ("SNYK-", "SNYK"),
43
+ ("SONATYPE-", "OSSINDEX"),
44
+ ("INT-", "INTERNAL"),
45
+ ]
46
+ SOURCES = ["NVD", "GITHUB", "OSV", "SNYK", "OSSINDEX", "VULNDB", "NPM", "RETIREJS", "TRIVY",
47
+ "INTERNAL"]
48
+
49
+
50
+ def _urllib_transport(timeout: float, context: Optional[ssl.SSLContext]) -> Transport:
51
+ def send(method: str, url: str, headers: Dict[str, str], body: Optional[bytes]):
52
+ req = urllib.request.Request(url, data=body, method=method, headers=headers)
53
+ try:
54
+ with urllib.request.urlopen(req, timeout=timeout, context=context) as resp:
55
+ return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read()
56
+ except urllib.error.HTTPError as err:
57
+ return err.code, {k.lower(): v for k, v in (err.headers or {}).items()}, err.read() or b""
58
+
59
+ return send
60
+
61
+
62
+ def guess_sources(vuln_id: str) -> List[str]:
63
+ """Sources to try for ``vuln_id``, most likely first."""
64
+ upper = vuln_id.upper()
65
+ first = [src for prefix, src in _SOURCE_BY_PREFIX if upper.startswith(prefix)]
66
+ return first + [s for s in SOURCES if s not in first]
67
+
68
+
69
+ class DependencyTrack:
70
+ """Dependency-Track API client.
71
+
72
+ Args:
73
+ url: Base URL of the API server, e.g. ``https://dtrack.example.com`` (the frontend URL
74
+ works when the frontend and API share a host). A trailing ``/api`` is fine.
75
+ api_key: An API key of a Dependency-Track team (Administration > Access Management >
76
+ Teams). bomscout needs VIEW_PORTFOLIO, VIEW_VULNERABILITY and
77
+ VIEW_POLICY_VIOLATION; VULNERABILITY_ANALYSIS only for recording an analysis.
78
+ timeout: Seconds per request.
79
+ verify: ``True`` (default), ``False`` to skip TLS verification, or a CA bundle path.
80
+ transport: Replace the HTTP layer (used by tests).
81
+ page_size: Items per page when walking paginated lists.
82
+ """
83
+
84
+ def __init__(self, url: str, api_key: str, *, timeout: float = 30.0,
85
+ verify: Any = True, transport: Optional[Transport] = None,
86
+ page_size: int = 100):
87
+ if not url:
88
+ raise DTError("Dependency-Track is not configured: set DT_URL to the API server's "
89
+ "URL and DT_API_KEY to a team API key, then restart the MCP server.")
90
+ if not re.match(r"^https?://", url):
91
+ url = "https://" + url
92
+ base = url.rstrip("/")
93
+ if base.endswith("/api"):
94
+ base = base[: -len("/api")]
95
+ self.base = base
96
+ self.api_key = api_key
97
+ self.page_size = page_size
98
+ if transport is None:
99
+ context = None
100
+ if base.startswith("https://"):
101
+ if verify is False:
102
+ context = ssl.create_default_context()
103
+ context.check_hostname = False
104
+ context.verify_mode = ssl.CERT_NONE
105
+ elif isinstance(verify, str):
106
+ context = ssl.create_default_context(cafile=verify)
107
+ transport = _urllib_transport(timeout, context)
108
+ self._send = transport
109
+
110
+ @classmethod
111
+ def from_env(cls, env: Optional[Mapping[str, str]] = None, **kwargs: Any) -> "DependencyTrack":
112
+ """Build a client from ``DT_URL``, ``DT_API_KEY`` (or the ``DEPENDENCY_TRACK_*``
113
+ spellings), ``DT_TIMEOUT``, ``DT_CA_BUNDLE`` and ``DT_INSECURE``."""
114
+ env = os.environ if env is None else env
115
+ url = env.get("DT_URL") or env.get("DEPENDENCY_TRACK_URL") or ""
116
+ key = env.get("DT_API_KEY") or env.get("DEPENDENCY_TRACK_API_KEY") or ""
117
+ verify: Any = True
118
+ if env.get("DT_CA_BUNDLE"):
119
+ verify = env["DT_CA_BUNDLE"]
120
+ if (env.get("DT_INSECURE") or "").lower() in ("1", "true", "yes"):
121
+ verify = False
122
+ timeout = float(env.get("DT_TIMEOUT") or 30)
123
+ kwargs.setdefault("timeout", timeout)
124
+ kwargs.setdefault("verify", verify)
125
+ return cls(url, key, **kwargs)
126
+
127
+ # ------------------------------------------------------------------ requests
128
+
129
+ def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None,
130
+ body: Any = None) -> Tuple[Any, Dict[str, str]]:
131
+ """Send one request to ``/api<path>`` and return (parsed JSON, lowercased headers)."""
132
+ query = {k: _param(v) for k, v in (params or {}).items() if v is not None and v != ""}
133
+ url = f"{self.base}/api{path}"
134
+ if query:
135
+ url += "?" + urllib.parse.urlencode(query)
136
+ headers = {"Accept": "application/json", "User-Agent": "bomscout"}
137
+ if self.api_key:
138
+ headers["X-Api-Key"] = self.api_key
139
+ data = None
140
+ if body is not None:
141
+ data = json.dumps(body).encode()
142
+ headers["Content-Type"] = "application/json"
143
+ try:
144
+ status, resp_headers, raw = self._send(method, url, headers, data)
145
+ except DTError:
146
+ raise
147
+ except Exception as err: # DNS, refused connection, TLS, timeout
148
+ reason = getattr(err, "reason", None) or err
149
+ raise DTError(f"Could not reach Dependency-Track at {self.base}: {reason}. Check "
150
+ "DT_URL (it must point at the API server) and the network.") from None
151
+ if status >= 400:
152
+ raise self._error(status, method, path, raw)
153
+ text = raw.decode("utf-8", "replace").strip() if raw else ""
154
+ if not text:
155
+ return None, resp_headers
156
+ try:
157
+ return json.loads(text), resp_headers
158
+ except ValueError:
159
+ if "<html" in text[:500].lower():
160
+ raise DTError(f"{self.base}/api{path} returned an HTML page, not JSON. DT_URL "
161
+ "probably points at the Dependency-Track frontend; set it to the "
162
+ "API server's URL.") from None
163
+ return text, resp_headers
164
+
165
+ def get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
166
+ return self.request("GET", path, params)[0]
167
+
168
+ def put(self, path: str, body: Any) -> Any:
169
+ return self.request("PUT", path, body=body)[0]
170
+
171
+ def get_list(self, path: str, params: Optional[Mapping[str, Any]] = None,
172
+ limit: Optional[int] = None) -> Tuple[List[Any], int]:
173
+ """Walk a paginated list. Returns (items, total). Stops after ``limit`` items."""
174
+ items: List[Any] = []
175
+ total: Optional[int] = None
176
+ page = 1
177
+ size = self.page_size if limit is None else max(1, min(self.page_size, limit))
178
+ while True:
179
+ p = dict(params or {})
180
+ p.update(pageNumber=page, pageSize=size)
181
+ data, headers = self.request("GET", path, p)
182
+ batch = data if isinstance(data, list) else []
183
+ items.extend(batch)
184
+ count = headers.get("x-total-count")
185
+ if count is not None and str(count).isdigit():
186
+ total = int(count)
187
+ if len(batch) < size or (total is not None and len(items) >= total):
188
+ break
189
+ if limit is not None and len(items) >= limit:
190
+ break
191
+ page += 1
192
+ if page > 1000: # a server that ignores paging; never loop forever
193
+ break
194
+ if limit is not None:
195
+ items = items[:limit]
196
+ return items, (total if total is not None else len(items))
197
+
198
+ def _error(self, status: int, method: str, path: str, raw: bytes) -> DTError:
199
+ detail = raw.decode("utf-8", "replace").strip()[:300] if raw else ""
200
+ if "<html" in detail.lower():
201
+ detail = ""
202
+ if status == 401:
203
+ return DTError("Dependency-Track rejected the API key (HTTP 401). Check DT_API_KEY: "
204
+ "it must be a team API key from Administration > Access Management > "
205
+ "Teams.", status=status)
206
+ if status == 403:
207
+ perm = next(p for prefix, p in _PERMISSIONS if path.startswith(prefix))
208
+ return DTError(f"The API key's team lacks the {perm} permission needed for {method} "
209
+ f"/api{path} (HTTP 403). Add it to the team in Administration > Access "
210
+ "Management > Teams.", status=status)
211
+ if status == 404:
212
+ return DTError(f"Not found in Dependency-Track: /api{path}" +
213
+ (f" ({detail})" if detail else ""), status=status)
214
+ return DTError(f"Dependency-Track returned HTTP {status} for {method} /api{path}" +
215
+ (f": {detail}" if detail else ""), status=status)
216
+
217
+ # ------------------------------------------------------------------ helpers
218
+
219
+ def version(self) -> Dict[str, Any]:
220
+ """``GET /api/version`` (no API key needed)."""
221
+ data = self.get("/version")
222
+ return data if isinstance(data, dict) else {}
223
+
224
+ def resolve_project(self, ref: str) -> Dict[str, Any]:
225
+ """Find one project by UUID, ``name@version``, or name (latest version).
226
+
227
+ A name with several versions and none marked latest raises :class:`DTError` listing
228
+ the versions, so the model can ask again with ``name@version``.
229
+ """
230
+ ref = (ref or "").strip()
231
+ if not ref:
232
+ raise DTError("Give a project: its UUID, its name, or name@version.")
233
+ if UUID_RE.match(ref):
234
+ try:
235
+ return self.get(f"/v1/project/{ref}")
236
+ except DTError as err:
237
+ if err.status == 404:
238
+ raise DTError(f"No project with UUID {ref}. Use list_projects to find it.",
239
+ status=404) from None
240
+ raise
241
+ name, version = ref, None
242
+ head, sep, tail = ref.rpartition("@")
243
+ if sep and head and tail: # "app@1.2", "@scope/app@1.2"; not "@scope/app"
244
+ name, version = head, tail
245
+ if version:
246
+ try:
247
+ return self.get("/v1/project/lookup", {"name": name, "version": version})
248
+ except DTError as err:
249
+ if err.status != 404:
250
+ raise
251
+ # a project name that itself contains "@": fall through to a name search
252
+ name, version = ref, None
253
+ matches, _ = self.get_list("/v1/project", {"name": name, "excludeInactive": "false"},
254
+ limit=200)
255
+ exact = [p for p in matches if p.get("name") == name]
256
+ if not exact:
257
+ raise DTError(f"No project named {name!r}. Use list_projects to search by part of "
258
+ "the name.", status=404)
259
+ if len(exact) == 1:
260
+ return self.get(f"/v1/project/{exact[0]['uuid']}")
261
+ latest = [p for p in exact if p.get("isLatest")]
262
+ active = [p for p in exact if p.get("active", True)]
263
+ pick = latest[0] if len(latest) == 1 else (active[0] if len(active) == 1 else None)
264
+ if pick is None:
265
+ versions = ", ".join(sorted(str(p.get("version") or "(no version)") for p in exact))
266
+ raise DTError(f"{name!r} has several versions ({versions}) and none is marked "
267
+ f"latest. Ask again as {name}@<version>.")
268
+ return self.get(f"/v1/project/{pick['uuid']}")
269
+
270
+ def find_vulnerability(self, vuln_id: str, source: str = "") -> Dict[str, Any]:
271
+ """Look up a vulnerability by id (CVE-..., GHSA-..., ...), guessing the source."""
272
+ vuln_id = (vuln_id or "").strip()
273
+ if not vuln_id:
274
+ raise DTError("Give a vulnerability id, e.g. CVE-2021-44228 or GHSA-jfh8-c2jp-5v3q.")
275
+ sources = [source.upper()] if source else guess_sources(vuln_id)
276
+ quoted = urllib.parse.quote(vuln_id, safe="")
277
+ for src in sources:
278
+ try:
279
+ data = self.get(f"/v1/vulnerability/source/{src}/vuln/{quoted}")
280
+ except DTError as err:
281
+ if err.status == 404:
282
+ continue
283
+ raise
284
+ if isinstance(data, dict) and data:
285
+ return data
286
+ tried = ", ".join(sources)
287
+ raise DTError(f"Dependency-Track has no vulnerability {vuln_id} (sources tried: {tried}). "
288
+ "It only knows vulnerabilities its analyzers have seen in some project or "
289
+ "mirrored from a feed.", status=404)
290
+
291
+
292
+ def _param(value: Any) -> str:
293
+ if isinstance(value, bool):
294
+ return "true" if value else "false"
295
+ return str(value)
bomscout/errors.py ADDED
@@ -0,0 +1,36 @@
1
+ """The one exception bomscout raises.
2
+
3
+ It subclasses the MCP SDK's own ``ToolError`` (whichever SDK is installed), so the server
4
+ sends its message to the model as the tool's error result instead of hiding it as an
5
+ internal error.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ from typing import Optional, Tuple, Type
12
+
13
+
14
+ def _tool_error_bases() -> Tuple[Type[Exception], ...]:
15
+ bases = []
16
+ for module in (
17
+ "mcp.server.mcpserver.exceptions", # MCP Python SDK 2.x (MCPServer)
18
+ "mcp.server.fastmcp.exceptions", # MCP Python SDK 1.x (FastMCP)
19
+ ):
20
+ try:
21
+ cls = getattr(importlib.import_module(module), "ToolError")
22
+ except Exception: # not installed, or a version without it
23
+ continue
24
+ if isinstance(cls, type) and issubclass(cls, Exception) and cls not in bases:
25
+ bases.append(cls)
26
+ bases = [b for b in bases if not any(o is not b and issubclass(o, b) for o in bases)]
27
+ return tuple(bases) or (Exception,)
28
+
29
+
30
+ class DTError(*_tool_error_bases()): # type: ignore[misc]
31
+ """A Dependency-Track request failed. The message says why and what to do."""
32
+
33
+ def __init__(self, message: str, *, status: Optional[int] = None):
34
+ super().__init__(message)
35
+ #: The HTTP status, when the server answered.
36
+ self.status = status
bomscout/scout.py ADDED
@@ -0,0 +1,257 @@
1
+ """The questions bomscout answers, as plain methods that return JSON-ready dicts.
2
+
3
+ The MCP server in :mod:`bomscout.server` is a thin layer over this class, so it can also be
4
+ used from scripts and notebooks::
5
+
6
+ from bomscout import Scout
7
+ scout = Scout.from_env()
8
+ print(scout.vulnerability_impact("CVE-2021-44228"))
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, Dict, List, Mapping, Optional
14
+
15
+ from .client import DependencyTrack
16
+ from .errors import DTError
17
+ from . import views
18
+
19
+ MAX_LIMIT = 500
20
+
21
+
22
+ def _limit(n: int, default: int) -> int:
23
+ try:
24
+ n = int(n)
25
+ except (TypeError, ValueError):
26
+ return default
27
+ return default if n <= 0 else min(n, MAX_LIMIT)
28
+
29
+
30
+ def _choice(value: str, choices: List[str], what: str) -> str:
31
+ try:
32
+ return views.normalize_choice(value, choices, what)
33
+ except ValueError as err:
34
+ raise DTError(str(err)) from None
35
+
36
+
37
+ class Scout:
38
+ """Answers portfolio questions from a Dependency-Track server."""
39
+
40
+ def __init__(self, client: DependencyTrack):
41
+ self.dt = client
42
+
43
+ @classmethod
44
+ def from_env(cls, env: Optional[Mapping[str, str]] = None, **kwargs: Any) -> "Scout":
45
+ return cls(DependencyTrack.from_env(env, **kwargs))
46
+
47
+ # ------------------------------------------------------------------ portfolio
48
+
49
+ def portfolio_overview(self, top: int = 10) -> Dict[str, Any]:
50
+ top = _limit(top, 10)
51
+ metrics = self.dt.get("/v1/metrics/portfolio/current")
52
+ projects, total = self.dt.get_list("/v1/project", {"excludeInactive": True}, limit=MAX_LIMIT)
53
+ ranked = sorted(projects, key=lambda p: -(p.get("lastInheritedRiskScore") or 0))
54
+ out: Dict[str, Any] = {}
55
+ if isinstance(metrics, dict) and metrics:
56
+ keys = ["projects", "vulnerableProjects", "components", "vulnerableComponents"]
57
+ out["portfolio"] = {k: metrics.get(k) for k in keys if metrics.get(k) is not None}
58
+ out["vulnerabilities"] = views.metrics_row(metrics)
59
+ if metrics.get("lastOccurrence"):
60
+ out["metrics_updated"] = metrics["lastOccurrence"]
61
+ else:
62
+ out["note"] = ("Portfolio metrics have not been calculated yet; Dependency-Track "
63
+ "computes them periodically after BOM uploads.")
64
+ out["active_projects"] = total
65
+ out["riskiest_projects"] = [views.project_row(p) for p in ranked[:top]
66
+ if (p.get("lastInheritedRiskScore") or 0) > 0]
67
+ if total > len(projects):
68
+ out["note_projects"] = f"Ranked the first {len(projects)} of {total} projects."
69
+ return out
70
+
71
+ def list_projects(self, name: str = "", tag: str = "", include_inactive: bool = False,
72
+ limit: int = 50) -> Dict[str, Any]:
73
+ limit = _limit(limit, 50)
74
+ params = {"excludeInactive": not include_inactive}
75
+ if tag:
76
+ path = f"/v1/project/tag/{_quote(tag)}"
77
+ else:
78
+ path = "/v1/project"
79
+ if name:
80
+ params["searchText"] = name
81
+ items, total = self.dt.get_list(path, params, limit=limit)
82
+ if tag and name:
83
+ items = [p for p in items if name.lower() in (p.get("name") or "").lower()]
84
+ total = len(items)
85
+ rows = [views.project_row(p) for p in items]
86
+ return _page(rows, total, "projects")
87
+
88
+ # ------------------------------------------------------------------ findings
89
+
90
+ def project_findings(self, project: str, min_severity: str = "", analysis_state: str = "",
91
+ include_suppressed: bool = False, limit: int = 50) -> Dict[str, Any]:
92
+ limit = _limit(limit, 50)
93
+ p = self.dt.resolve_project(project)
94
+ raw = self.dt.get(f"/v1/finding/project/{p['uuid']}", {"suppressed": include_suppressed})
95
+ rows = [views.finding_row(f) for f in raw or []]
96
+ summary = views.summarize_findings(rows)
97
+ if min_severity:
98
+ sev = _choice(min_severity, views.SEVERITIES, "severity")
99
+ cut = views.severity_rank(sev)
100
+ rows = [r for r in rows if views.severity_rank(r.get("severity")) <= cut]
101
+ if analysis_state:
102
+ state = _choice(analysis_state, views.ANALYSIS_STATES, "analysis state")
103
+ rows = [r for r in rows if r.get("analysis") == state]
104
+ rows = views.sort_findings(rows)
105
+ out = {"project": views.project_label(p), "project_uuid": p.get("uuid"), **summary}
106
+ out.update(_page(rows, len(rows), "findings", limit))
107
+ return out
108
+
109
+ def vulnerability_impact(self, vuln_id: str, source: str = "",
110
+ max_projects: int = 20) -> Dict[str, Any]:
111
+ max_projects = _limit(max_projects, 20)
112
+ vuln = self.dt.find_vulnerability(vuln_id, source)
113
+ src, vid = vuln.get("source"), vuln.get("vulnId")
114
+ affected = self.dt.get(f"/v1/vulnerability/source/{src}/vuln/{_quote(vid)}/projects",
115
+ {"excludeInactive": True}) or []
116
+ out: Dict[str, Any] = {"vulnerability": views.vulnerability_view(vuln),
117
+ "affected_projects": len(affected)}
118
+ impact = []
119
+ for proj in affected[:max_projects]:
120
+ row: Dict[str, Any] = {"project": views.project_label(proj), "project_uuid": proj.get("uuid")}
121
+ try:
122
+ findings = self.dt.get(f"/v1/finding/project/{proj['uuid']}", {"suppressed": True}) or []
123
+ except DTError as err:
124
+ row["error"] = str(err)
125
+ impact.append(row)
126
+ continue
127
+ hits = [f for f in findings if (f.get("vulnerability") or {}).get("uuid") == vuln.get("uuid")]
128
+ row["components"] = [{
129
+ "component": views.coordinates(f.get("component") or {}),
130
+ "component_uuid": (f.get("component") or {}).get("uuid"),
131
+ "analysis": (f.get("analysis") or {}).get("state") or "NOT_SET",
132
+ **({"suppressed": True} if (f.get("analysis") or {}).get("isSuppressed") else {}),
133
+ } for f in hits]
134
+ impact.append(row)
135
+ states = [c["analysis"] for r in impact for c in r.get("components", [])]
136
+ out["remediation"] = {s: states.count(s) for s in views.ANALYSIS_STATES if s in states}
137
+ out["projects"] = impact
138
+ if len(affected) > max_projects:
139
+ out["note"] = (f"Showing analysis for {max_projects} of {len(affected)} affected "
140
+ "projects; raise max_projects to see more.")
141
+ return out
142
+
143
+ # ------------------------------------------------------------------ components
144
+
145
+ def project_components(self, project: str, search: str = "", only_outdated: bool = False,
146
+ only_direct: bool = False, limit: int = 100) -> Dict[str, Any]:
147
+ limit = _limit(limit, 100)
148
+ p = self.dt.resolve_project(project)
149
+ params = {"onlyOutdated": only_outdated, "onlyDirect": only_direct}
150
+ if search:
151
+ params["searchText"] = search
152
+ items, total = self.dt.get_list(f"/v1/component/project/{p['uuid']}", params, limit=limit)
153
+ out = {"project": views.project_label(p), "project_uuid": p.get("uuid")}
154
+ out.update(_page([views.component_row(c) for c in items], total, "components"))
155
+ return out
156
+
157
+ def project_licenses(self, project: str) -> Dict[str, Any]:
158
+ p = self.dt.resolve_project(project)
159
+ items, total = self.dt.get_list(f"/v1/component/project/{p['uuid']}", {}, limit=5000)
160
+ out = {"project": views.project_label(p), "project_uuid": p.get("uuid"), "components": total}
161
+ out.update(views.license_summary(items))
162
+ if total > len(items):
163
+ out["note"] = f"Summarized the first {len(items)} of {total} components."
164
+ out["disclaimer"] = "License families are a quick triage aid, not legal advice."
165
+ return out
166
+
167
+ def find_component(self, purl: str = "", name: str = "", version: str = "", group: str = "",
168
+ limit: int = 50) -> Dict[str, Any]:
169
+ limit = _limit(limit, 50)
170
+ if not (purl or name):
171
+ raise DTError("Give a package URL (purl, e.g. pkg:maven/org.apache.logging.log4j/"
172
+ "log4j-core@2.14.1) or a component name.")
173
+ params = {"purl": purl, "name": name, "version": version, "group": group,
174
+ "excludeInactiveProjects": True}
175
+ items, total = self.dt.get_list("/v1/component/identity", params, limit=limit)
176
+ rows = [views.component_row(c) for c in items]
177
+ projects = sorted({r["project"] for r in rows if r.get("project")})
178
+ out = {"projects_using_it": projects}
179
+ out.update(_page(rows, total, "components"))
180
+ return out
181
+
182
+ # ------------------------------------------------------------------ policy
183
+
184
+ def policy_violations(self, project: str = "", violation_type: str = "",
185
+ include_suppressed: bool = False, limit: int = 50) -> Dict[str, Any]:
186
+ limit = _limit(limit, 50)
187
+ vtype = _choice(violation_type, views.VIOLATION_TYPES, "violation type") if violation_type else ""
188
+ out: Dict[str, Any] = {}
189
+ if project:
190
+ p = self.dt.resolve_project(project)
191
+ out.update(project=views.project_label(p), project_uuid=p.get("uuid"))
192
+ items, total = self.dt.get_list(f"/v1/violation/project/{p['uuid']}",
193
+ {"suppressed": include_suppressed}, limit=MAX_LIMIT)
194
+ else:
195
+ items, total = self.dt.get_list("/v1/violation", {"suppressed": include_suppressed},
196
+ limit=MAX_LIMIT)
197
+ rows = [views.violation_row(v) for v in items]
198
+ if vtype:
199
+ rows = [r for r in rows if r.get("type") == vtype]
200
+ total = len(rows)
201
+ order = {"FAIL": 0, "WARN": 1, "INFO": 2}
202
+ rows.sort(key=lambda r: (order.get(r.get("state") or "", 3), r.get("type") or "",
203
+ r.get("component") or ""))
204
+ out["by_state"] = {s: sum(1 for r in rows if r.get("state") == s) for s in order
205
+ if any(r.get("state") == s for r in rows)}
206
+ out.update(_page(rows, total, "violations", limit))
207
+ return out
208
+
209
+ # ------------------------------------------------------------------ triage (write)
210
+
211
+ def record_analysis(self, project: str, component_uuid: str, vulnerability_uuid: str,
212
+ state: str, justification: str = "", response: str = "",
213
+ details: str = "", comment: str = "",
214
+ suppress: Optional[bool] = None) -> Dict[str, Any]:
215
+ p = self.dt.resolve_project(project)
216
+ body: Dict[str, Any] = {
217
+ "project": p["uuid"],
218
+ "component": component_uuid,
219
+ "vulnerability": vulnerability_uuid,
220
+ "analysisState": _choice(state, views.ANALYSIS_STATES, "analysis state"),
221
+ }
222
+ if justification:
223
+ body["analysisJustification"] = _choice(justification, views.JUSTIFICATIONS, "justification")
224
+ if response:
225
+ body["analysisResponse"] = _choice(response, views.RESPONSES, "response")
226
+ if details:
227
+ body["analysisDetails"] = details
228
+ if comment:
229
+ body["comment"] = comment
230
+ if suppress is not None:
231
+ body["isSuppressed"] = bool(suppress)
232
+ result = self.dt.put("/v1/analysis", body) or {}
233
+ comments = result.get("analysisComments") or []
234
+ return {
235
+ "project": views.project_label(p),
236
+ "analysis": result.get("analysisState", body["analysisState"]),
237
+ "justification": result.get("analysisJustification"),
238
+ "response": result.get("analysisResponse"),
239
+ "suppressed": result.get("isSuppressed", body.get("isSuppressed")),
240
+ "latest_comment": views.short((comments[-1] or {}).get("comment"), 200) if comments else None,
241
+ }
242
+
243
+
244
+ def _quote(value: Any) -> str:
245
+ import urllib.parse
246
+
247
+ return urllib.parse.quote(str(value), safe="")
248
+
249
+
250
+ def _page(rows: List[Dict[str, Any]], total: int, what: str,
251
+ limit: Optional[int] = None) -> Dict[str, Any]:
252
+ shown = rows if limit is None else rows[:limit]
253
+ out: Dict[str, Any] = {"total": total, "shown": len(shown), what: shown}
254
+ if total > len(shown):
255
+ out["more"] = (f"{total - len(shown)} more {what} not shown; narrow the question "
256
+ "(filters) or raise limit.")
257
+ return out
bomscout/server.py ADDED
@@ -0,0 +1,231 @@
1
+ """The bomscout MCP server: Dependency-Track tools for AI assistants.
2
+
3
+ Runs on the official MCP Python SDK, 1.x (``FastMCP``) or 2.x (``MCPServer``). Every tool is
4
+ read-only unless ``BOMSCOUT_ALLOW_WRITE=1`` is set, which adds ``record_analysis`` for
5
+ triaging findings.
6
+ """
7
+
8
+ # No `from __future__ import annotations` here: MCP SDK 1.10 reads tool parameter
9
+ # annotations without resolving strings.
10
+ import json
11
+ import os
12
+ from typing import Annotated, Any, Callable, Mapping, Optional
13
+
14
+ import anyio
15
+
16
+ from . import __version__
17
+
18
+ try: # MCP Python SDK 2.x
19
+ from mcp.server.mcpserver import MCPServer as _Server
20
+
21
+ _SERVER_INFO = {"version": __version__}
22
+ except ImportError: # MCP Python SDK 1.x
23
+ from mcp.server.fastmcp import FastMCP as _Server # type: ignore[no-redef]
24
+
25
+ _SERVER_INFO = {}
26
+
27
+ from mcp.types import ToolAnnotations
28
+ from pydantic import Field
29
+
30
+ from .errors import DTError
31
+ from .scout import Scout
32
+
33
+ INSTRUCTIONS = (
34
+ "Tools for OWASP Dependency-Track: projects, vulnerabilities (findings), components, "
35
+ "licenses and policy violations across the organization's software portfolio. Projects can "
36
+ "be named by UUID, by name (latest version) or as name@version."
37
+ )
38
+
39
+ READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True,
40
+ openWorldHint=False)
41
+ WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=True,
42
+ openWorldHint=False)
43
+
44
+ Project = Annotated[str, Field(description="Project UUID, project name (its latest version), or name@version")]
45
+ Limit = Annotated[int, Field(description="Maximum rows to return (1-500)")]
46
+
47
+
48
+ def _dumps(data: Any) -> str:
49
+ return json.dumps(data, ensure_ascii=False, default=str)
50
+
51
+
52
+ def _truthy(value: Optional[str]) -> bool:
53
+ return (value or "").strip().lower() in ("1", "true", "yes", "on")
54
+
55
+
56
+ def build_server(scout: Optional[Scout] = None, *, allow_write: Optional[bool] = None,
57
+ env: Optional[Mapping[str, str]] = None) -> Any:
58
+ """Create the MCP server.
59
+
60
+ Args:
61
+ scout: The :class:`Scout` to answer with. By default one is built from the
62
+ environment on the first tool call, so the server starts (and lists its tools)
63
+ even before ``DT_URL`` and ``DT_API_KEY`` are set.
64
+ allow_write: Register ``record_analysis``. Defaults to ``BOMSCOUT_ALLOW_WRITE``.
65
+ env: Environment to read settings from (default ``os.environ``).
66
+ """
67
+ env = os.environ if env is None else env
68
+ if allow_write is None:
69
+ allow_write = _truthy(env.get("BOMSCOUT_ALLOW_WRITE"))
70
+ state = {"scout": scout}
71
+
72
+ def get_scout() -> Scout:
73
+ if state["scout"] is None:
74
+ state["scout"] = Scout.from_env(env)
75
+ return state["scout"]
76
+
77
+ async def run(fn: Callable[..., Any], *args: Any) -> str:
78
+ def call() -> Any:
79
+ return fn(get_scout(), *args)
80
+
81
+ return _dumps(await anyio.to_thread.run_sync(call))
82
+
83
+ srv = _Server(name="bomscout", instructions=INSTRUCTIONS, **_SERVER_INFO)
84
+
85
+ @srv.tool(annotations=READ, structured_output=False)
86
+ async def portfolio_overview(
87
+ top: Annotated[int, Field(description="How many of the riskiest projects to list")] = 10,
88
+ ):
89
+ """Security posture of the whole Dependency-Track portfolio: vulnerability counts by
90
+ severity, audited vs unaudited findings, policy violations, and the projects with the
91
+ highest risk score."""
92
+ return await run(Scout.portfolio_overview, top)
93
+
94
+ @srv.tool(annotations=READ, structured_output=False)
95
+ async def list_projects(
96
+ name: Annotated[str, Field(description="Part of the project name to search for (empty for all)")] = "",
97
+ tag: Annotated[str, Field(description="Only projects with this tag")] = "",
98
+ include_inactive: Annotated[bool, Field(description="Also list inactive projects")] = False,
99
+ limit: Limit = 50,
100
+ ):
101
+ """List Dependency-Track projects with their UUID, version, tags, risk score and
102
+ vulnerability counts. Use it to find the project a question is about."""
103
+ return await run(Scout.list_projects, name, tag, include_inactive, limit)
104
+
105
+ @srv.tool(annotations=READ, structured_output=False)
106
+ async def project_findings(
107
+ project: Project,
108
+ min_severity: Annotated[str, Field(description="Only findings at or above this severity: CRITICAL, HIGH, MEDIUM, LOW, INFO")] = "",
109
+ analysis_state: Annotated[str, Field(description="Only findings with this analysis state, e.g. NOT_SET for untriaged ones, EXPLOITABLE, IN_TRIAGE")] = "",
110
+ include_suppressed: Annotated[bool, Field(description="Also include suppressed findings")] = False,
111
+ limit: Limit = 50,
112
+ ):
113
+ """Vulnerabilities found in one project, most severe first: vulnerability id, severity,
114
+ CVSS, EPSS, affected component, and analysis (triage) state, plus totals by severity
115
+ and by analysis state."""
116
+ return await run(Scout.project_findings, project, min_severity, analysis_state,
117
+ include_suppressed, limit)
118
+
119
+ @srv.tool(annotations=READ, structured_output=False)
120
+ async def vulnerability_impact(
121
+ vuln_id: Annotated[str, Field(description="Vulnerability id, e.g. CVE-2021-44228 or GHSA-jfh8-c2jp-5v3q")],
122
+ source: Annotated[str, Field(description="Vulnerability source (NVD, GITHUB, OSV, SNYK...); guessed from the id when empty")] = "",
123
+ max_projects: Annotated[int, Field(description="Check the analysis state in at most this many affected projects")] = 20,
124
+ ):
125
+ """Details of one vulnerability (severity, CVSS, EPSS, description, fixed versions) and
126
+ every project it affects, with the affected component and its remediation (analysis)
127
+ status in each project."""
128
+ return await run(Scout.vulnerability_impact, vuln_id, source, max_projects)
129
+
130
+ @srv.tool(annotations=READ, structured_output=False)
131
+ async def project_components(
132
+ project: Project,
133
+ search: Annotated[str, Field(description="Part of a component name to search for")] = "",
134
+ only_outdated: Annotated[bool, Field(description="Only components with a newer version available")] = False,
135
+ only_direct: Annotated[bool, Field(description="Only direct dependencies")] = False,
136
+ limit: Limit = 100,
137
+ ):
138
+ """Components (dependencies) of one project from its SBOM: name, version, package URL,
139
+ license, newer version if known, and vulnerability counts."""
140
+ return await run(Scout.project_components, project, search, only_outdated, only_direct, limit)
141
+
142
+ @srv.tool(annotations=READ, structured_output=False)
143
+ async def project_licenses(project: Project):
144
+ """License summary of one project: how many components use each license, grouped as
145
+ strong copyleft, weak copyleft, permissive or unknown, with example components."""
146
+ return await run(Scout.project_licenses, project)
147
+
148
+ @srv.tool(annotations=READ, structured_output=False)
149
+ async def find_component(
150
+ purl: Annotated[str, Field(description="Package URL, e.g. pkg:npm/lodash@4.17.20 (without @version for any version)")] = "",
151
+ name: Annotated[str, Field(description="Component name, when no purl is given")] = "",
152
+ version: Annotated[str, Field(description="Component version, with name")] = "",
153
+ group: Annotated[str, Field(description="Component group or namespace, with name (e.g. org.apache.logging.log4j)")] = "",
154
+ limit: Limit = 50,
155
+ ):
156
+ """Find which projects across the portfolio use a component (by package URL or name and
157
+ version), e.g. every project that still ships log4j-core 2.14."""
158
+ return await run(Scout.find_component, purl, name, version, group, limit)
159
+
160
+ @srv.tool(annotations=READ, structured_output=False)
161
+ async def policy_violations(
162
+ project: Annotated[str, Field(description="Project UUID, name or name@version; empty for the whole portfolio")] = "",
163
+ violation_type: Annotated[str, Field(description="Only SECURITY, LICENSE or OPERATIONAL violations")] = "",
164
+ include_suppressed: Annotated[bool, Field(description="Also include suppressed violations")] = False,
165
+ limit: Limit = 50,
166
+ ):
167
+ """Policy violations (security, license, operational) for one project or the whole
168
+ portfolio, FAIL first: policy, condition, component and analysis state."""
169
+ return await run(Scout.policy_violations, project, violation_type, include_suppressed, limit)
170
+
171
+ if allow_write:
172
+ @srv.tool(annotations=WRITE, structured_output=False)
173
+ async def record_analysis(
174
+ project: Project,
175
+ component_uuid: Annotated[str, Field(description="component_uuid from project_findings")],
176
+ vulnerability_uuid: Annotated[str, Field(description="vulnerability_uuid from project_findings")],
177
+ state: Annotated[str, Field(description="Analysis state: EXPLOITABLE, IN_TRIAGE, FALSE_POSITIVE, NOT_AFFECTED, RESOLVED or NOT_SET")],
178
+ justification: Annotated[str, Field(description="Why it is not affected, e.g. CODE_NOT_REACHABLE, REQUIRES_CONFIGURATION, PROTECTED_AT_RUNTIME")] = "",
179
+ response: Annotated[str, Field(description="Planned response: CAN_NOT_FIX, WILL_NOT_FIX, UPDATE, ROLLBACK, WORKAROUND_AVAILABLE")] = "",
180
+ details: Annotated[str, Field(description="Analysis details shown in Dependency-Track and in VEX exports")] = "",
181
+ comment: Annotated[str, Field(description="Audit comment to add to the finding's history")] = "",
182
+ suppress: Annotated[Optional[bool], Field(description="Suppress (true) or unsuppress (false) the finding; unchanged when empty")] = None,
183
+ ):
184
+ """Record the triage decision for one finding in Dependency-Track (analysis state,
185
+ justification, response, details, comment, suppression). Confirm the decision with
186
+ the user first: it is visible to the whole team and exported in VEX documents."""
187
+ return await run(Scout.record_analysis, project, component_uuid, vulnerability_uuid,
188
+ state, justification, response, details, comment, suppress)
189
+
190
+ return srv
191
+
192
+
193
+ def check(env: Optional[Mapping[str, str]] = None) -> int:
194
+ """Check the connection and API key permissions; print a report. Returns an exit code."""
195
+ scout = Scout.from_env(env)
196
+ ok = True
197
+ try:
198
+ info = scout.dt.version()
199
+ print(f"Dependency-Track {info.get('version', '?')} at {scout.dt.base}")
200
+ except DTError as err:
201
+ print(f"FAIL {err}")
202
+ return 1
203
+ probes = [
204
+ ("VIEW_PORTFOLIO", "/v1/project", {"pageSize": 1}),
205
+ ("VIEW_VULNERABILITY", "/v1/finding", {"pageSize": 1}),
206
+ ("VIEW_POLICY_VIOLATION", "/v1/violation", {"pageSize": 1}),
207
+ ]
208
+ for perm, path, params in probes:
209
+ try:
210
+ scout.dt.get(path, params)
211
+ print(f"ok {perm}")
212
+ except DTError as err:
213
+ ok = False
214
+ print(f"FAIL {perm}: {err}")
215
+ return 0 if ok else 1
216
+
217
+
218
+ def main(argv: Optional[list] = None) -> int:
219
+ import argparse
220
+
221
+ ap = argparse.ArgumentParser(prog="bomscout", description="MCP server for OWASP Dependency-Track (stdio).")
222
+ ap.add_argument("command", nargs="?", choices=["serve", "check"], default="serve",
223
+ help="serve (default): run the MCP server on stdio; check: test DT_URL and DT_API_KEY")
224
+ ap.add_argument("--allow-write", action="store_true",
225
+ help="add the record_analysis tool (same as BOMSCOUT_ALLOW_WRITE=1)")
226
+ ap.add_argument("--version", action="version", version=f"bomscout {__version__}")
227
+ args = ap.parse_args(argv)
228
+ if args.command == "check":
229
+ return check()
230
+ build_server(allow_write=True if args.allow_write else None).run()
231
+ return 0
bomscout/views.py ADDED
@@ -0,0 +1,282 @@
1
+ """Turn Dependency-Track API objects into small rows a model can read.
2
+
3
+ The API returns large objects (a finding carries the full vulnerability description, every
4
+ CVSS vector, references...). These functions keep what answers a question and drop the
5
+ rest, so a tool result stays a few thousand tokens.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter, defaultdict
11
+ from typing import Any, Dict, Iterable, List, Optional
12
+
13
+ SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNASSIGNED"]
14
+ ANALYSIS_STATES = ["EXPLOITABLE", "IN_TRIAGE", "FALSE_POSITIVE", "NOT_AFFECTED", "RESOLVED",
15
+ "NOT_SET"]
16
+ JUSTIFICATIONS = ["CODE_NOT_PRESENT", "CODE_NOT_REACHABLE", "REQUIRES_CONFIGURATION",
17
+ "REQUIRES_DEPENDENCY", "REQUIRES_ENVIRONMENT", "PROTECTED_BY_COMPILER",
18
+ "PROTECTED_AT_RUNTIME", "PROTECTED_AT_PERIMETER",
19
+ "PROTECTED_BY_MITIGATING_CONTROL", "NOT_SET"]
20
+ RESPONSES = ["CAN_NOT_FIX", "WILL_NOT_FIX", "UPDATE", "ROLLBACK", "WORKAROUND_AVAILABLE",
21
+ "NOT_SET"]
22
+ VIOLATION_TYPES = ["SECURITY", "LICENSE", "OPERATIONAL"]
23
+
24
+ _METRIC_KEYS = ["critical", "high", "medium", "low", "unassigned", "vulnerabilities",
25
+ "findingsTotal", "findingsAudited", "findingsUnaudited", "suppressed",
26
+ "policyViolationsFail", "policyViolationsWarn", "policyViolationsInfo",
27
+ "policyViolationsTotal", "inheritedRiskScore"]
28
+
29
+
30
+ def severity_rank(severity: Optional[str]) -> int:
31
+ s = (severity or "UNASSIGNED").upper()
32
+ return SEVERITIES.index(s) if s in SEVERITIES else len(SEVERITIES)
33
+
34
+
35
+ def normalize_choice(value: str, choices: List[str], what: str) -> str:
36
+ """Accept any case and spaces/dashes ("false positive" -> FALSE_POSITIVE)."""
37
+ v = (value or "").strip().upper().replace(" ", "_").replace("-", "_")
38
+ if v not in choices:
39
+ raise ValueError(f"Unknown {what} {value!r}; use one of: {', '.join(choices)}.")
40
+ return v
41
+
42
+
43
+ def short(text: Optional[str], n: int = 160) -> Optional[str]:
44
+ if not text:
45
+ return None
46
+ text = " ".join(str(text).split())
47
+ return text if len(text) <= n else text[: n - 1].rstrip() + "…"
48
+
49
+
50
+ def coordinates(c: Dict[str, Any]) -> str:
51
+ """``group/name@version`` (or ``name@version``)."""
52
+ name = c.get("name") or "?"
53
+ if c.get("group"):
54
+ name = f"{c['group']}/{name}"
55
+ return f"{name}@{c['version']}" if c.get("version") else name
56
+
57
+
58
+ def project_label(p: Optional[Dict[str, Any]]) -> Optional[str]:
59
+ if not p:
60
+ return None
61
+ name = p.get("name") or p.get("uuid") or "?"
62
+ return f"{name}@{p['version']}" if p.get("version") else name
63
+
64
+
65
+ def metrics_row(m: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
66
+ if not m:
67
+ return None
68
+ return {k: m[k] for k in _METRIC_KEYS if m.get(k) not in (None, 0, 0.0)} or {"vulnerabilities": 0}
69
+
70
+
71
+ def project_row(p: Dict[str, Any]) -> Dict[str, Any]:
72
+ row: Dict[str, Any] = {
73
+ "project": project_label(p),
74
+ "uuid": p.get("uuid"),
75
+ "classifier": p.get("classifier"),
76
+ }
77
+ if p.get("active") is False:
78
+ row["active"] = False
79
+ if p.get("isLatest"):
80
+ row["latest"] = True
81
+ tags = [t.get("name") for t in p.get("tags") or [] if isinstance(t, dict) and t.get("name")]
82
+ if tags:
83
+ row["tags"] = tags
84
+ if p.get("lastInheritedRiskScore") is not None:
85
+ row["risk_score"] = p["lastInheritedRiskScore"]
86
+ m = p.get("metrics")
87
+ if m:
88
+ row["vulnerabilities"] = {s.lower(): m.get(s.lower(), 0) for s in SEVERITIES[:4]}
89
+ if m.get("policyViolationsTotal"):
90
+ row["policy_violations"] = m["policyViolationsTotal"]
91
+ if p.get("lastBomImport"):
92
+ row["last_bom_import"] = p["lastBomImport"]
93
+ return {k: v for k, v in row.items() if v is not None}
94
+
95
+
96
+ def aliases(v: Dict[str, Any]) -> List[str]:
97
+ out: List[str] = []
98
+ own = v.get("vulnId")
99
+ for a in v.get("aliases") or []:
100
+ if not isinstance(a, dict):
101
+ continue
102
+ for key in ("cveId", "ghsaId", "osvId", "snykId", "sonatypeId", "vulnDbId"):
103
+ val = a.get(key)
104
+ if val and val != own and val not in out:
105
+ out.append(val)
106
+ return out
107
+
108
+
109
+ def score(v: Dict[str, Any]) -> Optional[float]:
110
+ for key in ("cvssV3BaseScore", "cvssV4Score", "cvssV2BaseScore"):
111
+ if v.get(key) is not None:
112
+ return v[key]
113
+ return None
114
+
115
+
116
+ def finding_row(f: Dict[str, Any], *, with_project: bool = False) -> Dict[str, Any]:
117
+ c = f.get("component") or {}
118
+ v = f.get("vulnerability") or {}
119
+ a = f.get("analysis") or {}
120
+ row: Dict[str, Any] = {
121
+ "vuln": v.get("vulnId"),
122
+ "source": v.get("source"),
123
+ "severity": v.get("severity") or "UNASSIGNED",
124
+ "cvss": score(v),
125
+ "epss": v.get("epssScore"),
126
+ "aliases": aliases(v) or None,
127
+ "title": short(v.get("title") or v.get("description"), 120),
128
+ "component": coordinates(c),
129
+ "purl": c.get("purl"),
130
+ "analysis": a.get("state") or "NOT_SET",
131
+ "suppressed": True if a.get("isSuppressed") else None,
132
+ "component_uuid": c.get("uuid"),
133
+ "vulnerability_uuid": v.get("uuid"),
134
+ }
135
+ if with_project:
136
+ row["project"] = c.get("projectName") and (
137
+ f"{c['projectName']}@{c['projectVersion']}" if c.get("projectVersion") else c["projectName"])
138
+ row["project_uuid"] = c.get("project")
139
+ return {k: val for k, val in row.items() if val is not None}
140
+
141
+
142
+ def sort_findings(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
143
+ return sorted(rows, key=lambda r: (severity_rank(r.get("severity")), -(r.get("cvss") or 0),
144
+ -(r.get("epss") or 0), r.get("vuln") or ""))
145
+
146
+
147
+ def summarize_findings(rows: Iterable[Dict[str, Any]]) -> Dict[str, Any]:
148
+ rows = list(rows)
149
+ by_sev = Counter(r.get("severity", "UNASSIGNED") for r in rows)
150
+ by_state = Counter(r.get("analysis", "NOT_SET") for r in rows)
151
+ return {
152
+ "by_severity": {s: by_sev[s] for s in SEVERITIES if by_sev[s]},
153
+ "by_analysis": {s: by_state[s] for s in ANALYSIS_STATES if by_state[s]},
154
+ }
155
+
156
+
157
+ def vulnerability_view(v: Dict[str, Any]) -> Dict[str, Any]:
158
+ row: Dict[str, Any] = {
159
+ "vuln": v.get("vulnId"),
160
+ "source": v.get("source"),
161
+ "severity": v.get("severity"),
162
+ "cvss_v3": v.get("cvssV3BaseScore"),
163
+ "cvss_v3_vector": v.get("cvssV3Vector"),
164
+ "cvss_v4": v.get("cvssV4Score"),
165
+ "epss": v.get("epssScore"),
166
+ "epss_percentile": v.get("epssPercentile"),
167
+ "aliases": aliases(v) or None,
168
+ "title": v.get("title"),
169
+ "description": short(v.get("description"), 1200),
170
+ "recommendation": short(v.get("recommendation"), 600),
171
+ "cwes": [f"CWE-{c['cweId']}" for c in v.get("cwes") or [] if isinstance(c, dict) and c.get("cweId")] or None,
172
+ "published": v.get("published"),
173
+ "patched_versions": v.get("patchedVersions"),
174
+ "vulnerable_versions": v.get("vulnerableVersions"),
175
+ "references": short(v.get("references"), 600),
176
+ "uuid": v.get("uuid"),
177
+ }
178
+ return {k: val for k, val in row.items() if val not in (None, "", [])}
179
+
180
+
181
+ def license_of(c: Dict[str, Any]) -> str:
182
+ resolved = c.get("resolvedLicense") or {}
183
+ return (resolved.get("licenseId") or resolved.get("name") or c.get("licenseExpression")
184
+ or c.get("license") or "(none)")
185
+
186
+
187
+ def component_row(c: Dict[str, Any]) -> Dict[str, Any]:
188
+ meta = c.get("repositoryMeta") or {}
189
+ latest = meta.get("latestVersion")
190
+ row: Dict[str, Any] = {
191
+ "component": coordinates(c),
192
+ "purl": c.get("purl"),
193
+ "license": license_of(c),
194
+ "latest_version": latest if latest and latest != c.get("version") else None,
195
+ "internal": True if c.get("isInternal") or c.get("internal") else None,
196
+ "uuid": c.get("uuid"),
197
+ }
198
+ m = c.get("metrics") or {}
199
+ vulns = {s.lower(): m.get(s.lower()) for s in SEVERITIES[:4] if m.get(s.lower())}
200
+ if vulns:
201
+ row["vulnerabilities"] = vulns
202
+ proj = c.get("project")
203
+ if isinstance(proj, dict):
204
+ row["project"] = project_label(proj)
205
+ row["project_uuid"] = proj.get("uuid")
206
+ return {k: v for k, v in row.items() if v is not None}
207
+
208
+
209
+ # SPDX ids that usually need a closer look in commercial software. A summary, not legal advice.
210
+ COPYLEFT_STRONG = ("GPL-", "AGPL-", "SSPL-", "OSL-", "EUPL-", "CPAL-", "RPL-", "SleepyCat")
211
+ COPYLEFT_WEAK = ("LGPL-", "MPL-", "EPL-", "CDDL-", "CPL-", "MS-RL", "APSL-")
212
+
213
+
214
+ _FAMILIES = ["permissive", "weak copyleft", "strong copyleft"]
215
+
216
+
217
+ def _family_of_id(spdx_id: str) -> int:
218
+ if spdx_id.startswith(COPYLEFT_STRONG):
219
+ return 2
220
+ if spdx_id.startswith(COPYLEFT_WEAK):
221
+ return 1
222
+ return 0
223
+
224
+
225
+ def license_family(lic: str) -> str:
226
+ """Rough family of an SPDX id or expression.
227
+
228
+ ``A OR B`` counts as the more permissive choice (you may pick either); ``A AND B`` as the
229
+ more restrictive one. ``WITH`` exceptions (e.g. Classpath-exception-2.0) lower a strong
230
+ copyleft license to weak.
231
+ """
232
+ if lic == "(none)":
233
+ return "unknown"
234
+ expr = " ".join(lic.replace("(", " ").replace(")", " ").split())
235
+ best = None
236
+ for alternative in expr.split(" OR "):
237
+ worst = 0
238
+ for part in alternative.split(" AND "):
239
+ spdx_id, _, exception = part.partition(" WITH ")
240
+ fam = _family_of_id(spdx_id.strip())
241
+ if exception and fam == 2:
242
+ fam = 1
243
+ worst = max(worst, fam)
244
+ best = worst if best is None else min(best, worst)
245
+ return _FAMILIES[best or 0]
246
+
247
+
248
+ def license_summary(components: List[Dict[str, Any]], examples: int = 3) -> Dict[str, Any]:
249
+ groups: Dict[str, List[str]] = defaultdict(list)
250
+ for c in components:
251
+ groups[license_of(c)].append(coordinates(c))
252
+ rows = []
253
+ for lic, comps in sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0])):
254
+ rows.append({"license": lic, "family": license_family(lic), "components": len(comps),
255
+ "examples": sorted(comps)[:examples]})
256
+ fam = Counter()
257
+ for r in rows:
258
+ fam[r["family"]] += r["components"]
259
+ order = ["strong copyleft", "weak copyleft", "unknown", "permissive"]
260
+ return {"by_family": {f: fam[f] for f in order if fam[f]}, "licenses": rows}
261
+
262
+
263
+ def violation_row(v: Dict[str, Any]) -> Dict[str, Any]:
264
+ cond = v.get("policyCondition") or {}
265
+ policy = cond.get("policy") or {}
266
+ analysis = v.get("analysis") or {}
267
+ comp = v.get("component") or {}
268
+ condition = " ".join(str(x) for x in (cond.get("subject"), cond.get("operator"), cond.get("value")) if x)
269
+ proj = v.get("project") if isinstance(v.get("project"), dict) else comp.get("project")
270
+ row = {
271
+ "type": v.get("type"),
272
+ "policy": policy.get("name"),
273
+ "state": policy.get("violationState"),
274
+ "condition": condition or None,
275
+ "component": coordinates(comp) if comp else None,
276
+ "project": project_label(proj) if isinstance(proj, dict) else None,
277
+ "analysis": analysis.get("analysisState") or "NOT_SET",
278
+ "suppressed": True if analysis.get("isSuppressed") or analysis.get("suppressed") else None,
279
+ "text": short(v.get("text"), 160),
280
+ "uuid": v.get("uuid"),
281
+ }
282
+ return {k: val for k, val in row.items() if val is not None}
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.5
2
+ Name: bomscout
3
+ Version: 0.1.0
4
+ Summary: MCP server for OWASP Dependency-Track: ask Claude, Cursor or any MCP client which projects a CVE affects, what to fix first, licenses and policy violations across your SBOM portfolio
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/bomscout
6
+ Project-URL: Source, https://github.com/srikrishnaL/kitforge
7
+ Project-URL: Issues, https://github.com/srikrishnaL/kitforge/issues
8
+ Project-URL: Changelog, https://github.com/srikrishnaL/kitforge/blob/main/packages/bomscout/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: claude,cve,cyclonedx,dependency-track,dependencytrack,license compliance,mcp,mcp server,model context protocol,owasp,sbom,software composition analysis,supply chain security,triage,vex,vulnerability,vulnerability management
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Quality Assurance
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: mcp>=1.10
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest-mcp-server>=0.2; extra == 'test'
25
+ Requires-Dist: pytest>=7; extra == 'test'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # bomscout
29
+
30
+ **An MCP server for [OWASP Dependency-Track](https://dependencytrack.org/).** Ask Claude, Cursor,
31
+ VS Code or any MCP client about your software portfolio in plain words: "which of our projects
32
+ are affected by CVE-2021-44228, and has anyone triaged it?", "what should we fix first in
33
+ `shop`?", "do we ship any GPL code?".
34
+
35
+ Dependency-Track already knows the answers, but getting them means clicking through the UI or
36
+ writing scripts against several REST endpoints. bomscout wraps those endpoints as a handful of
37
+ read-only tools that return small, ranked results a model can reason over.
38
+
39
+ ```bash
40
+ pip install bomscout # or run it without installing: uvx bomscout
41
+ ```
42
+
43
+ ## Set up
44
+
45
+ You need the URL of the Dependency-Track **API server** and an API key of a team
46
+ (Administration > Access Management > Teams). Give the team `VIEW_PORTFOLIO`,
47
+ `VIEW_VULNERABILITY` and `VIEW_POLICY_VIOLATION`. Check the connection and permissions:
48
+
49
+ ```bash
50
+ DT_URL=https://dtrack.example.com DT_API_KEY=odt_... bomscout check
51
+ ```
52
+
53
+ **Claude Code**
54
+
55
+ ```bash
56
+ claude mcp add bomscout -e DT_URL=https://dtrack.example.com -e DT_API_KEY=odt_... -- uvx bomscout
57
+ ```
58
+
59
+ **Claude Desktop, Cursor, VS Code and others** (the usual `mcpServers` JSON):
60
+
61
+ ```json
62
+ {
63
+ "mcpServers": {
64
+ "bomscout": {
65
+ "command": "uvx",
66
+ "args": ["bomscout"],
67
+ "env": { "DT_URL": "https://dtrack.example.com", "DT_API_KEY": "odt_..." }
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ | Setting | Meaning |
74
+ | --- | --- |
75
+ | `DT_URL` | API server URL (a trailing `/api` is fine). `DEPENDENCY_TRACK_URL` also works. |
76
+ | `DT_API_KEY` | Team API key. `DEPENDENCY_TRACK_API_KEY` also works. |
77
+ | `DT_CA_BUNDLE` | Path to a CA bundle for a server with a private certificate. |
78
+ | `DT_INSECURE=1` | Skip TLS certificate checks (test servers only). |
79
+ | `DT_TIMEOUT` | Seconds per request (default 30). |
80
+ | `BOMSCOUT_ALLOW_WRITE=1` | Add the `record_analysis` tool (or run `bomscout --allow-write`). |
81
+
82
+ ## Tools
83
+
84
+ | Tool | Answers |
85
+ | --- | --- |
86
+ | `portfolio_overview` | Vulnerabilities by severity, audited vs unaudited findings, policy violations, riskiest projects |
87
+ | `list_projects` | Projects by name or tag, with UUID, version, risk score and vulnerability counts |
88
+ | `project_findings` | A project's vulnerabilities, most severe first (CVSS, EPSS, component, triage state); filter by severity or analysis state, e.g. untriaged only |
89
+ | `vulnerability_impact` | One CVE/GHSA: details, fixed versions, every affected project and its remediation status there |
90
+ | `project_components` | A project's dependencies with license and newer versions; only outdated, only direct |
91
+ | `project_licenses` | Components per license, grouped as strong copyleft, weak copyleft, permissive, unknown |
92
+ | `find_component` | Every project that uses a package, by package URL or name and version |
93
+ | `policy_violations` | Security, license and operational policy violations for a project or the portfolio, FAIL first |
94
+ | `record_analysis` | *Opt-in.* Record a triage decision (state, justification, response, comment, suppression) |
95
+
96
+ Projects can be named by UUID, by name (its latest version) or as `name@version`. All tools
97
+ except `record_analysis` are marked read-only, so clients can run them without asking.
98
+
99
+ ## Example
100
+
101
+ A tool result is compact JSON. `project_findings` with `project="shop", min_severity="HIGH"`:
102
+
103
+ ```json
104
+ {
105
+ "project": "shop@2.0",
106
+ "by_severity": {"CRITICAL": 1, "HIGH": 1},
107
+ "by_analysis": {"EXPLOITABLE": 1, "NOT_SET": 1},
108
+ "total": 2, "shown": 2,
109
+ "findings": [
110
+ {"vuln": "CVE-2021-44228", "source": "NVD", "severity": "CRITICAL", "cvss": 10.0, "epss": 0.944,
111
+ "aliases": ["GHSA-jfh8-c2jp-5v3q"], "component": "org.apache.logging.log4j/log4j-core@2.14.1",
112
+ "purl": "pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1", "analysis": "EXPLOITABLE",
113
+ "component_uuid": "...", "vulnerability_uuid": "..."}
114
+ ]
115
+ }
116
+ ```
117
+
118
+ The same questions work from Python, without MCP:
119
+
120
+ ```python
121
+ from bomscout import Scout
122
+
123
+ scout = Scout.from_env() # reads DT_URL and DT_API_KEY
124
+ impact = scout.vulnerability_impact("CVE-2021-44228")
125
+ for project in impact["projects"]:
126
+ print(project["project"], [c["analysis"] for c in project["components"]])
127
+ ```
128
+
129
+ ## Limits
130
+
131
+ - Dependency-Track **4.x** REST API (field names checked against the 4.14.6 API server).
132
+ The Hyades / v5 API is not supported yet.
133
+ - An API key sees what its team sees. With portfolio access control on, other teams' projects
134
+ are invisible to bomscout too.
135
+ - `vulnerability_impact` reads the findings of each affected project to report its analysis
136
+ state: one request per project, 20 projects by default (`max_projects`).
137
+ - License families are a quick triage aid, not legal advice. Components without a resolved
138
+ license count as "unknown".
139
+ - stdio transport only. Run one instance per user, with that user's (or a read-only team's)
140
+ API key.
141
+ - Writing is limited to `record_analysis`; bomscout never uploads BOMs, deletes projects or
142
+ changes policies.
143
+
144
+ ## Why this exists
145
+
146
+ Dependency-Track users asked for an MCP server so they could query their portfolio's security
147
+ posture in natural language instead of hand-writing API scripts:
148
+ [DependencyTrack/dependency-track#5791](https://github.com/DependencyTrack/dependency-track/issues/5791)
149
+ (open, 18 upvotes). Its examples ("show me all critical vulnerabilities", "summary of component
150
+ license risks", "what's the current remediation status for CVE-...") map to
151
+ `portfolio_overview` / `project_findings`, `project_licenses` and `vulnerability_impact`.
152
+
153
+ Part of [kitforge](https://github.com/srikrishnaL/kitforge). MIT licensed.
@@ -0,0 +1,12 @@
1
+ bomscout/__init__.py,sha256=-JjVtYQID1RmFzgZ3coMO-eagGG6R2puH3YBWc0bSGM,493
2
+ bomscout/__main__.py,sha256=WAhr-TR-SUgzU8lRacTT70n91sBZgxPy6yff-Zyeu3E,55
3
+ bomscout/client.py,sha256=zOIssJSM0JeSfSb-xxg18nxWo23iUpX5OLo-EKO_DAI,13939
4
+ bomscout/errors.py,sha256=n1JK4_SCFwtYbHtBTYaVsOUJvVcJ1ILjhtxEM2U-tqc,1331
5
+ bomscout/scout.py,sha256=UtdyRcTpFcElr3HzdyQ5c-kHY9uYM7a9oxyHGQj0StQ,12573
6
+ bomscout/server.py,sha256=G80Ykr80QZT1P6CQefqL9SuILcoHRTTBwqR6Tz4cUm4,11900
7
+ bomscout/views.py,sha256=0Dr7zJrXnGvLAcPQpNmhROR9pIWQFShboy-Jk9X2dUI,11376
8
+ bomscout-0.1.0.dist-info/METADATA,sha256=0aiRG4rYVr-S-wzoCcBbvPXZqKeys8J-DoKyaWekNgk,7068
9
+ bomscout-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ bomscout-0.1.0.dist-info/entry_points.txt,sha256=78I3FN_s_Xt8S-_jpCxVrTb_jbbAIdnos5r_rIYrBTQ,50
11
+ bomscout-0.1.0.dist-info/licenses/LICENSE,sha256=fl9U1idgeyJw-8GWneEYxVzZM_C29cBR63IAlNv7KjE,1080
12
+ bomscout-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bomscout = bomscout.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sri Krishna Lingamaneni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.