mcp-guardian
🛡️ MCP Guardian
Security, cost, and health audit for MCP infrastructure.
Always use the latest version:
npm install -g @mcp-guardian/server@latest— current is v1.3.5. See the Changelog for full version history and GitHub Releases for per-version source tags.
MCP Guardian is a security and governance proxy for Model Context Protocol (MCP) infrastructure. It sits between AI clients and MCP servers, enforcing active security policies, tracking real token costs, and monitoring health — all while providing enterprise-grade observability and audit trails.
Key positioning: Runtime governance and security proxy for MCP infrastructure — with threat modeling, semantic shell analysis, mTLS, and zero-trust networking.
It works as both an MCP server (so AI assistants like Cline/Claude can invoke its tools) and a standalone CLI.
Table of Contents
Related MCP server: SentinelGate
Why MCP Guardian?
As MCP adoption grows, so does the attack surface. MCP servers run arbitrary commands, access filesystems, make network calls, and handle sensitive data — often with zero visibility into their security posture or operational cost.
MCP Guardian provides:
Active policy enforcement (v0.4+) — YAML-configurable policy engine that blocks, flags, or passes every
tools/callin real time based on tool allowlists/denylists, regex patterns, rate limits, and token budgetsSecurity auditing — CVE scanning (OSV.dev + NVD), hardcoded secret detection, typo-squatting detection, command injection detection, and TLS validation
Real cost tracking — Proxy interceptor that captures actual
tools/calltraffic and counts tokens viatiktoken(o200k_base encoding) — no estimates, no mocksHealth monitoring — Live JSON-RPC 2.0 handshake probes with latency, success rate, tool count, and context pressure analysis
Agent-native — Runs as an MCP server so your AI assistant can self-audit its own infrastructure
Enterprise SIEM logging (v0.4+) — Structured JSON logs via pino with request-ID tracing, policy decision audit trails, and block events at WARN level
Session-based replay protection (v0.6.0) — Short-lived 5-min session tokens prevent JWT replay attacks. Nonce tracking detects token reuse
Hot-reload policies (v0.6.0) — File watcher atomically swaps policy engine on YAML changes — no restart needed
Circuit breaker (v0.5.2) — 3-state circuit breaker protects upstream MCP servers from cascading failures
OAuth 2.1 / OIDC (v0.5.0) — JWT validation with OIDC Discovery, bearer token extraction, agent identity mapping
RBAC (v0.5.1) — Scope-based and client-ID-based access control in policy engine
Web dashboard (v1.0) — Real-time monitoring dashboard with live Prometheus metrics, per-server circuit breaker status, policy editor, and auto-refresh
Redis shared state (v1.0) — Redis-backed session cache and rate limit counters for multi-replica HA
DPoP (v1.0) — RFC 9449 sender-constrained token support for replay-proof authentication
OpenTelemetry (v1.0) — Distributed tracing across proxy and MCP servers via OTLP
HTTP/SSE proxy (v0.8.0) — Full proxy support for remote HTTP/SSE-based MCP servers
Payload normalization (v1.2.0) — Multi-stage decoder defeats URL/hex/unicode/HTML entity/shell obfuscation bypass attacks before regex evaluation
Semantic shell analysis (v1.2.0) — AST-based tokenization detects command substitution, pipe chains, redirects, and 33 dangerous commands semantically
Dashboard authentication (v1.2.0) — JWT session tokens, API key auth, CSRF protection, and rate-limited login for the web dashboard
mTLS zero-trust networking (v1.3.0) — Mutual TLS with client certificates for proxy ↔ upstream MCP server communication
E2E proxy tests (v1.3.0) — Real proxy spawns with
default-policy.yaml, sends JSON-RPC, verifies block/pass/denySupply chain CI (v1.3.0) — GitHub Actions pipeline with
npm audit --audit-level=high, CycloneDX SBOM generation, and.npmrcenforcementOperational runbooks (v1.3.0) — 7 production runbooks covering circuit breaker, Redis, policy corruption, dashboard auth, latency, DB corruption, and token spikes with SLOs
Disaster recovery plan (v1.3.0) — RTO/RPO for all state types, backup strategy, recovery drills, and rollback procedures
Features
🔒 Security Scan (scan_security)
Check | Description |
CVE Checking | Queries OSV.dev (purl-based) and NIST NVD for known vulnerabilities. Rate-limited (5 req/min without API key, 20 req/min with key) |
Auth Probing | Detects missing authentication via env vars ( |
Transport Security | Flags unencrypted transports (HTTP, WS) and validates TLS certificates (expiry, issuer, validity) |
Typo-Squat Detection | Levenshtein distance matching against 24 known official MCP packages |
Secret Scanning | 6 regex patterns for hardcoded API keys, tokens, private keys, passwords, GitHub tokens, OpenAI keys |
Command Validation | Flags dangerous patterns (path traversal, shell chaining, |
🔴 Active Policy Engine (v0.4+) | YAML-configurable rules: tool allowlist/denylist, regex pattern blocking, rate limiting, token budgets. Operates in |
Scoring | Weighted 0–100 security score with actionable recommendations |
💰 Cost Audit (audit_costs)
Proxy Interceptor —
mcp-guardian proxysits between your AI client and MCP servers, capturing everytools/callrequest/responseReal Token Counting — Uses
tiktoken(o200k_base encoding) on actual JSON-RPC traffic — no hardcoded estimatesMulti-Model Pricing — 97 models across 17 providers (OpenAI, Anthropic, Google, DeepSeek, xAI, Meta, Mistral, and more)
Tool-Level Breakdown — Per-tool token usage, call counts, duration, and cost estimates
Custom Pricing — Override via
PRICING_OVERRIDESenv var:{"my-model": {"input": 2.0, "output": 6.0}}
❤️ Health Monitor (check_health)
Live Probes — Full JSON-RPC 2.0 handshake (initialize → initialized →
tools/list) with request/response correlationSSE Probing — Multi-path discovery (
/,/sse,/message) with auth header injection and timeout handlingLatency Tracking — End-to-end latency per server with historical success rates from SQLite
Overload Detection — Warns when >15 tools exposed; context pressure estimation
📊 Full Report (full_report)
Three Output Formats — Colored text, Markdown tables, structured JSON (with
resourceMIME type for agent consumption)Overall Score — Composite security + health score (0–100)
Database Storage — All scans, costs, health checks, and proxy-captured call records persisted in SQLite (4 tables, batched writes)
🔧 Production Features
Dependency Injection — IoC container (
src/container.ts) for testability and runtime swapsRate Limiting — Token-bucket rate limiter on OSV.dev and NVD API calls
Graceful Shutdown — SIGINT/SIGTERM handlers flush DB and close connections
Batched DB Writes — 1s debounced flush reduces I/O by 10x
Alert Thresholds — 6 CLI flags with exit codes 1/2 for CI/CD integration
GitHub Actions CI — Node 18/20/22 matrix, 97 tests across 13 suites
npm published —
@mcp-guardian/server@1.1.0— install vianpm install -g @mcp-guardian/server
Installation
From npm (recommended)
npm install -g @mcp-guardian/serverAfter global install, the mcp-guardian command is available in your PATH.
From source
git clone https://github.com/rudraneel93/mcp-guardian.git
cd mcp-guardian
npm install
npm run buildRequirements: Node.js ≥ 18, npm ≥ 9
Quick Start
Proxy Workflow (Real Cost Tracking)
The recommended workflow for getting real token cost data:
# 1. Start the proxy — it wraps your MCP servers and intercepts every tools/call
mcp-guardian proxy --config ./cline_mcp_settings.json
# 2. In another terminal, run your normal Cline/Claude workflows
# Every tools/call is captured with real token counts
# 3. When done, Ctrl+C the proxy, then audit real costs
mcp-guardian audit --config ./cline_mcp_settings.json
# 4. Generate full report with real security + cost + health data
mcp-guardian report --config ./cline_mcp_settings.jsonExample output (real data from proxy against 3 MCP servers):
💰 Cost Audit
github: 194 tokens, $0.0018 (gpt-4o)
filesystem: 245 tokens, $0.0026 (gpt-4o)
puppeteer: 216 tokens, $0.0021 (gpt-4o)
Total estimated cost: $0.0065
❤️ Health Check
github: 902ms latency, 100% success, 26 tools
filesystem: 1253ms latency, 100% success, 14 tools
puppeteer: 1275ms latency, 100% success, 7 tools
🔒 Security Scan
github - Score: D (0) — 20 CVEs, hardcoded token detected
filesystem - Score: C (50) — 20 CVEs, needs auth
puppeteer - Score: D (10) — 3 CVEs (1 critical), needs auth
Overall Score: 60/100Important: The cost audit will show
$0.0000until the proxy has been running and captured realtools/calltraffic. This is not a bug — thecall_recordstable starts empty.
One-Off Scan
# Quick security scan on auto-discovered configs
mcp-guardian scan
# Scan with thresholds for CI
mcp-guardian scan --config ./cline_mcp_settings.json --fail-on-critical --fail-on-secrets --threshold-score 70
# Check health
mcp-guardian health --server github-server --fail-on-overload --threshold-latency 2000
# Generate a Markdown report for documentation
mcp-guardian report --format markdown --output audit-report.mdCLI Reference
mcp-guardian proxy
Start the MCP proxy interceptor with optional active policy enforcement.
# Audit-only (passive)
mcp-guardian proxy --config ./cline_mcp_settings.json
# Active blocking with default policy
mcp-guardian proxy --config ./cline_mcp_settings.json --policy ./default-policy.yaml
# Active blocking with custom policy + mode override
mcp-guardian proxy --config ./cline_mcp_settings.json --policy ./my-policy.yaml --blocking-mode blockOption | Description |
| Path to MCP config file |
| Path to policy YAML file (enables active blocking) |
| Override policy mode: |
Policy Engine (v0.4+)
The policy engine evaluates every intercepted tools/call before it reaches the MCP server. Define rules in YAML:
# my-policy.yaml
version: "1.0"
policy:
mode: block
rules:
- name: "deny-shell-tools"
action: block
tools: { deny: ["execute_command", "bash", "sh", "eval", "exec"] }
- name: "block-injection"
action: block
patterns:
- "rm\\s+-rf"
- "curl\\s|wget\\s"
- ";\\s*\\w"
- "&&|\\|\\|"
- name: "rate-limit"
action: flag
maxCallsPerMinute: 60
- name: "token-budget"
action: flag
maxTokens: 50000Blocked calls return a JSON-RPC 2.0 error to the client:
{"jsonrpc":"2.0","id":"abc-123","error":{"code":-32001,"message":"Blocked by MCP Guardian policy: Tool 'execute_command' is explicitly denied"}}Policy modes:
Mode | Behavior |
| Pass all calls; log decisions only (passive) |
| Downgrade |
| Full active enforcement — blocked calls never reach the MCP server |
mcp-guardian scan
Run security scan on MCP servers.
mcp-guardian scan
mcp-guardian scan --config ./config.json --fail-on-secrets
mcp-guardian scan --all --threshold-score 70Option | Description |
| Path to an MCP config file |
| Aggregate all discoverable configs |
| Exit code 2 if any server score drops below |
| Exit code 1 if any critical CVE found |
| Exit code 1 if hardcoded secrets detected |
mcp-guardian audit
Audit token costs. Reads real call records if proxy was used, otherwise shows zero-data note.
mcp-guardian audit
mcp-guardian audit --server github-server
mcp-guardian audit --threshold-cost 0.50Option | Description |
| Path to an MCP config file |
| Aggregate all discoverable configs |
| Filter to a specific server |
| Exit code 2 if total cost exceeds |
mcp-guardian health
Check health, latency, and reliability of MCP servers. Uses real JSON-RPC handshake probes.
mcp-guardian health
mcp-guardian health --server filesystem
mcp-guardian health --threshold-latency 2000 --fail-on-overloadOption | Description |
| Path to an MCP config file |
| Aggregate all discoverable configs |
| Filter to a specific server |
| Exit code 2 if any server exceeds latency threshold |
| Exit code 1 if any server has tool overload (>15 tools) |
mcp-guardian report
Generate a complete security, cost, and health report.
mcp-guardian report
mcp-guardian report --format markdown
mcp-guardian report --format json --config ~/.cursor/mcp.json
mcp-guardian report --all --threshold-score 60Option | Description |
| Path to an MCP config file |
| Aggregate all discoverable configs |
| Output format: |
| Save report to a file instead of stdout |
| Exit code 2 if overall score drops below |
MCP Server (AI Assistant Integration)
Add to your cline_mcp_settings.json or claude_desktop_config.json:
{
"mcpServers": {
"mcp-guardian": {
"command": "npx",
"args": ["-y", "@mcp-guardian/server"]
}
}
}Or with a local install:
{
"mcpServers": {
"mcp-guardian": {
"command": "node",
"args": ["path/to/mcp-guardian/dist/index.js"]
}
}
}Available Tools
Tool | Parameters | Description |
|
| Scan MCP configs for CVEs, auth gaps, typo-squatting, hardcoded secrets, and dangerous commands |
|
| Estimate token usage and costs per server with multi-model pricing |
|
| Check latency, success rate, tool count, and context pressure |
|
| Generate complete audit report in any format |
JSON format reports also include a structured resource content type (MIME: application/json) so AI assistants can consume reports programmatically.
Available Resources & Prompts
Resource:
mcp-guardian://latest-scan— exposes the most recent security scan as structured JSONPrompt:
audit-config— generates structured audit instructions for an MCP config path, which the assistant can use to guide its investigation
Web Dashboard (v1.0)
MCP Guardian includes a built-in web dashboard for real-time monitoring of your MCP infrastructure.
Start the dashboard alongside the proxy:
DASHBOARD_ENABLED=true METRICS_ENABLED=true \
mcp-guardian proxy --policy ./default-policy.yaml --blocking-mode warnThen open http://localhost:4000 in your browser.
Tab | Description |
Overview | Live metrics grid (requests, blocked, sessions, policy mode) + per-server status table with circuit breaker states |
Policy Editor | View and reload the active policy in real-time |
Raw Metrics | Full Prometheus |
Dashboard features:
Real-time Prometheus metrics — Parses live Prometheus text format and displays per-server request counts, blocked counts, and circuit breaker states
Live policy viewer — Shows active policy mode and rules via
/api/policyendpointHot-reload — Policy changes are auto-detected by the file watcher; the dashboard reflects them within 300ms
Auto-refresh — Metrics and policy refresh every 5 seconds
Dark theme — GitHub-style dark UI designed for ops monitoring
Environment Variables for Dashboard
Variable | Purpose | Default |
| Enable the dashboard server |
|
| Dashboard HTTP port |
|
| Enable Prometheus metrics endpoint |
|
| Metrics server port |
|
The dashboard server proxies /metrics from the Prometheus server (port 9090) to the dashboard port (4000) so there are no CORS issues. All data displayed is live — zero mock data.
CI/CD Integration
Run MCP Guardian in CI to catch issues before deployment:
- name: MCP Guardian Security Scan
run: npx @mcp-guardian/server scan --config ./cline_mcp_settings.json --fail-on-critical --fail-on-secrets
env:
NVD_API_KEY: ${{ secrets.NVD_API_KEY }}
- name: MCP Guardian Cost Audit
run: npx @mcp-guardian/server audit --all --threshold-cost 0.50
- name: MCP Guardian Health Check
run: npx @mcp-guardian/server health --all --threshold-latency 3000 --fail-on-overloadExit Codes
Code | Meaning |
0 | All checks passed within thresholds |
1 | Critical security issue found (critical CVE, secret, overload) |
2 | Threshold exceeded (score, cost, or latency below/above limit) |
Production Deployment (K8s + Helm)
See the full guide at deploy/PRODUCTION.md.
Quick Helm Install
# Install from local chart
helm install mcp-guardian ./deploy/helm/mcp-guardian \
--set config.policy.mode=block \
--set config.mcpConfigPath=/etc/mcp-guardian/cline_mcp_settings.json
# Or from the repo (future)
helm repo add mcp-guardian https://rudraneel93.github.io/mcp-guardian
helm install mcp-guardian mcp-guardian/mcp-guardianKey Features
Helm chart with ConfigMap-backed policies, PVC persistence, and safe defaults
Fail-closed by default (block traffic if proxy crashes) — configurable to fail-open
Sidecar injection pattern documented for stdio MCP servers
Scaling guide with CPU/memory recommendations per traffic level
Pod Disruption Budget for HA, anti-affinity for multi-AZ
SIEM integration via pino structured JSON logs (Splunk, Datadog, Elasticsearch)
Performance Overhead
Scenario | p50 | p99 | Overhead |
Direct MCP (no proxy) | 5ms | 7ms | — |
Proxy (no policy) | 27ms | 77ms | +25.78ms |
Proxy (blocking policy) | 27ms | 74ms | +25.93ms |
Policy engine adds ~0.15ms — negligible. The ~26ms is Node.js child process stdio overhead.
Docker
A Docker image is available for running the proxy in containerized environments.
# Build
docker build -t mcp-guardian .
# Run proxy
docker run -i \
-v $(pwd)/cline_mcp_settings.json:/app/cline_mcp_settings.json \
-v mcp-guardian-db:/root/.mcp-guardian \
mcp-guardian --config /app/cline_mcp_settings.jsonThe Dockerfile uses node:20-alpine and runs mcp-guardian proxy as the default entrypoint.
Architecture
Trust Boundaries
┌─────────────────────────────────────────────────────────┐
│ TRUSTED ZONE │
│ ┌──────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ AI Client │───▶│ MCP Guardian │───▶│ MCP Server │ │
│ │ (Cline/ │ │ (Proxy) │ │ (stdio/SSE) │ │
│ │ Claude) │◀───│ │◀───│ │ │
│ └──────────┘ └──────┬───────┘ └──────────────┘ │
│ │ │
│ ┌──────────▼──────────┐ │
│ │ Policy Engine │ │
│ │ Auth Gateway │ │
│ │ Audit Logger (pino) │ │
│ │ Metrics (Prometheus)│ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────────┘
║
TRUST BOUNDARY
║
┌─────────────────────────────────────────────────────────┐
│ UNTRUSTED ZONE │
│ • External MCP servers (SSE/HTTP) │
│ • OIDC identity providers │
│ • CVE data sources (OSV.dev, NVD) │
│ • Package registries (npm, PyPI) │
│ • AI model outputs (prompt injection vectors) │
└─────────────────────────────────────────────────────────┘Comparison with Alternatives
Feature | MCP Guardian | MCP Shield | Guardrails-MCP | Envoy AI Gateway |
Active blocking | ✅ YAML policy engine | ✅ Inline firewall | ✅ Policy enforcement | ❌ Gateway only |
OAuth 2.1/OIDC | ✅ JWT + RBAC + DPoP | ❌ | ❌ | ✅ OAuth |
Session replay protection | ✅ 5-min tokens + nonces | ❌ | ❌ | ❌ |
Circuit breaker | ✅ 3-state per server | ❌ | ❌ | ✅ Built-in |
Cost tracking | ✅ Real token counting | ❌ | ❌ | ❌ |
Health monitoring | ✅ JSON-RPC probes | ❌ | ❌ | ❌ |
Prometheus metrics | ✅ Counters, gauges, histograms | ❌ | ❌ | ✅ |
Hot-reload policies | ✅ chokidar file watcher | ❌ | ❌ | ❌ |
Redis HA | ✅ Session + rate limit | ❌ | ❌ | ❌ |
OpenTelemetry | ✅ OTLP tracing | ❌ | ❌ | ✅ |
Web dashboard | ✅ Live metrics + policy | ❌ | ❌ | ❌ |
HTTP/SSE proxy | ✅ Full proxy | ❌ | ❌ | ✅ |
Helm chart | ✅ K8s deployment | ❌ | ❌ | ✅ |
E2E tests | ✅ 97 tests (13 suites) | ❌ | ❌ | ❌ |
Source Tree
mcp-guardian/
├── src/
│ ├── index.ts # MCP server entry (stdio transport)
│ ├── cli.ts # CLI wrapper (5 commands: proxy, scan, audit, health, report)
│ ├── container.ts # Dependency injection container (IoC)
│ ├── types.ts # Shared TypeScript interfaces (8 types)
│ ├── config-parser.ts # Multi-format config parsing with multi-file aggregation
│ │
│ ├── proxy/ # MCP Proxy Interceptor (real cost engine)
│ │ ├── proxy-server.ts # Intercepts tools/call, counts tokens via tiktoken
│ │ └── proxy-manager.ts # Spawns proxies for all stdio servers
│ │
│ ├── services/ # Orchestrators
│ │ ├── security-scanner.ts # Parallel security checks + weighted scoring
│ │ ├── cost-auditor.ts # Reads real call_records from DB (zero mock data)
│ │ └── health-monitor.ts # Live JSON-RPC probing + DB integration
│ │
│ ├── scanners/ # Individual security checks
│ │ ├── cve-checker.ts # OSV.dev → NVD fallback chain (rate-limited)
│ │ ├── auth-prober.ts # Auth/transport detection (env + URL patterns)
│ │ ├── typo-squat-detector.ts # Levenshtein distance (O(n) memory)
│ │ ├── secret-scanner.ts # 6 regex patterns for secrets
│ │ └── command-validator.ts # 10 suspicious pattern checks for command injection
│ │
│ ├── clients/ # External API clients
│ │ ├── osv-client.ts # api.osv.dev (purl-based, token-bucket rate-limited)
│ │ ├── nvd-client.ts # NIST NVD (API key support, rate-limited)
│ │ └── pricing-client.ts # 97 models, 17 providers, custom override support
│ │
│ ├── database/
│ │ └── history-db.ts # SQLite via sql.js (4 tables, batched writes, 1s debounce)
│ │
│ ├── reporter/
│ │ └── report-generator.ts # Text, Markdown, JSON formatting
│ │
│ └── utils/
│ ├── token-counter.ts # tiktoken (o200k_base) wrapper
│ ├── mcp-client.ts # Full JSON-RPC 2.0 state machine + SSE probing
│ ├── rate-limiter.ts # Token-bucket rate limiter
│ ├── tls-checker.ts # TLS certificate validation (expiry, issuer, chain)
│ ├── scoring.ts # Shared scoring utility
│ └── logger.ts # Colored console logger with log levels
│
tests/ # 74 tests across 11 suites (Vitest)
├── config-parser.test.ts
├── secret-scanner.test.ts
├── auth-prober.test.ts
├── typo-squat-detector.test.ts
├── scoring.test.ts
├── pricing-client.test.ts
├── services/
│ ├── cost-auditor.test.ts
│ └── security-scanner.test.ts
└── integration/
├── proxy-audit.test.ts
└── full-pipeline.test.tsData Flow (Proxy → DB → Audit)
AI Client (Cline/Claude)
│
│ tools/call JSON-RPC
▼
┌───────────────────┐
│ MCP Proxy Server │ ← mcp-guardian proxy
│ (proxy-server.ts) │
└───────┬───────────┘
│ counts tokens (tiktoken o200k_base)
▼
┌───────────────────┐
│ call_records table │ ← SQLite (sql.js)
│ (history-db.ts) │
└───────┬───────────┘
│ async getCallRecordsForServer()
▼
┌───────────────────┐
│ Cost Auditor │ ← mcp-guardian audit / report
│ (cost-auditor.ts) │
└───────────────────┘
│ per-tool breakdown + multi-model pricing (97 models)
▼
Cost Report ($0.0023, gpt-4o)Config Discovery
MCP Guardian auto-discovers config files from these standard locations:
Client | Config Path |
Cline (VS Code) |
|
Cline (VS Code Insiders) |
|
Cline (Linux) |
|
Cline (Windows) |
|
Claude Desktop (macOS) |
|
Claude Desktop (Linux) |
|
Cursor |
|
Windsurf |
|
Use --config / -c for a custom path, or --all / -a to aggregate all discoverable configs with deduplication (first file wins for duplicate server names).
Security Scoring Model
Each server receives a score from 0–100 with these deductions:
Finding | Deduction |
Critical CVEs detected | −40 |
High-severity CVEs | −20 |
Medium-severity CVEs | −10 |
No authentication | −20 |
Unencrypted transport | −10 |
Typo-squat detected | −30 |
Hardcoded secrets found | −15 |
High-severity command warning | −25 |
Medium-severity command warning | −10 |
Letter grades: A (80–100), B (60–79), C (40–59), D (0–39)
Pricing Models
97 models across 17 providers. Cached rates per 1M tokens (as of mid-2025):
Provider | Models | Example Rates (input/output per 1M) |
OpenAI (14) | gpt-4o, gpt-4.5-preview, o1, o3, o4-mini, gpt-3.5-turbo | $5/$15 |
Anthropic (8) | claude-3-5-sonnet, claude-opus, claude-haiku | $3/$15 |
Google (12) | gemini-2.5-pro, gemini-2.0-flash, gemma | $1.25/$10 |
DeepSeek (4) | deepseek-chat, deepseek-reasoner, deepseek-v3 | $0.14/$0.28 |
xAI/Grok (5) | grok-3, grok-3-mini | $3/$15 |
Meta/Llama (8) | llama-4-maverick, llama-3.3-70b | $0.2/$0.6 |
Mistral (9) | mistral-large, mixtral-8x22b, codestral | $2/$6 |
+ 10 more | Cohere, AI21, Reka, Amazon, Alibaba, Zhipu, 01.AI, Writer, Perplexity, HuggingFace | varies |
Unknown models receive a conservative default estimate of $10/$30 per million tokens. Override any model via the PRICING_OVERRIDES env var.
Environment Variables
Variable | Purpose | Default |
| NIST NVD API key for CVE lookups (20 req/min vs 5 without) | (none) |
| Override SQLite database path |
|
| Logging level: |
|
| Custom pricing JSON: | (none) |
| Optionally used by tiktoken for token counting | (none) |
Development
# Clone and install
git clone https://github.com/rudraneel93/mcp-guardian.git
cd mcp-guardian
npm install
# Development
npm run dev # Watch mode with tsx
npm run build # Compile TypeScript
npm run lint # Type check (tsc --noEmit)
npm test # 97 tests across 13 suites (Vitest)
npm run test:watch # Watch mode
# Contributing
# See CONTRIBUTING.md for guidelines on adding scanners, pricing models, and tests.FAQ
Why does mcp-guardian audit show $0.0000?
The cost audit reads real data from the proxy's database. You must run mcp-guardian proxy first to capture tools/call traffic, then run audit. Without proxy data, the call_records table is empty and the audit returns zero.
Do I need an NVD API key?
No, but you'll be rate-limited to 5 requests per minute without one. Get a free key at NIST NVD for 20 req/min.
How do I run the proxy alongside my AI assistant?
Start mcp-guardian proxy --config <path> in one terminal, then run your AI assistant normally in another. The proxy sits between the assistant and MCP servers, transparently capturing all tools/call traffic.
What does the proxy intercept?
The proxy only tracks tools/call JSON-RPC messages — it counts input tokens (the request) and output tokens (the response). It forwards all other messages without tracking.
Can I use MCP Guardian with SSE/HTTP transports?
The security scan and health monitor support SSE/HTTP transports. The proxy currently supports stdio transports only (it spawns child processes). Cost auditing via proxy works only for stdio-based MCP servers.
How do I override pricing for my custom model?
Set the PRICING_OVERRIDES environment variable with JSON:
export PRICING_OVERRIDES='{"my-custom-model": {"input": 2.0, "output": 6.0}}'Rates are in USD per 1 million tokens.
Where is the database stored?
By default, SQLite data is stored at ~/.mcp-guardian/history.db. Override with the MCP_GUARDIAN_DB_PATH environment variable. The database has 4 tables: security_scans, cost_records, health_checks, and call_records.
What's the difference between --config and --all?
--config <path>loads a single config file--allauto-discovers and aggregates all config files from known locations (Cline, Claude Desktop, Cursor, Windsurf), deduplicating servers by name
Can I run MCP Guardian in CI/CD?
Yes. Use the alert threshold flags (--fail-on-critical, --fail-on-secrets, --threshold-score, etc.) which return non-zero exit codes that CI systems understand. See the CI/CD Integration section for examples.
How accurate is the token counting?
Token counting uses tiktoken with the o200k_base encoding (used by GPT-4o and many modern models). For non-OpenAI models, this provides a close approximation since most modern tokenizers are similar in granularity.
Roadmap
Core security, cost, and health scanning
MCP server + CLI dual entry points (5 commands)
NVD + OSV.dev CVE integration (rate-limited)
SQLite history tracking (4 tables, batched writes)
Real MCP handshake probing (JSON-RPC 2.0 state machine)
SSE/HTTP transport support (multi-path discovery)
Custom pricing configuration (
PRICING_OVERRIDESenv var)Alert thresholds with exit codes (6 flags)
Multiple config file aggregation (
--all+ deduplication)MCP Proxy Interceptor — real token capture with zero mock data
Dependency injection container (IoC pattern)
Token-bucket rate limiter (OSV + NVD)
TLS certificate validation
Command injection validation (10 suspicious patterns)
Active policy engine — YAML-based pass/block/flag with allowlists, regex, rate limiting, token budgets
Structured JSON logging (pino) for SIEM ingestion
STRIDE threat model (SECURITY.md) + formal THREAT_MODEL.md
Payload normalization — multi-stage encode/decode bypass defense
Semantic shell AST analysis — command substitution, pipe, and dangerous command detection
Dashboard authentication — JWT sessions, API keys, CSRF protection
mTLS zero-trust networking for proxy ↔ upstream communication
168 tests across 16 suites (unit, fuzz, integration, E2E)
GitHub Actions CI (Node 18/20/22 matrix) + supply chain audit
Performance benchmarks (p50: 5ms baseline, +25.78ms proxy overhead, +0.15ms policy)
Helm chart + production deployment guide (K8s, fail-open/closed, sidecar pattern, scaling)
Published to npm as
@mcp-guardian/server@1.3.3OAuth 2.1 / OIDC proxy authentication (v0.5.0)
RBAC — scope & client-ID-based access control (v0.5.1)
Circuit breaker — 3-state protection for upstream servers (v0.5.2)
Per‑client rate limiting (v0.5.2)
Consistent SIEM fields — requestId, authnSuccess, authzAllowed (v0.5.2)
Session binding — replay protection via 5‑min session tokens (v0.6.0)
Hot‑reload policies — chokidar file watcher (v0.6.0)
Redis session cache — cross‑replica HA session store (v0.7.0)
Prometheus metrics endpoint — counters, gauges, histograms (v0.7.0)
E2E integration tests — real MCP server through proxy (v0.7.0)
Web dashboard — live metrics, policy editor, per-server status (v1.0)
Redis shared rate limit counters (v1.0)
DPoP support — RFC 9449 sender-constrained tokens (v1.0)
OpenTelemetry tracing — distributed request tracking (v1.0)
HTTP/SSE proxy server — remote MCP transport support (v0.8.0)
E2E proxy tests — real CLI spawn with policy file (v1.3.0)
Supply chain CI — npm audit, CycloneDX SBOM, npm provenance (v1.3.0)
Operational runbooks — 7 scenarios with SLOs (v1.3.0)
Disaster recovery plan — RTO/RPO, backup strategy, recovery drills (v1.3.0)
GitHub primary language corrected to TypeScript (v1.3.3)
npm keywords expanded to 22 terms for discoverability (v1.3.3)
OPA/Rego policy integration
Slack/Discord alerting
Multi-user proxy
Hosted SaaS version
License
MIT — see LICENSE for details.
Built with TypeScript, @modelcontextprotocol/sdk, tiktoken, sql.js, commander, chalk, zod, jose, pino, and prom-client.
Available Tools
4 toolsaudit_costsB
Audit token usage and estimate costs per MCP server
| Name | Required | Description | Default |
|---|---|---|---|
| serverName | No | Filter to a specific server name. If omitted, audits all. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist; the description only conveys the high-level purpose but does not disclose behavioral traits such as being read-only, potential side effects, authentication needs, or rate limits.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is very concise with one sentence that immediately states the action; no unnecessary words, but could be slightly more informative while remaining concise.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with one optional parameter and no output schema, the description covers the core purpose, but lacks behavioral or execution details that would make it fully complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with the parameter 'serverName' described; the description does not add additional meaning beyond the schema, so baseline score of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool audits token usage and estimates costs per MCP server, which is a specific and distinct action among sibling tools that focus on security, compliance, and trust.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use this tool versus alternatives like 'full_report' or 'compliance_posture'; no when-not-to-use or contextual hints provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
check_healthB
Check health, latency, and reliability of MCP servers
| Name | Required | Description | Default |
|---|---|---|---|
| serverName | No | Filter to a specific server name. If omitted, checks all. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations are absent, so the description bears full burden. It only mentions checking health/latency/reliability with no disclosure of side effects, authentication needs, or return format. The read-only nature is implied but not stated.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, clear sentence with no wasted words. It is front-loaded with the key action and resource.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the simplicity (1 optional param, no output schema, no annotations), the description is minimally adequate. However, it lacks details on output format, definition of 'health', and any thresholds, leaving room for ambiguity.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% and already describes the sole parameter (serverName: filter or omit for all). The tool description adds no extra semantic value beyond what the schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool checks health, latency, and reliability of MCP servers, using a specific verb and resource. It effectively distinguishes from sibling tools like check_sla, which focuses on service level agreements.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus alternatives (e.g., check_sla, audit_costs). The description does not specify prerequisites or conditions for use.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
full_reportA
Generate a complete security, cost, and health report for all MCP servers
| Name | Required | Description | Default |
|---|---|---|---|
| configPath | No | Path to MCP config file (optional) | |
| format | No | Output format (default: text) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must disclose behavioral traits. It implies a read-only report generation (non-destructive), but does not explicitly state safety, performance, or auth requirements. This is adequate but incomplete.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, front-loaded sentence that directly states the tool's purpose. Every word contributes value, with no extraneous information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple tool with two optional parameters and no output schema, the description is mostly complete. It lacks details on output structure or behavior, but given the low complexity, it is nearly sufficient.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, meaning the schema already explains the parameters (format and configPath). The description adds no extra semantic value beyond what the schema provides, so baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool generates a 'complete security, cost, and health report for all MCP servers', using a specific verb and resource. This differentiates it from sibling tools like check_health or audit_costs, which focus on individual aspects.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus its many siblings (e.g., check_health, audit_costs, scan_security). It does not mention alternatives, prerequisites, or exclusions, leaving the agent without context for selection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
scan_securityA
Scan MCP server configurations for security vulnerabilities (CVEs, auth, typo-squatting, secrets)
| Name | Required | Description | Default |
|---|---|---|---|
| configPath | No | Path to an MCP config file. If omitted, auto-discovers configs. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description carries full burden. It lists vulnerability categories but does not disclose whether the scan is read-only, requires permissions, or modifies state. Missing safety profile and behavioral details.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Single sentence with verb first, resource, and list of vulnerability types. No extraneous words, front-loaded key information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Lacks output schema and does not describe what the scan returns (e.g., severity, list of findings). For a tool that likely produces a report, missing return value information reduces completeness for agent decision-making.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema has 100% coverage with a single parameter 'configPath' described. The description adds value by explaining what the scan checks for (CVEs, auth, etc.), going beyond the parameter's schema description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
Description specifies verb 'Scan', resource 'MCP server configurations', and lists specific vulnerability types (CVEs, auth, typo-squatting, secrets). This clearly distinguishes it from sibling tools like 'scan_prompt_injection' and 'scan_response_dlp'.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit guidance on when to use this tool vs alternatives. The description implies it is a general security scan, but does not state when to use other scan tools. Usage context is only implied.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v2.3.18- First observed
audit_costs - First observed
check_health - First observed
full_report - First observed
scan_security
TDQS
Scored across 4 tools
Each tool targets a distinct concern: costs, security, health, and the aggregate report. full_report is the only overlapping tool, but it is clearly positioned as a consolidated view rather than a duplicate.
audit_costs, scan_security, and check_health follow a clear verb_noun pattern, but full_report breaks it by being a noun phrase instead of a verb-led action like generate_report. The pattern is still predictable and readable overall.
At four tools, the server is compact and well-scoped for MCP health, security, and cost oversight. Each tool earns its place by covering a distinct diagnostic dimension, with no redundant or extraneous operations.
The set covers security scanning, cost auditing, health checks, and a combined reporting path, giving agents the full diagnostic workflow for MCP server oversight. No obvious dead ends or required operations are absent.
Maintenance
Related MCP Connectors
AgentGuard — 20-tool AI safety MCP: policy preflight, risk scoring, audit logging, rate limits.
Security firewall for AI agents — scans MCP calls for injection, secrets, and risks.
Security & DLP proxy for MCP: tool-poisoning scans, PII redaction on tool args/results. Beta.
Zero-secret MCP gateway for AI agents: risk-scored, audited calls with human-in-the-loop approval.
Related MCP Servers
- AlicenseBqualityCmaintenanceSecurity gateway that wraps any MCP server with per-tool policies, approval gates, and optional Ed25519-signed decision receipts. Shadow mode logs every tool call without blocking; enforce mode applies block, rate-limit, and minimum-tier rules. Receipts are independently verifiable offline with no accounts needed.5587 npm10MIT

SentinelGateofficial
AlicenseNot gradedqualityAmaintenanceOpen-source MCP proxy that enforces security policies, content scanning, and audit logging between AI agents and tool servers25AGPL 3.0- AlicenseNot gradedqualityAmaintenanceGuardrail sidecar proxy between AI agents and their MCP/REST/CLI tools. Policy engine, human approval gates, time-limited grants, rate limiting, and OTEL tracing. One Go binary, one YAML config, fail-closed by default.1Apache 2.0
- AlicenseNot gradedqualityBmaintenanceMCP server for AI agent security guardrails. Provides input validation, prompt injection detection, PII redaction, output filtering, policy enforcement, rate limiting, and comprehensive audit logging.38 npm1MIT