mcp-tool-audit 0.3.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.
@@ -0,0 +1,2 @@
1
+ """MCP Server Auditor: static and live security checks for MCP servers."""
2
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
mcp_auditor/cli.py ADDED
@@ -0,0 +1,114 @@
1
+ """Command line entry point: mcp-audit <path|github-url> [--stdio CMD] [--format ...] [--fail-on ...]"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__, live, pin, report
11
+ from .detectors import run_all, sort_findings
12
+ from .models import SEVERITIES, Target, severity_rank
13
+ from .source import open_target
14
+
15
+
16
+ def build_parser() -> argparse.ArgumentParser:
17
+ p = argparse.ArgumentParser(
18
+ prog="mcp-audit", description="Scan an MCP server for security problems in the tools it exposes.",
19
+ formatter_class=argparse.RawDescriptionHelpFormatter,
20
+ epilog="examples:\n"
21
+ " mcp-audit scan the current folder\n"
22
+ " mcp-audit path/to/server scan a folder or a single file\n"
23
+ " mcp-audit https://github.com/owner/repo scan a GitHub repo\n"
24
+ " mcp-audit --stdio \"python server.py\" start a server and check its live tools\n"
25
+ " mcp-audit . --pin tools.lock.json save the tools once, then alert when they change\n"
26
+ " mcp-audit . --format sarif -o out.sarif report for GitHub code scanning")
27
+ p.add_argument("target", nargs="?", help="folder, single file, or https://github.com/owner/repo[/tree/branch/subdir] "
28
+ "(default: the current folder)")
29
+ p.add_argument("--stdio", metavar="CMD", help="also start this stdio server command and audit its live tools/list "
30
+ "(this runs the server's code)")
31
+ p.add_argument("--format", choices=["text", "json", "sarif"], default="text")
32
+ p.add_argument("-o", "--output", help="write the report to this file instead of stdout")
33
+ p.add_argument("--fail-on", choices=SEVERITIES + ["none"], default="high",
34
+ help="exit with code 1 if any finding is at or above this severity (default: high)")
35
+ p.add_argument("--timeout", type=float, default=30.0, help="seconds to wait for the --stdio server (default: 30)")
36
+ p.add_argument("--repeat", type=int, default=3, metavar="N",
37
+ help="with --stdio, ask for tools/list N times and flag tools that change between answers (default: 3)")
38
+ p.add_argument("--pin", metavar="FILE", help="first run: save every tool's definition to FILE. Later runs: report "
39
+ "tools that were added, changed or removed since. Delete FILE to accept the current tools.")
40
+ p.add_argument("--version", action="version", version=f"mcp-audit {__version__}")
41
+ return p
42
+
43
+
44
+ def main(argv: list[str] | None = None) -> int:
45
+ args = build_parser().parse_args(argv)
46
+ if not args.target and not args.stdio:
47
+ args.target = "."
48
+ workdir = None
49
+ try:
50
+ if args.target:
51
+ is_url = args.target.startswith(("https://", "http://"))
52
+ if is_url:
53
+ import tempfile
54
+ workdir = tempfile.mkdtemp(prefix="mcp-audit-")
55
+ target, root = open_target(args.target, workdir)
56
+ if args.target == ".":
57
+ target.label = str(Path.cwd())
58
+ else:
59
+ target, root, is_url = Target(args.stdio), None, False
60
+ extra = []
61
+ if args.stdio:
62
+ snapshots = live.list_tools(args.stdio, args.timeout, args.repeat)
63
+ target.tools += snapshots[0]
64
+ for n, later in enumerate(snapshots[1:], 2):
65
+ extra = pin.compare(pin.snapshot(snapshots[0]), later, f"between tools/list call 1 and call {n}")
66
+ if extra: # report the first flip only, not the same change once per call
67
+ # also run the detectors on the changed versions, so the new text gets checked too
68
+ first = pin.snapshot(snapshots[0])
69
+ target.tools += [t for k, t in zip(pin.snapshot(later), later) if first.get(k) != pin.definition(t)]
70
+ break
71
+ if args.pin and Path(args.pin).exists():
72
+ extra += pin.compare(pin.load(args.pin), target.tools, f"since it was pinned in {args.pin}")
73
+ elif args.pin:
74
+ pin.save(args.pin, target.tools)
75
+ print(f"mcp-audit: pinned {len(target.tools)} tools to {args.pin}. Future runs with --pin "
76
+ f"{args.pin} will report any change.", file=sys.stderr)
77
+ findings = sort_findings(run_all(target) + extra)
78
+ except Exception as e: # report any loader/live failure as a usage error, not a traceback
79
+ print(f"mcp-audit: error: {e}", file=sys.stderr)
80
+ return 2
81
+ finally:
82
+ if workdir:
83
+ shutil.rmtree(workdir, onerror=_force_remove)
84
+
85
+ if args.format == "text":
86
+ out = report.to_text(target, findings, color=None if not args.output else False)
87
+ elif args.format == "json":
88
+ out = report.to_json(target, findings)
89
+ else:
90
+ prefix = ""
91
+ if root is not None and not is_url:
92
+ try:
93
+ rel = os.path.relpath(Path(root).resolve(), Path.cwd())
94
+ except ValueError: # different drive on Windows
95
+ rel = ".."
96
+ prefix = "" if rel == "." or rel.startswith("..") else Path(rel).as_posix()
97
+ out = report.to_sarif(target, findings, prefix)
98
+
99
+ if args.output:
100
+ Path(args.output).write_text(out + "\n", encoding="utf-8")
101
+ else:
102
+ if hasattr(sys.stdout, "reconfigure"): # Windows consoles default to a legacy code page
103
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
104
+ print(out)
105
+
106
+ if args.fail_on != "none" and any(severity_rank(f.severity) >= severity_rank(args.fail_on) for f in findings):
107
+ return 1
108
+ return 0
109
+
110
+
111
+ def _force_remove(func, path, _exc):
112
+ """git marks pack files read-only, which breaks rmtree on Windows."""
113
+ os.chmod(path, 0o700)
114
+ func(path)
@@ -0,0 +1,15 @@
1
+ """One module per detector. Each exposes RULE and detect(target) -> list[Finding]."""
2
+ from . import broad_capabilities, missing_auth, rug_pull, secrets, tool_poisoning, unsafe_exec
3
+
4
+ DETECTORS = [tool_poisoning, broad_capabilities, secrets, unsafe_exec, missing_auth, rug_pull]
5
+ RULES = [d.RULE for d in DETECTORS]
6
+
7
+
8
+ def run_all(target):
9
+ return sort_findings([f for d in DETECTORS for f in d.detect(target)])
10
+
11
+
12
+ def sort_findings(findings):
13
+ """Worst first, then by rule and location."""
14
+ from ..models import severity_rank
15
+ return sorted(findings, key=lambda f: (-severity_rank(f.severity), f.rule.id, f.file or "", f.line or 0))
@@ -0,0 +1,78 @@
1
+ """Small AST helpers shared by the Python parts of the detectors."""
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from typing import Iterator
6
+
7
+ from ..models import SourceFile
8
+ from ..source import _is_tool_decorator
9
+
10
+
11
+ def parse(f: SourceFile) -> ast.Module | None:
12
+ try:
13
+ return ast.parse(f.text)
14
+ except SyntaxError:
15
+ return None
16
+
17
+
18
+ def dotted(func: ast.expr) -> str:
19
+ """`subprocess.run` -> "subprocess.run"; `Path(p).read_text` -> "?.read_text"."""
20
+ if isinstance(func, ast.Name):
21
+ return func.id
22
+ if isinstance(func, ast.Attribute):
23
+ return dotted(func.value) + "." + func.attr
24
+ return "?"
25
+
26
+
27
+ def names_in(node: ast.AST) -> set[str]:
28
+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
29
+
30
+
31
+ def is_tool(fn: ast.AST) -> bool:
32
+ return any(_is_tool_decorator(d) for d in getattr(fn, "decorator_list", []))
33
+
34
+
35
+ def functions(tree: ast.Module) -> Iterator[ast.FunctionDef | ast.AsyncFunctionDef]:
36
+ for node in ast.walk(tree):
37
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
38
+ yield node
39
+
40
+
41
+ def tainted_names(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
42
+ """Parameters of fn plus local names assigned from them (two rounds of propagation).
43
+
44
+ shortcut: no inter-procedural flow; a value passed through a helper function is lost.
45
+ """
46
+ tainted = {a.arg for a in fn.args.args + fn.args.kwonlyargs + fn.args.posonlyargs} - {"self", "cls", "ctx"}
47
+ if fn.args.vararg:
48
+ tainted.add(fn.args.vararg.arg)
49
+ for _ in range(2):
50
+ for node in ast.walk(fn):
51
+ if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)) and node.value is not None:
52
+ if names_in(node.value) & tainted:
53
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
54
+ for t in targets:
55
+ tainted |= names_in(t)
56
+ elif isinstance(node, (ast.With, ast.AsyncWith)):
57
+ for item in node.items:
58
+ if item.optional_vars is not None and names_in(item.context_expr) & tainted:
59
+ tainted |= names_in(item.optional_vars)
60
+ return tainted
61
+
62
+
63
+ def call_inputs(call: ast.Call) -> set[str]:
64
+ """Names that feed a call: its arguments plus the object a method is called on."""
65
+ used = set()
66
+ for a in call.args:
67
+ used |= names_in(a)
68
+ for kw in call.keywords:
69
+ if kw.arg != "shell":
70
+ used |= names_in(kw.value)
71
+ if isinstance(call.func, ast.Attribute):
72
+ used |= names_in(call.func.value)
73
+ return used
74
+
75
+
76
+ def is_literal(node: ast.AST) -> bool:
77
+ return isinstance(node, ast.Constant) or (
78
+ isinstance(node, (ast.List, ast.Tuple)) and all(isinstance(e, ast.Constant) for e in node.elts))
@@ -0,0 +1,104 @@
1
+ """MCP002: tools that run commands, touch arbitrary paths or reach arbitrary URLs with no allow-list.
2
+
3
+ A tool is flagged when its handler passes tool input into a shell/file/network call and the
4
+ handler contains nothing that looks like an allow-list or path check. Python handlers are
5
+ checked with the AST (input must actually reach the call); JS/TS/Go handlers with regexes
6
+ over the handler text. Tools with no visible handler (live tools/list, low-level SDK servers)
7
+ fall back to wording in the description.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import re
13
+
14
+ from ..models import Finding, Rule, SourceFile, Target, Tool
15
+ from . import _python as py
16
+
17
+ RULE = Rule("MCP002", "over-broad-capability", "Tool has shell, file or network access without an allow-list",
18
+ "Give the tool only what it needs: a fixed list of commands (no shell), a root directory that "
19
+ "resolved paths must stay inside, or a list of allowed hosts. An agent that gets prompt-injected "
20
+ "will use whatever the tool allows.")
21
+
22
+ # category -> (severity, what it does, python call-name regex, js/go text regex, guard regex, description wording)
23
+ CATEGORIES = {
24
+ "shell": ("high", "runs OS commands",
25
+ r"^(subprocess\.\w+|os\.(system|popen|exec\w*|spawn\w*)|asyncio\.create_subprocess_\w+)$",
26
+ r"(?:(?<![.\w$])|\b(?:child_process|cp|childProcess)\.)(execSync|execFileSync|spawnSync|execa|exec|execFile|spawn)\(|\bexec\.Command(Context)?\(|\bDeno\.Command\(",
27
+ r"allow(ed)?_?(list|commands?|programs?)|whitelist|ALLOWED_|\bin\s+(SAFE|ALLOW)\w*",
28
+ r"\b(run|execute|exec)s?\b.{0,20}\b(shell|terminal|system|bash|arbitrary)?\s*commands?\b|\bshell\b"),
29
+ "filesystem": ("medium", "reads or writes files at a path taken from tool input",
30
+ r"^(open|io\.open|os\.(remove|unlink|rmdir|rename|listdir|scandir|walk|makedirs)|shutil\.\w+)$|\.(read_text|write_text|read_bytes|write_bytes|unlink|rmdir|iterdir|rglob|glob|open)$",
31
+ r"\bfs(Promises)?\.(readFile|writeFile|appendFile|unlink|rm|rmdir|readdir|createReadStream|createWriteStream|rename)\w*\(|\b(readFile|writeFile|readdir|unlink)(Sync)?\(|\bos\.(ReadFile|WriteFile|Open|OpenFile|Create|Remove|RemoveAll|ReadDir)\(",
32
+ r"allow(ed)?_?(dirs?|directories|paths?|roots?|list)|is_relative_to|commonpath|realpath|\.resolve\(|startswith\(|startsWith\(|path\.relative|ALLOWED_|validatePath|safe_?path|filepath\.Rel|HasPrefix",
33
+ r"\b(read|write|delete|edit|move|create|list)s?\b.{0,25}\b(any|arbitrary)?\s*(files?|director(y|ies))\b"),
34
+ "network": ("medium", "makes requests to URLs taken from tool input",
35
+ r"^(requests|httpx)\.(get|post|put|patch|delete|head|request|stream)$|(^|\.)urlopen$|^aiohttp\.request$",
36
+ r"\bfetch\(|\baxios(\.\w+)?\(|\bgot(\.\w+)?\(|\bhttps?\.(get|request)\(|\bhttp\.(Get|Post|NewRequest(WithContext)?)\(",
37
+ r"allow(ed)?_?(hosts?|domains?|urls?|origins?|list)|ALLOWED_|whitelist|\.hostname\b|\.netloc\b|\bhostname\s+(not\s+)?in\b",
38
+ r"\b(fetch|download|retrieve|request|get)s?\b.{0,25}\b(any|arbitrary)?\s*(urls?|web ?pages?|websites?)\b"),
39
+ }
40
+
41
+
42
+ def _python(f: SourceFile, target: Target) -> list[Finding]:
43
+ tree = py.parse(f)
44
+ if tree is None:
45
+ return []
46
+ findings = []
47
+ for fn in py.functions(tree):
48
+ if not py.is_tool(fn):
49
+ continue
50
+ tool = target.tool_at(f.path, fn.lineno)
51
+ name = tool.name if tool else fn.name
52
+ body = ast.get_source_segment(f.text, fn) or ""
53
+ tainted = py.tainted_names(fn)
54
+ for cat, (sev, what, call_rx, _, guard_rx, _) in CATEGORIES.items():
55
+ if re.search(guard_rx, body):
56
+ continue
57
+ for call in (n for n in ast.walk(fn) if isinstance(n, ast.Call)):
58
+ if re.search(call_rx, py.dotted(call.func)) and py.call_inputs(call) & tainted:
59
+ findings.append(Finding(RULE, sev, f"Tool '{name}' {what} with no allow-list or path check.",
60
+ f.path, call.lineno, name, f.line_text(call.lineno)))
61
+ break
62
+ return findings
63
+
64
+
65
+ def _windowed(f: SourceFile, tool: Tool) -> list[Finding]:
66
+ lines = f.text.splitlines()[tool.line - 1: tool.end_line]
67
+ body = "\n".join(lines)
68
+ findings = []
69
+ for cat, (sev, what, _, text_rx, guard_rx, _) in CATEGORIES.items():
70
+ m = re.search(text_rx, body)
71
+ if m and not re.search(guard_rx, body):
72
+ line = tool.line + body.count("\n", 0, m.start())
73
+ findings.append(Finding(RULE, sev, f"Tool '{tool.name}' {what.replace(' taken from tool input', '')} "
74
+ "and its handler shows no allow-list or path check.", f.path, line, tool.name,
75
+ f.line_text(line)))
76
+ return findings
77
+
78
+
79
+ def _by_description(tool: Tool) -> list[Finding]:
80
+ findings = []
81
+ text = f"{tool.name.replace('_', ' ')} {tool.description}"
82
+ for cat, (sev, what, _, _, guard_rx, words_rx) in CATEGORIES.items():
83
+ if re.search(words_rx, text, re.I) and not re.search(r"allow(ed)?|restricted|only within|sandbox", text, re.I):
84
+ lower = {"high": "medium", "medium": "low"}[sev]
85
+ findings.append(Finding(RULE, lower, f"Tool '{tool.name}' description suggests it {what.split(' at ')[0].split(' to ')[0]} "
86
+ "and does not mention any restriction (handler code not available to check).",
87
+ tool.file, tool.line, tool.name, tool.description[:160]))
88
+ return findings
89
+
90
+
91
+ def detect(target: Target) -> list[Finding]:
92
+ findings = []
93
+ for f in target.files:
94
+ if f.is_python:
95
+ findings += _python(f, target)
96
+ for tool in target.tools:
97
+ f = target.file(tool.file) if tool.file else None
98
+ if f is not None and f.is_python and tool.end_line:
99
+ continue # handled by the AST pass above
100
+ if f is not None and tool.end_line:
101
+ findings += _windowed(f, tool)
102
+ else:
103
+ findings += _by_description(tool)
104
+ return findings
@@ -0,0 +1,57 @@
1
+ """MCP005: HTTP/SSE transport with no sign of inbound authentication.
2
+
3
+ A stdio server is only reachable by the process that started it. An SSE or
4
+ streamable-HTTP server is reachable by anything that can open a socket to it,
5
+ including web pages via DNS rebinding when it listens on localhost. If the codebase
6
+ starts such a transport and nothing in it checks an incoming credential, flag it.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from ..models import Finding, Rule, Target
13
+
14
+ RULE = Rule("MCP005", "missing-auth", "HTTP/SSE transport without authentication",
15
+ "Require a credential on every request (the MCP authorization spec uses OAuth 2.1 bearer tokens; "
16
+ "an API-key header is the minimum), check the Origin header, and bind to 127.0.0.1 unless the "
17
+ "server must be remote.")
18
+
19
+ TRANSPORT = re.compile(
20
+ r"""transport\s*[=:]\s*["'](sse|streamable-http|streamable_http|http)["']"""
21
+ r"|\b(SseServerTransport|SSEServerTransport|StreamableHTTPServerTransport)\b"
22
+ r"|\.(sse_app|streamable_http_app|http_app)\("
23
+ r"|\b(NewSSEServer|NewStreamableHTTPServer)\(")
24
+ INBOUND_AUTH = re.compile(
25
+ r"(?i)AuthSettings|TokenVerifier|auth_?(server_)?provider|requireBearerAuth|bearerAuth|BearerAuthBackend"
26
+ r"|(req|request)\.headers(\.get\(\s*|\[\s*)[\"'](authorization|x-api-key)"
27
+ r"|headers\.authorization|Header\.Get\(\s*\"(Authorization|X-API-Key)\""
28
+ r"|auth_?middleware|AuthenticationMiddleware|passport\.|verify_?(token|api_?key|jwt)|check_?auth|WithAuth\w*\("
29
+ # raw ASGI header lookups and constant-time token comparison are inbound checks too
30
+ r"|\.get\(\s*b[\"']authorization|Bearer\w*Middleware|Token\w*Middleware|compare_digest\(|timingSafeEqual\(")
31
+ ORIGIN_CHECK = re.compile(r"(?i)origin_?validation|allowed_?origins|validate_?origin|headers\.origin|Header\.Get\(\s*\"Origin\"|TrustedOrigins")
32
+ ALL_INTERFACES =re.compile(r"""["']0\.0\.0\.0["']|["']::["']|host\s*[=:]\s*["']["']""")
33
+
34
+
35
+ def detect(target: Target) -> list[Finding]:
36
+ code = [f for f in target.files if f.is_code]
37
+ if any(INBOUND_AUTH.search(f.text) for f in code):
38
+ return []
39
+ findings = []
40
+ for f in code:
41
+ # point at where the transport is used, not where it is imported
42
+ lines = [f.line_of(m.start()) for m in TRANSPORT.finditer(f.text)]
43
+ used = [n for n in lines if not re.match(r"(import|from)\b", f.line_text(n))]
44
+ line = next((n for n in used if re.search(r"(Transport|_app|Server)\(|\.run\(", f.line_text(n))), used[0] if used else None)
45
+ if line is None:
46
+ continue
47
+ exposed = bool(ALL_INTERFACES.search(f.text))
48
+ origin_checked = any(ORIGIN_CHECK.search(c.text) for c in code)
49
+ sev = "critical" if exposed else "medium" if origin_checked else "high"
50
+ findings.append(Finding(
51
+ RULE, sev,
52
+ "Server starts an HTTP/SSE transport and no inbound authentication was found in the codebase"
53
+ + (", and it binds to all network interfaces." if exposed else
54
+ " (an Origin check limits browser-based attacks, but any local process can still connect)."
55
+ if origin_checked else "."),
56
+ f.path, line, evidence=f.line_text(line)))
57
+ return findings
@@ -0,0 +1,120 @@
1
+ """MCP006: tool descriptions that can change after the user approved the server.
2
+
3
+ Users (or their client) review a server's tools once. If a description is fetched from
4
+ the network, read from the environment or built at runtime, the server can show one
5
+ thing at install time and another later: a "rug pull". Servers that announce
6
+ tools/list_changed can also swap their tool set at runtime.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import re
12
+
13
+ from ..models import Finding, Rule, SourceFile, Target
14
+ from . import _python as py
15
+ from ..source import imports_mcp
16
+
17
+ RULE = Rule("MCP006", "rug-pull-risk", "Tool description is dynamic or fetched remotely",
18
+ "Keep tool names and descriptions as literals in the code that gets reviewed and pinned. If tools "
19
+ "must change at runtime, make sure clients re-ask the user when tools/list changes.")
20
+
21
+ NETWORK = re.compile(r"\brequests\.|\bhttpx\.|\burlopen\(|\baiohttp\.|\bfetch\(|\baxios\b|\bhttp\.Get\(")
22
+ LIST_CHANGED = re.compile(r"sendToolListChanged\s*\(|send_tool_list_changed\s*\(|[\"']notifications/tools/list_changed[\"']"
23
+ r"|\btools\b[^\n]{0,40}\blist_?[cC]hanged[\"']?\s*[:=]\s*(true|True)\b")
24
+ COMMENT = re.compile(r"^\s*(//|#|\*|/\*)")
25
+ NEAR_TOOL = 10 # shortcut: a JS/Go tool's own description is assumed to sit within 10 lines of where the tool is declared
26
+ ENV = re.compile(r"\bos\.environ|\bgetenv\(|\bprocess\.env\b|\bos\.Getenv\(")
27
+ JS_DYNAMIC_DESC = re.compile(r"\bdescription\s*:\s*(`[^`]*\$\{|(?![\"'`\s])[^,\n}]+)")
28
+ JS_TOOL_DYNAMIC_DESC = re.compile(r"\.(?:tool|registerTool)\(\s*[\"'`][^\"'`]+[\"'`]\s*,\s*(?![\"'`{\s])([^,\n]+)")
29
+ GO_DYNAMIC_DESC = re.compile(r"\bWithDescription\(\s*(?!\")([^)\n]+)")
30
+
31
+
32
+ def _python(f: SourceFile) -> list[Finding]:
33
+ tree = py.parse(f)
34
+ if tree is None:
35
+ return []
36
+ constants = {t.id for node in tree.body if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
37
+ for t in node.targets if isinstance(t, ast.Name)}
38
+ findings = []
39
+ sdk = imports_mcp(f)
40
+
41
+ def check(expr: ast.expr, where: str, line: int) -> None:
42
+ # names used only as the function being called (dedent, textwrap.dedent) are not data
43
+ called = set().union(*(py.names_in(n.func) for n in ast.walk(expr) if isinstance(n, ast.Call)))
44
+ data = set().union(set(), *(py.names_in(a) for n in ast.walk(expr) if isinstance(n, ast.Call)
45
+ for a in n.args + [k.value for k in n.keywords]))
46
+ src = ast.get_source_segment(f.text, expr) or ""
47
+ if not (py.names_in(expr) - constants - (called - data)) and not NETWORK.search(src):
48
+ return
49
+ remote = bool(NETWORK.search(f.text))
50
+ env = bool(ENV.search(src))
51
+ sev = "high" if remote else "medium"
52
+ why = ("is built from a value and this file makes network requests (description may be fetched remotely)"
53
+ if remote else "comes from the environment" if env else "is built at runtime")
54
+ findings.append(Finding(RULE, sev, f"{where} description {why}.", f.path, line, evidence=src[:160]))
55
+
56
+ for node in ast.walk(tree):
57
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and py.is_tool(node):
58
+ dec = next(d for d in node.decorator_list if py._is_tool_decorator(d))
59
+ for kw in getattr(dec, "keywords", []):
60
+ if kw.arg == "description" and not isinstance(kw.value, ast.Constant):
61
+ check(kw.value, f"Tool '{node.name}'", node.lineno)
62
+ elif sdk and isinstance(node, ast.Call) and getattr(node.func, "id", getattr(node.func, "attr", None)) == "Tool":
63
+ for kw in node.keywords:
64
+ if kw.arg == "description" and not isinstance(kw.value, ast.Constant):
65
+ check(kw.value, "Tool(...)", node.lineno)
66
+ elif isinstance(node, ast.Assign):
67
+ for t in node.targets:
68
+ if isinstance(t, ast.Attribute) and (t.attr == "__doc__" or sdk and t.attr == "description") and not isinstance(node.value, ast.Constant):
69
+ check(node.value, f"Assignment to {ast.get_source_segment(f.text, t)}:", node.lineno)
70
+ return findings
71
+
72
+
73
+ def _text(f: SourceFile, target: Target) -> list[Finding]:
74
+ findings = []
75
+ remote = bool(NETWORK.search(f.text))
76
+ # Only a tool's own description counts: the first "description" within NEAR_TOOL lines of the tool,
77
+ # or a non-literal second argument on the tool line itself.
78
+ own_lines = set()
79
+ for t in target.tools:
80
+ if t.file == f.path and t.line:
81
+ for n in range(t.line, t.line + NEAR_TOOL):
82
+ if re.search(r"\bdescription\s*:|WithDescription\(|Description:", f.line_text(n)) or n == t.line and JS_TOOL_DYNAMIC_DESC.search(f.line_text(n)):
83
+ own_lines.add(n)
84
+ break
85
+ rxs = [GO_DYNAMIC_DESC] if f.suffix == ".go" else [JS_DYNAMIC_DESC, JS_TOOL_DYNAMIC_DESC]
86
+ for rx in rxs:
87
+ for m in rx.finditer(f.text):
88
+ value = m.group(1).strip()
89
+ if re.fullmatch(r"[A-Z0-9_.]+|\w+\.(description|DESCRIPTION)|t\(.*\)|i18n.*", value):
90
+ continue # shortcut: assumes UPPER_CASE names and *.description are constants defined in code
91
+ if value.startswith("`"): # template literal: static if it only interpolates UPPER_CASE constants
92
+ end = f.text.find("`", m.start(1) + 1)
93
+ parts = re.findall(r"\$\{([^}]*)\}", f.text[m.start(1): end])
94
+ if all(re.fullmatch(r"\s*[A-Z0-9_.]+\s*", p) for p in parts):
95
+ continue
96
+ line = f.line_of(m.start())
97
+ if line not in own_lines:
98
+ continue
99
+ env = bool(ENV.search(value))
100
+ sev = "high" if remote and re.search(r"await|fetch|response|res\.|data\b|json", value) else "medium" if env else "low"
101
+ findings.append(Finding(RULE, sev, "Tool description is not a string literal"
102
+ + (" and comes from the environment" if env else "")
103
+ + (" (file also makes network requests)" if sev == "high" else "") + ".",
104
+ f.path, line, evidence=f.line_text(line)))
105
+ return findings
106
+
107
+
108
+ def detect(target: Target) -> list[Finding]:
109
+ findings = []
110
+ for f in target.files:
111
+ if not f.is_code:
112
+ continue
113
+ findings += _python(f) if f.is_python else _text(f, target)
114
+ m = next((m for m in LIST_CHANGED.finditer(f.text) if not COMMENT.match(f.line_text(f.line_of(m.start())))), None)
115
+ if m:
116
+ line = f.line_of(m.start())
117
+ findings.append(Finding(RULE, "low", "Server can change its tool list at runtime (tools/list_changed). "
118
+ "Clients that do not re-review changed tools will use the new definitions silently.",
119
+ f.path, line, evidence=f.line_text(line)))
120
+ return findings
@@ -0,0 +1,83 @@
1
+ """MCP003: hard-coded secrets in server code or config.
2
+
3
+ Provider patterns are adapted from the gitleaks default rule set (MIT). A generic
4
+ `key = "value"` rule catches the rest, filtered by placeholder words and entropy.
5
+ Matched values are masked before they reach any report.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from collections import Counter
12
+
13
+ from ..models import Finding, Rule, Target
14
+
15
+ RULE = Rule("MCP003", "hardcoded-secret", "Hard-coded secret in server code or config",
16
+ "Move the value to an environment variable or a secret manager, and rotate it: anything that was "
17
+ "committed should be treated as leaked.")
18
+
19
+ PROVIDERS = [
20
+ ("AWS access key ID", r"\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b"),
21
+ ("GitHub token", r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"),
22
+ ("GitHub fine-grained token", r"\bgithub_pat_[A-Za-z0-9_]{60,}\b"),
23
+ ("Anthropic API key", r"\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,}"),
24
+ ("OpenAI API key", r"\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}T3BlbkFJ[A-Za-z0-9_-]{20,}"),
25
+ ("Slack token", r"\bxox[abposr]-[0-9A-Za-z-]{10,}"),
26
+ ("Slack webhook", r"https://hooks\.slack\.com/services/[A-Za-z0-9/_+-]{40,}"),
27
+ ("Google API key", r"\bAIza[0-9A-Za-z_-]{35}\b"),
28
+ ("Stripe secret key", r"\b(?:sk|rk)_live_[0-9A-Za-z]{20,}\b"),
29
+ ("Private key", r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----"),
30
+ ("JSON Web Token", r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"),
31
+ ("Hugging Face token", r"\bhf_[A-Za-z]{34}\b"),
32
+ ("npm token", r"\bnpm_[A-Za-z0-9]{36}\b"),
33
+ ]
34
+ PROVIDERS = [(name, re.compile(rx)) for name, rx in PROVIDERS]
35
+
36
+ GENERIC = re.compile(
37
+ r"""(?i)\b([\w-]*(?:api[_-]?key|secret|token|passw(?:or)?d|access[_-]?key|auth[_-]?key)[\w-]*)["']?\s*[:=]\s*["']([^"'\s]{16,})["']""")
38
+ PLACEHOLDER = re.compile(r"(?i)your|example|xxx|changeme|placeholder|dummy|sample|redacted|<|>|\$\{|\{\{|process\.env|environ|getenv|\*\*\*")
39
+
40
+ KEY_BODY = re.compile(r"\A(?:\s|\\n|\\r)*(?:[A-Za-z0-9+/=]|\\n){64,}")
41
+ UUID = re.compile(r"(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
42
+
43
+
44
+ def entropy(s: str) -> float:
45
+ return -sum(c / len(s) * math.log2(c / len(s)) for c in Counter(s).values())
46
+
47
+
48
+ def mask(value: str) -> str:
49
+ return value[:4] + "*" * min(len(value) - 4, 12) + f" ({len(value)} chars)"
50
+
51
+
52
+ def detect(target: Target) -> list[Finding]:
53
+ findings = []
54
+ for f in target.files:
55
+ lines = f.text.splitlines()
56
+ for n, line in enumerate(lines, 1):
57
+ if len(line) > 2000: # minified or generated
58
+ continue
59
+ hit = False
60
+ for name, rx in PROVIDERS:
61
+ m = rx.search(line)
62
+ if m and PLACEHOLDER.search(m.group(0)): # AKIAIOSFODNN7EXAMPLE, xoxb-your-token
63
+ m = None
64
+ if m and name == "Private key" and not KEY_BODY.search(" ".join([line[m.end():]] + lines[n:n + 2])):
65
+ m = None # only the header: a label, placeholder or code that formats keys
66
+ if m:
67
+ findings.append(Finding(RULE, "high" if name != "JSON Web Token" else "medium",
68
+ f"{name} committed in source.", f.path, n, evidence=mask(m.group(0))))
69
+ hit = True
70
+ break
71
+ if hit:
72
+ continue
73
+ m = GENERIC.search(line)
74
+ value = m.group(2) if m else ""
75
+ # a list of secret *names* ("GITHUB_TOKEN,NPM_TOKEN", "api_key|password") is not a secret
76
+ names_only = re.fullmatch(r"[A-Z0-9_,|. -]+", value) or re.fullmatch(r"(?i)\w+(\s*[,|]\s*\w+)+", value)
77
+ # random secrets almost always contain a digit; theme scopes ("keyword.control.ts") and words don't.
78
+ # UUIDs are request/record ids far more often than credentials.
79
+ not_secret = not re.search(r"\d", value) or UUID.fullmatch(value)
80
+ if m and not PLACEHOLDER.search(value) and not names_only and not not_secret and entropy(value) >= 3.5:
81
+ findings.append(Finding(RULE, "medium", f"Possible secret assigned to '{m.group(1)}'.", f.path, n,
82
+ evidence=mask(m.group(2))))
83
+ return findings