mcp-guard

by sainitish1609

Not rated
GitHub

About

MCP server: redacts secrets from tool results, defends against prompt injection, and blocks agent writes to sensitive paths.

Details

Author
sainitish1609
Categories
Other

Setup

Install mcp-guard in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/sainitish1609/mcp-guard

Follow the installation instructions in the repository README, then restart your MCP client.

The local privacy firewall, prompt-injection shield, secret sanitizer, and token compressor for AI coding agents.

A zero-dependency security proxy for Model Context Protocol (MCP) servers.

mcp-guardis an ultra-fast, zero-dependency Go binary that sits transparently between your editor (Claude Code, Cursor, VS Code, Copilot) and anyModel Context Protocol (MCP)server — overstdioorHTTP/SSE.

It ensures your API keys, database credentials, and protected paths (~/.ssh,.env,.git) arenever leaked to cloud LLMs, that malicious contentcannot hijack your agent, and that autonomous tool executioncannot touch what it shouldn't— all while trimming token spend.

When AI agents run tools like@modelcontextprotocol/server-filesystemorpostgres-mcp, they read raw files and query results straight off your machine. Three things go wrong:
- Secrets leak.A file with AWS keys, JWTs, or DB passwords gets shipped verbatim to a cloud LLM.
- Agents get hijacked.A file or web page can carryhidden instructions— invisible Unicode or "ignore all previous instructions" — that the model obeys (prompt injection / tool poisoning).
- Agents overreach.An autonomous agent overwrites~/.ssh/authorized_keys, pipescurl … | bash, or reads 100 files in a burst.

mcp-guardrunslocallyand fixes all three without breaking agent execution:

- 🔒Zero-Trust I/O Inspection— intercepts both requests and responses on every transport.
- ⚡Zero-Dependency Go Binary— pure standard library, sub-millisecond overhead.
- 🔄Recoverable Guardrail Errors— returns structuredisError: trueresults so agents self-correct instead of crashing.
- 📊Visible Value— a session summary shows exactly what it protected and how many tokens/dollars it saved.

🎯 Threat Model — what this does and doesn't replace

mcp-guardisdefense-in-depth for the agent boundary, not a replacement for good security hygiene. Being precise about that matters more than sounding impressive.

- Short-lived credentials.If you can use STS / OIDC federation / SSO, do that first — it is the stronger control. Rotation shrinks the blast radius;mcp-guardreduces the chance of disclosure in the first place. They solve different halves, and the credential fix is the more important one.
- A secrets manager or least-privilege IAM.A key that was never on disk cannot be read off disk.
- Reviewing what your agent actually does.Guardrails constrain the blast radius; they do not make an unreviewed agent trustworthy.

Known limitations — read these before relying on it

- Detection is heuristic.Named-pattern secret matching is high-precision and masks by default; the entropy catch-all is lower-precision (it fires on integrity hashes and base64 fixtures) so it isaudit-only by defaultand only masks when you opt in. Injection detection is signature-based. A novel credential format or a carefully-worded injectionwillget through — treat it as a layer, not a guarantee.
- It only sees traffic that flows through it.An MCP server that makes its own outbound network calls (afetch-style server, telemetry, a phone-home) is invisible tomcp-guard. It secures the client↔server channel, not the server's own egress.
- Request-side secret scanning warns, it does not block.Some tools legitimately need credentials in their arguments, so blocking by default would break them.
- Compression can alter text.It is off by default and skips read-for-edit tools, because rewriting a file the agent is about to patch corrupts the diff.
- It does not authenticate the MCP server.A malicious server can still return wrong (if sanitized) answers. Injection defense reduces that risk; it does not eliminate it.

If you find a case where a real secret or injection payload slips through, that is a bug worthopening an issuefor — false negatives and false positives are both regressions.

┌─────────────────────────┐ ┌────────────────────────────────────┐ ┌─────────────────────────┐ │ │ request │ mcp-guard │ request │ │ │ Editor / MCP Client ├─────────►│ ┌──────────────────────────────┐ ├─────────►│ MCP Server │ │ │ │ │ → guardrails · shell block │ │ │ (filesystem, postgres, │ │ (Claude Code / Cursor │ │ │ rate-limit · req-secrets │ │ │ github, http, …) │ │ / VS Code / Copilot) │◄─────────┤ │ ← redact · entropy · inject │ │◄─────────┤ │ │ │ response │ │ defense · compression │ │ response │ │ └─────────────────────────┘ │ └──────────────────────────────┘ │ └─────────────────────────┘ │ stdio · HTTP / SSE · audit │ └────────────────────────────────────┘

1. 🔑 Secret & Credential Redaction (Server ➔ Client)

Scansevery stringin a tool result — includingstructuredContentmirrors and tool descriptions — for 12+ credential formats before they reach the LLM:

- Cloud & AI keys:AWS (AKIA…), Anthropic, OpenAI, Stripe, Google, Slack, GitHub PATs.
- Database URIs:masks the password inpostgres://user:pass@host,mongodb+srv://,redis://:pass@host— even passwords containing@.
- Private keys & JWTs:full-block masking for RSA/PEM keys and Bearer tokens.
- 🆕 High-entropy catch-all (audit-only by default):a Shannon-entropy pass flagsunknown-formatgenerated secrets that match no named pattern, using a character-class discriminator to avoid git SHAs, UUIDs, and file paths. Because the heuristic also fires on integrity hashes, base64 fixtures, and signed URLs, itreportsby default (logging the detector and byte offsets) and only masks when you opt in with--entropy-maskor--profile strict. This keeps it from silently corrupting otherwise-valid structured data.

# Before mcp-guard: AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE DATABASE_URL=postgres://admin:P@ssw0rd123!@db.internal:5432/prod SESSION=nQ7wLp4sZa1cFd8gHj0tYuXk9mR2vB3E # After mcp-guard: AWS_ACCESS_KEY_ID=[REDACTED:aws-access-key] DATABASE_URL=postgres://admin:[REDACTED:uri-credentials]@db.internal:5432/prod SESSION=[REDACTED:high-entropy] # entropy match — masked under --entropy-mask / --profile strict; # audit-only (logged, not masked) by default

2. 🧬 Prompt-Injection & Tool-Poisoning Defense 🆕

Content coming back from a server (file bodies, web pages, even amalicious server's own tool descriptions) can carry instructions aimed at your agent. mcp-guard neutralizes both vectors:

- Hidden Unicode— strips invisible "tag" characters (U+E0000block used to smuggle invisible ASCII), bidirectional-override controls, and zero-width spaces. Legitimate script/emoji joiners are preserved.
- Injection directives— high-signal phrases like"ignore all previous instructions","do not tell the user", or"reveal your system prompt"are replaced with a visible[mcp-guard: neutralized-injection]marker (or detect-only, your choice).

3. 🛡️ Directory Guardrails & Write Protection (Client ➔ Server)

Blocks agents from modifying protected paths — through relative traversal (../.ssh)and symlink escapes🆕 (aproject/data → ~/.sshlink is resolved and caught):

- Protected directories (anywhere in the path):~/.ssh,.aws,.gnupg,.kube,.git,.env
- Sensitive files:id_rsa,id_ed25519,authorized_keys,.npmrc,.netrc,.pypirc,.dockercfg
- Shell-script blocking:refuses
.sh/.ps1,bash -c, andcurl … | shpatterns by default.
- 🆕 Optional sensitive-read blocking:hard-block
readsof protected paths (default: allow the read and redact its contents instead).

4. 🚦 Exfiltration & Anomaly Guardrails 🆕

A behavioral layer on top of per-call checks:

- Rate limiting— throttle runaway or compromised agents past a calls-per-minute cap.
- Read-burst detection— warns on a sudden spike of distinct file reads (a classic bulk-exfiltration signature).
- Outbound secret scanning— warns when a
tool call's argumentscarry secret-shaped data, so a key the agent just read can't silently be forwarded to a phone-home server unnoticed.

Strips redundant comments and whitespace to save context-window capacity, with a code-aware token estimator for accurate accounting.

Compression automatically skips read-for-edit tools (read_file,get_file_contents) to preserve exact diff boundaries for safe file editing.*

6. 📊 Session Summary & Structured Audit 🆕

- On exit (and onSIGUSR1) mcp-guard prints asummary: secrets redacted by type, writes/reads/shell blocked, injections neutralized, tokens saved, and anestimated$saved.
- All activity streams tostderras human text orJSON Lines(--log-format json) for SIEM ingestion. stdout carries only the MCP protocol.

mcp-guard session summary secrets redacted 4 aws-access-key 1 uri-credentials 1 high-entropy 2 writes blocked 1 injections neutralized 3 tokens saved 1840 est. cost saved $0.0055

7. 🎛️ Policy Profiles & Hot Reload 🆕

- Profilesapply per-server strictness in one flag:--profile strict|standard|permissive(e.g. lock down a shell server, relax a read-only docs server).
- Hot reload— sendSIGHUPto re-read the config and swap policy live, without dropping the agent connection.

Prebuilt binary(no Go toolchain required) — grab it from thelatest release:

# macOS (Apple Silicon) — swap darwin_arm64 for your platform curl -sSL https://github.com/sainitish1609/mcp-guard/releases/latest/download/mcp-guard_darwin_arm64.tar.gz | tar xz sudo mv mcp-guard /usr/local/bin/
go install github.com/sainitish1609/mcp-guard/cmd/mcp-guard@latest
git clone https://github.com/sainitish1609/mcp-guard.git cd mcp-guard go build -o mcp-guard ./cmd/mcp-guard

Builds for macOS, Linux, and Windows (amd64 + arm64). Every protection works on all platforms; theSIGHUP/SIGUSR1signal hooks are Unix-only, and the end-of-session summary still prints on exit everywhere.

Wrap any standard MCP server command usingmcp-guard --:

claude mcp add postgres -- mcp-guard --profile strict --max-tokens 4000 -- npx -y @modelcontextprotocol/server-postgres
{ "mcpServers": { "filesystem": { "command": "mcp-guard", "args": [ "--redact-secrets", "--scan-injection", "--block-shell", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/Users/username/projects" ] } } }

Protect aremoteMCP server that speaks Streamable-HTTP/SSE — same pipeline, no child process:

mcp-guard --profile strict --http-listen :8080 --http-upstream https://my-mcp-host.example/mcp

Point your client athttp://localhost:8080and every JSON and SSE message is inspected in flight.

Signals:SIGHUPreloads config live ·SIGUSR1prints an interim session summary.

# Run unit and integration tests go test ./... -v # Run static analysis go vet ./...

Try it end-to-end against a real server:

printf '%s\n%s\n' \ '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"x","version":"1"}}}' \ '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_text_file","arguments":{"path":"/path/to/a/.env"}}}' \ | mcp-guard --profile strict -- npx -y @modelcontextprotocol/server-filesystem /path/to

Distributed under the MIT License. SeeLICENSEfor details.

Transaction-complete hotel booking over MCP — 300K+ properties, real hotel confirmation numbers, loyalty points, secure checkout. Hotels are merchant of record. Builders set their own booking fee via Stripe Connect. Built on proven distribution infrastructure.

An MCP server for AI video generation. MCP server for AI video generation. Lets Claude, ChatGPT, OpenClaw , Hermes & other agents create AI videos and publish them to YouTube, TikTok, Instagram etc..

Institutional research and manager diligence reports on hedge funds, venture capital and private equity managers. Summary of filings, personnel changes, media screening and social signals delivered to you in minutes.

ALTER - identity infrastructure for the AI economy

D2C eCommerce fulfillment platform: manage orders, inventory, shipments, campaigns, and billing via AI agents

Apigene MCP Gateway is the runtime layer that connects AI agents to APIs and MCP servers via Model Context Protocol.

MCP to interface with multiple blockchains, staking, DeFi, swap, bridging, wallet management, DCA, Limit Orders, Coin Lookup, Tracking and more.

MCP server for Bitnovo Pay integration with AI agents. Provides cryptocurrency payment capabilities through Bitnovo Pay API. Features include payment creation, status checking, QR code generation, and webhook management with support for multiple tunnel providers (ngrok, zrok, manual).

Shop for gift cards, esims, phone topups. Pay with cards and crypto.

You built it, now get users! GoToMarket MCP server

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.