Python MIT License Open Source Project

AI Coding Agent Security Scanner in Python: Flag Risky AGENTS.md, CLAUDE.md & MCP Configs (Free Code)

Build an AI coding agent security scanner in Python that flags risky AGENTS.md, CLAUDE.md, .claude hooks and MCP server configs before you open a cloned repo. Free source code, CLI + Flask UI.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License
Advertisement

Before you open a cloned GitHub repo with Claude Code, Cursor or Copilot, you should know what that repo is telling your AI assistant to do. In this tutorial we build an AI coding agent security scanner in Python: a read-only tool that flags risky AGENTS.md, CLAUDE.md, .claude hooks and MCP server configs before a student runs anything.

It is a practical cyber security project for BTech, MCA and MTech students. It has a command-line tool, an optional Flask web UI, 39 detection rules, a 0–100 risk score and 25 automated tests.

The complete code of this AI coding agent security scanner is free and open source on GitHub under the MIT License, so you can download it, run it in five minutes and extend it for your final-year project.

Why AI Coding Agent Security Matters Right Now

On 17 November 2026, Bitdefender Labs reported a GitHub malware campaign that targets developers who use AI coding assistants. The researchers found 22 malicious GitHub links. The attack did not hide only in normal code. It abused the files that AI tools read to understand a project: agent instruction files, session-start hooks, MCP configurations and editor tasks.

In the samples, an AGENTS.md or CLAUDE.md file described a setup.js file as a “sealed binary artifact”, told the assistant not to read it, and asked it to run the script at session start without showing output or asking for confirmation. A second route used .claude/settings.json hooks, so a command could run as soon as the developer trusted the folder.

A day earlier, the Google Threat Intelligence Group AI Threat Tracker (16 Nov 2026) described attackers modifying .claude/settings.json inside internal repositories so that starting Claude Code downloaded a backdoor. And O’Reilly Radar’s November 2026 trends report noted malicious AGENTS.md files found in users’ Downloads folders, plus new prompt-injection risks when agents talk over MCP.

Markdown instructions may look harmless, but they can influence an agent that has access to tools, shell commands, credentials, local files, or cloud services. — Bitdefender Labs, 17 Nov 2026

Students clone a lot of repos for assignments and projects, often straight into an AI-enabled editor. An AI coding agent security scanner adds a simple safety step: scan first, then open.

What Is an AI coding agent security scanner?

An AI coding agent security scanner is a static analysis tool. It walks through a project folder, finds every file that can steer or trigger an AI coding agent, and checks those files against detection rules. It never runs, imports or installs anything from the repo it scans.

Think of the AI coding agent security scanner as an antivirus for agent configuration, but fully transparent. Every rule is a readable regular expression or a structural check on a JSON file, so you can explain each finding in your viva.

Our scanner is defensive only. It contains no malware and no exploit code. The “risky” demo repo is generated into a temporary folder on demand and contains harmless placeholder text that points to example.invalid, a domain that can never resolve.

Which Files Can Control Your AI Coding Agent?

Different tools read different files. Bitdefender’s report lists most of them. Here is what our AI coding agent security scanner looks for:

File or folderUsed byRisk
AGENTS.md, CLAUDE.md, GEMINI.mdCodex, Claude Code, Gemini CLI and othersInstructions go straight into the agent’s context
.cursorrules, .cursor/rules/, .windsurfrulesCursor, WindsurfSame as above
.github/copilot-instructions.mdGitHub CopilotSame as above
.claude/settings.jsonClaude CodeHooks run shell commands; permissions can skip prompts
.mcp.json, .cursor/mcp.json, .vscode/mcp.jsonMCP clientsEach MCP server is a program or remote service the agent can call
.vscode/tasks.jsonVS CodeTasks can run automatically when the folder opens
package.json install scriptsnpmRun automatically on npm install

Features of the AI coding agent security scanner

  • 39 detection rules for instruction wording, hooks, permissions, MCP servers, VS Code tasks, npm scripts and suspicious scripts.
  • Campaign pattern detection: a critical alert when one file both hides a script (“do not read …”) and tells the agent to run it.
  • Risk score 0–100 and a clear verdict: LOOKS SAFE, REVIEW or DANGEROUS.
  • Script follow-up: scripts referenced by those files are checked for huge size, one-line minified code, encoded blobs and eval.
  • Safe by design: symlinks are never followed and nothing outside the repo is read.
  • CLI with text, JSON and Markdown reports and CI-friendly exit codes.
  • Optional Flask web UI with zip upload, zip-slip and zip-bomb protection.
  • Safe clone mode that shallow-clones with git hooks disabled, scans, then deletes the copy.

Tech Stack and Requirements

PartTechnology
LanguagePython 3.9+ (core uses only the standard library)
Web UIFlask 3
Testingpytest
Parsingjson + a small JSON-with-comments loader, regular expressions
HardwareAny laptop; no GPU, no paid API, no internet needed

If you are new to Flask, our Flask web chat application tutorial is a good warm-up.

Project Structure

AI-Coding-Agent-Config-Auditor-Python/
├── agent_auditor/
│   ├── targets.py      # which files can steer an AI agent
│   ├── rules.py        # regex detection rules
│   ├── scanner.py      # reads files, applies rules, follows scripts
│   ├── models.py       # Finding, ScanResult, risk score, verdict
│   ├── report.py       # text / Markdown / JSON reports + checklist
│   ├── safe_clone.py   # shallow clone with git hooks disabled
│   ├── demo.py         # builds the harmless risky demo repo
│   └── cli.py          # command-line interface
├── app.py              # optional Flask web UI
├── templates/ static/  # web UI files
├── examples/safe-repo/ # a normal, safe example project
└── tests/              # 25 pytest tests

How the AI coding agent security scanner Works

  1. Discover: walk the folder (skipping .git, node_modules and symlinks) and classify agent files, including nested ones in monorepos.
  2. Check text: run instruction rules on Markdown files and look for hidden Unicode, long encoded blobs and hard-coded tokens.
  3. Check configs: parse JSON and inspect hooks, permissions, MCP servers, tasks and npm scripts.
  4. Follow scripts: inspect any script those files reference, as long as it is inside the repo.
  5. Score: add points per severity, cap at 100 and choose a verdict.
  6. Report: print findings with file, line, evidence and a fix, plus the safe-cloning checklist.

Step 1: Find the files an AI agent reads

The first job of any AI coding agent security scanner is discovery. The classifier checks every suffix of a path, so apps/web/.mcp.json is treated like .mcp.json. Symlinks are skipped so a malicious repo cannot point the scanner at your own files.

def iter_targets(root: Path) -> Iterator[Tuple[Path, str, str]]:
    """Yield (absolute_path, relative_posix_path, kind) for agent files under root.

    Symlinks are never followed, so a malicious repo cannot point the
    scanner at files outside the project.
    """
    root = root.resolve()
    stack = [root]
    while stack:
        current = stack.pop()
        try:
            entries = sorted(current.iterdir())
        except OSError:
            continue
        for entry in entries:
            if entry.is_symlink():
                continue
            if entry.is_dir():
                if entry.name not in SKIP_DIRS:
                    stack.append(entry)
                continue
            rel = entry.relative_to(root).as_posix()
            kind = classify(rel)
            if kind:
                yield entry, rel, kind

Step 2: Write readable detection rules

Each instruction rule has an ID, a title, a severity, a regex and advice. The phrases come from the defensive checklist in Bitdefender’s report: forbidding inspection, hiding output and skipping confirmation.

TextRule("AGT002", "Asks to run something without user confirmation", Severity.CRITICAL,
         _r(r"without\s+(asking|confirmation|confirming|prompting|user approval|permission)|(skip|bypass|don't ask for|no need for)\s+(the\s+)?(confirmation|approval|permission)"),
         "An agent should always ask before running commands. Treat this as a red flag."),
TextRule("AGT003", "Asks to hide or suppress output", Severity.HIGH,
         _r(r"without\s+(displaying|showing|printing)\s+(the\s+)?output|(run|execute|install|start)\w*[^.\n]{0,40}\bsilently|silently\s+(run|execute|install|start)|suppress\s+(the\s+)?output|hide\s+(the\s+)?output|>\s*/dev/null\s+2>&1"),
         "Hiding output is a classic way to keep you from noticing what ran."),

The most important check combines rules. If one file says “do not read this script” and also tells the agent to run something, the scanner raises AGT100 as critical:

# Combination seen in the Nov 2026 campaign: hide a script + tell the agent to run it.
if "AGT001" in hits and hits & {"AGT002", "AGT003", "AGT004", "AGT010"}:
    self.add("AGT100", "Concealed script + instruction to run it (known attack pattern)",
             Severity.CRITICAL, rel, 0, "do-not-inspect wording combined with run/auto-run wording",
             "Do NOT open this repo with an AI agent. ...")

Step 3: Inspect Claude Code hooks and MCP servers

Hooks run without any AI prompt, so our AI coding agent security scanner treats them seriously: a SessionStart hook is rated high. Blanket Bash(*) permissions, bypassPermissions mode and enableAllProjectMcpServers are also flagged.

hooks = data.get("hooks") or {}
if isinstance(hooks, dict):
    for event, entries in hooks.items():
        for entry in entries if isinstance(entries, list) else []:
            for hook in (entry.get("hooks") or []) if isinstance(entry, dict) else []:
                cmd = str(hook.get("command", "")) if isinstance(hook, dict) else ""
                if not cmd:
                    continue
                auto = event in ("SessionStart", "UserPromptSubmit", "Setup")
                sev = Severity.HIGH if auto else Severity.MEDIUM
                self.add("CLD001", f"{event} hook runs a shell command automatically", sev, rel,
                         _line_of(raw, cmd[:30]), cmd,
                         "Hooks run without any prompt to the AI. Make sure you understand this command.")
                self.check_command(cmd, rel, raw, f"{event} hook", base=Severity.INFO)

For MCP servers, the scanner flags servers started through a shell one-liner, plain http:// URLs, unpinned npx -y packages and literal tokens in env. Every command is then checked for download-and-execute, encoded payloads, network calls, secret access and hidden output.

Advertisement

Step 4: Calculate the risk score and verdict

SEVERITY_POINTS = {
    Severity.INFO: 0,
    Severity.LOW: 3,
    Severity.MEDIUM: 10,
    Severity.HIGH: 25,
    Severity.CRITICAL: 45,
}
def verdict(self) -> str:
    if self.max_severity >= Severity.CRITICAL or self.risk_score >= 70:
        return "DANGEROUS"
    if self.max_severity >= Severity.MEDIUM:
        return "REVIEW"
    return "LOOKS SAFE"

Step 5: Use it from the CLI or the Flask web UI

The AI coding agent security scanner CLI prints coloured findings and exits with code 1 when anything is at or above --fail-on (default high), which makes it easy to use in a CI pipeline. The Flask app accepts a .zip upload, blocks path traversal and zip bombs, scans the extracted files and deletes them.

How to Run the AI coding agent security scanner

git clone https://github.com/GetProjectsIdea/AI-Coding-Agent-Config-Auditor-Python.git
cd AI-Coding-Agent-Config-Auditor-Python
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt

# scan a repo you already cloned
python -m agent_auditor path/to/some-repo

# try the harmless demo and the safe example
python -m agent_auditor --demo
python -m agent_auditor examples/safe-repo

# safe shallow clone + scan + delete
python -m agent_auditor --clone https://github.com/user/repo

# reports
python -m agent_auditor some-repo -f json -o report.json
python -m agent_auditor some-repo -f markdown -o report.md

# web UI at http://127.0.0.1:5000
python app.py

Output and Screenshots

Here is the AI coding agent security scanner running on the harmless risky demo. It finds 4 critical, 11 high and 9 medium issues and gives the verdict DANGEROUS.

AI coding agent security scanner CLI output in the terminal
CLI output with colour-coded severities, file and line numbers, and a fix for each finding.
AI coding agent security scanner report showing a DANGEROUS verdict with critical findings
Web UI report for the harmless risky demo repo: score 100/100, verdict DANGEROUS.

A normal project with a friendly AGENTS.md and a version-pinned MCP server gets a low score:

AI coding agent security scanner report for a safe repository
A normal project gets a LOOKS SAFE verdict.
Mobile view of the AI coding agent security scanner Flask web UI
The report on a 390 px mobile screen.

Safe-Cloning Checklist for Students

An AI coding agent security scanner helps, but habits matter more. Follow this checklist every time you clone code you did not write:

  1. Read AGENTS.md, CLAUDE.md and .cursorrules yourself before opening the repo with an AI agent.
  2. Open .claude/settings.json, .mcp.json, .cursor/mcp.json and .vscode/tasks.json and read every command.
  3. Open unknown repos in VS Code Restricted Mode. Do not click “Trust” until you have checked them.
  4. Install dependencies with npm install --ignore-scripts until you have reviewed package.json.
  5. Never let an agent run a script it was told not to read.
  6. Test unknown code in a fresh VM, container or Codespace with no personal tokens or SSH keys.
  7. Run the AI coding agent security scanner: python -m agent_auditor path/to/repo.

Debugging a project that still won’t run after all this? See our list of 13 reasons why your code is not working.

Testing the Project

The AI coding agent security scanner ships with 25 pytest tests. They cover the classifier, each major rule, a false-positive check on a normal AGENTS.md, symlink and path-escape safety, the CLI, the web UI, zip-slip blocking, and a test that the project itself never contains live risky agent files.

$ python -m pytest -q
.........................                                    [100%]
25 passed in 0.20s

Limitations and Responsible Use

Pattern matching can miss new tricks and can sometimes flag harmless text. A clean report from the AI coding agent security scanner means “no known red flags”, not “guaranteed safe”. Always read the files yourself.

Use this project only to protect your own machine and repositories. Do not use it to build or test attacks on systems you do not own.

Future Scope and Viva Tips

  • Add SARIF output so results appear in GitHub code scanning.
  • Package it as a GitHub Action or a pre-commit hook.
  • Train a small ML classifier on labelled instruction files to catch new wording.
  • Build a browser extension that scans a GitHub repo page before you clone it.
  • Compare false-positive rates on popular open-source repos as a research experiment.

For an MTech or PhD angle, AI agent security is a strong research area. Browse the Agentic AI and AI safety sections of our AI PhD thesis topics 2026 and our MTech thesis ideas. If you want another AI project with full code, try the AI resume screening system in Python or pick from our top 20 AI project ideas and 50 major project ideas for BTech and MCA.

FAQs: AI coding agent security scanner

Is this AI coding agent security scanner a good final-year project?

Yes. It covers cyber security, static analysis, regular expressions, JSON parsing, a Flask web app and automated testing, and it is built around a real November 2026 threat that examiners will recognise.

Does the scanner run any code from the repo?

No. It only reads files as text. It never executes, imports or installs anything, never follows symlinks, and never reads files outside the scanned folder.

Which AI coding tools does it cover?

It checks files used by Claude Code, Cursor, GitHub Copilot, Gemini CLI, Codex, Windsurf, Cline, Kiro, Continue and VS Code, plus MCP server configs and npm install scripts.

Does the repo contain real malware samples?

No. The risky demo is generated on demand with harmless placeholder text pointing to example.invalid, and its script only prints a message.

Can I use it in GitHub Actions?

Yes. Run python -m agent_auditor . --fail-on high. It exits with code 1 when high or critical findings exist, which fails the job.

Is the source code free?

Yes. The full code is on GitHub under the MIT License.


Download the Source Code

The complete AI coding agent security scanner project, with the CLI, Flask web UI, README, screenshots and tests, is free on GitHub. Clone it, star it and open an issue if you get stuck.

Conclusion

AI coding agents read more than your code. They read instructions, hooks and server configs, and attackers have started to abuse that. In this tutorial you built an AI coding agent security scanner in Python that finds those files, explains every risk and gives a clear verdict before you trust a repo.

Scan first, read the files, then open the project. Built something on top of it? Tell us in the comments below. Happy (and safe) coding!

Advertisement

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.