Skip to main content
Glama
rudraneel93

mcp-guardian

by rudraneel93

🛡️ MCP Guardian

Security, cost, and health audit for MCP infrastructure.

npm version npm downloads TypeScript MCP SDK License CI

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/call in real time based on tool allowlists/denylists, regex patterns, rate limits, and token budgets

  • Security 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/call traffic and counts tokens via tiktoken (o200k_base encoding) — no estimates, no mocks

  • Health 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/deny

  • Supply chain CI (v1.3.0) — GitHub Actions pipeline with npm audit --audit-level=high, CycloneDX SBOM generation, and .npmrc enforcement

  • Operational 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 (API_KEY, AUTH_TOKEN, etc.) and URL credentials

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, rm -rf, curl/wget in commands, and more)

🔴 Active Policy Engine (v0.4+)

YAML-configurable rules: tool allowlist/denylist, regex pattern blocking, rate limiting, token budgets. Operates in audit (passive), warn (flag only), or block (active enforcement) modes

Scoring

Weighted 0–100 security score with actionable recommendations

💰 Cost Audit (audit_costs)

  • Proxy Interceptormcp-guardian proxy sits between your AI client and MCP servers, capturing every tools/call request/response

  • Real Token Counting — Uses tiktoken (o200k_base encoding) on actual JSON-RPC traffic — no hardcoded estimates

  • Multi-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_OVERRIDES env 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 correlation

  • SSE Probing — Multi-path discovery (/, /sse, /message) with auth header injection and timeout handling

  • Latency 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 resource MIME 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 swaps

  • Rate 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 via npm install -g @mcp-guardian/server


Installation

npm install -g @mcp-guardian/server

After 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 build

Requirements: 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.json

Example 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/100

Important: The cost audit will show $0.0000 until the proxy has been running and captured real tools/call traffic. This is not a bug — the call_records table 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.md

CLI 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 block

Option

Description

-c, --config <path>

Path to MCP config file

--policy <path>

Path to policy YAML file (enables active blocking)

--blocking-mode <mode>

Override policy mode: audit (passive), warn (flag), block (enforce)

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: 50000

Blocked 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

audit

Pass all calls; log decisions only (passive)

warn

Downgrade block actions to flag; log warnings

block

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 70

Option

Description

-c, --config <path>

Path to an MCP config file

-a, --all

Aggregate all discoverable configs

--threshold-score <n>

Exit code 2 if any server score drops below n

--fail-on-critical

Exit code 1 if any critical CVE found

--fail-on-secrets

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.50

Option

Description

-c, --config <path>

Path to an MCP config file

-a, --all

Aggregate all discoverable configs

-s, --server <name>

Filter to a specific server

--threshold-cost <n>

Exit code 2 if total cost exceeds n USD

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-overload

Option

Description

-c, --config <path>

Path to an MCP config file

-a, --all

Aggregate all discoverable configs

-s, --server <name>

Filter to a specific server

--threshold-latency <ms>

Exit code 2 if any server exceeds latency threshold

--fail-on-overload

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 60

Option

Description

-c, --config <path>

Path to an MCP config file

-a, --all

Aggregate all discoverable configs

-f, --format <fmt>

Output format: text (default), markdown, or json

--output <path>

Save report to a file instead of stdout

--threshold-score <n>

Exit code 2 if overall score drops below n


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_security

configPath?

Scan MCP configs for CVEs, auth gaps, typo-squatting, hardcoded secrets, and dangerous commands

audit_costs

serverName?

Estimate token usage and costs per server with multi-model pricing

check_health

serverName?

Check latency, success rate, tool count, and context pressure

full_report

configPath?, format? (json|markdown|text)

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 JSON

  • Prompt: 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 warn

Then 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 /metrics output for debugging

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/policy endpoint

  • Hot-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

DASHBOARD_ENABLED

Enable the dashboard server

false

DASHBOARD_PORT

Dashboard HTTP port

4000

METRICS_ENABLED

Enable Prometheus metrics endpoint

false

METRICS_PORT

Metrics server port

9090

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-overload

Exit 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-guardian

Key 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.json

The 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.ts

Data 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)

~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

Cline (VS Code Insiders)

~/Library/Application Support/Code - Insiders/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

Cline (Linux)

~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

Cline (Windows)

%APPDATA%/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json

Claude Desktop (macOS)

~/Library/Application Support/Claude/claude_desktop_config.json

Claude Desktop (Linux)

~/.config/Claude/claude_desktop_config.json

Cursor

~/.cursor/mcp.json

Windsurf

~/.codeium/windsurf/mcp_config.json

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

NVD_API_KEY

NIST NVD API key for CVE lookups (20 req/min vs 5 without)

(none)

MCP_GUARDIAN_DB_PATH

Override SQLite database path

~/.mcp-guardian/history.db

LOG_LEVEL

Logging level: DEBUG, INFO, WARN, ERROR

INFO

PRICING_OVERRIDES

Custom pricing JSON: {"my-model": {"input": 2.0, "output": 6.0}}

(none)

OPENAI_API_KEY

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

  • --all auto-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_OVERRIDES env 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.3

  • OAuth 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 tools
audit_costsB

Audit token usage and estimate costs per MCP server

ParametersJSON Schema
NameRequiredDescriptionDefault
serverNameNoFilter to a specific server name. If omitted, audits all.

TDQS

B3.2/5.0
Behavior2/5

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.

Conciseness4/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines2/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
serverNameNoFilter to a specific server name. If omitted, checks all.

TDQS

B3.3/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines2/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
configPathNoPath to MCP config file (optional)
formatNoOutput format (default: text)

TDQS

A3.6/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines2/5

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)

ParametersJSON Schema
NameRequiredDescriptionDefault
configPathNoPath to an MCP config file. If omitted, auto-discovers configs.

TDQS

A3.6/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness2/5

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.

Parameters4/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

  1. 4 tool updatesv2.3.18
    • First observedaudit_costs
    • First observedcheck_health
    • First observedfull_report
    • First observedscan_security

TDQS

A3.8/5.0

Scored across 4 tools

Disambiguation5/5

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.

Naming Consistency4/5

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.

Tool Count5/5

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.

Completeness5/5

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

ActivityInactive
ResponsivenessResponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    C
    maintenance
    Security 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.
    5
    587 npm
    10
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Open-source MCP proxy that enforces security policies, content scanning, and audit logging between AI agents and tool servers
    25
    AGPL 3.0
  • A
    license
    Not graded
    quality
    A
    maintenance
    Guardrail 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.
    1
    Apache 2.0
  • A
    license
    Not graded
    quality
    B
    maintenance
    MCP 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 npm
    1
    MIT