Metadata-Version: 2.4
Name: mcp-security-auditor
Version: 1.0.0
Summary: Security evaluation tool for MCP (Model Context Protocol) servers
Project-URL: Homepage, https://github.com/mcp-security-auditor/mcp-security-auditor
Project-URL: Documentation, https://github.com/mcp-security-auditor/mcp-security-auditor#readme
Project-URL: Repository, https://github.com/mcp-security-auditor/mcp-security-auditor
Project-URL: Issues, https://github.com/mcp-security-auditor/mcp-security-auditor/issues
Author-email: Prabhu Raja <prabhuswamiji@gmail.com>
License-Expression: MIT
Keywords: ai,audit,llm,mcp,model-context-protocol,scanner,security,vulnerability
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Requires-Dist: pyyaml>=6.0
Requires-Dist: tomli>=2.0; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: black>=23.0; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Provides-Extra: vuln-check
Requires-Dist: pip-audit>=2.0; extra == 'vuln-check'
Description-Content-Type: text/markdown

# 🔒 MCP Security Auditor

[![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)](https://pypi.org/project/mcp-security-auditor/)
[![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-passing-success.svg)](tests/)

A comprehensive security evaluation tool for Model Context Protocol (MCP) servers. Automatically scan MCP servers for vulnerabilities, misconfigurations, and security risks before deploying them in production or sensitive environments.

**🎯 Key Benefits:**
- 🔍 **Comprehensive Analysis**: 8 specialized analyzers covering 50+ vulnerability types
- ⚡ **Fast Scanning**: Complete security audits in seconds
- 🎨 **Multiple Formats**: Text, JSON, HTML, SARIF, Markdown, SIEM formats
- 🔄 **CI/CD Ready**: Seamless integration with GitHub Actions, GitLab, Azure DevOps
- 🏆 **Security Certification**: Official certification system (Basic/Standard/Enterprise)
- 🌐 **Multi-Language**: Python, TypeScript, JavaScript support
- 📊 **Actionable Reports**: Detailed remediation guidance with code examples

**Perfect for:**
- 🏢 Enterprise security teams evaluating MCP servers
- 👨‍💻 Developers building MCP servers
- 🔐 Security engineers conducting audits
- ☁️ DevOps teams integrating security checks
- 📋 Compliance teams requiring security certifications

---

## 📋 Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
  - [Command Overview](#command-overview)
  - [Basic Scanning](#basic-scanning)
  - [Output Formats](#output-formats)
  - [CI/CD Integration](#cicd-integration)
  - [Analyzer Selection](#analyzer-selection)
  - [Read-Only Mode Enforcement](#read-only-mode-enforcement)
  - [Configuration Management](#configuration-management)
  - [Security Certification](#security-certification)
- [Real-World Examples](#real-world-examples)
- [Output Example](#output-example)
- [CI/CD Platform Integration](#cicd-platform-integration)
- [SIEM Integration](#siem-integration)
- [Performance](#performance)
- [Exit Codes](#exit-codes)
- [Supported Languages & Frameworks](#supported-languages--frameworks)
- [Best Practices](#best-practices)
- [Common Vulnerabilities Detected](#common-vulnerabilities-detected)
- [Troubleshooting](#troubleshooting)
- [FAQ](#frequently-asked-questions-faq)
- [Roadmap](#roadmap)
- [Contributing](#contributing)
- [License](#license)
- [Security](#security)

---

## Features

### 🔍 Static Code Analysis
- **Dangerous Code Patterns**: Detect `eval()`, `exec()`, `subprocess.call()`, `os.system()` and other risky execution patterns
- **Unsafe Deserialization**: Identify `pickle.load()`, `yaml.load()`, and other unsafe deserialization methods
- **Insecure Cryptography**: Flag weak hash algorithms (MD5, SHA1), insecure random number generation
- **SSL/TLS Verification**: Detect disabled certificate verification (`verify=False`)
- **File Operation Safety**: Identify path traversal vulnerabilities and unsafe file operations
- **Multi-Language Support**: Analyze Python, TypeScript, and JavaScript codebases

### 🔒 Read-Only Mode Enforcement
- **Database Write Detection**: Flag INSERT, UPDATE, DELETE, DROP, TRUNCATE, ALTER, CREATE operations
- **Connection Analysis**: Detect database connections without read-only mode
  - PostgreSQL (checks for `default_transaction_read_only`)
  - MySQL (checks for read-only connections)
  - SQLite (detects write operations)
  - MongoDB (verifies read-only mode)
  - Redis (checks for write commands)
  - Elasticsearch (detects index/update operations)
- **Cloud Storage Write Detection**: Identify write operations for AWS S3, Google Cloud Storage, Azure Blob
- **Tool Annotation Audit**: Verify `readOnlyHint` is properly set on all tools
- **Write Operation Summary**: Clear indication if MCP server has write capabilities

### 🛡️ Injection Pattern Detection
- **SQL Injection**: Detect string concatenation in SQL queries and missing parameterization
- **Command Injection**: Find user input in shell commands, especially with `shell=True`
- **Prompt Injection**: Identify user-controlled input in LLM system prompts
- **Path Traversal**: Detect unsafe path construction with user input
- **Template Injection**: Find unsafe template rendering with user data

### 🔐 Permission Analysis
- **Tool Annotation Auditing**: Verify MCP tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`)
- **Missing Annotations**: Flag destructive operations without proper annotations
- **Incorrect Annotations**: Detect tools marked as read-only that perform write operations
- **Implicit Permission Detection**: Find undeclared filesystem, network, and system access
- **Privilege Escalation**: Identify `sudo`, `chmod`, `chown`, and other privilege elevation patterns

### 🌐 Network Security Analysis
- **Endpoint Discovery**: Extract and categorize all external URLs and API endpoints
- **SSRF Vulnerability Detection**: Identify user-controlled URLs in HTTP requests
- **Protocol Security**: Flag insecure protocols (HTTP, FTP) for sensitive operations
- **Suspicious Endpoints**: Detect connections to:
  - Temporary webhook services (webhook.site, ngrok, etc.)
  - Unknown or untrusted domains
  - IP addresses instead of domain names
- **Data Exfiltration Patterns**: Identify potential data leakage vectors

### 📦 Dependency Security
- **Dependency Extraction**: Parse `requirements.txt`, `pyproject.toml`, `package.json`
- **Version Tracking**: Extract and report all dependency versions
- **Vulnerability Scanning**: Optional integration with vulnerability databases (OSV, NVD)
- **Typosquatting Detection**: Identify suspicious package names similar to popular packages
- **Version Pinning Audit**: Ensure reproducible builds with pinned versions
- **Lockfile Verification**: Check for missing or outdated lockfiles

### 🔑 Secrets Detection
- **API Key Detection**: Find exposed API keys from 30+ services including:
  - AWS Access Keys (AKIA...), Secret Keys
  - OpenAI (sk-...), Anthropic (sk-ant-...)
  - GitHub, GitLab tokens
  - Stripe, SendGrid, Twilio keys
  - Database connection strings
- **Credential Scanning**: Detect hardcoded passwords, tokens, and authentication credentials
- **Private Key Detection**: Find exposed SSH, PGP, SSL/TLS private keys
- **High-Entropy String Analysis**: Identify potential secrets through entropy analysis
- **JWT Token Detection**: Find hardcoded JWT tokens and secrets

### ⚙️ Configuration Security
- **Debug Mode Detection**: Flag development settings in production (`DEBUG=True`, verbose logging)
- **CORS Misconfiguration**: Find overly permissive CORS settings (`Access-Control-Allow-Origin: *`)
- **Insecure Defaults**: Detect unsafe default configurations
- **Environment File Audit**: Check for committed `.env`, `.env.local`, config files with secrets
- **Logging Security**: Identify excessive logging that may leak sensitive data

## Installation

### From PyPI (Recommended)

```bash
# Install latest version
pip install mcp-security-auditor

# Install with vulnerability checking support
pip install mcp-security-auditor[vuln-check]

# Install with all optional dependencies
pip install mcp-security-auditor[dev]
```

### From Source

```bash
# Clone the repository
git clone https://github.com/prabhubng/mcp-security-auditor
cd mcp-security-auditor

# Install in development mode
pip install -e .

# Or install with development dependencies
pip install -e ".[dev]"
```

### Requirements

- **Python**: 3.10 or higher
- **Operating System**: Windows, macOS, Linux (platform-independent)
- **Optional**: Git (for scanning repositories via URL)

### Verify Installation

```bash
# Check version
mcp-audit --version

# Show help
mcp-audit --help
```

## Quick Start

### 1. Scan Your First MCP Server

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

# Output will show:
# - Security risk score (0-100)
# - Findings by severity (Critical, High, Medium, Low, Info)
# - Detailed vulnerability descriptions
# - Remediation recommendations
```

### 2. Focus on Specific Issues

```bash
# Only show high and critical severity issues
mcp-audit scan ./my-mcp-server --severity high

# Check for secrets and credentials
mcp-audit scan ./my-mcp-server --include-analyzers secrets

# Verify read-only mode for database MCP
mcp-audit scan ./db-mcp --include-analyzers readonly
```

### 3. Generate Reports

```bash
# HTML report (great for sharing with team)
mcp-audit scan ./my-mcp-server --format html --output security-report.html

# JSON report (for automation/integration)
mcp-audit scan ./my-mcp-server --format json --output results.json

# SARIF report (for GitHub Security tab)
mcp-audit scan ./my-mcp-server --format sarif --output results.sarif
```

### 4. CI/CD Integration

```bash
# Fail build if high or critical issues found
mcp-audit ci ./my-mcp-server --fail-on high

# Generate SARIF for GitHub/GitLab
mcp-audit ci ./my-mcp-server --format sarif --output security.sarif
```

### 5. Scan Remote Repository

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

# With severity filter
mcp-audit scan https://github.com/user/mcp-server.git --severity high
```

## Usage

### Command Overview

```bash
mcp-audit <command> [options]

Commands:
  scan      - Scan an MCP server for security vulnerabilities
  ci        - Run in CI/CD mode with exit codes based on findings
  report    - Generate report from previous scan results
  init      - Initialize configuration file
  certify   - Generate security certification for MCP server
```

### Basic Scanning

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

# Scan current directory
mcp-audit scan .

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

# Verbose output with detailed analyzer information
mcp-audit scan ./my-server --verbose

# Quiet mode (only show summary)
mcp-audit scan ./my-server --quiet

# Filter by severity threshold
mcp-audit scan ./server --severity high  # Only show high and critical
mcp-audit scan ./server --severity medium  # Show medium, high, and critical
```

### Output Formats

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

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

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

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

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

# SIEM integration formats
mcp-audit scan ./server --format siem --siem-format cef        # CEF (ArcSight, QRadar)
mcp-audit scan ./server --format siem --siem-format leef       # LEEF (QRadar)
mcp-audit scan ./server --format siem --siem-format splunk     # Splunk HEC
mcp-audit scan ./server --format siem --siem-format json-syslog # JSON Syslog

# Disable colored output (useful for CI/CD)
mcp-audit scan ./server --no-color
```

### CI/CD Integration

The `ci` command is optimized for CI/CD pipelines with appropriate exit codes:

```bash
# Exit 1 if high or critical findings are found
mcp-audit ci ./server --fail-on high

# Exit 1 if any medium, high, or critical findings
mcp-audit ci ./server --fail-on medium

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

# Generate JSON for custom processing
mcp-audit ci ./server --format json --output results.json

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

# Example: Generate baseline from current scan
mcp-audit scan ./server --format json --output baseline.json
# Review and edit baseline.json to add finding IDs to "suppressed_findings" array
```

**Exit Codes:**
- `0` - Success, no findings above threshold
- `1` - Findings found at or above severity threshold
- `2` - Error during scan (invalid path, parse error, etc.)

### Analyzer Selection

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

# Available analyzers:
#   static       - Static code analysis
#   permissions  - Permission and annotation analysis
#   network      - Network security analysis
#   dependencies - Dependency vulnerability scanning
#   injection    - Injection vulnerability detection
#   config       - Configuration security analysis
#   secrets      - Secrets and credential detection
#   readonly     - Read-only mode enforcement (critical for database MCPs)

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

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

# Fast scan: only critical analyzers
mcp-audit scan ./server --include-analyzers static secrets readonly

### Read-Only Mode Enforcement

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

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

# Combine with other critical analyzers
mcp-audit scan ./my-database-mcp --include-analyzers readonly static secrets
```

The read-only analyzer checks:

**SQL Operations:**
- Write operations: `INSERT`, `UPDATE`, `DELETE`, `DROP`, `TRUNCATE`, `ALTER`, `CREATE`
- Database-specific syntax variations

**Database Connections:**
- **PostgreSQL**: Verifies `default_transaction_read_only=on` in connection options
- **MySQL**: Checks for `SET SESSION TRANSACTION READ ONLY`
- **SQLite**: Detects `PRAGMA query_only` or read-only connection flags
- **MongoDB**: Verifies read preference and role restrictions
- **Redis**: Flags write commands (SET, DEL, FLUSHDB, etc.)
- **Elasticsearch**: Detects index/update/delete operations

**Cloud Storage:**
- **AWS S3**: Flags `put_object`, `delete_object`, `create_bucket` operations
- **Google Cloud Storage**: Detects `upload_blob`, `delete` operations
- **Azure Blob**: Identifies write/delete operations

**Tool Annotations:**
- Verifies `readOnlyHint` is properly set on all tools
- Flags tools performing write operations without `destructiveHint`

**Example Remediation:**

PostgreSQL:
```python
# ❌ UNSAFE - has write access
conn = psycopg2.connect(host="localhost", database="mydb", user="admin")

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

MongoDB:
```python
# ❌ UNSAFE
client = MongoClient("mongodb://localhost:27017/")

# ✅ SAFE - using read-only role
client = MongoClient("mongodb://readonly_user:pass@localhost:27017/")
db = client.mydb
# Ensure user has only read role in MongoDB
```

### Configuration Management

Initialize a configuration file with sensible defaults:

```bash
# Generate default configuration
mcp-audit init

# Generate with custom path
mcp-audit init --output config/security-audit.yaml

# Use custom configuration in scan
mcp-audit scan ./server --config config/security-audit.yaml
```

**Configuration File Structure (`.mcp-audit.yaml`):**

```yaml
# Minimum severity level to report
severity_threshold: info  # Options: critical, high, medium, low, info

# Analyzers to run (true = enabled)
analyzers:
  static: true        # Static code analysis
  permissions: true   # Permission and annotation checks
  network: true       # Network security analysis
  dependencies: true  # Dependency vulnerability scanning
  injection: true     # Injection vulnerability detection
  config: true        # Configuration security
  secrets: true       # Secrets detection
  readonly: true      # Read-only mode enforcement

# Custom security rules
rules:
  # Patterns considered dangerous
  dangerous_patterns:
    - pattern: "eval\\("
      severity: critical
      description: "Dynamic code execution detected"
    - pattern: "exec\\("
      severity: critical
      description: "System command execution detected"
  
  # Allowed external domains
  allowed_domains:
    - "api.anthropic.com"
    - "api.openai.com"
    - "modelcontextprotocol.io"
    - "your-trusted-api.com"
  
  # Forbidden permissions
  forbidden_permissions:
    - "system.shell"
    - "filesystem.root"

# Dependency scanning configuration
dependencies:
  check_vulnerabilities: true
  vulnerability_sources:
    - osv  # Open Source Vulnerabilities
    - nvd  # National Vulnerability Database

# Read-only mode enforcement
readonly:
  require_readonly_annotation: true  # All tools must declare readOnlyHint
  strict_mode: false                  # Fail on any write operation
  allowed_write_tools: []             # Exceptions (if strict_mode: false)

# Secrets detection patterns
secrets:
  patterns:
    - name: "AWS Access Key"
      pattern: "AKIA[0-9A-Z]{16}"
      severity: critical
    - name: "Generic API Key"
      pattern: "[a-zA-Z0-9_-]*api[_-]?key[a-zA-Z0-9_-]*\\s*[=:]\\s*['\"][^'\"]{16,}['\"]"
      severity: high

# CI/CD settings
ci:
  fail_on: high           # Exit 1 if findings at this level or above
  output_format: sarif    # Default format for CI mode

# SIEM integration
siem:
  format: cef
  vendor: "MCPAuditor"
  product: "MCP Security Auditor"
  version: "1.0"

# Report generation
report:
  include_remediation: true      # Include fix recommendations
  include_code_snippets: true    # Show vulnerable code
  max_snippet_lines: 10          # Lines of context
```

### Security Certification

Generate official security certification for your MCP server:

```bash
# Standard certification (recommended)
mcp-audit certify ./server --level standard --output certification.json

# Basic certification (lenient)
mcp-audit certify ./server --level basic --output cert.json

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

**Certification Levels:**

| Level | Critical | High | Medium | Use Case |
|-------|----------|------|--------|----------|
| **Basic** | 0 | ≤3 | ≤10 | Development, testing environments |
| **Standard** | 0 | 0 | ≤5 | Production, general use |
| **Enterprise** | 0 | 0 | 0 | High-security, sensitive data environments |

**Certification Output:**

```json
{
  "certified": true,
  "level": "standard",
  "certification_id": "MCP-CERT-20260123153045",
  "target": "./my-mcp-server",
  "scan_date": "2026-01-23T15:30:45.123456",
  "expiry_date": "2027-01-23T15:30:45.123456",
  "risk_score": 12,
  "findings_summary": {
    "critical": 0,
    "high": 0,
    "medium": 2,
    "low": 5,
    "info": 3
  },
  "thresholds": {
    "critical": 0,
    "high": 0,
    "medium": 5
  },
  "scanner_version": "1.0.0"
}
```

**Exit Codes:**
- `0` - Certification passed
- `1` - Certification failed (findings exceed threshold)

## Real-World Examples

### Example 1: Database MCP Security Audit

Scenario: You have an MCP server that connects to PostgreSQL for data retrieval.

```bash
# Full security scan
mcp-audit scan ./postgres-mcp --verbose

# Focus on read-only violations
mcp-audit scan ./postgres-mcp --include-analyzers readonly --severity high

# Generate report for security review
mcp-audit scan ./postgres-mcp --format html --output postgres-security.html
```

**Common Findings:**
- Missing `default_transaction_read_only=on` in connection
- Tools performing DELETE/UPDATE without `destructiveHint`
- SQL injection vulnerabilities in query construction

### Example 2: Pre-Deployment CI/CD Check

Scenario: Integrate security checks into your GitHub Actions workflow.

```bash
# In CI/CD pipeline (see GitHub Actions section below)
mcp-audit ci . --fail-on high --format sarif --output results.sarif

# Exit code 0 = passed, 1 = failed, 2 = error
# Automatically upload SARIF to GitHub Security tab
```

### Example 3: Third-Party MCP Evaluation

Scenario: Evaluate a community MCP server before installing.

```bash
# Scan directly from GitHub
mcp-audit scan https://github.com/community/cool-mcp-server.git

# Focus on critical issues
mcp-audit scan https://github.com/community/cool-mcp-server.git \
  --severity high \
  --format markdown \
  --output evaluation.md

# Check for secrets in code
mcp-audit scan https://github.com/community/cool-mcp-server.git \
  --include-analyzers secrets static
```

### Example 4: Security Certification

Scenario: Get official certification for your production MCP.

```bash
# Run full scan first
mcp-audit scan ./production-mcp --format json --output full-scan.json

# Apply for standard certification
mcp-audit certify ./production-mcp --level standard --output cert.json

# If failed, review issues and fix
mcp-audit scan ./production-mcp --severity medium

# Re-certify after fixes
mcp-audit certify ./production-mcp --level standard --output cert.json
```

### Example 5: SIEM Integration

Scenario: Send security findings to your SIEM platform.

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

# Splunk HTTP Event Collector format
mcp-audit scan ./mcp-server --format siem --siem-format splunk > findings.json

# Pipe to syslog
mcp-audit scan ./mcp-server --format siem --siem-format json-syslog | \
  logger -t mcp-audit -n siem.company.com -P 514
```

### Example 6: Baseline Management for Known Issues

Scenario: Suppress known/accepted findings in CI/CD.

```bash
# Initial scan - save as baseline
mcp-audit scan ./mcp-server --format json --output baseline.json

# Edit baseline.json to add accepted finding IDs:
# {
#   "suppressed_findings": [
#     "finding-id-1",
#     "finding-id-2"
#   ]
# }

# Future CI runs ignore baseline findings
mcp-audit ci ./mcp-server --baseline baseline.json --fail-on high
```

### Example 7: Custom Configuration

Scenario: Enforce company-specific security policies.

```bash
# Generate configuration template
mcp-audit init --output .mcp-audit.yaml

# Edit .mcp-audit.yaml with your policies:
# - allowed_domains: [api.company.com]
# - forbidden_permissions: [system.shell]
# - custom dangerous_patterns

# Run scan with custom config
mcp-audit scan ./mcp-server --config .mcp-audit.yaml
```

## Output Example

### Text Output (Console)

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

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

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

Analyzers Run:
  ✓ static        - Static code analysis
  ✓ permissions   - Permission and annotation checks
  ✓ network       - Network security analysis
  ✓ secrets       - Secrets detection
  ✓ readonly      - Read-only mode enforcement
  ✓ injection     - Injection vulnerability detection
  ○ dependencies  - (skipped)
  ○ config        - (skipped)

Risk Score: 45/100 (MEDIUM)

Findings Summary:
  Critical  : 1  🔴
  High      : 2  🟠
  Medium    : 5  🟡
  Low       : 3  ⚪
  Info      : 1  🔵

======================================================================
CRITICAL Findings (1)
======================================================================

[CRIT-001] Hardcoded Anthropic API Key
    Severity: CRITICAL
    Category: secrets
    Confidence: HIGH
    CWE: CWE-798 (Hardcoded Credentials)
    OWASP: A07:2021 - Identification and Authentication Failures
    
    Location: src/api.py:45
    
    Code Context:
      43 |
      44 | # API configuration
      45 | API_KEY = "sk-ant-api03-abc123def456ghi789..."  ← VULNERABLE
      46 | 
      47 | def get_api_client():
    
    Impact:
      Exposed API key allows unauthorized access to Anthropic API,
      potentially leading to:
      - Unauthorized API usage and billing
      - Data exfiltration through API calls
      - Reputation damage
    
    Remediation:
      1. Remove the API key from source code immediately
      2. Revoke the exposed key in Anthropic Console
      3. Use environment variables: os.environ.get("ANTHROPIC_API_KEY")
      4. Never commit secrets to version control
      5. Consider using a secrets management system (AWS Secrets Manager,
         HashiCorp Vault, etc.)
    
    References:
      - https://docs.anthropic.com/en/api/security
      - https://cwe.mitre.org/data/definitions/798.html

======================================================================
HIGH Findings (2)
======================================================================

[HIGH-001] SQL Injection via String Concatenation
    Severity: HIGH
    Category: injection
    Confidence: HIGH
    CWE: CWE-89 (SQL Injection)
    
    Location: src/database.py:137
    
    Code Context:
      135 | def query_user(name):
      136 |     cursor = conn.cursor()
      137 |     query = f"SELECT * FROM users WHERE name = '{name}'"  ← VULNERABLE
      138 |     cursor.execute(query)
    
    Remediation:
      Use parameterized queries:
        cursor.execute("SELECT * FROM users WHERE name = %s", (name,))

[HIGH-002] Tool 'delete_files' has incorrect readOnlyHint
    Severity: HIGH
    Category: permissions
    Confidence: HIGH
    
    Location: src/tools.py:54
    
    Tool Definition:
      @mcp.tool(
          name="delete_files",
          annotations={
              "readOnlyHint": True,  ← INCORRECT (performs deletion)
          }
      )
    
    Impact:
      Tool performs destructive file operations but claims to be read-only,
      potentially bypassing safety checks.
    
    Remediation:
      Update annotations:
        annotations={
            "readOnlyHint": False,
            "destructiveHint": True,
        }

======================================================================
MEDIUM Findings (5)
======================================================================

[MED-001] Database Connection Without Read-Only Mode
    Severity: MEDIUM
    Category: readonly
    
    Location: src/database.py:23
    
    Code Context:
      22 | import psycopg2
      23 | conn = psycopg2.connect(host="localhost", database="mydb")
    
    Remediation:
      conn = psycopg2.connect(
          host="localhost",
          database="mydb",
          options="-c default_transaction_read_only=on"
      )

[MED-002] Insecure HTTP Endpoint
    Severity: MEDIUM
    Category: network
    Location: src/api.py:161
    Endpoint: http://analytics.example.com/track
    
    Remediation: Use HTTPS for all external communications

... (3 more medium findings)

======================================================================
Scan Complete
======================================================================

Summary:
  ⚠️  Found 11 security issues
  🔴  1 CRITICAL - Fix immediately
  🟠  2 HIGH - Fix before deployment
  🟡  5 MEDIUM - Address soon
  
  📊 Risk Score: 45/100 (MEDIUM RISK)
  
Next Steps:
  1. Address all CRITICAL and HIGH severity findings
  2. Review MEDIUM severity findings
  3. Re-run scan to verify fixes
  4. Consider security certification: mcp-audit certify ./server --level standard

💡 Tip: Generate detailed HTML report:
   mcp-audit scan ./server --format html --output report.html
```

### JSON Output (Programmatic)

```json
{
  "scan_id": "a1b2c3d4",
  "scan_date": "2026-01-23T10:30:00.123456",
  "scanner_version": "1.0.0",
  "target_path": "/path/to/mcp-server",
  "scan_duration_seconds": 2.5,
  "server_info": {
    "name": "my-mcp-server",
    "version": "1.0.0",
    "language": "python",
    "framework": "fastmcp",
    "path": "/path/to/mcp-server",
    "tools": [
      {
        "name": "delete_files",
        "description": "Delete files at the specified path",
        "annotations": {
          "readOnlyHint": true,
          "destructiveHint": false
        },
        "file_path": "src/tools.py",
        "line_number": 54
      }
    ],
    "dependencies": [
      {"name": "fastmcp", "version": "0.1.0", "source": "pypi"},
      {"name": "pydantic", "version": "2.5.0", "source": "pypi"}
    ],
    "endpoints": [
      {
        "url": "http://analytics.example.com/track",
        "method": "POST",
        "file_path": "src/api.py",
        "line_number": 161
      }
    ]
  },
  "findings": [
    {
      "id": "CRIT-001",
      "title": "Hardcoded Anthropic API Key",
      "severity": "critical",
      "category": "secrets",
      "confidence": "high",
      "cwe": "CWE-798",
      "owasp": "A07:2021",
      "description": "Anthropic API key found in source code",
      "file_path": "src/api.py",
      "line_number": 45,
      "code_snippet": "API_KEY = \"sk-ant-api03-abc123...\"",
      "impact": "Exposed API key allows unauthorized access...",
      "remediation": "Remove API key from source code...",
      "references": [
        "https://docs.anthropic.com/en/api/security",
        "https://cwe.mitre.org/data/definitions/798.html"
      ]
    }
  ],
  "risk_score": 45,
  "findings_summary": {
    "critical": 1,
    "high": 2,
    "medium": 5,
    "low": 3,
    "info": 1,
    "total": 12
  },
  "analyzers_run": [
    "static", "permissions", "network", "secrets", "readonly", "injection"
  ]
}
```

## CI/CD Platform Integration

### GitHub Actions

**Basic Security Scan:**

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

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  security-scan:
    runs-on: ubuntu-latest
    permissions:
      # Required for uploading SARIF results
      security-events: write
      contents: read
    
    steps:
      - name: Checkout code
        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 . --fail-on high --format sarif --output results.sarif
      
      - name: Upload SARIF to GitHub Security
        uses: github/codeql-action/upload-sarif@v3
        if: always()  # Upload even if scan fails
        with:
          sarif_file: results.sarif
      
      - name: Upload Scan Results as Artifact
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: security-scan-results
          path: results.sarif
```

**Advanced with HTML Report:**

```yaml
name: MCP Security - Full Report

on:
  schedule:
    - cron: '0 0 * * 0'  # Weekly on Sunday
  workflow_dispatch:     # Manual trigger

jobs:
  security-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      
      - name: Install auditor
        run: pip install mcp-security-auditor
      
      - name: Run comprehensive scan
        run: |
          mcp-audit scan . --format html --output security-report.html
          mcp-audit scan . --format json --output security-report.json
      
      - name: Generate certification
        run: mcp-audit certify . --level standard --output certification.json
        continue-on-error: true
      
      - name: Upload reports
        uses: actions/upload-artifact@v4
        with:
          name: security-reports
          path: |
            security-report.html
            security-report.json
            certification.json
```

### GitLab CI/CD

**Basic Integration:**

```yaml
# .gitlab-ci.yml
stages:
  - test
  - security

mcp-security-scan:
  stage: security
  image: python:3.11
  before_script:
    - pip install mcp-security-auditor
  script:
    - mcp-audit ci . --fail-on high --format json --output gl-sast-report.json
  artifacts:
    reports:
      sast: gl-sast-report.json
    paths:
      - gl-sast-report.json
    expire_in: 1 week
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
    - if: $CI_MERGE_REQUEST_ID
```

**With HTML Report:**

```yaml
mcp-security-full:
  stage: security
  image: python:3.11
  script:
    - pip install mcp-security-auditor
    - mcp-audit scan . --format html --output security-report.html
    - mcp-audit scan . --format json --output security-report.json
  artifacts:
    paths:
      - security-report.html
      - security-report.json
    expire_in: 30 days
  only:
    - main
    - merge_requests
```

### Azure DevOps

```yaml
# azure-pipelines.yml
trigger:
  - main
  - develop

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.11'
    addToPath: true

- script: |
    pip install mcp-security-auditor
  displayName: 'Install MCP Security Auditor'

- script: |
    mcp-audit ci . --fail-on high --format sarif --output results.sarif
  displayName: 'Run MCP Security Scan'
  continueOnError: true

- task: PublishBuildArtifacts@1
  inputs:
    pathToPublish: 'results.sarif'
    artifactName: 'CodeAnalysisLogs'
  displayName: 'Publish Security Results'

- script: |
    mcp-audit scan . --format html --output $(Build.ArtifactStagingDirectory)/security-report.html
  displayName: 'Generate HTML Report'

- task: PublishBuildArtifacts@1
  inputs:
    pathToPublish: '$(Build.ArtifactStagingDirectory)/security-report.html'
    artifactName: 'SecurityReports'
  displayName: 'Publish HTML Report'
```

### Jenkins

```groovy
// Jenkinsfile
pipeline {
    agent any
    
    stages {
        stage('Setup') {
            steps {
                sh 'pip install mcp-security-auditor'
            }
        }
        
        stage('Security Scan') {
            steps {
                sh 'mcp-audit ci . --fail-on high --format json --output results.json'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'results.json'
                }
            }
        }
        
        stage('Generate Report') {
            steps {
                sh 'mcp-audit scan . --format html --output security-report.html'
            }
            post {
                always {
                    publishHTML([
                        reportName: 'MCP Security Report',
                        reportDir: '.',
                        reportFiles: 'security-report.html',
                        keepAll: true
                    ])
                }
            }
        }
    }
}
```

### CircleCI

```yaml
# .circleci/config.yml
version: 2.1

jobs:
  security-scan:
    docker:
      - image: python:3.11
    steps:
      - checkout
      - run:
          name: Install MCP Security Auditor
          command: pip install mcp-security-auditor
      - run:
          name: Run Security Scan
          command: mcp-audit ci . --fail-on high --format json --output results.json
      - store_artifacts:
          path: results.json
          destination: security-scan

workflows:
  version: 2
  build-and-scan:
    jobs:
      - security-scan
```

## 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
```

## Performance

### Scan Speed

MCP Security Auditor is optimized for fast scans without compromising accuracy:

| Project Size | Files | Lines of Code | Scan Time | Analyzers |
|--------------|-------|---------------|-----------|-----------|
| **Small** | 1-10 | < 1,000 | 1-3 sec | All (8) |
| **Medium** | 10-50 | 1K-10K | 5-15 sec | All (8) |
| **Large** | 50-200 | 10K-50K | 20-40 sec | All (8) |
| **Very Large** | 200+ | 50K+ | 1-2 min | All (8) |

### Performance Tips

**1. Selective Analyzer Execution**
```bash
# Fast CI check (2-5 seconds)
mcp-audit scan . --include-analyzers static secrets readonly

# Skip slow analyzers
mcp-audit scan . --skip-analyzers dependencies network
```

**2. Severity Filtering**
```bash
# Only analyze critical issues (faster)
mcp-audit scan . --severity critical

# Common production filter
mcp-audit scan . --severity high
```

**3. Parallel Scanning**
```bash
# Scan multiple servers in parallel
for server in server1 server2 server3; do
    (mcp-audit scan "./$server" --output "${server}.json" &)
done
wait
```

**4. CI/CD Optimization**
```yaml
# Use ci command (optimized for speed)
mcp-audit ci . --fail-on high

# Cache pip packages in CI
- uses: actions/cache@v3
  with:
    path: ~/.cache/pip
    key: ${{ runner.os }}-pip-mcp-audit
```

### Resource Usage

| Metric | Typical | Peak |
|--------|---------|------|
| **Memory** | 50-100 MB | 200 MB |
| **CPU** | 1 core | 1-2 cores |
| **Disk I/O** | Minimal | Low |
| **Network** | None* | None* |

\* No network calls except when scanning from Git URLs or using vulnerability database lookups (optional)

### Benchmarks

Tested on: Intel i7-10th Gen, 16GB RAM, SSD

```bash
# Real-world MCP server (FastMCP, 25 files, 2,500 LOC)
$ time mcp-audit scan ./mcp-server
Scan completed in 3.2 seconds

# Large MCP server (50 files, 8,000 LOC)
$ time mcp-audit scan ./large-server
Scan completed in 12.7 seconds

# With all analyzers, HTML output
$ time mcp-audit scan ./server --format html --output report.html
Scan completed in 4.1 seconds
```

## Exit Codes

The tool uses standard exit codes for automation and CI/CD integration:

| Code | Meaning | Example |
|------|---------|---------|
| **0** | Success, no findings above threshold | `mcp-audit ci . --fail-on high` (no high/critical found) |
| **1** | Findings found at or above threshold | `mcp-audit ci . --fail-on high` (high/critical found) |
| **2** | Error during scan (invalid path, parse error) | `mcp-audit scan /nonexistent` |

### Exit Code Examples

```bash
# Exit 0 - Clean scan
$ mcp-audit ci ./secure-server --fail-on high
✅ No findings at or above 'high' severity
$ echo $?
0

# Exit 1 - Security issues found
$ mcp-audit ci ./vulnerable-server --fail-on medium
❌ Found 3 findings at or above 'medium' severity
$ echo $?
1

# Exit 2 - Scan error
$ mcp-audit scan /invalid/path
❌ Scan failed: Target path does not exist
$ echo $?
2

# Use in scripts
if mcp-audit ci . --fail-on high; then
    echo "Security check passed"
    deploy_to_production
else
    echo "Security issues found, blocking deployment"
    exit 1
fi
```

## Supported Languages & Frameworks

### Python
- **FastMCP**: Full support with automatic tool extraction
- **MCP Python SDK**: Official SDK support
- **Framework Detection**: Automatic detection via imports and dependencies
- **Analyzed Files**: `.py`, `pyproject.toml`, `requirements.txt`, `setup.py`

### TypeScript
- **MCP TypeScript SDK**: Full support (`@modelcontextprotocol/sdk`)
- **Framework Detection**: Via `package.json` dependencies
- **Analyzed Files**: `.ts`, `.tsx`, `package.json`, `tsconfig.json`

### JavaScript
- **MCP JavaScript SDK**: Full support
- **Modern JavaScript**: ES6+, CommonJS, ESM modules
- **Analyzed Files**: `.js`, `.mjs`, `.cjs`, `package.json`

### Detection Capabilities
- ✅ Automatic language detection
- ✅ Framework/SDK identification
- ✅ Tool definition extraction
- ✅ Dependency analysis
- ✅ Permission annotation parsing
- ✅ Multi-file project support

## Best Practices

### 1. Pre-Deployment Scanning
Always scan MCP servers before deploying to production:

```bash
# Development
mcp-audit scan . --severity medium

# Staging
mcp-audit scan . --severity high --format html --output staging-report.html

# Production
mcp-audit ci . --fail-on high
```

### 2. Read-Only Mode for Data Access
Enforce read-only mode for all data retrieval MCPs:

```bash
# Always check read-only enforcement
mcp-audit scan . --include-analyzers readonly

# Strict enforcement in CI
mcp-audit ci . --fail-on medium --include-analyzers readonly static
```

**Python PostgreSQL Example:**
```python
# ✅ SECURE: Read-only enforced
import psycopg2

conn = psycopg2.connect(
    host="db.example.com",
    database="mydb",
    user="readonly_user",
    password=os.environ["DB_PASSWORD"],
    options="-c default_transaction_read_only=on"
)
```

### 3. Tool Annotation Guidelines
Always annotate tools with accurate hints:

```python
# ✅ CORRECT: Destructive tool properly annotated
@mcp.tool(
    name="delete_user",
    annotations={
        "readOnlyHint": False,
        "destructiveHint": True,
        "idempotentHint": False,
    }
)
async def delete_user(user_id: str) -> str:
    """Delete a user account."""
    # ... deletion logic ...
    return f"Deleted user {user_id}"

# ✅ CORRECT: Read-only tool properly annotated
@mcp.tool(
    name="get_user",
    annotations={
        "readOnlyHint": True,
        "destructiveHint": False,
        "idempotentHint": True,
    }
)
async def get_user(user_id: str) -> dict:
    """Retrieve user information."""
    # ... retrieval logic ...
    return user_data
```

### 4. Secrets Management
Never hardcode secrets - use environment variables:

```python
# ❌ WRONG: Hardcoded secret
API_KEY = "sk-ant-api03-abc123..."

# ✅ CORRECT: Environment variable
import os
API_KEY = os.environ.get("ANTHROPIC_API_KEY")
if not API_KEY:
    raise ValueError("ANTHROPIC_API_KEY environment variable not set")
```

### 5. SQL Injection Prevention
Always use parameterized queries:

```python
# ❌ WRONG: String concatenation
query = f"SELECT * FROM users WHERE email = '{email}'"
cursor.execute(query)

# ✅ CORRECT: Parameterized query
query = "SELECT * FROM users WHERE email = %s"
cursor.execute(query, (email,))
```

### 6. Input Validation
Validate and sanitize all user inputs:

```python
from pathlib import Path

@mcp.tool(name="read_file")
async def read_file(file_path: str) -> str:
    # ✅ Validate and sanitize path
    base_dir = Path("/allowed/directory")
    requested_path = (base_dir / file_path).resolve()
    
    # Prevent path traversal
    if not str(requested_path).startswith(str(base_dir)):
        raise ValueError("Invalid path: outside allowed directory")
    
    # Check if file exists
    if not requested_path.is_file():
        raise FileNotFoundError(f"File not found: {file_path}")
    
    return requested_path.read_text()
```

### 7. Regular Security Audits
Schedule regular security scans:

```bash
# Weekly comprehensive scan
mcp-audit scan . --format html --output weekly-report-$(date +%Y%m%d).html

# Daily critical checks in CI
mcp-audit ci . --fail-on high --include-analyzers static secrets readonly
```

### 8. Baseline Management
Track and manage security findings over time:

```bash
# Week 1: Create baseline
mcp-audit scan . --format json --output baseline-week1.json

# Week 2: Compare against baseline
mcp-audit ci . --baseline baseline-week1.json --fail-on high

# Update baseline after fixing issues
mcp-audit scan . --format json --output baseline-week2.json
```

### 9. HTTPS Only for External Calls
Always use HTTPS for external API calls:

```python
import httpx

# ❌ WRONG: HTTP not secure
response = httpx.get("http://api.example.com/data")

# ❌ WRONG: Disabled SSL verification
response = httpx.get("https://api.example.com/data", verify=False)

# ✅ CORRECT: HTTPS with verification
response = httpx.get("https://api.example.com/data", verify=True)
```

### 10. Certification Before Release
Obtain security certification before releasing:

```bash
# Target standard certification for production
mcp-audit certify . --level standard --output certification.json

# Enterprise certification for high-security environments
mcp-audit certify . --level enterprise --output certification.json
```

## Common Vulnerabilities Detected

The MCP Security Auditor can detect 50+ types of security issues. Here are the most common:

### Critical Severity
- **Hardcoded API Keys**: AWS, OpenAI, Anthropic, GitHub tokens in source code
- **SQL Injection**: String concatenation in SQL queries
- **Command Injection**: User input in `subprocess.run()`, `os.system()`
- **Code Execution**: Use of `eval()`, `exec()` with user input
- **Private Keys**: Exposed SSH, SSL/TLS private keys

### High Severity
- **Missing Tool Annotations**: Destructive tools without `destructiveHint`
- **Incorrect Annotations**: Write operations marked as read-only
- **SSRF Vulnerabilities**: User-controlled URLs in HTTP requests
- **Unsafe Deserialization**: `pickle.load()`, `yaml.load()` without SafeLoader
- **Disabled SSL Verification**: `verify=False` in HTTP clients
- **Write Operations Without Read-Only Mode**: Database connections allowing writes

### Medium Severity
- **Weak Cryptography**: MD5, SHA1 for password hashing
- **Insecure Random**: Using `random` instead of `secrets` for tokens
- **HTTP Instead of HTTPS**: Unencrypted external connections
- **Missing Permission Declarations**: Implicit filesystem/network access
- **Path Traversal**: Unsafe file path construction
- **Excessive Logging**: Potential PII/secret leakage in logs

### Low Severity
- **Debug Mode Enabled**: `DEBUG=True` in production
- **Missing Version Pins**: Unpinned dependencies
- **Suspicious Endpoints**: Connections to webhook.site, ngrok
- **Deprecated Functions**: Use of outdated/unsafe APIs

## Troubleshooting

### Common Issues

**Issue: "Target path does not exist"**
```bash
# Solution: Check path is correct
mcp-audit scan ./correct-path-to-server

# For Windows users, use forward slashes or escape backslashes
mcp-audit scan C:/work/mcp-server
# or
mcp-audit scan C:\\work\\mcp-server
```

**Issue: "Failed to clone repository"**
```bash
# Solution: Ensure Git is installed and accessible
git --version

# Check repository URL is correct
mcp-audit scan https://github.com/user/repo.git
```

**Issue: "No tools found"**
```bash
# Run with verbose to see what's being detected
mcp-audit scan . --verbose

# Tools might be in subdirectory
mcp-audit scan ./src

# Ensure using FastMCP or MCP SDK decorators
# Python: @mcp.tool() or @server.tool()
# TypeScript: server.tool() or registerTool()
```

**Issue: "Too many false positives"**
```bash
# Increase severity threshold
mcp-audit scan . --severity high

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

# Use baseline to suppress known issues
mcp-audit scan . --format json --output baseline.json
# Edit baseline.json to add suppressed_findings
mcp-audit ci . --baseline baseline.json
```

**Issue: "SARIF upload fails in GitHub Actions"**
```yaml
# Ensure security-events permission is granted
permissions:
  security-events: write
  contents: read

# Use if: always() to upload even on scan failure
- name: Upload SARIF
  uses: github/codeql-action/upload-sarif@v3
  if: always()
  with:
    sarif_file: results.sarif
```

### Getting Help

- **Documentation**: Check this README thoroughly
- **Issues**: [GitHub Issues](https://github.com/prabhubng/mcp-security-auditor/issues)
- **Verbose Mode**: Run with `--verbose` for detailed output
- **Example Servers**: Check `tests/fixtures/` for example vulnerable servers

## Roadmap

### v1.0 (Current - January 2026)
- ✅ **Static Code Analysis**: Detect dangerous patterns, unsafe functions
- ✅ **Permission Auditing**: Verify tool annotations and implicit permissions
- ✅ **Network Security**: Endpoint discovery, SSRF detection, protocol analysis
- ✅ **Dependency Scanning**: Extract and analyze dependencies
- ✅ **Secrets Detection**: 30+ secret patterns including API keys, tokens
- ✅ **Read-Only Mode Enforcement**: Database, cloud storage write detection
- ✅ **Injection Detection**: SQL, command, prompt injection patterns
- ✅ **Configuration Analysis**: Debug mode, CORS, environment files
- ✅ **CI/CD Integration**: Exit codes, baselines, multiple output formats
- ✅ **SIEM Integration**: CEF, LEEF, Splunk, JSON-syslog formats
- ✅ **Multi-Format Reports**: Text, JSON, HTML, Markdown, SARIF
- ✅ **Security Certification**: Basic, Standard, Enterprise levels
- ✅ **Multi-Language Support**: Python, TypeScript, JavaScript

### v1.1 (Q2 2026)
- 🔄 **Enhanced Dependency Analysis**: CVE database integration (OSV, NVD)
- 🔄 **Advanced Pattern Detection**: Custom rule engine with regex
- 🔄 **Performance Optimization**: Faster scans for large codebases
- 🔄 **Report Enhancements**: PDF export, custom templates
- 🔄 **IDE Integration**: VSCode extension, JetBrains plugin
- 🔄 **Git History Scanning**: Scan commit history for leaked secrets

### v2.0 (Q4 2026)
- 🔲 **Dynamic Analysis**: Runtime behavior monitoring
- 🔲 **Sandboxed Execution**: Safe test execution environment
- 🔲 **Behavioral Analysis**: Detect anomalous patterns at runtime
- 🔲 **Fuzzing Capabilities**: Automated input fuzzing for tools
- 🔲 **API Compatibility Testing**: Test against MCP specification
- 🔲 **Interactive Mode**: Guided security review process
- 🔲 **Machine Learning**: AI-powered vulnerability detection
- 🔲 **Integration Testing**: Automated security test generation

### v3.0 (2027)
- 🔲 **Cloud Native**: Serverless scanning, managed service
- 🔲 **Real-Time Monitoring**: Continuous security monitoring
- 🔲 **Threat Intelligence**: Integration with threat feeds
- 🔲 **Compliance Frameworks**: SOC2, ISO27001, GDPR mappings
- 🔲 **Multi-Tenant Support**: Enterprise organization features
- 🔲 **Advanced Remediation**: Automated fix suggestions and PRs

### Community Requests
Vote on features at: [GitHub Discussions](https://github.com/prabhubng/mcp-security-auditor/discussions)

## Frequently Asked Questions (FAQ)

### General Questions

**Q: What is MCP?**
A: MCP (Model Context Protocol) is an open protocol that standardizes how applications provide context to LLMs. MCP servers expose tools, resources, and prompts that LLMs can use.

**Q: Why do I need to scan MCP servers?**
A: MCP servers can access sensitive data, execute commands, and interact with external systems. Security vulnerabilities can lead to data breaches, unauthorized access, or system compromise. This tool helps identify risks before deployment.

**Q: Is this tool free?**
A: Yes! MCP Security Auditor is open source and free to use under the MIT license.

**Q: What languages are supported?**
A: Currently Python, TypeScript, and JavaScript. See [Supported Languages](#supported-languages--frameworks) section.

### Scanning Questions

**Q: How long does a scan take?**
A: Typical scans complete in 2-5 seconds for small projects, 10-30 seconds for medium projects. Large codebases may take 1-2 minutes.

**Q: Can I scan private repositories?**
A: Yes, if you have access. Clone the repo locally and scan it, or provide Git credentials for remote scanning.

**Q: Does the scanner send data to external servers?**
A: No. All analysis is done locally. The tool never sends your code to external servers.

**Q: Can I scan multiple MCP servers at once?**
A: Not directly, but you can script it:
```bash
for dir in server1 server2 server3; do
    mcp-audit scan "./$dir" --format json --output "${dir}-report.json"
done
```

**Q: What's the difference between `scan` and `ci` commands?**
A: 
- `scan`: Interactive scanning with detailed output, multiple formats
- `ci`: Optimized for CI/CD with exit codes, baseline support, faster execution

### Finding Questions

**Q: What do the severity levels mean?**
A:
- **Critical**: Immediate security risk, fix before deployment
- **High**: Significant risk, fix soon
- **Medium**: Notable risk, address before production
- **Low**: Minor issue, fix when convenient
- **Info**: Informational, no immediate risk

**Q: Why am I getting false positives?**
A: Static analysis has limitations. Use `--severity high` to reduce noise, create a baseline for known issues, or skip specific analyzers.

**Q: How do I suppress false positives?**
A:
```bash
# Create baseline
mcp-audit scan . --format json --output baseline.json

# Edit baseline.json, add finding IDs to "suppressed_findings": []

# Use baseline in CI
mcp-audit ci . --baseline baseline.json
```

**Q: What is a "risk score"?**
A: A 0-100 score indicating overall security risk. Higher = more risky. Based on finding count, severity, and confidence levels.

### Configuration Questions

**Q: Do I need a configuration file?**
A: No, it's optional. The tool works with sensible defaults. Use `mcp-audit init` to create a custom config if needed.

**Q: Where should I put the config file?**
A: By default, `.mcp-audit.yaml` in your project root. Or specify with `--config path/to/config.yaml`.

**Q: Can I customize detection rules?**
A: Yes! Add custom patterns in `.mcp-audit.yaml`:
```yaml
rules:
  dangerous_patterns:
    - pattern: "my_unsafe_function\\("
      severity: high
      description: "Custom unsafe function detected"
```

### CI/CD Questions

**Q: Which output format should I use in CI?**
A:
- GitHub Actions: SARIF (uploads to Security tab)
- GitLab CI: JSON (SAST reports)
- Jenkins/Other: JSON or text

**Q: How do I fail builds on security issues?**
A:
```bash
# Exit 1 if high or critical found
mcp-audit ci . --fail-on high

# Exit 1 if any medium+ found
mcp-audit ci . --fail-on medium
```

**Q: Can I run only specific checks in CI?**
A: Yes:
```bash
# Fast CI: only critical checks
mcp-audit ci . --include-analyzers static secrets readonly
```

### Certification Questions

**Q: What is security certification?**
A: An official assessment that your MCP server meets specific security standards (Basic, Standard, or Enterprise).

**Q: How do I get certified?**
A:
```bash
mcp-audit certify . --level standard --output cert.json
```

**Q: What's the difference between certification levels?**
A:
- **Basic**: ≤3 high, ≤10 medium (dev/test)
- **Standard**: 0 high, ≤5 medium (production)
- **Enterprise**: 0 high, 0 medium (high security)

**Q: How long is certification valid?**
A: 1 year from scan date. Re-certify annually or after major changes.

### Read-Only Mode Questions

**Q: Why is read-only mode important?**
A: Many MCP servers only need to read data. Read-only mode prevents accidental data modification, deletion, or corruption.

**Q: How do I enforce read-only mode?**
A: For PostgreSQL:
```python
conn = psycopg2.connect(
    ...,
    options="-c default_transaction_read_only=on"
)
```
See [Read-Only Mode Enforcement](#read-only-mode-enforcement) for other databases.

**Q: What if my MCP needs write access?**
A: That's fine! Just properly annotate tools with `destructiveHint: True` and document write operations clearly.

### Integration Questions

**Q: Can I integrate with my SIEM?**
A: Yes:
```bash
# CEF format (ArcSight, QRadar)
mcp-audit scan . --format siem --siem-format cef

# Splunk HEC
mcp-audit scan . --format siem --siem-format splunk
```

**Q: Does it work with GitHub Security tab?**
A: Yes, use SARIF format:
```bash
mcp-audit ci . --format sarif --output results.sarif
# Upload with github/codeql-action/upload-sarif
```

**Q: Can I use it as a pre-commit hook?**
A:
```bash
# .git/hooks/pre-commit
#!/bin/bash
mcp-audit ci . --fail-on high --quiet || exit 1
```

### Troubleshooting

**Q: "No tools found" - why?**
A: Ensure you're using MCP SDK decorators (`@mcp.tool()`, `server.tool()`). Run with `--verbose` to see what's detected.

**Q: Scan is too slow, how to speed up?**
A:
```bash
# Skip slow analyzers
mcp-audit scan . --skip-analyzers dependencies

# Run only fast analyzers
mcp-audit scan . --include-analyzers static secrets
```

**Q: How do I report bugs?**
A: [GitHub Issues](https://github.com/prabhubng/mcp-security-auditor/issues) - include version, command, and error message.

## Contributing

Contributions are welcome! We appreciate:

- 🐛 **Bug Reports**: Report issues with detailed reproduction steps
- ✨ **Feature Requests**: Suggest new analyzers, formats, or integrations
- 📝 **Documentation**: Improve README, add examples, fix typos
- 🔧 **Code Contributions**: Add analyzers, fix bugs, improve performance
- 🧪 **Test Cases**: Add vulnerable code samples for testing

### Development Setup

```bash
# Clone repository
git clone https://github.com/prabhubng/mcp-security-auditor
cd mcp-security-auditor

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linters
black .
ruff check .
mypy .
```

### Contribution Guidelines

1. **Fork the repository** and create a feature branch
2. **Write tests** for new functionality
3. **Follow code style**: Black formatting, type hints
4. **Update documentation** if adding features
5. **Submit a pull request** with clear description

### Adding New Analyzers

```python
# mcp_auditor/analyzers/my_analyzer.py
from .base import BaseAnalyzer
from ..core.models import Finding

class MyAnalyzer(BaseAnalyzer):
    """Analyze for specific security issue."""
    
    async def analyze(self, path, server_info):
        findings = []
        # Your analysis logic here
        return findings
```

See `tests/fixtures/` for example vulnerable code to test against.

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