mcpscan-cli 0.19.1__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.
mcpscan/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """mcpscan — supply-chain security scanner for MCP servers and Claude Code projects."""
2
+
3
+ __version__ = "0.19.1"
mcpscan/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Enable `python -m mcpscan`."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
mcpscan/cli.py ADDED
@@ -0,0 +1,150 @@
1
+ """Command-line interface for mcpscan."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .discover import render_discovery_json, render_discovery_sarif, render_discovery_text, run_discovery
11
+ from .drift import DRIFT_RULE, check_drift
12
+ from .findings import Severity
13
+ from .fixer import apply_fixes, compute_fixes, render_preview
14
+ from .report import render
15
+ from .scanner import scan_files
16
+
17
+ EXIT_OK = 0
18
+ EXIT_FINDINGS = 1
19
+ EXIT_ERROR = 2
20
+
21
+
22
+ def build_parser() -> argparse.ArgumentParser:
23
+ p = argparse.ArgumentParser(
24
+ prog="mcpscan",
25
+ description="Supply-chain security scanner for MCP servers and Claude Code projects.",
26
+ )
27
+ p.add_argument("path", nargs="?", default=".", help="file or directory to scan (default: .)")
28
+ p.add_argument("-f", "--format", choices=["text", "json", "sarif"], default="text",
29
+ help="output format (default: text)")
30
+ p.add_argument("--json", action="store_true", help="shorthand for --format json")
31
+ p.add_argument("-o", "--output", help="write report to this file instead of stdout")
32
+ p.add_argument("--min-severity", default="low",
33
+ help="minimum severity that causes a non-zero exit "
34
+ "(info|low|medium|high|critical; default: low)")
35
+ p.add_argument("--no-color", action="store_true", help="disable ANSI colors")
36
+ p.add_argument("--list-rules", action="store_true", help="list all rules and exit")
37
+ p.add_argument("--fix", action="store_true",
38
+ help="preview mechanical one-line fixes for fixable findings (dry run)")
39
+ p.add_argument("--apply-fix", action="store_true",
40
+ help="write the fixes shown by --fix to disk (implies --fix)")
41
+ p.add_argument("--discover", action="store_true",
42
+ help="scan known MCP client config locations on this machine "
43
+ "(Claude Desktop, Claude Code, Cursor, VS Code, Windsurf) "
44
+ "instead of a path — closes OWASP MCP09:2025 (Shadow MCP Servers)")
45
+ p.add_argument("-V", "--version", action="version", version=f"mcpscan {__version__}")
46
+ return p
47
+
48
+
49
+ def list_rules() -> str:
50
+ from . import rules as rules_pkg
51
+ from .rules.base import Rule
52
+ # DRIFT_RULE is discovery-only (needs cross-run state) and deliberately
53
+ # isn't in rules_pkg's REGISTRY — merged in here so `--list-rules` still
54
+ # lists every rule id mcpscan can produce, not just the per-file ones.
55
+ rows = sorted([*rules_pkg.all_rules(), DRIFT_RULE], key=lambda r: r.id)
56
+ lines = [f"{'ID':<8} {'SEVERITY':<9} {'FIX':<5} {'OWASP':<10} NAME",
57
+ f"{'-'*8} {'-'*9} {'-'*5} {'-'*10} {'-'*40}"]
58
+ for r in rows:
59
+ fixable = "yes" if type(r).fix_line is not Rule.fix_line else "-"
60
+ lines.append(f"{r.id:<8} {r.severity.label:<9} {fixable:<5} {r.owasp or '-':<10} {r.name}")
61
+ lines.append(f"\n{len(rows)} rules.")
62
+ return "\n".join(lines)
63
+
64
+
65
+ def _run_discover(args: argparse.Namespace, fmt: str, color: bool, threshold: Severity) -> int:
66
+ if args.fix or args.apply_fix:
67
+ print("mcpscan: --discover does not support --fix/--apply-fix yet", file=sys.stderr)
68
+ return EXIT_ERROR
69
+ if args.path != ".":
70
+ print(f"mcpscan: --discover ignores the path argument ('{args.path}') — "
71
+ f"it scans known client config locations, not a project directory",
72
+ file=sys.stderr)
73
+
74
+ discovery = run_discovery()
75
+ check_drift(discovery)
76
+ if fmt == "json":
77
+ text = render_discovery_json(discovery)
78
+ elif fmt == "sarif":
79
+ text = render_discovery_sarif(discovery)
80
+ else:
81
+ text = render_discovery_text(discovery, color=color)
82
+
83
+ if args.output:
84
+ with open(args.output, "w", encoding="utf-8") as fh:
85
+ fh.write(text + "\n")
86
+ print(f"mcpscan: wrote {fmt} discovery report to {args.output}", file=sys.stderr)
87
+ else:
88
+ try:
89
+ sys.stdout.reconfigure(encoding="utf-8")
90
+ except Exception:
91
+ pass
92
+ print(text)
93
+
94
+ at_or_above = any(f.severity >= threshold for f in discovery.all_findings())
95
+ return EXIT_FINDINGS if at_or_above else EXIT_OK
96
+
97
+
98
+ def main(argv=None) -> int:
99
+ args = build_parser().parse_args(argv)
100
+
101
+ if args.list_rules:
102
+ print(list_rules())
103
+ return EXIT_OK
104
+
105
+ try:
106
+ threshold = Severity.parse(args.min_severity)
107
+ except ValueError as exc:
108
+ print(f"mcpscan: {exc}", file=sys.stderr)
109
+ return EXIT_ERROR
110
+
111
+ fmt = "json" if args.json else args.format
112
+ color = (not args.no_color) and args.output is None and sys.stdout.isatty()
113
+
114
+ if args.discover:
115
+ return _run_discover(args, fmt, color, threshold)
116
+
117
+ if not os.path.exists(args.path):
118
+ print(f"mcpscan: path not found: {args.path}", file=sys.stderr)
119
+ return EXIT_ERROR
120
+
121
+ report, files = scan_files(args.path)
122
+
123
+ if args.fix or args.apply_fix:
124
+ fixes = compute_fixes(report, files)
125
+ print(render_preview(fixes))
126
+ if args.apply_fix and fixes:
127
+ modified = apply_fixes(fixes, files)
128
+ print(f"\nmcpscan: applied {len(fixes)} fix(es) across {len(modified)} file(s).",
129
+ file=sys.stderr)
130
+ return EXIT_FINDINGS if report.at_or_above(threshold) else EXIT_OK
131
+
132
+ text = render(report, fmt, color=color)
133
+
134
+ if args.output:
135
+ with open(args.output, "w", encoding="utf-8") as fh:
136
+ fh.write(text + "\n")
137
+ print(f"mcpscan: wrote {fmt} report to {args.output}", file=sys.stderr)
138
+ else:
139
+ # Force UTF-8 so redaction/box glyphs survive a Windows console.
140
+ try:
141
+ sys.stdout.reconfigure(encoding="utf-8")
142
+ except Exception:
143
+ pass
144
+ print(text)
145
+
146
+ return EXIT_FINDINGS if report.at_or_above(threshold) else EXIT_OK
147
+
148
+
149
+ if __name__ == "__main__": # pragma: no cover
150
+ sys.exit(main())
mcpscan/discover.py ADDED
@@ -0,0 +1,260 @@
1
+ """``--discover``: enumerate known MCP client config locations on this machine.
2
+
3
+ Closes OWASP MCP09:2025 (Shadow MCP Servers). A normal `mcpscan <path>` scan
4
+ only ever sees what you point it at; most engineers don't remember every MCP
5
+ client they've installed, so a laptop routinely has MCP server configs a
6
+ security review never sees. This module answers a narrower, cheaper question
7
+ than full shadow-IT discovery: on *this* machine, which of the well-known MCP
8
+ client config files exist, and what does mcpscan's existing rule set find in
9
+ each one.
10
+
11
+ Scope, deliberately:
12
+
13
+ - Per-machine only. There is no fleet/remote-collection piece here — that
14
+ needs an inventory or agent backend this project doesn't have. Run this on
15
+ each machine you want visibility into.
16
+ - Only *known, standard* config paths are checked (Claude Desktop, Claude
17
+ Code CLI, Cursor, VS Code, Windsurf — see ``known_locations()`` for exact
18
+ paths and sources). This is not a filesystem-wide crawl for anything named
19
+ "mcp.json" outside a project; that's already what a normal directory scan
20
+ does for a project you're already reviewing.
21
+ - A location that doesn't exist on this OS/user account is not a finding —
22
+ it's recorded as "checked, not present" so a report can't be misread as
23
+ "everything is clean" when a client was simply never installed here.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import sys
31
+ from dataclasses import dataclass, field
32
+ from typing import List, Optional
33
+
34
+ from .findings import Finding, Report
35
+ from .scanner import scan_files
36
+
37
+
38
+ def _home() -> str:
39
+ """Home directory, resolved via env vars first so this stays testable.
40
+
41
+ ``os.path.expanduser("~")`` is correct at runtime but its behavior is
42
+ tied to the *actual* host OS, not a value we can override in a test —
43
+ checking HOME/USERPROFILE ourselves first means the known-location table
44
+ can be exercised for every OS branch from a single CI runner.
45
+ """
46
+ return os.environ.get("HOME") or os.environ.get("USERPROFILE") or os.path.expanduser("~")
47
+
48
+
49
+ def _appdata() -> str:
50
+ return os.environ.get("APPDATA") or os.path.join(_home(), "AppData", "Roaming")
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ClientLocation:
55
+ client: str # human label, e.g. "Claude Desktop"
56
+ path: str # absolute path this OS/account would use
57
+
58
+
59
+ def known_locations(platform: Optional[str] = None) -> List[ClientLocation]:
60
+ """Well-known, user-scope MCP client config paths for *platform*.
61
+
62
+ Defaults to :data:`sys.platform`; a caller (tests) can pass another
63
+ value to inspect what mcpscan would check on a different OS.
64
+
65
+ Deliberately excludes project-scoped files (``.cursor/mcp.json``,
66
+ ``.vscode/mcp.json``, a repo's own ``.mcp.json``, a workspace's
67
+ ``.amazonq/mcp.json``) — those already surface in a normal directory
68
+ scan of the project (``loaders.MANIFEST_NAMES`` matches "mcp.json" by
69
+ basename regardless of which directory it's under, and MCP004's
70
+ candidate filter matches any ``.json`` file — verified directly against
71
+ a scratch ``.amazonq/mcp.json`` fixture with ``autoApprove: true`` before
72
+ adding these two entries, to confirm project-scoped Amazon Q/Cline
73
+ configs weren't a silent gap already). This table is only the
74
+ global/user-level configs a directory scan would never see because
75
+ they live outside any project tree.
76
+
77
+ Sources (verified, not guessed, 2026-07-09; two more added 2026-07-27):
78
+ - Claude Desktop: Anthropic's own MCP quickstart / support docs.
79
+ - Cursor: cursor.com/docs/mcp.
80
+ - VS Code / Copilot: code.visualstudio.com/docs/agents/reference/mcp-configuration.
81
+ - Claude Code CLI: code.claude.com/docs/en/mcp.
82
+ - Windsurf: docs.windsurf.com/windsurf/cascade/mcp.
83
+ - Amazon Q Developer CLI (global): docs.aws.amazon.com/amazonq — a
84
+ *separate* config from the workspace-scoped ``.amazonq/mcp.json`` that
85
+ CVE-2026-12957 (Wiz Research) disclosed; that workspace file is a
86
+ project-scoped path a normal scan already covers, but this global one
87
+ at ``~/.aws/amazonq/mcp.json`` applies across every workspace and
88
+ lives outside any project tree, so ``--discover`` is the only mcpscan
89
+ mode that would ever see it.
90
+ - Cline (global, VS Code extension storage):
91
+ github.com/cline/cline discussion #2355 + confirmed extension id
92
+ ``saoudrizwan.claude-dev``. Cline's settings live in VS Code's
93
+ per-extension ``globalStorage``, not a project-relative path, so this
94
+ is also otherwise invisible to a directory scan.
95
+ """
96
+ plat = platform or sys.platform
97
+ home = _home()
98
+ appdata = _appdata()
99
+ out: List[ClientLocation] = []
100
+
101
+ if plat == "win32":
102
+ out.append(ClientLocation("Claude Desktop", os.path.join(appdata, "Claude", "claude_desktop_config.json")))
103
+ elif plat == "darwin":
104
+ out.append(ClientLocation("Claude Desktop", os.path.join(
105
+ home, "Library", "Application Support", "Claude", "claude_desktop_config.json")))
106
+ else:
107
+ out.append(ClientLocation("Claude Desktop", os.path.join(
108
+ home, ".config", "claude-desktop", "claude_desktop_config.json")))
109
+
110
+ # Claude Code CLI — global, user-scope servers live under ~/.claude.json.
111
+ # Project-scope (.mcp.json) and local-scope (also inside ~/.claude.json,
112
+ # but keyed per-project) are out of scope here for the same reason as
113
+ # Cursor/VS Code project files above.
114
+ out.append(ClientLocation("Claude Code CLI (user)", os.path.join(home, ".claude.json")))
115
+
116
+ out.append(ClientLocation("Cursor (global)", os.path.join(home, ".cursor", "mcp.json")))
117
+
118
+ if plat == "win32":
119
+ out.append(ClientLocation("VS Code (user)", os.path.join(appdata, "Code", "User", "mcp.json")))
120
+ elif plat == "darwin":
121
+ out.append(ClientLocation("VS Code (user)", os.path.join(
122
+ home, "Library", "Application Support", "Code", "User", "mcp.json")))
123
+ else:
124
+ out.append(ClientLocation("VS Code (user)", os.path.join(home, ".config", "Code", "User", "mcp.json")))
125
+
126
+ out.append(ClientLocation("Windsurf", os.path.join(home, ".codeium", "windsurf", "mcp_config.json")))
127
+
128
+ # Amazon Q Developer CLI's *global* config — same ~/.aws prefix on every
129
+ # OS (AWS CLI convention), no platform branch needed.
130
+ out.append(ClientLocation("Amazon Q Developer CLI (global)",
131
+ os.path.join(home, ".aws", "amazonq", "mcp.json")))
132
+
133
+ cline_settings = os.path.join("Code", "User", "globalStorage", "saoudrizwan.claude-dev",
134
+ "settings", "cline_mcp_settings.json")
135
+ if plat == "win32":
136
+ out.append(ClientLocation("Cline (global)", os.path.join(appdata, cline_settings)))
137
+ elif plat == "darwin":
138
+ out.append(ClientLocation("Cline (global)", os.path.join(
139
+ home, "Library", "Application Support", cline_settings)))
140
+ else:
141
+ out.append(ClientLocation("Cline (global)", os.path.join(home, ".config", cline_settings)))
142
+
143
+ return out
144
+
145
+
146
+ @dataclass
147
+ class LocationResult:
148
+ location: ClientLocation
149
+ found: bool
150
+ report: Optional[Report] = None
151
+
152
+
153
+ @dataclass
154
+ class DiscoveryResult:
155
+ results: List[LocationResult] = field(default_factory=list)
156
+ platform: str = ""
157
+
158
+ @property
159
+ def found_count(self) -> int:
160
+ return sum(1 for r in self.results if r.found)
161
+
162
+ def all_findings(self) -> List[Finding]:
163
+ return [f for r in self.results if r.report for f in r.report.findings]
164
+
165
+
166
+ def run_discovery(platform: Optional[str] = None) -> DiscoveryResult:
167
+ """Check every known location; scan the ones that exist with the normal rule set."""
168
+ plat = platform or sys.platform
169
+ result = DiscoveryResult(platform=plat)
170
+ for loc in known_locations(plat):
171
+ if not os.path.isfile(loc.path):
172
+ result.results.append(LocationResult(loc, found=False))
173
+ continue
174
+ report, _files = scan_files(loc.path)
175
+ report.root = loc.path
176
+ result.results.append(LocationResult(loc, found=True, report=report))
177
+ return result
178
+
179
+
180
+ def render_discovery_text(discovery: DiscoveryResult, color: bool = True) -> str:
181
+ from .report import render_text # local import: avoid a report<->discover cycle
182
+
183
+ lines = [f"mcpscan --discover checked {len(discovery.results)} known MCP client "
184
+ f"config location(s) for {discovery.platform}", ""]
185
+ for r in discovery.results:
186
+ loc = r.location
187
+ if not r.found:
188
+ lines.append(f"[ ] {loc.client} — not present ({loc.path})")
189
+ continue
190
+ lines.append(f"[x] {loc.client} — {loc.path}")
191
+ lines.append(render_text(r.report, color=color))
192
+ findings = discovery.all_findings()
193
+ lines.append(f"Discovery summary: {discovery.found_count}/{len(discovery.results)} "
194
+ f"location(s) present, {len(findings)} finding(s) total.")
195
+ return "\n".join(lines)
196
+
197
+
198
+ def render_discovery_sarif(discovery: DiscoveryResult) -> str:
199
+ """SARIF 2.1.0 for a discovery run, one ``run`` spanning every location.
200
+
201
+ Reuses :func:`report._sarif_rules`/``_sarif_result`` rather than
202
+ duplicating SARIF's rule/result shape here. Results are pointed at each
203
+ location's full config path (``location.path``), not ``finding.path`` —
204
+ a single-file scan records only the bare filename (e.g. ``mcp.json``),
205
+ which collides across clients (Cursor and VS Code both use that name) and
206
+ wouldn't tell a reader which location a result came from.
207
+ """
208
+ from .report import _sarif_rules, _sarif_result # local: avoid report<->discover cycle
209
+
210
+ all_findings = discovery.all_findings()
211
+ results = [
212
+ _sarif_result(f, r.location.path)
213
+ for r in discovery.results if r.found and r.report
214
+ for f in r.report.sorted()
215
+ ]
216
+ sarif = {
217
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
218
+ "version": "2.1.0",
219
+ "runs": [{
220
+ "tool": {"driver": {
221
+ "name": "mcpscan",
222
+ "informationUri": "https://github.com/glatinone/mcpscan",
223
+ "rules": _sarif_rules(all_findings),
224
+ }},
225
+ "results": results,
226
+ }],
227
+ }
228
+ return json.dumps(sarif, indent=2)
229
+
230
+
231
+ def render_discovery_json(discovery: DiscoveryResult) -> str:
232
+ payload = {
233
+ "tool": "mcpscan",
234
+ "mode": "discover",
235
+ "platform": discovery.platform,
236
+ "locations": [
237
+ {
238
+ "client": r.location.client,
239
+ "path": r.location.path,
240
+ "found": r.found,
241
+ "findings": [
242
+ {
243
+ "rule_id": f.rule_id,
244
+ "title": f.title,
245
+ "severity": f.severity.label,
246
+ "path": f.path,
247
+ "line": f.line,
248
+ "detail": f.detail,
249
+ "snippet": f.snippet,
250
+ "owasp": f.owasp,
251
+ }
252
+ for f in r.report.sorted()
253
+ ] if r.found and r.report else [],
254
+ }
255
+ for r in discovery.results
256
+ ],
257
+ "found_count": discovery.found_count,
258
+ "total_findings": len(discovery.all_findings()),
259
+ }
260
+ return json.dumps(payload, indent=2)
mcpscan/drift.py ADDED
@@ -0,0 +1,174 @@
1
+ """MCP014 — a remote MCP server's URL domain silently changed since the last
2
+ ``--discover`` run.
3
+
4
+ This is a different angle on the same OWASP MCP09:2025 (Shadow MCP Servers)
5
+ territory ``--discover`` (v0.7.0) already covers: that feature answers "what's
6
+ configured right now"; this answers "did a *previously seen* server config get
7
+ silently rewritten between runs." That's exactly the mechanism Mitiga Labs
8
+ disclosed (2026-04-10): a malicious npm postinstall hook rewrites a known
9
+ server's URL in ``~/.claude.json`` to an attacker-controlled proxy, intercepting
10
+ OAuth bearer tokens (GitHub/Jira/Confluence) in transit. The server's *name* in
11
+ the config never changes, so a scan that only ever looks at the current state
12
+ can't tell "trusted server" from "trusted name, hijacked endpoint." Anthropic
13
+ classified the report out of scope, citing "requires initial code execution" as
14
+ a prerequisite — the silent config rewrite is exactly what happens *after* that
15
+ initial foothold, and it's the part a periodic scan can still catch.
16
+
17
+ Design, deliberately:
18
+
19
+ - Diff against a local baseline cache, not a hardcoded vendor-domain allowlist.
20
+ A maintained list of "known-good" domains per server name would go stale
21
+ immediately and either miss real vendors or false-positive on legitimate
22
+ self-hosted deployments. A fingerprint of "what did *this* install look like
23
+ the last time mcpscan ran here" needs no such list and still catches the
24
+ actual attack pattern: an unauthorized, silent change to what the user
25
+ already configured.
26
+ - First sighting of a server name at a location is never a finding — there's
27
+ nothing to diff against yet. It's recorded as the new baseline, same as
28
+ ``--discover`` itself records "checked, not present" rather than guessing.
29
+ - A domain change *is* a finding, and the new domain becomes the baseline going
30
+ forward — "alert once, then trust the new state," not a permanent lock. A
31
+ legitimate migration (a team moving a self-hosted server to a new domain)
32
+ trips this exactly once; a silent hijack also trips it exactly once, which
33
+ is the point of a tripwire — one automated pass catches either.
34
+ - Local, stdio/command-launched servers have no domain and are out of scope —
35
+ the same boundary MCP012 (auth gaps) already draws for the same reason.
36
+ - Only the hostname is fingerprinted (scheme/port/path/query ignored) — a
37
+ server adding a query param or switching a path isn't a trust-boundary
38
+ change; a changed hostname is who you're actually talking to.
39
+
40
+ Discovery-only, and deliberately not a normal :class:`~.rules.base.Rule`: a
41
+ `Rule` is a stateless function of the files in front of it, but this check
42
+ needs state that persists *across* runs (the baseline cache) and only makes
43
+ sense for the known, named server entries ``--discover`` already enumerates —
44
+ running it against an arbitrary project's `mcp.json` would either need the
45
+ same cross-run state (which a one-off project scan has no business keeping)
46
+ or silently do nothing. It still carries a `Rule`-shaped id/name/severity/owasp
47
+ so it can appear in `--list-rules` and flow through the existing SARIF/JSON/
48
+ text renderers exactly like every other finding.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import json
54
+ import os
55
+ from typing import Dict, Optional
56
+ from urllib.parse import urlsplit
57
+
58
+ from .discover import DiscoveryResult, _home
59
+ from .findings import Finding, Severity
60
+ from .rules.auth_gaps import _URL_KEYS, _iter_server_entries
61
+ from .rules.base import Rule
62
+
63
+ RULE_ID = "MCP014"
64
+
65
+
66
+ class DomainDriftRule(Rule):
67
+ """Descriptor only — see module docstring for why this isn't registered."""
68
+
69
+ id = RULE_ID
70
+ name = "Remote MCP server domain changed since last --discover scan (discovery-only)"
71
+ severity = Severity.HIGH
72
+ owasp = "MCP04:2025" # Software Supply Chain Attacks & Dependency Tampering
73
+
74
+
75
+ # Not decorated with @register: this never runs via the normal per-file scan
76
+ # (`mcpscan/scanner.py`'s `rules_pkg.all_rules()` loop) — only `check_drift()`,
77
+ # called explicitly from `--discover`, produces its findings.
78
+ DRIFT_RULE = DomainDriftRule()
79
+
80
+
81
+ def default_baseline_path() -> str:
82
+ """Where the domain baseline lives, overridable for tests/CI isolation."""
83
+ override = os.environ.get("MCPSCAN_BASELINE_PATH")
84
+ if override:
85
+ return override
86
+ return os.path.join(_home(), ".mcpscan", "discover_baseline.json")
87
+
88
+
89
+ def _load_baseline(path: str) -> Dict[str, str]:
90
+ try:
91
+ with open(path, "r", encoding="utf-8") as fh:
92
+ data = json.load(fh)
93
+ except (OSError, ValueError):
94
+ return {}
95
+ servers = data.get("servers")
96
+ return dict(servers) if isinstance(servers, dict) else {}
97
+
98
+
99
+ def _save_baseline(path: str, servers: Dict[str, str]) -> None:
100
+ parent = os.path.dirname(path)
101
+ if parent:
102
+ os.makedirs(parent, exist_ok=True)
103
+ with open(path, "w", encoding="utf-8") as fh:
104
+ json.dump({"version": 1, "servers": servers}, fh, indent=2, sort_keys=True)
105
+
106
+
107
+ def _domain(url: str) -> Optional[str]:
108
+ host = urlsplit(url).hostname
109
+ return host.lower() if host else None
110
+
111
+
112
+ def _baseline_key(location_path: str, server_name: str) -> str:
113
+ return f"{location_path}::{server_name}"
114
+
115
+
116
+ def check_drift(discovery: DiscoveryResult, baseline_path: Optional[str] = None) -> None:
117
+ """Diff every present location's remote server domains against the local
118
+ baseline, in place: appends a Finding to that location's report for every
119
+ domain change, then persists the updated baseline.
120
+
121
+ Call this once per real ``--discover`` invocation, right after
122
+ :func:`~.discover.run_discovery`. A missing/unreadable/unwritable baseline
123
+ file degrades gracefully to "nothing to diff against yet," never to an
124
+ error — a first run anywhere, or a read-only filesystem, just means the
125
+ tripwire doesn't arm until a baseline can actually be written.
126
+ """
127
+ path = baseline_path or default_baseline_path()
128
+ baseline = _load_baseline(path)
129
+ changed = False
130
+
131
+ for result in discovery.results:
132
+ if not result.found or result.report is None:
133
+ continue
134
+ try:
135
+ with open(result.location.path, "r", encoding="utf-8") as fh:
136
+ data = json.load(fh)
137
+ except (OSError, ValueError):
138
+ continue
139
+
140
+ for name, cfg in _iter_server_entries(data):
141
+ url = next((cfg.get(k) for k in _URL_KEYS if isinstance(cfg.get(k), str)), None)
142
+ if not url or not url.startswith(("http://", "https://")):
143
+ continue # local/stdio server: no domain to fingerprint
144
+ domain = _domain(url)
145
+ if not domain:
146
+ continue
147
+
148
+ key = _baseline_key(result.location.path, name)
149
+ previous = baseline.get(key)
150
+ if previous is not None and previous != domain:
151
+ result.report.add(Finding(
152
+ rule_id=RULE_ID,
153
+ title=f"'{name}' now points at a different domain than last scan",
154
+ severity=DRIFT_RULE.severity,
155
+ path=os.path.basename(result.location.path),
156
+ line=0,
157
+ detail=(
158
+ f"Previously seen at '{previous}', now '{domain}'. If this server's "
159
+ "URL wasn't intentionally changed, treat this as a possible silent "
160
+ "config hijack (e.g. a malicious install script rewriting this file) "
161
+ "rather than routine drift — verify before trusting it again."
162
+ ),
163
+ snippet=f'"{name}": {{"url": "{url}"}}',
164
+ owasp=DRIFT_RULE.owasp,
165
+ ))
166
+ if previous != domain:
167
+ baseline[key] = domain
168
+ changed = True
169
+
170
+ if changed:
171
+ try:
172
+ _save_baseline(path, baseline)
173
+ except OSError:
174
+ pass
mcpscan/findings.py ADDED
@@ -0,0 +1,84 @@
1
+ """Core data model: severities, findings, and the aggregated report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import IntEnum
7
+ from typing import List, Optional
8
+
9
+
10
+ class Severity(IntEnum):
11
+ """Ordered so comparisons work: CRITICAL > HIGH > ... > INFO."""
12
+
13
+ INFO = 0
14
+ LOW = 1
15
+ MEDIUM = 2
16
+ HIGH = 3
17
+ CRITICAL = 4
18
+
19
+ @classmethod
20
+ def parse(cls, name: str) -> "Severity":
21
+ try:
22
+ return cls[name.strip().upper()]
23
+ except KeyError as exc:
24
+ valid = ", ".join(s.name.lower() for s in cls)
25
+ raise ValueError(f"unknown severity '{name}' (choose: {valid})") from exc
26
+
27
+ @property
28
+ def label(self) -> str:
29
+ return self.name.lower()
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Finding:
34
+ """A single issue discovered by a rule."""
35
+
36
+ rule_id: str # stable id, e.g. "MCP001"
37
+ title: str # short human summary
38
+ severity: Severity
39
+ path: str # file the finding lives in (relative to scan root)
40
+ line: int = 0 # 1-based line number, 0 if not applicable
41
+ detail: str = "" # longer explanation / remediation hint
42
+ snippet: str = "" # the offending text, trimmed
43
+ owasp: str = "" # OWASP MCP Top 10 (2025) category id, e.g. "MCP05:2025"
44
+
45
+ def location(self) -> str:
46
+ return f"{self.path}:{self.line}" if self.line else self.path
47
+
48
+
49
+ @dataclass
50
+ class Report:
51
+ """Aggregates findings across a scan and answers questions about them."""
52
+
53
+ root: str
54
+ findings: List[Finding] = field(default_factory=list)
55
+ files_scanned: int = 0
56
+ suppressed: int = 0
57
+ errors: List[str] = field(default_factory=list)
58
+
59
+ def add(self, finding: Finding) -> None:
60
+ self.findings.append(finding)
61
+
62
+ def extend(self, findings: List[Finding]) -> None:
63
+ self.findings.extend(findings)
64
+
65
+ def at_or_above(self, threshold: Severity) -> List[Finding]:
66
+ return [f for f in self.findings if f.severity >= threshold]
67
+
68
+ def highest(self) -> Optional[Severity]:
69
+ if not self.findings:
70
+ return None
71
+ return max(f.severity for f in self.findings)
72
+
73
+ def counts(self) -> dict:
74
+ out = {s.label: 0 for s in Severity}
75
+ for f in self.findings:
76
+ out[f.severity.label] += 1
77
+ return out
78
+
79
+ def sorted(self) -> List[Finding]:
80
+ # Most severe first, then by file/line for stable output.
81
+ return sorted(
82
+ self.findings,
83
+ key=lambda f: (-int(f.severity), f.path, f.line, f.rule_id),
84
+ )