mcp-vet-scanner 0.2.1__tar.gz
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.
- mcp_vet_scanner-0.2.1/LICENSE +21 -0
- mcp_vet_scanner-0.2.1/PKG-INFO +193 -0
- mcp_vet_scanner-0.2.1/README.md +162 -0
- mcp_vet_scanner-0.2.1/pyproject.toml +44 -0
- mcp_vet_scanner-0.2.1/setup.cfg +4 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/__init__.py +3 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/__main__.py +3 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/checks.py +118 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/cli.py +61 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/jsflow.py +970 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/models.py +37 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/pyast.py +492 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/report.py +78 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/rules.py +143 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/scanner.py +238 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet/unicode_check.py +74 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet_scanner.egg-info/PKG-INFO +193 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet_scanner.egg-info/SOURCES.txt +21 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet_scanner.egg-info/dependency_links.txt +1 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet_scanner.egg-info/entry_points.txt +2 -0
- mcp_vet_scanner-0.2.1/src/mcp_vet_scanner.egg-info/top_level.txt +1 -0
- mcp_vet_scanner-0.2.1/tests/test_recall.py +71 -0
- mcp_vet_scanner-0.2.1/tests/test_scan.py +437 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sonuoffsec
|
|
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.
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcp-vet-scanner
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Static security scanner for MCP (Model Context Protocol) servers. Zero dependencies.
|
|
5
|
+
Author: sonuoffsec
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/sonuoffsec/mcp-vet
|
|
8
|
+
Project-URL: Source, https://github.com/sonuoffsec/mcp-vet
|
|
9
|
+
Project-URL: Issues, https://github.com/sonuoffsec/mcp-vet/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/sonuoffsec/mcp-vet/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: mcp,model-context-protocol,llm-security,ai-security,prompt-injection,tool-poisoning,sast,security,linter
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Information Technology
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Security
|
|
25
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
26
|
+
Classifier: Topic :: Software Development :: Testing
|
|
27
|
+
Requires-Python: >=3.9
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
[](https://github.com/sonuoffsec/mcp-vet/actions/workflows/ci.yml)
|
|
35
|
+

|
|
36
|
+

|
|
37
|
+

|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
Static security scanner for **MCP (Model Context Protocol) servers** written in **Python, JavaScript and TypeScript**. Point it at a server's source or config and it flags the problems that let an attacker hijack an AI agent: tool poisoning, command injection, path traversal, SSRF, SQL injection, unsafe deserialization, leaked secrets and unauthenticated transports.
|
|
41
|
+
|
|
42
|
+
Zero dependencies. One command. Works in CI.
|
|
43
|
+
|
|
44
|
+

|
|
45
|
+
|
|
46
|
+
<sub>The image above is generated from the scanner's real output by `assets/build_terminal_svg.py --png`.</sub>
|
|
47
|
+
|
|
48
|
+
## Why
|
|
49
|
+
|
|
50
|
+
An MCP server lets an AI take real actions: read files, run commands, call APIs. A weak server can leak data or run an attacker's instructions, and most people install them without reading the code. mcp-vet is a linter for that gap.
|
|
51
|
+
|
|
52
|
+
## Install
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install mcp-vet-scanner # needs Python 3.9+, no other dependencies
|
|
56
|
+
mcp-vet --version # the command is `mcp-vet`
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The PyPI package is called `mcp-vet-scanner` because `mcp-vet` is too similar to an unrelated project already on PyPI. The command, the repository and the Python module are all `mcp-vet`.
|
|
60
|
+
|
|
61
|
+
From source:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
git clone https://github.com/sonuoffsec/mcp-vet && cd mcp-vet
|
|
65
|
+
pip install -e .
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Or run it without installing: `PYTHONPATH=src python -m mcp_vet ./my-server`.
|
|
69
|
+
|
|
70
|
+
## Use
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
mcp-vet ./my-server # human-readable report
|
|
74
|
+
mcp-vet ./my-server -f json -o out.json # machine-readable
|
|
75
|
+
mcp-vet ./my-server -f sarif -o out.sarif # GitHub code scanning
|
|
76
|
+
mcp-vet ./my-server --fail-on MEDIUM # CI gate (default: HIGH)
|
|
77
|
+
mcp-vet --list-rules
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Exit code is `1` when a finding at or above `--fail-on` exists, `2` on usage errors, otherwise `0`.
|
|
81
|
+
|
|
82
|
+
## Rules
|
|
83
|
+
|
|
84
|
+
| ID | Severity | What it catches |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| MCP001 | HIGH / MEDIUM | Shell or dynamic code execution. **Python:** HIGH only when a tool argument reaches `shell=True`, `os.system`, `eval` or chooses the program; MEDIUM if the command is non-constant but not tool-controlled; constants are ignored. **JS/TS:** pattern-based |
|
|
87
|
+
| MCP002 | HIGH | Tool poisoning: instructions aimed at the model hidden in descriptions or code |
|
|
88
|
+
| MCP003 | CRITICAL | Hardcoded secrets (AWS, GitHub, OpenAI/Anthropic-style keys, Slack, private keys). Output is redacted |
|
|
89
|
+
| MCP004 | HIGH | HTTP/SSE transport with no authentication anywhere in the project, especially when bound to `0.0.0.0` |
|
|
90
|
+
| MCP005 | MEDIUM | Tool argument controls a file path with no containment check (path traversal) |
|
|
91
|
+
| MCP006 | LOW | Unpinned dependencies (`requirements.txt`, `package.json`) |
|
|
92
|
+
| MCP007 | HIGH | MCP config granting access to `/`, `~` or a whole drive |
|
|
93
|
+
| MCP008 | HIGH | Hidden Unicode (zero-width, bidi, tag characters) that can conceal instructions. In `.md`/`.txt` only bidi overrides, tag characters and runs of 3+ zero-width characters count, so Persian, Thai and emoji text is not flagged |
|
|
94
|
+
| MCP009 | MEDIUM | Tool argument controls the URL of an outbound request (SSRF) |
|
|
95
|
+
| MCP010 | HIGH / MEDIUM | SQL built from tool input: HIGH when a query that looks like SQL is assembled with f-strings, `+`, `%` or `.format`; MEDIUM when the caller passes the whole query. ORM statements such as `select(...).where(...)` are not flagged |
|
|
96
|
+
| MCP011 | HIGH | Tool argument passed to an unsafe deserializer (`pickle`, `marshal`, `dill`, `yaml.load` without a safe loader) |
|
|
97
|
+
|
|
98
|
+
## Suppress a finding
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
os.system(cmd) # mcp-vet: ignore MCP001
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Omit the rule ID to suppress every rule on that line.
|
|
105
|
+
|
|
106
|
+
## GitHub Action
|
|
107
|
+
|
|
108
|
+
```yaml
|
|
109
|
+
- run: pip install mcp-vet-scanner
|
|
110
|
+
- run: mcp-vet . -f sarif -o mcp-vet.sarif --fail-on HIGH
|
|
111
|
+
- uses: github/codeql-action/upload-sarif@v3
|
|
112
|
+
if: always()
|
|
113
|
+
with: { sarif_file: mcp-vet.sarif }
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## How it works
|
|
117
|
+
|
|
118
|
+
- **Python files are parsed into an AST** and checked with simple taint tracking. Values that come from a tool's parameters are "tainted". Taint follows assignments, and calls to functions named like `validate`, `sanitize`, `safe`, `check`, `allow` or `quote` (for example `shlex.quote`) clear it. A tool that runs a constant command is not flagged.
|
|
119
|
+
- **JavaScript and TypeScript get their own analyzer**, with no dependencies. A tokenizer (strings, template literals, comments, regex literals) feeds a scope-aware pass that finds tool handlers (`server.tool`, `registerTool`, `setRequestHandler`) and HTTP routes (Express, Fastify), follows tool arguments through assignments and destructuring, and understands `import { a as b }`, `require`, `promisify(exec)`, `execa`, `shelljs` and Zod schemas that constrain an input (`z.enum`, `z.number`, `z.string().uuid()`). It also knows that a ternary's value comes only from its branches, that an equality test yields a boolean, and that `ORDERS[args.sort]` returns a value the caller does not control. It is a purpose-built analyzer, not a full JavaScript parser: a file it cannot tokenize falls back to line patterns, reported at lower confidence.
|
|
120
|
+
- **Config and manifest files** (`package.json`, `requirements.txt`, MCP client config) are checked with direct rules.
|
|
121
|
+
- **HTTP route handlers count as entry points.** Python functions decorated like `@app.post("/mcp/call")` (FastAPI, Flask) are treated like tool handlers, so hand-rolled MCP-over-HTTP servers are analyzed too.
|
|
122
|
+
- **Authentication and path guards are looked for per app**: in the same folder, or any parent folder, that has its own `requirements.txt`, `package.json` or `Dockerfile`. One app's auth does not hide another app's gap.
|
|
123
|
+
- **Allowlist checks count.** A parameter tested with `if x not in ALLOWED: return/raise`, or looked up with `if registry.get(x) is None: raise`, is treated as validated. A filesystem existence check (`os.path.exists`, `isfile`) is not.
|
|
124
|
+
- **One hop into helpers.** If a tool passes a tool argument to a plain function defined in the same file, and that function runs a command, opens a path or makes a request, the tool's call is reported.
|
|
125
|
+
- **Wide sink coverage.** File operations include `open`, `Path(...).read_text/unlink/...`, `os.remove/listdir/rename`, `shutil.copy/rmtree/move` and `send_file`. Command execution includes `os.system`, `subprocess` with `shell=True`, a caller-chosen program (`cmd.split()`, `shlex.split`), `os.exec*` and `__import__('os').system`.
|
|
126
|
+
- Test files and test directories are skipped by default (`--include-tests` to scan them).
|
|
127
|
+
|
|
128
|
+
## Tested on real servers
|
|
129
|
+
|
|
130
|
+
All runs were static: the code was cloned and read, never executed.
|
|
131
|
+
|
|
132
|
+
**Precision on 67 small community MCP servers** (about 29,500 files in Python, JavaScript and TypeScript):
|
|
133
|
+
|
|
134
|
+
- The first pass (v0.1) reported **715 HIGH or CRITICAL findings**. Almost all were false positives: emoji and Persian/Sinhala text flagged as hidden Unicode, code that *reads* `.env` flagged as tool poisoning, Playwright's `$eval` flagged as `eval`, security libraries that contain the very strings they block. Each cause was fixed and became a regression test.
|
|
135
|
+
- Today there are **12 HIGH or CRITICAL findings in 6 repos**. Eight of them I reviewed by hand and **none is a vulnerability**: blocklists and defensive examples in security libraries, attack payloads in test data, defensive prompt text, a test credential, and a zero-width character in a docstring. The other **4 are SQL findings (MCP010) in a single repo**, a low-code platform that executes SQL stored in its application configuration by design. I traced six more findings in that repo to code that is escaped (`pg.escapeIdentifier`) or parameterized and fixed the analyzer for those patterns. The remaining four run configured SQL, and the analyzer cannot tell configuration from request data once both pass through a context object, so I have **not** confirmed whether any of them is exploitable.
|
|
136
|
+
- The file-path findings (MCP005, MEDIUM) are the most useful tier: **40 findings in 8 repos**. I checked 24 of them (the flagged line and its enclosing function): 22 were a tool argument deciding where a file is read, written, copied, listed or deleted (`save_to`, `world_path`, `directory`, `filePath`, `session_id`), and 2 were false positives (validated by a registry lookup; guarded by the caller), both fixed. I did not read all 40. Many of these servers are local developer tools where choosing a path is the point, so "real" means the rule's condition holds, not that the server is exploitable.
|
|
137
|
+
- Two further JavaScript findings I read and confirmed: a tool that reads an arbitrary caller-supplied file path, and a tool that fetches a caller-supplied URL (`faucetUrl: z.string().url()` checks the format only).
|
|
138
|
+
- When the JS/TS analyzer was first enabled it reported **391 JS findings against 102 from the old patterns**. Nearly all of the 337 new ones were false positives: `/regex/.exec()` mistaken for `child_process.exec`, SQL fragments built from a ternary of constants, `ORDERS[args.sort]` allowlist lookups, query-builder helpers that return `?` placeholders, `items.map(() => '?')`, `pg.escapeIdentifier` under another name. Each was fixed and tested, and the JS/TS count is now **72**.
|
|
139
|
+
- The SQL rule first reported 23 findings on one Python repo, **all false positives** (SQLAlchemy ORM statements). It now only flags SQL built by string formatting, or a query passed in whole by the caller.
|
|
140
|
+
- The official `modelcontextprotocol/servers` repo (TypeScript) produces **no findings** other than four unpinned workspace dependencies, and the Python SDK produces two MEDIUM `shell=True` calls in its developer CLI.
|
|
141
|
+
|
|
142
|
+
**Recall on a deliberately vulnerable server.** DVAP's MCP lab contains an unauthenticated endpoint, an arbitrary file read and two SSRF calls. **The first version of this scanner found none of them.** It only understood the official SDK's decorators, and one app's auth elsewhere in the repo hid the missing auth. After adding route-handler support and per-app scoping, it finds all of them (plus a further SSRF in a second lab). That is one server, so treat it as a sanity check, not a measured recall rate.
|
|
143
|
+
|
|
144
|
+
**Recall suite.** `tests/recall_cases.py` and `tests/recall_cases_js.py` hold 118 vulnerable snippets (each must trigger its rule) and 82 safe twins (none may produce a MEDIUM or higher finding), 63 and 43 of them JavaScript or TypeScript. It runs with the tests, and `python tests/test_recall.py` prints a per-rule table. A lesson from building it: the first version scored 37 of 37, which proved little, because I wrote the cases knowing how the scanner works. A probe with 18 harder Python variants (`os.remove`, `shutil.copy`, `subprocess.run(x.split())`, `pickle.loads`, a tainted value passed through a helper, `__import__('os').system`...) found that **13 of 18 were missed**, and a probe with 21 harder JS variants found 4 misses and 1 false positive. Those drove the file-operation, command-construction, helper-tracking, SQL, deserialization, alias-resolution and Zod work, and every variant is now a permanent test case. The suite measures known bug classes and regressions, not unknown ones.
|
|
145
|
+
|
|
146
|
+
**What this does not show.** The rules were tuned on this same sample, so the precision above is optimistic. None of the 67 servers was malicious, so I have not measured how well tool-poisoning detection (MCP002) works against real attacks beyond the patterns in the tests.
|
|
147
|
+
|
|
148
|
+
## Limits (read this)
|
|
149
|
+
|
|
150
|
+
- **Static analysis.** It does not run your server, so runtime-only bugs are missed.
|
|
151
|
+
- **Taint tracking is shallow.** It follows assignments inside a function and one call into a helper defined in the same file. It does not follow data across files, through classes, or two helpers deep. Sanitizer detection is name-based (`validate`, `sanitize`, `safe`, `resolve_`, `quote`...), so a function called `validate_path` that does not validate will be trusted.
|
|
152
|
+
- **Not covered:** XSS, authorization logic, race conditions, prototype pollution, and logic flaws in how a tool uses the model's output. Unsafe deserialization in JS/TS is limited to `node-serialize`.
|
|
153
|
+
- **The JS/TS analyzer is not a full parser.** It will miss taint that flows through classes, `.map` callbacks or dynamic property access, and it can be fooled by unusual code layout. Files over about 600 KB, `.d.ts` files and minified bundles are not analyzed.
|
|
154
|
+
- **MCP004 and MCP005 trust any auth or guard code in the same app.** One unrelated `Authorization` header in the app will silence MCP004, and an existence check such as `os.path.isfile` is correctly *not* treated as a guard, but a badly written custom one named `validate_path` would be.
|
|
155
|
+
- **Recall is measured on one server** (DVAP's MCP lab) and precision on 67 servers that were also used to tune the rules. Expect different results on code that looks unlike these.
|
|
156
|
+
- A clean report is not a security guarantee.
|
|
157
|
+
|
|
158
|
+
## Develop
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
python -m unittest discover -s tests
|
|
162
|
+
python -m mcp_vet src # the scanner scans itself
|
|
163
|
+
python assets/build_terminal_svg.py --png # regenerate the terminal image above (needs Edge or Chrome)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The `examples/` folder holds a deliberately vulnerable server and a clean one. Never deploy the vulnerable one.
|
|
167
|
+
|
|
168
|
+
## Roadmap
|
|
169
|
+
|
|
170
|
+
- Parse tool schemas and flag over-permissive inputs
|
|
171
|
+
- SSRF and unsafe-deserialization rules
|
|
172
|
+
- Dependency CVE lookup
|
|
173
|
+
- Dataset mode: batch-scan many public servers and emit aggregate statistics
|
|
174
|
+
- Prompt-injection guardrail benchmark (companion project)
|
|
175
|
+
|
|
176
|
+
## Responsible use
|
|
177
|
+
|
|
178
|
+
- Use mcp-vet on code you own, or code you are authorized to review. It only reads files; it never connects to or executes a server.
|
|
179
|
+
- If you find a vulnerability in someone else's project, report it privately to the maintainers and allow a reasonable time (commonly 90 days) before publishing details.
|
|
180
|
+
- Findings are heuristic signals, not proof of a vulnerability. Verify each one before acting on it or reporting it.
|
|
181
|
+
- Example files in `examples/` are intentionally insecure and use only documentation placeholder credentials. Never deploy them.
|
|
182
|
+
|
|
183
|
+
## Disclaimer
|
|
184
|
+
|
|
185
|
+
This is an independent open-source project. It is not affiliated with, endorsed by, or sponsored by Anthropic or the Model Context Protocol project, and it is unrelated to the PyPI project `mcpvet`, which is a different tool. "MCP" and other names mentioned belong to their respective owners.
|
|
186
|
+
|
|
187
|
+
The software is provided "as is", without warranty of any kind (see [LICENSE](LICENSE)). A clean scan is not a guarantee that a server is secure.
|
|
188
|
+
|
|
189
|
+
Found a security problem in mcp-vet itself? See [SECURITY.md](SECURITY.md).
|
|
190
|
+
|
|
191
|
+
## License
|
|
192
|
+
|
|
193
|
+
MIT
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
[](https://github.com/sonuoffsec/mcp-vet/actions/workflows/ci.yml)
|
|
4
|
+

|
|
5
|
+

|
|
6
|
+

|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
Static security scanner for **MCP (Model Context Protocol) servers** written in **Python, JavaScript and TypeScript**. Point it at a server's source or config and it flags the problems that let an attacker hijack an AI agent: tool poisoning, command injection, path traversal, SSRF, SQL injection, unsafe deserialization, leaked secrets and unauthenticated transports.
|
|
10
|
+
|
|
11
|
+
Zero dependencies. One command. Works in CI.
|
|
12
|
+
|
|
13
|
+

|
|
14
|
+
|
|
15
|
+
<sub>The image above is generated from the scanner's real output by `assets/build_terminal_svg.py --png`.</sub>
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
|
|
19
|
+
An MCP server lets an AI take real actions: read files, run commands, call APIs. A weak server can leak data or run an attacker's instructions, and most people install them without reading the code. mcp-vet is a linter for that gap.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install mcp-vet-scanner # needs Python 3.9+, no other dependencies
|
|
25
|
+
mcp-vet --version # the command is `mcp-vet`
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The PyPI package is called `mcp-vet-scanner` because `mcp-vet` is too similar to an unrelated project already on PyPI. The command, the repository and the Python module are all `mcp-vet`.
|
|
29
|
+
|
|
30
|
+
From source:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
git clone https://github.com/sonuoffsec/mcp-vet && cd mcp-vet
|
|
34
|
+
pip install -e .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or run it without installing: `PYTHONPATH=src python -m mcp_vet ./my-server`.
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
mcp-vet ./my-server # human-readable report
|
|
43
|
+
mcp-vet ./my-server -f json -o out.json # machine-readable
|
|
44
|
+
mcp-vet ./my-server -f sarif -o out.sarif # GitHub code scanning
|
|
45
|
+
mcp-vet ./my-server --fail-on MEDIUM # CI gate (default: HIGH)
|
|
46
|
+
mcp-vet --list-rules
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Exit code is `1` when a finding at or above `--fail-on` exists, `2` on usage errors, otherwise `0`.
|
|
50
|
+
|
|
51
|
+
## Rules
|
|
52
|
+
|
|
53
|
+
| ID | Severity | What it catches |
|
|
54
|
+
|---|---|---|
|
|
55
|
+
| MCP001 | HIGH / MEDIUM | Shell or dynamic code execution. **Python:** HIGH only when a tool argument reaches `shell=True`, `os.system`, `eval` or chooses the program; MEDIUM if the command is non-constant but not tool-controlled; constants are ignored. **JS/TS:** pattern-based |
|
|
56
|
+
| MCP002 | HIGH | Tool poisoning: instructions aimed at the model hidden in descriptions or code |
|
|
57
|
+
| MCP003 | CRITICAL | Hardcoded secrets (AWS, GitHub, OpenAI/Anthropic-style keys, Slack, private keys). Output is redacted |
|
|
58
|
+
| MCP004 | HIGH | HTTP/SSE transport with no authentication anywhere in the project, especially when bound to `0.0.0.0` |
|
|
59
|
+
| MCP005 | MEDIUM | Tool argument controls a file path with no containment check (path traversal) |
|
|
60
|
+
| MCP006 | LOW | Unpinned dependencies (`requirements.txt`, `package.json`) |
|
|
61
|
+
| MCP007 | HIGH | MCP config granting access to `/`, `~` or a whole drive |
|
|
62
|
+
| MCP008 | HIGH | Hidden Unicode (zero-width, bidi, tag characters) that can conceal instructions. In `.md`/`.txt` only bidi overrides, tag characters and runs of 3+ zero-width characters count, so Persian, Thai and emoji text is not flagged |
|
|
63
|
+
| MCP009 | MEDIUM | Tool argument controls the URL of an outbound request (SSRF) |
|
|
64
|
+
| MCP010 | HIGH / MEDIUM | SQL built from tool input: HIGH when a query that looks like SQL is assembled with f-strings, `+`, `%` or `.format`; MEDIUM when the caller passes the whole query. ORM statements such as `select(...).where(...)` are not flagged |
|
|
65
|
+
| MCP011 | HIGH | Tool argument passed to an unsafe deserializer (`pickle`, `marshal`, `dill`, `yaml.load` without a safe loader) |
|
|
66
|
+
|
|
67
|
+
## Suppress a finding
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
os.system(cmd) # mcp-vet: ignore MCP001
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Omit the rule ID to suppress every rule on that line.
|
|
74
|
+
|
|
75
|
+
## GitHub Action
|
|
76
|
+
|
|
77
|
+
```yaml
|
|
78
|
+
- run: pip install mcp-vet-scanner
|
|
79
|
+
- run: mcp-vet . -f sarif -o mcp-vet.sarif --fail-on HIGH
|
|
80
|
+
- uses: github/codeql-action/upload-sarif@v3
|
|
81
|
+
if: always()
|
|
82
|
+
with: { sarif_file: mcp-vet.sarif }
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## How it works
|
|
86
|
+
|
|
87
|
+
- **Python files are parsed into an AST** and checked with simple taint tracking. Values that come from a tool's parameters are "tainted". Taint follows assignments, and calls to functions named like `validate`, `sanitize`, `safe`, `check`, `allow` or `quote` (for example `shlex.quote`) clear it. A tool that runs a constant command is not flagged.
|
|
88
|
+
- **JavaScript and TypeScript get their own analyzer**, with no dependencies. A tokenizer (strings, template literals, comments, regex literals) feeds a scope-aware pass that finds tool handlers (`server.tool`, `registerTool`, `setRequestHandler`) and HTTP routes (Express, Fastify), follows tool arguments through assignments and destructuring, and understands `import { a as b }`, `require`, `promisify(exec)`, `execa`, `shelljs` and Zod schemas that constrain an input (`z.enum`, `z.number`, `z.string().uuid()`). It also knows that a ternary's value comes only from its branches, that an equality test yields a boolean, and that `ORDERS[args.sort]` returns a value the caller does not control. It is a purpose-built analyzer, not a full JavaScript parser: a file it cannot tokenize falls back to line patterns, reported at lower confidence.
|
|
89
|
+
- **Config and manifest files** (`package.json`, `requirements.txt`, MCP client config) are checked with direct rules.
|
|
90
|
+
- **HTTP route handlers count as entry points.** Python functions decorated like `@app.post("/mcp/call")` (FastAPI, Flask) are treated like tool handlers, so hand-rolled MCP-over-HTTP servers are analyzed too.
|
|
91
|
+
- **Authentication and path guards are looked for per app**: in the same folder, or any parent folder, that has its own `requirements.txt`, `package.json` or `Dockerfile`. One app's auth does not hide another app's gap.
|
|
92
|
+
- **Allowlist checks count.** A parameter tested with `if x not in ALLOWED: return/raise`, or looked up with `if registry.get(x) is None: raise`, is treated as validated. A filesystem existence check (`os.path.exists`, `isfile`) is not.
|
|
93
|
+
- **One hop into helpers.** If a tool passes a tool argument to a plain function defined in the same file, and that function runs a command, opens a path or makes a request, the tool's call is reported.
|
|
94
|
+
- **Wide sink coverage.** File operations include `open`, `Path(...).read_text/unlink/...`, `os.remove/listdir/rename`, `shutil.copy/rmtree/move` and `send_file`. Command execution includes `os.system`, `subprocess` with `shell=True`, a caller-chosen program (`cmd.split()`, `shlex.split`), `os.exec*` and `__import__('os').system`.
|
|
95
|
+
- Test files and test directories are skipped by default (`--include-tests` to scan them).
|
|
96
|
+
|
|
97
|
+
## Tested on real servers
|
|
98
|
+
|
|
99
|
+
All runs were static: the code was cloned and read, never executed.
|
|
100
|
+
|
|
101
|
+
**Precision on 67 small community MCP servers** (about 29,500 files in Python, JavaScript and TypeScript):
|
|
102
|
+
|
|
103
|
+
- The first pass (v0.1) reported **715 HIGH or CRITICAL findings**. Almost all were false positives: emoji and Persian/Sinhala text flagged as hidden Unicode, code that *reads* `.env` flagged as tool poisoning, Playwright's `$eval` flagged as `eval`, security libraries that contain the very strings they block. Each cause was fixed and became a regression test.
|
|
104
|
+
- Today there are **12 HIGH or CRITICAL findings in 6 repos**. Eight of them I reviewed by hand and **none is a vulnerability**: blocklists and defensive examples in security libraries, attack payloads in test data, defensive prompt text, a test credential, and a zero-width character in a docstring. The other **4 are SQL findings (MCP010) in a single repo**, a low-code platform that executes SQL stored in its application configuration by design. I traced six more findings in that repo to code that is escaped (`pg.escapeIdentifier`) or parameterized and fixed the analyzer for those patterns. The remaining four run configured SQL, and the analyzer cannot tell configuration from request data once both pass through a context object, so I have **not** confirmed whether any of them is exploitable.
|
|
105
|
+
- The file-path findings (MCP005, MEDIUM) are the most useful tier: **40 findings in 8 repos**. I checked 24 of them (the flagged line and its enclosing function): 22 were a tool argument deciding where a file is read, written, copied, listed or deleted (`save_to`, `world_path`, `directory`, `filePath`, `session_id`), and 2 were false positives (validated by a registry lookup; guarded by the caller), both fixed. I did not read all 40. Many of these servers are local developer tools where choosing a path is the point, so "real" means the rule's condition holds, not that the server is exploitable.
|
|
106
|
+
- Two further JavaScript findings I read and confirmed: a tool that reads an arbitrary caller-supplied file path, and a tool that fetches a caller-supplied URL (`faucetUrl: z.string().url()` checks the format only).
|
|
107
|
+
- When the JS/TS analyzer was first enabled it reported **391 JS findings against 102 from the old patterns**. Nearly all of the 337 new ones were false positives: `/regex/.exec()` mistaken for `child_process.exec`, SQL fragments built from a ternary of constants, `ORDERS[args.sort]` allowlist lookups, query-builder helpers that return `?` placeholders, `items.map(() => '?')`, `pg.escapeIdentifier` under another name. Each was fixed and tested, and the JS/TS count is now **72**.
|
|
108
|
+
- The SQL rule first reported 23 findings on one Python repo, **all false positives** (SQLAlchemy ORM statements). It now only flags SQL built by string formatting, or a query passed in whole by the caller.
|
|
109
|
+
- The official `modelcontextprotocol/servers` repo (TypeScript) produces **no findings** other than four unpinned workspace dependencies, and the Python SDK produces two MEDIUM `shell=True` calls in its developer CLI.
|
|
110
|
+
|
|
111
|
+
**Recall on a deliberately vulnerable server.** DVAP's MCP lab contains an unauthenticated endpoint, an arbitrary file read and two SSRF calls. **The first version of this scanner found none of them.** It only understood the official SDK's decorators, and one app's auth elsewhere in the repo hid the missing auth. After adding route-handler support and per-app scoping, it finds all of them (plus a further SSRF in a second lab). That is one server, so treat it as a sanity check, not a measured recall rate.
|
|
112
|
+
|
|
113
|
+
**Recall suite.** `tests/recall_cases.py` and `tests/recall_cases_js.py` hold 118 vulnerable snippets (each must trigger its rule) and 82 safe twins (none may produce a MEDIUM or higher finding), 63 and 43 of them JavaScript or TypeScript. It runs with the tests, and `python tests/test_recall.py` prints a per-rule table. A lesson from building it: the first version scored 37 of 37, which proved little, because I wrote the cases knowing how the scanner works. A probe with 18 harder Python variants (`os.remove`, `shutil.copy`, `subprocess.run(x.split())`, `pickle.loads`, a tainted value passed through a helper, `__import__('os').system`...) found that **13 of 18 were missed**, and a probe with 21 harder JS variants found 4 misses and 1 false positive. Those drove the file-operation, command-construction, helper-tracking, SQL, deserialization, alias-resolution and Zod work, and every variant is now a permanent test case. The suite measures known bug classes and regressions, not unknown ones.
|
|
114
|
+
|
|
115
|
+
**What this does not show.** The rules were tuned on this same sample, so the precision above is optimistic. None of the 67 servers was malicious, so I have not measured how well tool-poisoning detection (MCP002) works against real attacks beyond the patterns in the tests.
|
|
116
|
+
|
|
117
|
+
## Limits (read this)
|
|
118
|
+
|
|
119
|
+
- **Static analysis.** It does not run your server, so runtime-only bugs are missed.
|
|
120
|
+
- **Taint tracking is shallow.** It follows assignments inside a function and one call into a helper defined in the same file. It does not follow data across files, through classes, or two helpers deep. Sanitizer detection is name-based (`validate`, `sanitize`, `safe`, `resolve_`, `quote`...), so a function called `validate_path` that does not validate will be trusted.
|
|
121
|
+
- **Not covered:** XSS, authorization logic, race conditions, prototype pollution, and logic flaws in how a tool uses the model's output. Unsafe deserialization in JS/TS is limited to `node-serialize`.
|
|
122
|
+
- **The JS/TS analyzer is not a full parser.** It will miss taint that flows through classes, `.map` callbacks or dynamic property access, and it can be fooled by unusual code layout. Files over about 600 KB, `.d.ts` files and minified bundles are not analyzed.
|
|
123
|
+
- **MCP004 and MCP005 trust any auth or guard code in the same app.** One unrelated `Authorization` header in the app will silence MCP004, and an existence check such as `os.path.isfile` is correctly *not* treated as a guard, but a badly written custom one named `validate_path` would be.
|
|
124
|
+
- **Recall is measured on one server** (DVAP's MCP lab) and precision on 67 servers that were also used to tune the rules. Expect different results on code that looks unlike these.
|
|
125
|
+
- A clean report is not a security guarantee.
|
|
126
|
+
|
|
127
|
+
## Develop
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
python -m unittest discover -s tests
|
|
131
|
+
python -m mcp_vet src # the scanner scans itself
|
|
132
|
+
python assets/build_terminal_svg.py --png # regenerate the terminal image above (needs Edge or Chrome)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The `examples/` folder holds a deliberately vulnerable server and a clean one. Never deploy the vulnerable one.
|
|
136
|
+
|
|
137
|
+
## Roadmap
|
|
138
|
+
|
|
139
|
+
- Parse tool schemas and flag over-permissive inputs
|
|
140
|
+
- SSRF and unsafe-deserialization rules
|
|
141
|
+
- Dependency CVE lookup
|
|
142
|
+
- Dataset mode: batch-scan many public servers and emit aggregate statistics
|
|
143
|
+
- Prompt-injection guardrail benchmark (companion project)
|
|
144
|
+
|
|
145
|
+
## Responsible use
|
|
146
|
+
|
|
147
|
+
- Use mcp-vet on code you own, or code you are authorized to review. It only reads files; it never connects to or executes a server.
|
|
148
|
+
- If you find a vulnerability in someone else's project, report it privately to the maintainers and allow a reasonable time (commonly 90 days) before publishing details.
|
|
149
|
+
- Findings are heuristic signals, not proof of a vulnerability. Verify each one before acting on it or reporting it.
|
|
150
|
+
- Example files in `examples/` are intentionally insecure and use only documentation placeholder credentials. Never deploy them.
|
|
151
|
+
|
|
152
|
+
## Disclaimer
|
|
153
|
+
|
|
154
|
+
This is an independent open-source project. It is not affiliated with, endorsed by, or sponsored by Anthropic or the Model Context Protocol project, and it is unrelated to the PyPI project `mcpvet`, which is a different tool. "MCP" and other names mentioned belong to their respective owners.
|
|
155
|
+
|
|
156
|
+
The software is provided "as is", without warranty of any kind (see [LICENSE](LICENSE)). A clean scan is not a guarantee that a server is secure.
|
|
157
|
+
|
|
158
|
+
Found a security problem in mcp-vet itself? See [SECURITY.md](SECURITY.md).
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mcp-vet-scanner"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Static security scanner for MCP (Model Context Protocol) servers. Zero dependencies."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "sonuoffsec" }]
|
|
13
|
+
keywords = ["mcp", "model-context-protocol", "llm-security", "ai-security", "prompt-injection",
|
|
14
|
+
"tool-poisoning", "sast", "security", "linter"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Intended Audience :: Information Technology",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.9",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Topic :: Security",
|
|
29
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
30
|
+
"Topic :: Software Development :: Testing",
|
|
31
|
+
]
|
|
32
|
+
dependencies = []
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://github.com/sonuoffsec/mcp-vet"
|
|
36
|
+
Source = "https://github.com/sonuoffsec/mcp-vet"
|
|
37
|
+
Issues = "https://github.com/sonuoffsec/mcp-vet/issues"
|
|
38
|
+
Changelog = "https://github.com/sonuoffsec/mcp-vet/blob/main/CHANGELOG.md"
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
mcp-vet = "mcp_vet.cli:main"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""File-level checks that need more than a single-line regex."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import List, Optional
|
|
8
|
+
|
|
9
|
+
from .models import Finding
|
|
10
|
+
from .rules import RULES, CODE_EXTS
|
|
11
|
+
|
|
12
|
+
TOOL_MARKERS = re.compile(
|
|
13
|
+
r"(@\w+\.tool\b|[\"']/mcp(/|[\"'])|tools/call|\bserver\.tool\(|registerTool|@tool\b|setRequestHandler|CallToolRequestSchema|FastMCP)"
|
|
14
|
+
)
|
|
15
|
+
NET_TRANSPORT = re.compile(
|
|
16
|
+
r"(transport\s*=\s*['\"](sse|streamable-http|http)['\"]"
|
|
17
|
+
r"|SSEServerTransport|StreamableHTTPServerTransport|SseServerTransport"
|
|
18
|
+
r"|sse_app\(|streamable_http_app\(|\bapp\.listen\(|\bFastAPI\(|\bFlask\(|uvicorn\.run\()"
|
|
19
|
+
)
|
|
20
|
+
AUTH_HINT = re.compile(
|
|
21
|
+
r"(authorization|bearer|api[_-]?key|oauth|auth_?middleware|verify_?token|jwt|x-api-key)",
|
|
22
|
+
re.IGNORECASE,
|
|
23
|
+
)
|
|
24
|
+
OPEN_BIND = re.compile(r"0\.0\.0\.0|host\s*=\s*['\"]::['\"]")
|
|
25
|
+
FILE_READ = re.compile(
|
|
26
|
+
r"(\bopen\s*\(|\.read_text\s*\(|\.read_bytes\s*\(|\breadFile(Sync)?\s*\(|createReadStream\s*\()"
|
|
27
|
+
)
|
|
28
|
+
PATH_GUARD = re.compile(
|
|
29
|
+
r"(is_relative_to|commonpath|\.relative_to\(|realpath|path\.relative\(|startsWith\(\s*(root|base|allowed|safe))",
|
|
30
|
+
re.IGNORECASE,
|
|
31
|
+
)
|
|
32
|
+
MODULE_ANCHORED = re.compile(r"(import\.meta|__dirname|__filename|new URL\()")
|
|
33
|
+
BROAD_SCOPES = {"/", "~", "~/", "c:\\", "c:/", "c:\\\\", "/home", "/users", "/root"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _finding(rule_id: str, file: str, line: int, snippet: str, extra: str = "") -> Finding:
|
|
37
|
+
r = RULES[rule_id]
|
|
38
|
+
msg = r.message + (f" {extra}" if extra else "")
|
|
39
|
+
return Finding(r.id, r.title, r.severity, file, line, snippet.strip()[:200], msg, r.remediation)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _line_of(text: str, index: int) -> int:
|
|
43
|
+
return text.count("\n", 0, index) + 1
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_network_auth(file: str, text: str, ext: str,
|
|
47
|
+
project_has_auth: Optional[bool] = None) -> List[Finding]:
|
|
48
|
+
"""project_has_auth: True if ANY code file in the project shows auth handling."""
|
|
49
|
+
if ext not in CODE_EXTS or not TOOL_MARKERS.search(text):
|
|
50
|
+
return []
|
|
51
|
+
has_auth = AUTH_HINT.search(text) is not None if project_has_auth is None else project_has_auth
|
|
52
|
+
net = NET_TRANSPORT.search(text)
|
|
53
|
+
if not net or has_auth:
|
|
54
|
+
return []
|
|
55
|
+
bind = OPEN_BIND.search(text)
|
|
56
|
+
anchor = bind or net
|
|
57
|
+
line = _line_of(text, anchor.start())
|
|
58
|
+
snippet = text.splitlines()[line - 1]
|
|
59
|
+
f = _finding("MCP004", file, line, snippet,
|
|
60
|
+
"It also binds to all interfaces." if bind else "")
|
|
61
|
+
return [f]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def check_file_read(file: str, text: str, ext: str,
|
|
65
|
+
project_has_guard: Optional[bool] = None) -> List[Finding]:
|
|
66
|
+
"""Regex fallback for JS/TS (Python uses pyast). project_has_guard looks across files."""
|
|
67
|
+
if ext not in CODE_EXTS or not TOOL_MARKERS.search(text):
|
|
68
|
+
return []
|
|
69
|
+
has_guard = PATH_GUARD.search(text) is not None if project_has_guard is None else project_has_guard
|
|
70
|
+
if has_guard:
|
|
71
|
+
return []
|
|
72
|
+
for read in FILE_READ.finditer(text):
|
|
73
|
+
line = _line_of(text, read.start())
|
|
74
|
+
src = text.splitlines()[line - 1]
|
|
75
|
+
if MODULE_ANCHORED.search(src):
|
|
76
|
+
continue # path is relative to this module, not tool input
|
|
77
|
+
f = _finding("MCP005", file, line, src,
|
|
78
|
+
"Unverified: this language has no taint analysis, so the path may be constant.")
|
|
79
|
+
return [replace(f, severity="LOW")]
|
|
80
|
+
return []
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def check_dependencies(file: str, text: str, name: str) -> List[Finding]:
|
|
84
|
+
out: List[Finding] = []
|
|
85
|
+
lname = name.lower()
|
|
86
|
+
if lname.startswith("requirements") and lname.endswith(".txt"):
|
|
87
|
+
for i, raw in enumerate(text.splitlines(), 1):
|
|
88
|
+
line = raw.split("#", 1)[0].strip()
|
|
89
|
+
if not line or line.startswith("-"):
|
|
90
|
+
continue
|
|
91
|
+
if "==" in line or " @ " in line or line.startswith(("git+", "http")):
|
|
92
|
+
continue
|
|
93
|
+
out.append(_finding("MCP006", file, i, raw))
|
|
94
|
+
elif lname == "package.json":
|
|
95
|
+
try:
|
|
96
|
+
data = json.loads(text)
|
|
97
|
+
except ValueError:
|
|
98
|
+
return out
|
|
99
|
+
for section in ("dependencies", "devDependencies"):
|
|
100
|
+
for pkg, ver in (data.get(section) or {}).items():
|
|
101
|
+
if str(ver).strip() in ("*", "latest", "", "x"):
|
|
102
|
+
needle = f'"{pkg}"'
|
|
103
|
+
idx = text.find(needle)
|
|
104
|
+
line = _line_of(text, idx) if idx >= 0 else 1
|
|
105
|
+
out.append(_finding("MCP006", file, line, f'{pkg}: "{ver}"'))
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def check_broad_scope(file: str, text: str, ext: str) -> List[Finding]:
|
|
110
|
+
if ext != ".json":
|
|
111
|
+
return []
|
|
112
|
+
out: List[Finding] = []
|
|
113
|
+
for m in re.finditer(r'"args"\s*:\s*\[(.*?)\]', text, re.S):
|
|
114
|
+
for item in re.findall(r'"((?:[^"\\]|\\.)*)"', m.group(1)):
|
|
115
|
+
if item.strip().lower() in BROAD_SCOPES:
|
|
116
|
+
line = _line_of(text, m.start(1) + m.group(1).find(f'"{item}"'))
|
|
117
|
+
out.append(_finding("MCP007", file, line, f'"args": [... "{item}" ...]'))
|
|
118
|
+
return out
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import __version__
|
|
7
|
+
from .models import SEVERITIES, severity_rank
|
|
8
|
+
from .report import as_json, as_sarif, as_text, rules_table
|
|
9
|
+
from .scanner import scan
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
13
|
+
p = argparse.ArgumentParser(prog="mcp-vet",
|
|
14
|
+
description="Static security scanner for MCP servers.")
|
|
15
|
+
p.add_argument("path", nargs="?", help="directory or file to scan")
|
|
16
|
+
p.add_argument("-f", "--format", choices=["text", "json", "sarif"], default="text")
|
|
17
|
+
p.add_argument("-o", "--output", help="write the report to a file")
|
|
18
|
+
p.add_argument("--fail-on", choices=SEVERITIES, default="HIGH",
|
|
19
|
+
help="exit with code 1 if a finding at or above this severity exists (default HIGH)")
|
|
20
|
+
p.add_argument("--min-severity", choices=SEVERITIES, default="INFO",
|
|
21
|
+
help="hide findings below this severity")
|
|
22
|
+
p.add_argument("--include-tests", action="store_true",
|
|
23
|
+
help="also scan test files and test directories (skipped by default)")
|
|
24
|
+
p.add_argument("--list-rules", action="store_true", help="print all rules and exit")
|
|
25
|
+
p.add_argument("--version", action="version", version=f"mcp-vet {__version__}")
|
|
26
|
+
return p
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv=None) -> int:
|
|
30
|
+
args = build_parser().parse_args(argv)
|
|
31
|
+
if args.list_rules:
|
|
32
|
+
print(rules_table())
|
|
33
|
+
return 0
|
|
34
|
+
if not args.path:
|
|
35
|
+
print("error: path is required", file=sys.stderr)
|
|
36
|
+
return 2
|
|
37
|
+
try:
|
|
38
|
+
result = scan(args.path, include_tests=args.include_tests)
|
|
39
|
+
except FileNotFoundError:
|
|
40
|
+
print(f"error: {args.path} not found", file=sys.stderr)
|
|
41
|
+
return 2
|
|
42
|
+
|
|
43
|
+
floor = severity_rank(args.min_severity)
|
|
44
|
+
result.findings = [f for f in result.findings if severity_rank(f.severity) >= floor]
|
|
45
|
+
|
|
46
|
+
if args.format == "json":
|
|
47
|
+
text = as_json(result)
|
|
48
|
+
elif args.format == "sarif":
|
|
49
|
+
text = as_sarif(result)
|
|
50
|
+
else:
|
|
51
|
+
text = as_text(result, color=sys.stdout.isatty() and not args.output)
|
|
52
|
+
|
|
53
|
+
if args.output:
|
|
54
|
+
with open(args.output, "w", encoding="utf-8") as fh:
|
|
55
|
+
fh.write(text + "\n")
|
|
56
|
+
else:
|
|
57
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
58
|
+
print(text)
|
|
59
|
+
|
|
60
|
+
gate = severity_rank(args.fail_on)
|
|
61
|
+
return 1 if any(severity_rank(f.severity) >= gate for f in result.findings) else 0
|