agentconfig-audit-lite 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentconfig_audit_lite-0.1.0.dist-info/METADATA +125 -0
- agentconfig_audit_lite-0.1.0.dist-info/RECORD +7 -0
- agentconfig_audit_lite-0.1.0.dist-info/WHEEL +5 -0
- agentconfig_audit_lite-0.1.0.dist-info/entry_points.txt +2 -0
- agentconfig_audit_lite-0.1.0.dist-info/licenses/LICENSE +21 -0
- agentconfig_audit_lite-0.1.0.dist-info/top_level.txt +1 -0
- agentconfig_audit_lite.py +355 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentconfig-audit-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Audit MCP config for secrets: plaintext tokens and unpinned npx/uvx servers in .mcp.json and CLAUDE.md.
|
|
5
|
+
Author: Alessio Auretto
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/alessio1999xx-debug/agentconfig-audit-lite
|
|
8
|
+
Project-URL: Pro version, https://py-forge.com/products/agentconfig-audit-mcp-and-rules-scanner
|
|
9
|
+
Keywords: mcp,mcp-security,model-context-protocol,claude-code,cursor,ai-agents,secret-scanning,cli,stdlib
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Security
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# agentconfig-audit-lite: audit MCP config for secrets, unpinned servers and unsafe Claude Code settings
|
|
28
|
+
|
|
29
|
+
agentconfig-audit-lite helps with auditing MCP config for secrets and a quick check of the AI agent setup in one project: it lists the MCP server configs and agent rule files it finds, and flags plaintext tokens, `npx`/`uvx` MCP servers with no version pin, and Claude Code settings that don't keep the agent away from `.env` files and migrations. One file, Python 3.9+ standard library only, read-only, MIT.
|
|
30
|
+
|
|
31
|
+
- Optional `pip install`, or just download the one file. No config, no state, no network calls.
|
|
32
|
+
- Secrets are shown as masked previews only (`ghp_****(40 chars)`), never in full.
|
|
33
|
+
- Flags: `--file`, `--version`. After `pip install`, use `agentconfig-audit-lite` in place of `python3 agentconfig_audit_lite.py`.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install agentconfig-audit-lite
|
|
39
|
+
agentconfig-audit-lite --help
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or download the single file (Python 3.9+, stdlib only, no extra packages):
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
curl -fsSLO https://raw.githubusercontent.com/alessio1999xx-debug/agentconfig-audit-lite/main/agentconfig_audit_lite.py
|
|
46
|
+
python3 agentconfig_audit_lite.py --help
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Scan a project's MCP config and CLAUDE.md / AGENTS.md rules
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
python3 agentconfig_audit_lite.py ~/code/my-app
|
|
53
|
+
# agentconfig-audit-lite 0.1.0: /home/me/code/my-app
|
|
54
|
+
#
|
|
55
|
+
# Found 3 agent config / rule file(s):
|
|
56
|
+
# settings .claude/settings.json
|
|
57
|
+
# mcp .mcp.json
|
|
58
|
+
# rules CLAUDE.md
|
|
59
|
+
#
|
|
60
|
+
# 3 finding(s):
|
|
61
|
+
# FAIL [unpinned-server] .mcp.json: server 'github' runs `npx @modelcontextprotocol/server-github` with no version pin (pin e.g. pkg@1.2.3 or pkg==1.2.3)
|
|
62
|
+
# FAIL [plaintext-secret] .mcp.json: server 'github' env GITHUB_PERSONAL_ACCESS_TOKEN = ghp_****(40 chars) (GitHub token)
|
|
63
|
+
# FAIL [migrations-not-denied] .claude/settings.json: project has a migrations dir but no Edit and Write deny rules for it and no PreToolUse hook
|
|
64
|
+
|
|
65
|
+
# also check a config that lives outside the project
|
|
66
|
+
python3 agentconfig_audit_lite.py . --file ~/.cursor/mcp.json --file ~/.claude/settings.json
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Which MCP configs and agent rule files it checks
|
|
70
|
+
|
|
71
|
+
Files (searched in the project dir, skipping `.git`, `node_modules`, virtualenvs and build dirs):
|
|
72
|
+
|
|
73
|
+
- MCP configs: `.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`, `mcp.json`, `claude_desktop_config.json`, `mcp_config.json`
|
|
74
|
+
- Agent rule files: `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, `GEMINI.md`, `.cursorrules`, `.windsurfrules`, `.cursor/rules/*`, `copilot-instructions.md`
|
|
75
|
+
- Claude Code settings: `.claude/settings.json`, `.claude/settings.local.json` (any `.claude/settings*.json`)
|
|
76
|
+
|
|
77
|
+
Checks:
|
|
78
|
+
|
|
79
|
+
| Check | What it flags |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| `plaintext-secret` | Known token formats (GitHub, OpenAI/Anthropic-style `sk-`, AWS, Slack, GitLab, Google, Stripe live, Bearer, private keys) in MCP `env`/`headers`/args and rule files, plus hardcoded values under names like `*_TOKEN` or `*_PASSWORD`. `${VAR}` references are fine. |
|
|
82
|
+
| `unpinned-server` | `npx`, `uvx` or `bunx` MCP servers with no exact version (`pkg`, `pkg@latest`, `pkg@^1.2`). `pkg@1.2.3` and `pkg==1.2.3` pass. |
|
|
83
|
+
| `env-not-denied` | The project has a `.env` file (not `.env.example`) and Claude Code settings have no `Read(...env...)` deny rule and no `PreToolUse` hook. |
|
|
84
|
+
| `migrations-not-denied` | The project has a `migrations` dir and settings don't deny both `Edit` and `Write` on it, and there's no `PreToolUse` hook. |
|
|
85
|
+
| `secret-in-allow-rule` | A token pasted into a `permissions.allow` rule in `.claude/settings*.json` (this happens when you approve a command that had a key in it). |
|
|
86
|
+
|
|
87
|
+
The two Claude Code settings checks only run when the project uses Claude Code (a `CLAUDE.md` or `.claude/settings*.json` exists). A `PreToolUse` hook is counted as protection, but the lite version doesn't check what the hook actually does. A rule in `CLAUDE.md` saying "don't touch .env" is not counted: it's an instruction, not a permission.
|
|
88
|
+
|
|
89
|
+
JSON with comments can't be parsed by the standard library; those files get a `NOTE` and a plain-text token scan only.
|
|
90
|
+
|
|
91
|
+
## Exit codes for CI or cron
|
|
92
|
+
|
|
93
|
+
| Exit code | Meaning |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `0` | No findings |
|
|
96
|
+
| `1` | At least one finding |
|
|
97
|
+
| `2` | Bad arguments, project dir or `--file` not found |
|
|
98
|
+
|
|
99
|
+
## agentconfig-audit-lite vs AgentConfig Audit
|
|
100
|
+
|
|
101
|
+
agentconfig-audit-lite checks one project dir and prints a plain text list. That's it.
|
|
102
|
+
|
|
103
|
+
The full **[AgentConfig Audit](https://py-forge.com/products/agentconfig-audit-mcp-and-rules-scanner?utm_source=github&utm_medium=readme&utm_campaign=agentconfig-audit-lite)** helps with:
|
|
104
|
+
|
|
105
|
+
- finding the MCP configs installed on the machine (Claude Desktop, Cursor, VS Code, Windsurf, Codex, `~/.claude.json`) on macOS, Linux and Windows
|
|
106
|
+
- MCP servers given the whole filesystem (`/`, `~`, `/home`, `C:\`) and remote MCP endpoints with no auth header or plain `http://`
|
|
107
|
+
- hidden Unicode (zero-width and bidi override characters) and prompt-injection phrases in rule files
|
|
108
|
+
- JSON and SARIF 2.1.0 reports, written to a file if you want
|
|
109
|
+
- a suggested fix or command for each finding, severity levels and a `--strict` mode for HIGH/CRITICAL only
|
|
110
|
+
|
|
111
|
+
One-time payment, yours to keep. No subscription.
|
|
112
|
+
|
|
113
|
+
Or get every PyForge tool, current and future, with the [All-Access Pass](https://py-forge.com/pass?utm_source=github&utm_medium=readme&utm_campaign=agentconfig-audit-lite).
|
|
114
|
+
|
|
115
|
+
## Tests
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
python3 test_agentconfig_audit_lite.py
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The tests are offline and build their fixtures in temp dirs. Fake tokens are generated at runtime.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT (this lite version). The full AgentConfig Audit is sold separately under its own license.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
agentconfig_audit_lite.py,sha256=ql_VEy1QwUkYYBEo9L40frFhJ-fIxBESU3m3fVuPz_E,15712
|
|
2
|
+
agentconfig_audit_lite-0.1.0.dist-info/licenses/LICENSE,sha256=hHuiZGVU1W0vbSggaTAy28kRUnwp6e85CqEFKsatpcE,1087
|
|
3
|
+
agentconfig_audit_lite-0.1.0.dist-info/METADATA,sha256=mnmxH4sBV78v_I7RRSY3bO1oeFhnX_IBWio_1Npqe9U,6757
|
|
4
|
+
agentconfig_audit_lite-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
agentconfig_audit_lite-0.1.0.dist-info/entry_points.txt,sha256=suw3doPE13Wh7hOEiHh7FwGvM4ByBUOr6dxBzqGHYFU,71
|
|
6
|
+
agentconfig_audit_lite-0.1.0.dist-info/top_level.txt,sha256=_DEqKLPXPE7-1eVwWeizsmUvyLEaW0p3eNT52PlnyQo,23
|
|
7
|
+
agentconfig_audit_lite-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PyForge (https://py-forge.com)
|
|
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 @@
|
|
|
1
|
+
agentconfig_audit_lite
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""agentconfig-audit-lite: audit MCP configs and AI agent rule files in one project.
|
|
3
|
+
|
|
4
|
+
Lists the MCP server configs and agent rule files in one project directory
|
|
5
|
+
(CLAUDE.md, AGENTS.md, .cursor/rules, .claude/settings*.json, .mcp.json,
|
|
6
|
+
.cursor/mcp.json, claude_desktop_config.json, ...) and flags:
|
|
7
|
+
|
|
8
|
+
- plaintext tokens / API keys (masked in the report)
|
|
9
|
+
- npx / uvx MCP servers launched without a version pin
|
|
10
|
+
- Claude Code settings with no Read deny for .env files or no Edit/Write
|
|
11
|
+
deny for migrations (and no PreToolUse hook)
|
|
12
|
+
- tokens embedded in .claude/settings*.json permission allow rules
|
|
13
|
+
|
|
14
|
+
Read-only, plain text report, exit 1 when something is found. One file,
|
|
15
|
+
Python 3.9+ standard library only. MIT License.
|
|
16
|
+
|
|
17
|
+
Full version (machine-wide config discovery, JSON/SARIF reports, fix
|
|
18
|
+
commands, more checks): https://py-forge.com/products/agentconfig-audit-mcp-and-rules-scanner
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import sys
|
|
28
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
|
|
32
|
+
SKIP_DIRS = {".git", ".hg", ".svn", "node_modules", ".venv", "venv", "env",
|
|
33
|
+
"__pycache__", "build", "dist", ".tox", ".mypy_cache", ".next"}
|
|
34
|
+
|
|
35
|
+
RULE_FILE_NAMES = {"claude.md", "claude.local.md", "agents.md", "agent.md", "gemini.md",
|
|
36
|
+
".cursorrules", ".windsurfrules", "copilot-instructions.md"}
|
|
37
|
+
MCP_FILE_NAMES = {".mcp.json", "mcp.json", "claude_desktop_config.json", "mcp_config.json"}
|
|
38
|
+
|
|
39
|
+
# (regex, label). Group 1, when present, is the secret value itself.
|
|
40
|
+
SECRET_PATTERNS: List[Tuple[str, str]] = [
|
|
41
|
+
(r"\b(sk-ant-[A-Za-z0-9_\-]{20,})", "Anthropic API key"),
|
|
42
|
+
(r"\b(sk-(?:proj-)?[A-Za-z0-9_\-]{20,})", "OpenAI-style API key"),
|
|
43
|
+
(r"\b(ghp_[A-Za-z0-9]{36,})\b", "GitHub token"),
|
|
44
|
+
(r"\b(gh[ousr]_[A-Za-z0-9]{36,})\b", "GitHub token"),
|
|
45
|
+
(r"\b(github_pat_[A-Za-z0-9_]{40,})\b", "GitHub fine-grained token"),
|
|
46
|
+
(r"\b(glpat-[A-Za-z0-9_\-]{20,})\b", "GitLab token"),
|
|
47
|
+
(r"\b(xox[baprs]-[A-Za-z0-9\-]{10,})\b", "Slack token"),
|
|
48
|
+
(r"\b(AKIA[0-9A-Z]{16})\b", "AWS access key ID"),
|
|
49
|
+
(r"\b(AIza[0-9A-Za-z_\-]{35})\b", "Google API key"),
|
|
50
|
+
(r"\b((?:sk|rk)_live_[0-9A-Za-z]{16,})\b", "Stripe live key"),
|
|
51
|
+
(r"(?i)\bbearer\s+([A-Za-z0-9_\-\.=]{20,})", "Bearer token"),
|
|
52
|
+
(r"(-----BEGIN [A-Z ]*PRIVATE KEY-----)", "private key"),
|
|
53
|
+
]
|
|
54
|
+
SECRETISH_KEY = re.compile(r"(?i)(token|secret|passw(or)?d|api[_-]?key|access[_-]?key|private[_-]?key|auth)")
|
|
55
|
+
PLACEHOLDER = re.compile(r"(?i)^(\$\{?[A-Z0-9_:\-]+\}?|<[^>]*>|x+|\*+|your[_-].*|changeme|placeholder|example.*|\.\.\.)$")
|
|
56
|
+
RUNNERS = {"npx", "uvx", "bunx"}
|
|
57
|
+
RANGE_CHARS = set("^~><*x|")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def mask(value: str) -> str:
|
|
61
|
+
"""Masked preview: first 4 characters, then the length. Never the full value."""
|
|
62
|
+
value = value.strip()
|
|
63
|
+
if value.startswith("-----BEGIN"):
|
|
64
|
+
return value[:16] + "..."
|
|
65
|
+
return "%s****(%d chars)" % (value[:4], len(value))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_secrets(text: str) -> List[Tuple[str, str]]:
|
|
69
|
+
"""Return (label, masked preview) for every known token pattern in text."""
|
|
70
|
+
out: List[Tuple[str, str]] = []
|
|
71
|
+
seen = set()
|
|
72
|
+
for pattern, label in SECRET_PATTERNS:
|
|
73
|
+
for m in re.finditer(pattern, text):
|
|
74
|
+
val = m.group(1)
|
|
75
|
+
if PLACEHOLDER.match(val) or val in seen:
|
|
76
|
+
continue
|
|
77
|
+
if any(val in s or s in val for s in seen):
|
|
78
|
+
continue
|
|
79
|
+
seen.add(val)
|
|
80
|
+
out.append((label, mask(val)))
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Finding:
|
|
85
|
+
def __init__(self, path: str, check: str, message: str):
|
|
86
|
+
self.path, self.check, self.message = path, check, message
|
|
87
|
+
|
|
88
|
+
def __repr__(self) -> str:
|
|
89
|
+
return "Finding(%r, %r, %r)" % (self.path, self.check, self.message)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------------------------------------------------------------- discovery
|
|
93
|
+
|
|
94
|
+
def classify(rel: str) -> Optional[str]:
|
|
95
|
+
"""Return 'mcp', 'settings', 'rules' or None for a project-relative path."""
|
|
96
|
+
parts = rel.replace("\\", "/").split("/")
|
|
97
|
+
name = parts[-1].lower()
|
|
98
|
+
parent = parts[-2].lower() if len(parts) > 1 else ""
|
|
99
|
+
if parent == ".claude" and re.match(r"^settings.*\.json$", name):
|
|
100
|
+
return "settings"
|
|
101
|
+
if name in MCP_FILE_NAMES:
|
|
102
|
+
return "mcp"
|
|
103
|
+
if name in RULE_FILE_NAMES:
|
|
104
|
+
return "rules"
|
|
105
|
+
if ".cursor" in [p.lower() for p in parts[:-1]] and "rules" in [p.lower() for p in parts[:-1]]:
|
|
106
|
+
return "rules"
|
|
107
|
+
if name.endswith(".mdc") and ".cursor" in [p.lower() for p in parts]:
|
|
108
|
+
return "rules"
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def discover(root: str) -> List[Tuple[str, str]]:
|
|
113
|
+
"""Walk one project dir; return sorted (relative path, kind)."""
|
|
114
|
+
found: List[Tuple[str, str]] = []
|
|
115
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
116
|
+
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS)
|
|
117
|
+
for fname in filenames:
|
|
118
|
+
rel = os.path.relpath(os.path.join(dirpath, fname), root)
|
|
119
|
+
kind = classify(rel)
|
|
120
|
+
if kind:
|
|
121
|
+
found.append((rel, kind))
|
|
122
|
+
return sorted(found)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------- checks
|
|
126
|
+
|
|
127
|
+
def _package_arg(cmd: str, args: List[str]) -> Optional[str]:
|
|
128
|
+
"""Return the package spec an npx/uvx/bunx call will run, or None."""
|
|
129
|
+
i = 0
|
|
130
|
+
while i < len(args):
|
|
131
|
+
a = args[i]
|
|
132
|
+
if a in ("--package", "-p", "--from", "--with") and i + 1 < len(args):
|
|
133
|
+
return args[i + 1]
|
|
134
|
+
if a.startswith(("--package=", "--from=")):
|
|
135
|
+
return a.split("=", 1)[1]
|
|
136
|
+
if a.startswith("-"):
|
|
137
|
+
i += 1
|
|
138
|
+
continue
|
|
139
|
+
return a
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def is_pinned(spec: str) -> bool:
|
|
144
|
+
if "==" in spec:
|
|
145
|
+
return not any(c in spec.split("==", 1)[1] for c in "*")
|
|
146
|
+
body = spec[1:] if spec.startswith("@") else spec
|
|
147
|
+
if "@" not in body:
|
|
148
|
+
return False
|
|
149
|
+
ver = body.split("@", 1)[1].strip()
|
|
150
|
+
if not ver or ver.lower() in ("latest", "next", "canary", "beta"):
|
|
151
|
+
return False
|
|
152
|
+
if any(c in RANGE_CHARS for c in ver) or not ver[0].isdigit():
|
|
153
|
+
return False
|
|
154
|
+
return True
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def check_mcp_servers(rel: str, data: Any) -> List[Finding]:
|
|
158
|
+
out: List[Finding] = []
|
|
159
|
+
if not isinstance(data, dict):
|
|
160
|
+
return out
|
|
161
|
+
servers = data.get("mcpServers")
|
|
162
|
+
if not isinstance(servers, dict):
|
|
163
|
+
servers = data.get("servers") if isinstance(data.get("servers"), dict) else {}
|
|
164
|
+
# ~/.claude.json style: per-project mcpServers blocks
|
|
165
|
+
projects = data.get("projects")
|
|
166
|
+
if isinstance(projects, dict):
|
|
167
|
+
for proj in projects.values():
|
|
168
|
+
if isinstance(proj, dict) and isinstance(proj.get("mcpServers"), dict):
|
|
169
|
+
servers = dict(servers, **proj["mcpServers"])
|
|
170
|
+
for name, cfg in servers.items():
|
|
171
|
+
if not isinstance(cfg, dict):
|
|
172
|
+
continue
|
|
173
|
+
cmd = str(cfg.get("command", "") or "")
|
|
174
|
+
args = cfg.get("args") or []
|
|
175
|
+
args = [str(a) for a in args] if isinstance(args, list) else []
|
|
176
|
+
cmd_parts = cmd.split()
|
|
177
|
+
if len(cmd_parts) > 1: # "npx -y pkg" written as one string
|
|
178
|
+
cmd, args = cmd_parts[0], cmd_parts[1:] + args
|
|
179
|
+
runner = os.path.basename(cmd).lower()
|
|
180
|
+
if runner.endswith(".cmd") or runner.endswith(".exe"):
|
|
181
|
+
runner = runner[:-4]
|
|
182
|
+
if runner in RUNNERS:
|
|
183
|
+
spec = _package_arg(runner, args)
|
|
184
|
+
if spec and not is_pinned(spec):
|
|
185
|
+
out.append(Finding(rel, "unpinned-server",
|
|
186
|
+
"server '%s' runs `%s %s` with no version pin (pin e.g. pkg@1.2.3 or pkg==1.2.3)"
|
|
187
|
+
% (name, runner, spec)))
|
|
188
|
+
for section in ("env", "headers"):
|
|
189
|
+
block = cfg.get(section)
|
|
190
|
+
if not isinstance(block, dict):
|
|
191
|
+
continue
|
|
192
|
+
for key, val in block.items():
|
|
193
|
+
if not isinstance(val, str) or PLACEHOLDER.match(val.strip()) or "${" in val:
|
|
194
|
+
continue
|
|
195
|
+
hits = find_secrets(val)
|
|
196
|
+
if hits:
|
|
197
|
+
for label, prev in hits:
|
|
198
|
+
out.append(Finding(rel, "plaintext-secret",
|
|
199
|
+
"server '%s' %s %s = %s (%s)" % (name, section, key, prev, label)))
|
|
200
|
+
elif SECRETISH_KEY.search(key) and len(val) >= 12 and " " not in val:
|
|
201
|
+
out.append(Finding(rel, "plaintext-secret",
|
|
202
|
+
"server '%s' %s %s = %s (hardcoded value)" % (name, section, key, mask(val))))
|
|
203
|
+
for label, prev in find_secrets(" ".join(args + [str(cfg.get("url", ""))])):
|
|
204
|
+
out.append(Finding(rel, "plaintext-secret", "server '%s' args/url contain %s %s" % (name, label, prev)))
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _rules(settings: List[Dict[str, Any]], key: str) -> List[str]:
|
|
209
|
+
rules: List[str] = []
|
|
210
|
+
for s in settings:
|
|
211
|
+
perms = s.get("permissions") if isinstance(s, dict) else None
|
|
212
|
+
if isinstance(perms, dict) and isinstance(perms.get(key), list):
|
|
213
|
+
rules.extend(str(r) for r in perms[key])
|
|
214
|
+
return rules
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _has_pretooluse(settings: List[Dict[str, Any]]) -> bool:
|
|
218
|
+
for s in settings:
|
|
219
|
+
hooks = s.get("hooks") if isinstance(s, dict) else None
|
|
220
|
+
if isinstance(hooks, dict) and hooks.get("PreToolUse"):
|
|
221
|
+
return True
|
|
222
|
+
return False
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def check_claude_settings(root: str, files: Dict[str, Any], has_env: bool, has_migrations: bool) -> List[Finding]:
|
|
226
|
+
"""files: rel path -> parsed JSON for .claude/settings*.json in the project root."""
|
|
227
|
+
out: List[Finding] = []
|
|
228
|
+
for rel, data in files.items():
|
|
229
|
+
for rule in _rules([data], "allow"):
|
|
230
|
+
for label, prev in find_secrets(rule):
|
|
231
|
+
out.append(Finding(rel, "secret-in-allow-rule",
|
|
232
|
+
"permissions.allow rule contains %s %s; rotate it and allow the command without the token"
|
|
233
|
+
% (label, prev)))
|
|
234
|
+
settings = list(files.values())
|
|
235
|
+
where = ", ".join(sorted(files)) or ".claude/settings.json (missing)"
|
|
236
|
+
hook = _has_pretooluse(settings)
|
|
237
|
+
deny = _rules(settings, "deny")
|
|
238
|
+
if has_env and not hook:
|
|
239
|
+
if not any(re.match(r"^Read\(.*\.env", r) for r in deny):
|
|
240
|
+
out.append(Finding(where, "env-not-denied",
|
|
241
|
+
"project has .env files but no Read deny rule such as \"Read(./.env*)\" and no PreToolUse hook"))
|
|
242
|
+
if has_migrations and not hook:
|
|
243
|
+
tools = {m.group(1) for r in deny for m in [re.match(r"^(Edit|Write|MultiEdit)\(.*migrations", r)] if m}
|
|
244
|
+
if not ({"Edit", "Write"} <= tools):
|
|
245
|
+
out.append(Finding(where, "migrations-not-denied",
|
|
246
|
+
"project has a migrations dir but no Edit and Write deny rules for it and no PreToolUse hook"))
|
|
247
|
+
return out
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def project_flags(root: str) -> Tuple[bool, bool]:
|
|
251
|
+
has_env = has_mig = False
|
|
252
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
253
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
254
|
+
if any(d.lower() == "migrations" for d in dirnames) or os.path.basename(dirpath).lower() == "migrations":
|
|
255
|
+
has_mig = True
|
|
256
|
+
if any(f == ".env" or f.startswith(".env.") for f in filenames
|
|
257
|
+
if not f.endswith((".example", ".sample", ".template", ".dist"))):
|
|
258
|
+
has_env = True
|
|
259
|
+
return has_env, has_mig
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def audit(root: str, extra_files: Iterable[str] = ()) -> Tuple[List[Tuple[str, str]], List[Finding], List[str]]:
|
|
263
|
+
extra_files = list(extra_files)
|
|
264
|
+
"""Return (inventory, findings, notes). Read-only."""
|
|
265
|
+
inventory = discover(root)
|
|
266
|
+
for f in extra_files:
|
|
267
|
+
name = os.path.basename(f)
|
|
268
|
+
inventory.append((f, "settings" if name.startswith("settings") else
|
|
269
|
+
("mcp" if name.endswith(".json") else "rules")))
|
|
270
|
+
findings: List[Finding] = []
|
|
271
|
+
notes: List[str] = []
|
|
272
|
+
claude_settings: Dict[str, Any] = {}
|
|
273
|
+
uses_claude = False
|
|
274
|
+
for rel, kind in inventory:
|
|
275
|
+
path = rel if os.path.isabs(rel) or rel in extra_files else os.path.join(root, rel)
|
|
276
|
+
try:
|
|
277
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
278
|
+
text = fh.read()
|
|
279
|
+
except OSError as exc:
|
|
280
|
+
notes.append("%s: could not read (%s)" % (rel, exc.strerror or exc))
|
|
281
|
+
continue
|
|
282
|
+
if os.path.basename(rel).lower().startswith("claude") or kind == "settings":
|
|
283
|
+
uses_claude = True
|
|
284
|
+
if kind in ("mcp", "settings"):
|
|
285
|
+
try:
|
|
286
|
+
data = json.loads(text)
|
|
287
|
+
except ValueError:
|
|
288
|
+
notes.append("%s: not valid JSON, skipped structured checks" % rel)
|
|
289
|
+
data = None
|
|
290
|
+
for label, prev in find_secrets(text):
|
|
291
|
+
findings.append(Finding(rel, "plaintext-secret", "%s %s" % (label, prev)))
|
|
292
|
+
if data is not None:
|
|
293
|
+
findings.extend(check_mcp_servers(rel, data))
|
|
294
|
+
if kind == "settings":
|
|
295
|
+
if os.path.dirname(rel).replace("\\", "/") == ".claude":
|
|
296
|
+
claude_settings[rel] = data
|
|
297
|
+
else:
|
|
298
|
+
for r in _rules([data], "allow"):
|
|
299
|
+
for label, prev in find_secrets(r):
|
|
300
|
+
findings.append(Finding(rel, "secret-in-allow-rule",
|
|
301
|
+
"permissions.allow rule contains %s %s" % (label, prev)))
|
|
302
|
+
else:
|
|
303
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
304
|
+
for label, prev in find_secrets(line):
|
|
305
|
+
findings.append(Finding("%s:%d" % (rel, n), "plaintext-secret", "%s %s" % (label, prev)))
|
|
306
|
+
if uses_claude or claude_settings:
|
|
307
|
+
has_env, has_mig = project_flags(root)
|
|
308
|
+
findings.extend(check_claude_settings(root, claude_settings, has_env, has_mig))
|
|
309
|
+
return inventory, findings, notes
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def render(root: str, inventory, findings, notes) -> str:
|
|
313
|
+
lines = ["agentconfig-audit-lite %s: %s" % (__version__, os.path.abspath(root)), ""]
|
|
314
|
+
lines.append("Found %d agent config / rule file(s):" % len(inventory))
|
|
315
|
+
for rel, kind in inventory:
|
|
316
|
+
lines.append(" %-9s %s" % (kind, rel))
|
|
317
|
+
if not inventory:
|
|
318
|
+
lines.append(" (none)")
|
|
319
|
+
lines.append("")
|
|
320
|
+
for n in notes:
|
|
321
|
+
lines.append("NOTE " + n)
|
|
322
|
+
if findings:
|
|
323
|
+
lines.append("%d finding(s):" % len(findings))
|
|
324
|
+
for f in findings:
|
|
325
|
+
lines.append(" FAIL [%s] %s: %s" % (f.check, f.path, f.message))
|
|
326
|
+
else:
|
|
327
|
+
lines.append("OK: no findings")
|
|
328
|
+
return "\n".join(lines)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
332
|
+
ap = argparse.ArgumentParser(
|
|
333
|
+
prog="agentconfig-audit-lite",
|
|
334
|
+
description="Read-only audit of MCP configs and AI agent rule files in one project dir. "
|
|
335
|
+
"Exit 0 = clean, 1 = findings, 2 = usage error.")
|
|
336
|
+
ap.add_argument("project", nargs="?", default=".", help="project directory to scan (default: .)")
|
|
337
|
+
ap.add_argument("--file", action="append", default=[], metavar="PATH",
|
|
338
|
+
help="also check this config file, e.g. ~/.cursor/mcp.json (repeatable)")
|
|
339
|
+
ap.add_argument("--version", action="version", version="%(prog)s " + __version__)
|
|
340
|
+
args = ap.parse_args(argv)
|
|
341
|
+
if not os.path.isdir(args.project):
|
|
342
|
+
print("error: not a directory: %s" % args.project, file=sys.stderr)
|
|
343
|
+
return 2
|
|
344
|
+
extra = [os.path.expanduser(f) for f in args.file]
|
|
345
|
+
for f in extra:
|
|
346
|
+
if not os.path.isfile(f):
|
|
347
|
+
print("error: file not found: %s" % f, file=sys.stderr)
|
|
348
|
+
return 2
|
|
349
|
+
inventory, findings, notes = audit(args.project, extra)
|
|
350
|
+
print(render(args.project, inventory, findings, notes))
|
|
351
|
+
return 1 if findings else 0
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
if __name__ == "__main__":
|
|
355
|
+
sys.exit(main())
|