mcp-sdk-audit 0.1.2__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.
@@ -0,0 +1,3 @@
1
+ """mcp-sdk-audit: find MCP SDK advisories and the code that stays exposed after upgrading."""
2
+
3
+ __version__ = "0.1.2"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,109 @@
1
+ """Advisory data: load the bundled snapshot or refresh it from the GitHub Advisory Database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.request
7
+ from dataclasses import dataclass
8
+ from importlib import resources
9
+ from pathlib import Path
10
+
11
+ # Packages published by the modelcontextprotocol org, per ecosystem.
12
+ TRACKED = {
13
+ "npm": [
14
+ "@modelcontextprotocol/sdk",
15
+ "@modelcontextprotocol/client",
16
+ "@modelcontextprotocol/server",
17
+ "@modelcontextprotocol/server-legacy",
18
+ "@modelcontextprotocol/core",
19
+ "@modelcontextprotocol/node",
20
+ "@modelcontextprotocol/express",
21
+ "@modelcontextprotocol/hono",
22
+ "@modelcontextprotocol/fastify",
23
+ ],
24
+ "pip": ["mcp"],
25
+ "go": ["github.com/modelcontextprotocol/go-sdk"],
26
+ }
27
+
28
+ API = "https://api.github.com/advisories"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Affected:
33
+ ghsa: str
34
+ cve: str | None
35
+ severity: str
36
+ summary: str
37
+ url: str
38
+ ecosystem: str
39
+ package: str
40
+ vulnerable_range: str
41
+ patched: str | None
42
+
43
+
44
+ def _get(url: str, token: str | None) -> list[dict]:
45
+ req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
46
+ if token:
47
+ req.add_header("Authorization", f"Bearer {token}")
48
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310 - fixed https URL
49
+ return json.load(resp)
50
+
51
+
52
+ def fetch(token: str | None = None) -> list[dict]:
53
+ """Fetch all reviewed advisories that affect a tracked package. Returns raw-ish records."""
54
+ seen: dict[str, dict] = {}
55
+ for eco, pkgs in TRACKED.items():
56
+ for pkg in pkgs:
57
+ page = 1
58
+ while True:
59
+ url = f"{API}?ecosystem={eco}&affects={pkg}&per_page=100&page={page}"
60
+ batch = _get(url, token)
61
+ for a in batch:
62
+ seen[a["ghsa_id"]] = {
63
+ "ghsa": a["ghsa_id"],
64
+ "cve": a.get("cve_id"),
65
+ "severity": a.get("severity") or "unknown",
66
+ "summary": a.get("summary", ""),
67
+ "url": a.get("html_url", ""),
68
+ "published": (a.get("published_at") or "")[:10],
69
+ "affected": [
70
+ {
71
+ "ecosystem": v["package"]["ecosystem"],
72
+ "package": v["package"]["name"],
73
+ "vulnerable_range": v.get("vulnerable_version_range") or "",
74
+ "patched": v.get("first_patched_version"),
75
+ }
76
+ for v in a.get("vulnerabilities", [])
77
+ ],
78
+ }
79
+ if len(batch) < 100:
80
+ break
81
+ page += 1
82
+ return sorted(seen.values(), key=lambda r: (r["published"], r["ghsa"]), reverse=True)
83
+
84
+
85
+ def load(path: str | Path | None = None) -> list[dict]:
86
+ if path:
87
+ return json.loads(Path(path).read_text(encoding="utf-8"))["advisories"]
88
+ text = resources.files("mcp_sdk_audit.data").joinpath("advisories.json").read_text(encoding="utf-8")
89
+ return json.loads(text)["advisories"]
90
+
91
+
92
+ def flatten(records: list[dict]) -> list[Affected]:
93
+ out = []
94
+ for r in records:
95
+ for a in r["affected"]:
96
+ out.append(
97
+ Affected(
98
+ ghsa=r["ghsa"],
99
+ cve=r.get("cve"),
100
+ severity=r["severity"],
101
+ summary=r["summary"],
102
+ url=r["url"],
103
+ ecosystem=a["ecosystem"],
104
+ package=a["package"],
105
+ vulnerable_range=a["vulnerable_range"],
106
+ patched=a.get("patched"),
107
+ )
108
+ )
109
+ return out
mcp_sdk_audit/cli.py ADDED
@@ -0,0 +1,86 @@
1
+ """Command line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from . import __version__, advisories, output
11
+ from .scanner import SEV_ORDER, scan
12
+
13
+
14
+ def main(argv: list[str] | None = None) -> int:
15
+ p = argparse.ArgumentParser(
16
+ prog="mcp-sdk-audit",
17
+ description="Find MCP SDK versions with known advisories, and the code that stays exposed after you upgrade.",
18
+ )
19
+ p.add_argument("path", nargs="?", default=".", help="project directory or single file (default: .)")
20
+ p.add_argument("-f", "--format", choices=["text", "json", "sarif"], default="text")
21
+ p.add_argument("-o", "--output", help="write report to this file instead of stdout")
22
+ p.add_argument(
23
+ "--fail-on",
24
+ choices=["critical", "high", "medium", "low", "none"],
25
+ default="medium",
26
+ help="exit 1 if anything at or above this severity is found (default: medium)",
27
+ )
28
+ p.add_argument("--online", action="store_true", help="fetch the latest advisories from the GitHub Advisory Database")
29
+ p.add_argument("--advisories", metavar="FILE", help="use an advisories JSON file instead of the bundled snapshot")
30
+ p.add_argument("--no-deps", action="store_true", help="skip lockfile checks")
31
+ p.add_argument("--no-source", action="store_true", help="skip source code rules")
32
+ p.add_argument("--include-tests", action="store_true", help="also apply source rules to test files and fixtures")
33
+ p.add_argument("--list-rules", action="store_true", help="print the source rules and exit")
34
+ p.add_argument("--update-snapshot", metavar="FILE", help=argparse.SUPPRESS)
35
+ p.add_argument("--no-color", action="store_true")
36
+ p.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
37
+ a = p.parse_args(argv)
38
+
39
+ if a.list_rules:
40
+ print(output.rules_table())
41
+ return 0
42
+
43
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
44
+ if a.update_snapshot:
45
+ records = advisories.fetch(token)
46
+ with open(a.update_snapshot, "w", encoding="utf-8", newline="\n") as fh:
47
+ json.dump({"source": advisories.API, "advisories": records}, fh, indent=2)
48
+ fh.write("\n")
49
+ print(f"wrote {len(records)} advisories to {a.update_snapshot}")
50
+ return 0
51
+
52
+ if a.online:
53
+ try:
54
+ records = advisories.fetch(token)
55
+ except OSError as e:
56
+ print(f"warning: could not fetch advisories ({e}); using bundled snapshot", file=sys.stderr)
57
+ records = advisories.load(a.advisories)
58
+ else:
59
+ records = advisories.load(a.advisories)
60
+
61
+ if not os.path.exists(a.path):
62
+ print(f"error: {a.path} does not exist", file=sys.stderr)
63
+ return 2
64
+
65
+ report = scan(a.path, records, deps=not a.no_deps, source=not a.no_source, include_tests=a.include_tests)
66
+
67
+ if a.format == "json":
68
+ rendered = output.as_json(report)
69
+ elif a.format == "sarif":
70
+ rendered = output.sarif(report)
71
+ else:
72
+ color = not a.no_color and not a.output and sys.stdout.isatty() and "NO_COLOR" not in os.environ
73
+ rendered = output.text(report, color=color)
74
+
75
+ if a.output:
76
+ with open(a.output, "w", encoding="utf-8", newline="\n") as fh:
77
+ fh.write(rendered + "\n")
78
+ else:
79
+ sys.stdout.write(rendered + "\n")
80
+
81
+ threshold = 0 if a.fail_on == "none" else SEV_ORDER[a.fail_on]
82
+ return 1 if threshold and report.max_severity() >= threshold else 0
83
+
84
+
85
+ if __name__ == "__main__":
86
+ raise SystemExit(main())
File without changes