# MCP Security Auditor

[![PyPI version](https://badge.fury.io/py/mcp-security-auditor.svg)](https://badge.fury.io/py/mcp-security-auditor)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://img.shields.io/badge/tests-112%20passed-brightgreen.svg)]()
[![Coverage](https://img.shields.io/badge/coverage-70%25-yellowgreen.svg)]()

A comprehensive security evaluation tool for Model Context Protocol (MCP) servers. Scan MCP servers for vulnerabilities, misconfigurations, and security risks before deploying them in sensitive environments like banking, legal, and enterprise data systems.

## Why MCP Security Auditor?

As AI assistants gain access to databases, filesystems, and APIs through MCP, security becomes critical. This tool helps you:

- 🛡️ **Prevent Data Breaches**: Detect hardcoded secrets and credentials
- 🔒 **Enforce Read-Only Mode**: Ensure database MCPs can't modify data
- ⚠️ **Find Injection Risks**: Detect prompt injection and SQL injection vulnerabilities
- ✅ **CI/CD Ready**: Integrate security scanning into your deployment pipeline
- 📊 **Compliance Reports**: Generate SARIF, HTML, and SIEM-compatible reports

## Features

### 🔍 Static Analysis
- **Dangerous Code Patterns**: Detect eval(), exec(), subprocess calls, and other risky patterns
- **Injection Vulnerabilities**: Find prompt injection, SQL injection, and command injection risks
- **Insecure Cryptography**: Identify weak hash algorithms and disabled SSL verification

### 🔒 Read-Only Mode Enforcement (NEW)
- **Database Write Detection**: Flag INSERT, UPDATE, DELETE, DROP, TRUNCATE operations
- **Connection Analysis**: Detect database connections without read-only mode (PostgreSQL, MySQL, SQLite, MongoDB, Redis)
- **Tool Annotation Audit**: Verify readOnlyHint is properly set on all tools
- **Cloud Storage**: Check S3, GCS, Azure Blob for write operations
- **Summary Report**: Clear indication if MCP server has write capabilities

### 🔐 Permission Analysis
- **Tool Annotation Auditing**: Verify MCP tool annotations (readOnlyHint, destructiveHint)
- **Implicit Permission Detection**: Find undeclared filesystem, network, and system access
- **Privilege Escalation Detection**: Identify sudo, chmod, and other elevation patterns

### 🌐 Network Analysis
- **Endpoint Discovery**: Extract and analyze all external URLs
- **SSRF Detection**: Find server-side request forgery vulnerabilities
- **Data Exfiltration Patterns**: Detect potential data leakage vectors
- **Protocol Security**: Flag insecure HTTP/FTP connections

### 📦 Dependency Analysis
- **Vulnerability Scanning**: Check dependencies against CVE databases
- **Typosquatting Detection**: Identify malicious package lookalikes
- **Version Pinning Audit**: Ensure reproducible builds
- **Lockfile Verification**: Check for missing or outdated lockfiles

### 🔑 Secrets Detection
- **API Key Detection**: Find exposed AWS, OpenAI, Anthropic, and other API keys
- **Credential Scanning**: Detect hardcoded passwords and tokens
- **Private Key Detection**: Find exposed SSH/PGP/SSL private keys
- **High-Entropy Analysis**: Identify potential secrets through entropy analysis

### ⚙️ Configuration Analysis
- **Debug Mode Detection**: Flag development settings in production
- **CORS Misconfiguration**: Find overly permissive CORS settings
- **Environment File Audit**: Check for committed .env files

## Installation

```bash
# Install from PyPI
pip install mcp-security-auditor

# Or install from source
git clone https://github.com/mcp-security-auditor/mcp-security-auditor
cd mcp-security-auditor
pip install -e .
```

## Quick Start

```bash
# Scan a local MCP server
mcp-audit scan ./my-mcp-server

# Scan with specific severity threshold
mcp-audit scan ./my-mcp-server --severity high

# Generate HTML report
mcp-audit scan ./my-mcp-server --format html --output report.html

# CI/CD mode with exit codes
mcp-audit ci ./my-mcp-server --fail-on high
```

## Usage

### Basic Scanning

```bash
# Scan local directory
mcp-audit scan /path/to/mcp-server

# Scan from Git URL
mcp-audit scan https://github.com/user/mcp-server.git

# Verbose output
mcp-audit scan ./my-server --verbose
```

### Output Formats

```bash
# Text output (default)
mcp-audit scan ./server

# JSON for programmatic use
mcp-audit scan ./server --format json --output results.json

# SARIF for GitHub/GitLab integration
mcp-audit scan ./server --format sarif --output results.sarif

# HTML for readable reports
mcp-audit scan ./server --format html --output report.html

# Markdown for documentation
mcp-audit scan ./server --format markdown --output report.md

# SIEM integration (CEF, LEEF, Splunk)
mcp-audit scan ./server --format siem --siem-format cef
mcp-audit scan ./server --format siem --siem-format splunk
```

### CI/CD Integration

```bash
# Fail on high or critical findings
mcp-audit ci ./server --fail-on high

# Generate SARIF for GitHub Security tab
mcp-audit ci ./server --format sarif --output security.sarif

# Use baseline to suppress known issues
mcp-audit ci ./server --baseline baseline.json
```

### Analyzer Selection

```bash
# Run only specific analyzers
mcp-audit scan ./server --include-analyzers static permissions

# Skip specific analyzers
mcp-audit scan ./server --skip-analyzers dependencies network

# Run only read-only mode checks (for database MCPs)
mcp-audit scan ./server --include-analyzers readonly
```

### Read-Only Mode Enforcement

For database MCPs or any MCP connecting to external data stores, ensuring read-only mode is critical:

```bash
# Check specifically for read-only mode violations
mcp-audit scan ./my-database-mcp --include-analyzers readonly

# Full scan with focus on high-severity write issues
mcp-audit scan ./my-database-mcp --severity high
```

The read-only analyzer checks:
- **SQL Operations**: INSERT, UPDATE, DELETE, DROP, TRUNCATE, ALTER, CREATE
- **Database Connections**: PostgreSQL, MySQL, SQLite, MongoDB, Redis, Elasticsearch
- **Cloud Storage**: AWS S3, Google Cloud Storage, Azure Blob
- **Tool Annotations**: Verifies `readOnlyHint` is properly set

Example remediation for PostgreSQL:
```python
# Before (UNSAFE - has write access)
conn = psycopg2.connect(host="localhost", database="mydb")

# After (SAFE - read-only mode enforced)
conn = psycopg2.connect(
    host="localhost",
    database="mydb",
    options="-c default_transaction_read_only=on"
)
```

### Configuration

Initialize a configuration file:

```bash
mcp-audit init --output .mcp-audit.yaml
```

Example configuration:

```yaml
# .mcp-audit.yaml
severity_threshold: info

analyzers:
  static: true
  permissions: true
  network: true
  dependencies: true
  injection: true
  config: true
  secrets: true

rules:
  allowed_domains:
    - api.anthropic.com
    - api.openai.com
    - your-internal-api.com
  
  forbidden_permissions:
    - system.shell
    - filesystem.root

ci:
  fail_on: high
  output_format: sarif
```

### Security Certification

Generate a security certification for your MCP server:

```bash
# Basic certification
mcp-audit certify ./server --level basic --output cert.json

# Enterprise certification (strictest)
mcp-audit certify ./server --level enterprise --output cert.json
```

Certification levels:
- **Basic**: No critical issues, up to 3 high severity
- **Standard**: No critical or high issues, up to 5 medium severity
- **Enterprise**: No critical, high, or medium issues

## Output Example

```
======================================================================
MCP Security Audit Report
======================================================================

Target: /path/to/mcp-server
Scan ID: a1b2c3d4
Date: 2024-01-15T10:30:00Z
Duration: 2.5s

Server Info:
  Name: my-mcp-server
  Language: python
  Framework: fastmcp
  Tools: 5
  Dependencies: 12

Risk Score: 45/100 (MEDIUM)

Findings Summary:
  Critical  : 0
  High      : 2
  Medium    : 5
  Low       : 3
  Info      : 1

======================================================================
Detailed Findings
======================================================================

[1] Hardcoded API Key
    Severity: CRITICAL
    Category: secrets
    CWE: CWE-798
    Location: src/api.py:45
    Code:
      43     
      44     # API configuration
  >>> 45     API_KEY = "sk-ant-abc123..."
      46     
    Remediation: Remove the API key from source code...

[2] Tool 'delete_files' missing destructiveHint annotation
    Severity: HIGH
    Category: permissions
    Location: src/tools.py:120
    Remediation: Set destructiveHint=True in tool annotations...
```

## GitHub Actions Integration

```yaml
# .github/workflows/security.yml
name: MCP Security Scan

on: [push, pull_request]

jobs:
  security-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      
      - name: Install MCP Security Auditor
        run: pip install mcp-security-auditor
      
      - name: Run Security Scan
        run: mcp-audit ci . --format sarif --output results.sarif
      
      - name: Upload SARIF results
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: results.sarif
```

## GitLab CI Integration

```yaml
# .gitlab-ci.yml
security-scan:
  image: python:3.11
  stage: test
  script:
    - pip install mcp-security-auditor
    - mcp-audit ci . --format json --output gl-sast-report.json
  artifacts:
    reports:
      sast: gl-sast-report.json
```

## SIEM Integration

### Splunk

```bash
# Generate Splunk-formatted events
mcp-audit scan ./server --format siem --siem-format splunk > events.json

# Configure Splunk HTTP Event Collector to ingest events
```

### CEF (ArcSight, QRadar)

```bash
# Generate CEF events
mcp-audit scan ./server --format siem --siem-format cef > events.cef
```

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success, no findings above threshold |
| 1 | Findings found above threshold |
| 2 | Error during scan |

## Supported Languages

- **Python**: FastMCP, MCP Python SDK
- **TypeScript**: MCP TypeScript SDK
- **JavaScript**: MCP JavaScript implementations

## Roadmap

### v1.0 (Current)
- ✅ Static code analysis
- ✅ Permission auditing
- ✅ Network analysis
- ✅ Dependency scanning
- ✅ Secrets detection
- ✅ CI/CD integration
- ✅ SIEM integration

### v2.0 (Planned)
- 🔲 Dynamic/runtime testing
- 🔲 Sandboxed execution
- 🔲 Behavioral analysis
- 🔲 Fuzzing capabilities
- 🔲 API compatibility testing

## Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

## License

MIT License - see LICENSE file for details.

## Security

If you discover a security vulnerability in this tool, please report it via GitHub Security Advisories.
