Skip to main content

MCPShield - Secure infrastructure access for AI agents (databases, APIs, cloud) with deterministic policy enforcement and AI-powered policy generation

Project description

MCPShield

Secure infrastructure access for AI agents — databases, APIs, cloud platforms, and more — with deterministic policy enforcement and comprehensive auditing.

Features

  • MCP Server: Claude Code compatible stdio protocol
  • Multi-Infrastructure Support: PostgreSQL, MySQL, SQLite, MongoDB, Redis — ready for APIs, cloud, and custom systems
  • Fail-Closed Policy Engine: YAML-based security rules with default deny
  • Centralized Policy Management: Policies authored in dashboard, automatically synced
  • Audit Trail: Complete event logging to MCPShield control plane with policy_hash tracking
  • Event Spooling: Never lose audit events, even when offline
  • Developer-Friendly: Clear logs, helpful errors, easy configuration

Quick Start

Installation

pip install mcpshield

Super Quick Setup (Interactive)

The easiest way to get started:

mcpshield init

This interactive wizard will:

  • Ask which infrastructure you want to secure (PostgreSQL, MySQL, SQLite, MongoDB, Redis)
  • Configure your infrastructure connection
  • Set up your MCPShield API key
  • Automatically integrate with Claude Code and/or Cursor
  • Guide you through policy creation

Setup (Environment Variables - Recommended)

No configuration file needed! Just set environment variables and run.

  1. Create project and policy in MCPShield dashboard:

  2. Set environment variables:

    macOS/Linux:

    export PG_DSN="postgresql://user:pass@localhost:5432/dbname"
    export MCPSHIELD_API_KEY="mcps_your_key"
    export PROJECT_ID="proj_your_id"
    export API_BASE_URL="https://api.mcpshield.xyz"  # Optional, this is the default
    

    Windows (PowerShell):

    $env:PG_DSN = "postgresql://user:pass@localhost:5432/dbname"
    $env:MCPSHIELD_API_KEY = "mcps_your_key"
    $env:PROJECT_ID = "proj_your_id"
    $env:API_BASE_URL = "https://api.mcpshield.xyz"  # Optional, this is the default
    

    Or use a .env file:

    # .env
    PG_DSN=postgresql://user:pass@localhost:5432/dbname
    MCPSHIELD_API_KEY=mcps_your_key
    PROJECT_ID=proj_your_id
    API_BASE_URL=https://api.mcpshield.xyz
    POLICY_SOURCE=remote
    
  3. Verify setup:

    mcpshield doctor
    
    # Or with .env file:
    mcpshield doctor --env-file .env
    
  4. Run the gateway:

    mcpshield serve
    
    # Or with .env file:
    mcpshield serve --env-file .env
    

Setup (YAML Config - Optional)

For advanced users who prefer a configuration file, you can create mcpshield.yaml:

database:
  dsn: null  # Set via PG_DSN env var

api:
  base_url: "https://api.mcpshield.xyz"
  project_id: null  # Set via PROJECT_ID env var
  api_key: null  # Set via MCPSHIELD_API_KEY env var

policy:
  source: "remote"
  refresh_seconds: 60

# Optional: local policy file for fallback
# policy:
#   source: "remote_with_fallback"
#   file: "policy.yaml"

Then run with --config:

mcpshield doctor --config mcpshield.yaml
mcpshield serve --config mcpshield.yaml

Claude Code Integration

Add to your Claude Code MCP configuration (~/.claude/mcp.json):

Option 1: Environment Variables Only (Recommended)

{
  "mcpServers": {
    "mcpshield": {
      "command": "mcpshield",
      "args": ["serve"],
      "env": {
        "PG_DSN": "postgresql://user:pass@localhost:5432/db",
        "MCPSHIELD_API_KEY": "mcps_...",
        "PROJECT_ID": "proj_...",
        "API_BASE_URL": "https://api.mcpshield.xyz"
      }
    }
  }
}

Option 2: With .env File

{
  "mcpServers": {
    "mcpshield": {
      "command": "mcpshield",
      "args": ["serve", "--env-file", "/path/to/.env"]
    }
  }
}

Option 3: With YAML Config

{
  "mcpServers": {
    "mcpshield": {
      "command": "mcpshield",
      "args": ["serve", "--config", "/path/to/mcpshield.yaml"],
      "env": {
        "PG_DSN": "postgresql://user:pass@localhost:5432/db",
        "MCPSHIELD_API_KEY": "mcps_...",
        "PROJECT_ID": "proj_..."
      }
    }
  }
}

How Policy Synchronization Works

┌──────────────────────────────────────────────────────────────┐
│                     MCPShield Dashboard                      │
│                                                              │
│  1. Author policy in UI                                      │
│  2. Save policy (stored in database)                         │
│  3. policy_hash computed (SHA-256)                           │
└──────────────────────────┬───────────────────────────────────┘
                           │
                           │ GET /projects/{id}/policy
                           │
                           ▼
                  ┌────────────────────┐
                  │  MCPShield Gateway │
                  │                    │
                  │  On startup:       │
                  │  • Fetch policy    │
                  │  • Cache locally   │
                  │  • Compute hash    │
                  │                    │
                  │  Every 60s:        │
                  │  • Re-fetch policy │
                  │  • Update cache    │
                  │  • Update hash     │
                  └────────────────────┘
                           │
                           │ Every request includes:
                           │ • decision (allow/deny)
                           │ • policy_hash
                           │
                           ▼
                  ┌────────────────────┐
                  │   Audit Events     │
                  │                    │
                  │  {                 │
                  │    decision: allow │
                  │    policy_hash:... │
                  │  }                 │
                  └────────────────────┘

Configuration

Environment Variables

MCPShield supports configuration via environment variables (no YAML file required):

Required:

  • DSN, PG_DSN, or DATABASE_URL - Infrastructure connection string (database, API, etc.)
  • MCPSHIELD_BACKEND - Infrastructure type: postgres, mysql, sqlite, mongodb, or redis
  • PROJECT_ID - Your MCPShield project ID
  • MCPSHIELD_API_KEY - Your MCPShield API key

Optional:

  • API_BASE_URL - API endpoint (default: https://api.mcpshield.xyz)
  • POLICY_SOURCE - Policy source: remote, remote_with_fallback, or local (default: remote)
  • POLICY_FILE - Path to local policy file (for fallback)
  • POLICY_REFRESH_SECONDS - Policy refresh interval (default: 60)
  • SPOOL_DIR - Event spool directory (default: ~/.mcpshield/spool)
  • POLICY_CACHE_DIR - Policy cache directory (default: ~/.mcpshield/cache)
  • LOG_LEVEL - Logging level: DEBUG, INFO, WARNING, ERROR (default: INFO)
  • LOG_DECISIONS - Log policy decisions: true or false (default: true)
  • BATCH_SIZE - Event batch size (default: 10)
  • BATCH_TIMEOUT - Event batch timeout in seconds (default: 5)

Policy Source Options

remote (Recommended - Default):

  • Fetches policy from MCPShield API only
  • No local policy file needed
  • Fails if API unreachable (fail-closed)
  • Always uses latest policy from dashboard
  • Policy cached locally at ~/.mcpshield/cache/policy.yaml

remote_with_fallback:

  • Tries API first
  • Falls back to cached policy if API fails
  • Falls back to local file if cache unavailable
  • Provides resilience during API outages

local:

  • Uses local policy file only
  • No API calls
  • Useful for offline development
  • Requires POLICY_FILE to be set

Fail-Closed Behavior

Gateway WILL NOT start if:

  • Policy source is remote and API is unreachable (and no cache exists)
  • Policy source is remote_with_fallback and ALL of: API fails, no cache, no local file
  • This ensures gateway never operates without a policy

Documentation

Available Tools by Database Type

MCPShield provides consistent tooling across all supported infrastructure types:

PostgreSQL

  • postgres_query - Execute SQL queries (SELECT, INSERT, UPDATE, DELETE)
  • postgres_describe - List tables, columns, and types
  • postgres_dump - Generate SQL DDL backup (CREATE TABLE, indexes, constraints)
  • postgres_diagram - Generate Mermaid ER diagrams

MySQL

  • mysql_query - Execute SQL queries (SELECT, INSERT, UPDATE, DELETE)
  • mysql_describe - List tables, columns, and types
  • mysql_dump - Generate SQL DDL backup (CREATE TABLE, indexes, constraints)
  • mysql_diagram - Generate Mermaid ER diagrams

SQLite

  • sqlite_query - Execute SQL queries (SELECT, INSERT, UPDATE, DELETE)
  • sqlite_describe - List tables, columns, and types
  • sqlite_dump - Generate SQL DDL backup (CREATE TABLE, indexes, constraints)
  • sqlite_diagram - Generate Mermaid ER diagrams

MongoDB

  • mongodb_query - Execute find queries on collections
  • mongodb_aggregate - Execute aggregation pipelines
  • mongodb_describe - List collections and document structure
  • mongodb_insert - Insert documents into collections
  • mongodb_update - Update documents in collections
  • mongodb_delete - Delete documents from collections
  • mongodb_dump - Export collections and optionally documents
  • mongodb_diagram - Generate Mermaid ER diagrams of collections

Redis

  • redis_get - Get value by key
  • redis_set - Set key-value pairs with optional TTL
  • redis_delete - Delete one or more keys
  • redis_keys - List keys matching a pattern (uses SCAN)
  • redis_info - Get server info and stats
  • redis_describe - Database statistics and key patterns
  • redis_backup - Export keys and values matching a pattern

Security

MCPShield is designed with security-first principles:

  • Default Deny: All operations blocked unless explicitly allowed
  • Read-Only Enforcement: Blocks destructive SQL keywords
  • Schema Validation: Only access allowed tables
  • Data Redaction: Remove sensitive data (emails, phones) from results
  • Rate Limiting: Enforce query limits and timeouts
  • Audit Everything: Complete audit trail with policy_hash tracking

CLI Commands

# Run the gateway (env vars only)
mcpshield serve

# Run the gateway (with .env file)
mcpshield serve --env-file .env

# Run the gateway (with YAML config)
mcpshield serve --config mcpshield.yaml

# Validate configuration
mcpshield validate
mcpshield validate --env-file .env
mcpshield validate --config mcpshield.yaml

# Run diagnostics
mcpshield doctor
mcpshield doctor --env-file .env
mcpshield doctor --config mcpshield.yaml

# Get version
mcpshield --version

Support

License

MIT License - see LICENSE file for details

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcpshield-0.3.2.tar.gz (49.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcpshield-0.3.2-py3-none-any.whl (49.2 kB view details)

Uploaded Python 3

File details

Details for the file mcpshield-0.3.2.tar.gz.

File metadata

  • Download URL: mcpshield-0.3.2.tar.gz
  • Upload date:
  • Size: 49.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for mcpshield-0.3.2.tar.gz
Algorithm Hash digest
SHA256 5cd72cd44910908e910b1c322d9de736ebed5a78f5ab2591378a422bd92e60ca
MD5 b1c9a7871f24533834bf60d0c458caf0
BLAKE2b-256 2cd2cbc1b2832e803f16e42d45a2868d5ff7760889b5f8287ee8aa15021c3caf

See more details on using hashes here.

File details

Details for the file mcpshield-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: mcpshield-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 49.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for mcpshield-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 56b3717ff793882f1671f56cef165054658db5ab63c725ef4810756d0134990f
MD5 a3389a0a273dc6ca9ba12ae6bfb6265a
BLAKE2b-256 f6a92a51fb44bceb3fd6821997eae0a3bcc72944ef860736267791509fb0728e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page