Dev.to Security 🔐 Cybersecurity 👁 0 📖 9 min read

Building a .env secret scanner MCP server in 2026

Building a .env secret scanner MCP server in 2026 Build a tiny FastMCP server in Python with one tool, scan_env_file. It parses the file locally, matches key patterns for OpenAI, Anthropic, AWS, Stripe and GitHub, fla

Building a .env secret scanner MCP server in 2026

Build a tiny FastMCP server in Python with one tool, scan_env_file. It parses the file locally, matches key patterns for OpenAI, Anthropic, AWS, Stripe and GitHub, flags high-entropy values and weak defaults, and returns masked findings. The agent gets line numbers and key names. It never sees the secret itself. The server is under 100 lines, needs no API keys, and works in Claude Code and Claude Desktop.

The .env Security Scanner I link to below is one I built. Before writing it I tried four online secret checkers, and all four wanted my .env pasted into a form that posted to their server. That's a strange thing to ask of a file full of secrets. Mine runs client-side in your browser. It's free, there's no signup and nothing gets uploaded. If you have a better one, tell me.

What we're building and how to wire it up

On Wednesday, October 21, I asked Claude Code to untangle the config loading in a side project. Reasonable request. It opened .env to "understand the variables", and my Stripe test key and a live OpenAI key scrolled past in the transcript. I didn't care about the test key. I rotated the OpenAI one within ten minutes. That was the right call, and it was also an irritating way to spend a Wednesday night.

So here's the goal. I wanted an MCP tool the agent calls instead of reading the file. You ask "is my .env safe to commit?" and the model gets back something like line 7, OPENAI_API_KEY, openai, sk-p...(164 chars). It can tell you which keys look live, suggest a secrets manager, or write a .env.example, and the raw value stays inside the server process. The useful result is a short, boring list of line numbers. That's the outcome I wanted.

Auth, such as it is

A stdio MCP server has no tokens or OAuth. The client spawns it as a child process, and it runs with your user's file permissions. That's the scary part. A tool that takes a path argument can read ~/.ssh/id_ed25519 just as easily as .env. The one piece of "auth" I added is a root directory in ENV_SCANNER_ROOT. The tool refuses any path that resolves outside it, symlinks included, because Path.resolve() follows them before the check.

You need Python 3.10 or newer (the mcp package requires it) and uv. For Claude Code, one command registers the server:

claude mcp add --transport stdio env-scanner --env ENV_SCANNER_ROOT=$HOME/code -- uv run --with "mcp[cli]" mcp run /Users/you/tools/env_scan.py

Claude Desktop needs an entry in ~/Library/Application Support/Claude/claude_desktop_config.json. Two gotchas cost me time here:

  • PATH isn't your shell's PATH. GUI apps on macOS don't read your .zshrc, so "command": "uv" failed with spawn uv ENOENT. Run which uv and paste the absolute path (mine is /Users/me/.local/bin/uv).
  • The working directory isn't your project. The server gets launched from somewhere you didn't choose, so ./.env resolves to nonsense. Use absolute paths for the script and in every tool call. I put that requirement in the tool's docstring so the model knows to send them.

The scanner itself

I ported the key patterns from the browser version I'd already written. If you only need to check one file before a commit and don't want to wire up MCP at all, paste it into the .env Security Scanner and you're done. For agent use, this is the whole server:

# env_scan.py
# Run: uv run --with "mcp[cli]" mcp run env_scan.py
import math
import os
import re
import sys
from collections import Counter
from pathlib import Path

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("env-scanner")

# Only files under this directory can be scanned. Defaults to $HOME.
ROOT = Path(os.environ.get("ENV_SCANNER_ROOT", str(Path.home()))).resolve()

# ORDER MATTERS: Anthropic keys also start with "sk-", so test them before OpenAI.
PATTERNS = [
    ("anthropic", re.compile(r"sk-ant-[A-Za-z0-9_\-]{20,}")),
    ("openai", re.compile(r"sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{20,}")),
    ("aws_access_key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
    ("stripe", re.compile(r"\b(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{24,}")),
    ("github", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})")),
]

WEAK_VALUES = {"changeme", "password", "secret", "admin", "test", "123456", "example"}
SENSITIVE_KEY = re.compile(r"SECRET|PASSWORD|PASSWD|TOKEN|API_KEY|PRIVATE", re.I)
HEX_ONLY = re.compile(r"[0-9a-fA-F]{32,}")


def shannon_entropy(s: str) -> float:
    n = len(s)
    return -sum(c / n * math.log2(c / n) for c in Counter(s).values())


def mask(value: str) -> str:
    # Never hand the raw secret back to the model. This is the whole point.
    if len(value) <= 8:
        return "*" * len(value)
    return f"{value[:4]}...({len(value)} chars)"


def parse_env(text: str):
    for lineno, raw in enumerate(text.splitlines(), start=1):
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        if line.startswith("export "):
            line = line[len("export "):]
        key, _, value = line.partition("=")
        value = value.strip()
        if len(value) > 1 and value[0] in "'\"" and value.endswith(value[0]):
            value = value[1:-1]
        elif " #" in value:
            # Unquoted inline comment. A password containing " #" gets cut here.
            value = value.split(" #", 1)[0].rstrip()
        yield lineno, key.strip(), value


@mcp.tool()
def scan_env_file(path: str) -> dict:
    """Scan a .env file for leaked API keys, high-entropy secrets and insecure
    defaults. Returns masked findings only. `path` must be ABSOLUTE and inside
    ENV_SCANNER_ROOT. Do not read the .env file directly; call this instead."""
    target = Path(path).expanduser().resolve()
    if not target.is_relative_to(ROOT):
        return {"error": f"refusing to read outside {ROOT}"}
    if not target.is_file():
        return {"error": f"not a file: {target}"}

    findings = []
    text = target.read_text(encoding="utf-8", errors="replace")
    for lineno, key, value in parse_env(text):
        hit = next((name for name, rx in PATTERNS if rx.search(value)), None)
        if hit:
            findings.append({"line": lineno, "key": key, "type": hit,
                             "severity": "high", "value": mask(value)})
            continue
        if value.lower() in WEAK_VALUES and SENSITIVE_KEY.search(key):
            findings.append({"line": lineno, "key": key, "type": "insecure_default",
                             "severity": "medium", "value": mask(value)})
            continue
        if key.upper() == "DEBUG" and value.lower() in ("1", "true", "yes"):
            findings.append({"line": lineno, "key": key, "type": "debug_enabled",
                             "severity": "low", "value": value})
            continue
        # Hex tops out at 4 bits/char, so it needs a lower bar than base62/base64.
        threshold = 3.5 if HEX_ONLY.fullmatch(value) else 4.0
        if len(value) >= 24 and shannon_entropy(value) > threshold:
            findings.append({"line": lineno, "key": key, "type": "high_entropy",
                             "severity": "medium", "value": mask(value)})

    # stderr only. Anything on stdout corrupts the JSON-RPC stream.
    print(f"scanned {target}: {len(findings)} findings", file=sys.stderr)
    return {"file": str(target), "count": len(findings), "findings": findings}


if __name__ == "__main__":
    mcp.run()

A few notes on the parts that bit me. The masked value keeps four characters, which sounds risky until you notice those four are basically the provider tag (sk-a, AKIA, ghp_). The model needs that much to say "this looks like a GitHub token". The length helps too, because a 164-character sk-proj- string is a different animal from a 51-character legacy key.

The parser is deliberately dumb. It doesn't handle multiline values or ${VAR} interpolation. If your .env relies on those, swap parse_env for dotenv_values from python-dotenv. I didn't, because I wanted zero dependencies beyond mcp, and none of my files use them.

How it stacks up against gitleaks and TruffleHog

I'm not pretending a 95-line script competes with real secret scanners. They solve a different problem, at a different moment in the workflow.

This MCP server Gitleaks TruffleHog
Who calls it The agent, mid-conversation You or a pre-commit hook You or CI
Scans git history No, one file at a time Yes Yes
Checks whether a key is live No No Yes, for many detectors
Output safe to hand an LLM Masked by default Only with --redact Raw value in JSON output, filter it first
Rule coverage 5 providers plus entropy Large default ruleset Hundreds of detectors
Setup One claude mcp add line Single binary Single binary

If I were setting up a team repo tomorrow, I'd put gitleaks in pre-commit and TruffleHog in CI and not lose sleep. The MCP server is for the moment when an agent is about to touch config and you want it to know what's sensitive without reading it. You could also wrap gitleaks detect --no-git --redact in an MCP tool and get a much bigger ruleset for free. I might do that next, honestly. The custom version was faster to reason about, and I wanted to understand every line of what the model gets to see.

What went wrong the first time

Plenty. In rough order of how dumb I felt:

I returned the raw values. My first version put "value": value in every finding. It worked perfectly. The model said "your OpenAI key on line 7 is exposed" and then quoted the key back to me. The secret ended up in the transcript anyway, which was the exact thing I'd built this to prevent. The mask() function exists because of that afternoon.

Anthropic keys came back as OpenAI keys. Both prefixes start with sk-, and the OpenAI regex is loose enough to swallow sk-ant-api03-... whole. Python dicts keep insertion order, so my original dict happened to work. Then I alphabetized it during a cleanup and broke detection without noticing for two days. I changed it to a list with a comment shouting about order.

A debug print() killed the server. I added print(f"found {hit}") while testing, and Claude Desktop started reporting the server as disconnected with a JSON parse error in the logs. Stdio transport means stdout is the protocol channel, so any stray print is a malformed message. It took me 47 minutes to find, mostly because I kept staring at the regex. Everything diagnostic goes to sys.stderr now.

The entropy threshold is a guess. I started at 4.5 bits per character and it missed every hex-encoded secret, because hex can't exceed 4.0 by definition (16 symbols, log2 of 16). Dropping to 4.0 globally flagged a bunch of long URLs. The split threshold in the code above is what I landed on after running it against 11 old .env files I had lying around. That came to 382 lines and produced 9 false positives, all of them DATABASE_URL values with embedded passwords. I'm keeping those. A Postgres URL with a password in it probably should get flagged. I don't know if 4.0 holds up on other people's files, though, and I'd like to hear if it doesn't.

The model kept reading the file anyway. Even with the tool registered, Claude sometimes just opened .env with its file-read tool, because that's the obvious move. The fix that mostly worked was the last line of the docstring: "Do not read the .env file directly; call this instead." Tool descriptions are effectively prompts. In Claude Code I also added .env to the deny list in project settings so a direct read gets blocked outright. That's the belt to the docstring's suspenders.

FAQ

Q: Why not let the agent run gitleaks through a shell tool?

A: You can, and it's a fine setup if you remember --redact. Without that flag the finding includes the secret, and you're back to leaking it into the transcript. I'd rather the safe output be the default and not something the model has to remember.

Q: Does this work outside Claude?

A: Yes. Any MCP client that speaks stdio can launch it, including Cursor, VS Code with MCP support and the MCP Inspector (uv run --with "mcp[cli]" mcp dev env_scan.py). The Inspector is also the quickest way to test the tool without an LLM in the loop.

Q: Should the scanner also check whether .env is gitignored?

A: Probably. It's a ten-line addition with git check-ignore, and it'd catch the most common real leak. I left it out to keep the example focused, but it's on my list.

Q: Is keeping four characters of each key really safe?

A: For the providers covered here, the first four characters are a public prefix, so you're disclosing the key type and nothing more. If you have custom internal tokens where the prefix carries meaning, set mask() to show zero characters.

Written with AI assistance and human review. Try the tool at aidevhub.io/env-security-scanner.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.