# eSentire MCP Scanner

> [!IMPORTANT]
> The eSentire-Labs project has been sunset.
> This repository no longer receives updates or maintenance.
> Use at your own risk.

[![Python](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![Security](https://img.shields.io/badge/security-vulnerability%20scanner-red.svg)](https://github.com/your-repo/mcp-scanner)

> A comprehensive security vulnerability scanner for Model Context Protocol (MCP) servers

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
- [Configuration](#configuration)
- [Security Checks](#security-checks)
- [Code Structure](#code-structure)

## Overview

The eSentire MCP Scanner is a specialized security tool designed to analyze and assess Model Context Protocol (MCP) server implementations. As MCP continues to evolve and enable powerful agentic AI capabilities across various platforms (including Slack, Box, and AWS S3), ensuring its security becomes increasingly critical. This scanner addresses emerging security challenges in the MCP ecosystem by detecting and analyzing potential vulnerabilities such as malicious prompt injections, tool description poisoning and name collisions.

Our scanner connects directly to MCP servers and performs comprehensive security assessments by examining server features, metadata, and implementation patterns. It provides detailed reports to help maintain the security and integrity of MCP implementations.

## Features

### 🔍 Security Analysis
- [ ] Authentication mechanism detection and analysis
- [ ] HTTPS/TLS compliance verification
- [ ] Server and feature name collision detection
- [ ] Cross-server feature similarity detection
- [ ] Intra-server feature reference analysis
- [ ] Cross-origin violations detection
- [ ] Feature description poisoning detection
- [ ] Variable poisoning analysis
- [ ] Prompt injection vulnerability assessment
- [ ] Rug pull attempt detection
- [ ] Installer spoofing identification

### 📊 Reporting
- [ ] JSON output for programmatic analysis
- [ ] Professional HTML reports with interactive elements
- [ ] PDF reports for executive summaries
- [ ] Color-coded security status indicators
- [ ] Detailed vulnerability explanations

### 🛠️ Flexibility
- [ ] Multiple MCP server configuration support
- [ ] Configurable scan parameters

## Installation

### Prerequisites

- Python 3.8 or higher
- Git
- pip (Python package installer)
- **OpenAI API Key**: Required for LLM-based analysis features (description poisoning detection)
- **Docker**: Must be running if scanning Docker-based MCP servers
- **Local MCP Servers**: Must be properly configured and runnable in their environments

### Environment Setup

1. **OpenAI API Key**: Set your OpenAI API key as an environment variable:
   ```bash
   export OPENAI_API_KEY="your-API-key-here"
   ```
   Without this key, LLM-based security analysis features will be disabled.

2. **Docker Requirements**: If scanning Docker-based MCP servers, ensure Docker is running:
   ```bash
   # Check if Docker is running
   docker --version
   docker ps
   ```

3. **Local Server Requirements**: For local MCP servers:
   - Each server must be in its proper environment
   - All dependencies must be installed and configured
   - Servers must be runnable without errors before scanning
   - Test servers individually before running the scanner

### Installation Steps

```bash
# Clone the repository
git clone https://github.com/esentire/mcp-scanner.git
cd mcp-scanner

# Create and activate a virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows, use: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
```

## Quick Start

### Live Demonstration



[![MCP Scanner Demo](figs/demo-thumbnail.png)](https://github.com/user-attachments/assets/ab586fe7-8546-40dc-ab81-2069419a1d2c)

*The above demonstration shows the complete scanning process from start to finish*

### Common usage examples:

```bash
# Scan local MCP server (The scanner reads the Claude desktop and Cursor MCP files by default and asks if you want to add more files)
python main.py

# Pass external config file
python main.py --config ABSOLUTE PATH IS REQUIRED

# Generate PDF report
python main.py --pdf

# Specify custom output location
python main.py --output ./reports/scan_results.json
```

## Usage

### Basic Command Options

```bash
python main.py [OPTIONS]

Options:
  --config FILE      External file path for scan
  --output FILE      Output file path for scan results (default: ./scan_results.json)
  --pdf              Generate PDF report
```
### Configuration File Format

The scanner accepts a JSON configuration file that specifies scan settings and MCP file locations. Here's the format:

```json
{
  "mcpServers": {
    "time": {
        "command": "uvx",
        "args": [
          "mcp-server-time",
          "--local-timezone=America/New_York"
        ]
      },
      "mcp-server-test": {
            "command": "/Users/Parya.Abadeh/.local/bin/uv",
            "args": [
                "--directory",
                "path to mcp-server-test",
                "run",
                "main.py"
            ]
        },
        "postgres": {
        "command": "npx",
        "args": [
            "-y",
            "@modelcontextprotocol/server-postgres",
            "postgresql://localhost/mydb"
        ]
    }
  }
}
```

### Scanner Settings

The scanner can be configured with the following settings:

#### MCP Files
- `claude_desktop`: Path to Claude desktop MCP configuration (default: automatically detected)
- `cursor`: Path to Cursor MCP configuration (default: automatically detected)
- `custom_file`: an additional MCP file to scan

#### Report Configuration
- `output_dir`: Directory for storing scan results (default: ./scan_results)
- `pdf`: PDF report generation settings
  - `enabled`: Enable/disable PDF report generation


## Security Checks

### Authentication Analysis

The scanner analyzes MCP server authentication mechanisms to identify security weaknesses:

- **Authentication Detection**: Identifies if servers implement authentication (API keys, OAuth, browser-based auth)
- **Authentication Type Classification**: Categorizes auth types (no_auth, api_key, oauth, browser_interactive, etc.)
- **Security Risk Assessment**: Flags servers without authentication as high-risk
- **OAuth Endpoint Discovery**: Automatically detects OAuth endpoints for URL-based servers
- **Browser Authentication Detection**: Identifies servers requiring browser-based authentication flows

**Security Issues Detected:**
- Servers without any authentication mechanism
- Weak or missing access controls
- Improperly configured authentication flows

### HTTPS Compliance

Verifies that MCP servers use secure communication protocols:

- **URL Analysis**: Examines all server URLs and endpoints for HTTPS usage
- **Argument Inspection**: Checks command-line arguments for HTTP URLs
- **Configuration Review**: Identifies insecure configurations in server settings
- **Encryption Verification**: Ensures sensitive data transmission is encrypted

**Security Issues Detected:**
- HTTP URLs instead of HTTPS (unencrypted communication)
- Mixed protocol usage in configurations
- Exposure of sensitive data over insecure channels

### Collision Detection

Identifies naming conflicts and feature relationships that could lead to confusion or security issues:

- **Feature Name Analysis**: Detects duplicate tool, prompt, and resource names within servers
- **Server Name Conflicts**: Identifies servers with conflicting or confusing names
- **Cross-Server Collisions**: Finds similar feature names across different servers (similarity threshold: 0.9)
- **Popular Name Conflicts**: Detects conflicts with well-known MCP server names
- **Intra-Server References**: Analyzes how features reference each other within the same server
- **Reference Chain Detection**: Identifies potential security issues like circular dependencies
- **Context Extraction**: Provides surrounding context for detected feature references
- **Naming Variation Handling**: Accounts for different naming styles (underscores/hyphens)

**Security Issues Detected:**
- Identical or highly similar feature names that could cause confusion
- Server impersonation through similar naming
- Namespace pollution attacks
- Circular feature dependencies
- Hidden feature chaining
- Unauthorized feature access through indirect references
- Cross-server feature collisions with detailed context

### Vulnerability Detection

#### Feature Description Poisoning
Detects malicious or misleading content in tool, prompt, and resource descriptions using AI-powered analysis:

- **LLM-Based Detection**: Uses OpenAI GPT models to analyze description content for malicious intent
- **Pattern Recognition**: Identifies suspicious patterns in feature descriptions
- **Context Analysis**: Evaluates descriptions for deceptive or harmful content
- **Multi-Feature Scanning**: Analyzes tools, prompts, and resources comprehensively

**Security Issues Detected:**
- Misleading feature descriptions designed to trick users
- Hidden malicious functionality in seemingly benign tools
- Social engineering attempts through feature descriptions
- Deceptive content designed to bypass security controls

#### Variable Poisoning
Analyzes variable names and descriptions in tools and prompts for security risks:

- **Dangerous Variable Names**: Identifies potentially harmful variable names (e.g., system paths, credentials)
- **Variable Description Analysis**: Uses LLM analysis to detect malicious content in variable descriptions
- **Input Parameter Security**: Evaluates tool and prompt input parameters for security risks
- **Data Exfiltration Vectors**: Identifies variables that could be used for data extraction

**Security Issues Detected:**
- Variables with dangerous or suspicious names
- Variable descriptions containing malicious instructions
- Input parameters designed for unauthorized access
- Potential data exfiltration mechanisms

#### Prompt Injection
Identifies vulnerabilities to prompt injection attacks in MCP prompts:

- **Injection Pattern Detection**: Scans for common prompt injection techniques
- **Dynamic Prompt Analysis**: Tests prompts with various injection payloads
- **Context Manipulation**: Identifies prompts vulnerable to context manipulation
- **Security Boundary Testing**: Evaluates prompt security controls

**Security Issues Detected:**
- Prompts susceptible to injection attacks
- Weak input validation in prompt processing
- Context manipulation vulnerabilities
- Bypasses of security controls through prompt manipulation

#### Rug Pull Attempts
Detects tools/resources/prompts that change their description or behavior after user consent:

- **Description Consistency Monitoring**: Tracks changes in tool/resource/prompt descriptions post-consent
- **Behavioral Drift Detection**: Identifies discrepancies between consented functionality and actual behavior
- **Consent Exploitation Analysis**: Detects tools that abuse user consent by altering their purpose
- **Trust Violation Indicators**: Flags servers that misuse user consent through post-approval changes

**Security Issues Detected:**
- Tools that modify their descriptions after user has consented to their use
- Resources that change behavior from what was originally agreed upon
- Prompts that alter their functionality after consent was granted
- Servers that exploit user consent by changing tool/resource/prompt definitions

#### Installer Spoofing
Identifies servers using unofficial or potentially malicious installation methods:

- **Official Source Verification**: Compares installation commands against known official sources
- **Unofficial Installer Detection**: Identifies non-standard installation methods
- **Package Source Analysis**: Evaluates the legitimacy of package sources
- **Supply Chain Security**: Assesses installation security risks

**Security Issues Detected:**
- Use of unofficial or unverified installation sources
- Potentially compromised package repositories
- Installation methods that bypass security controls
- Supply chain attack vectors through malicious installers

#### Cross-Origin Violations
The scanner detects when MCP servers inappropriately reference other MCP server names in their tool, prompt, or resource descriptions. This security check helps identify:

- **Impersonation attempts**: Servers claiming to work "like the github server" or similar
- **Misleading descriptions**: Tools that reference functionality from other popular MCP servers
- **Supply chain confusion**: Servers that may attempt to masquerade as legitimate alternatives

**Detection Features:**
- **Smart token analysis**: Analyzes descriptions word-by-word to identify server name references
- **Duplicate word elimination**: Removes duplicate words from descriptions before analysis to prevent multiple violations for the same reference
- **Normalization**: Handles variations like underscores, hyphens, and punctuation (e.g., "github_server", "github-server", "github.")
- **Popular server database**: Maintains a list of well-known MCP servers to check against
- **Cross-configuration detection**: Identifies references to other servers in your configuration

**Example violations:**
- Tool description: "This tool works like the github server to fetch files" → Flags "github"
- Resource description: "Similar to filesystem access but over time" → Flags "filesystem" and "time"
- Prompt description: "Query data like the postgres server would" → Flags "postgres"

The scanner will report: `Cross-origin violation in tool 'example_tool': References 'github'`

## Code Structure

The MCP eSentire Scanner is organized into modular components for maintainability and extensibility:

```
MCP_eSentire_Scanner/
├── main.py                          # Main entry point and CLI interface
├── server_scanner.py                # Core MCP server scanning logic
├── config_manager.py                # Configuration file management
├── requirements.txt                 # Python dependencies
├── README.md                        # Documentation
│
├── analyzer_helpers/                # Security analysis modules
│   ├── auth_analyzer.py            # Authentication mechanism detection
│   ├── cross_origin_analyzer.py    # Cross-origin violations detection
│   ├── feature_name_collision_analyzer.py  # Name collision detection
│   ├── server_name_collision_analyzer.py   # Server name conflict analysis
│   ├── feature_description_poisoning_analyzer.py  # Malicious description detection
│   ├── feature_variables_analyzer.py       # Variable poisoning analysis
│   ├── prompt_injection_analyzer.py        # Prompt injection detection
│   ├── rug_pull_analyzer.py               # Rug pull attempt detection
│   ├── installer_spoofing_analyzer.py     # Installation source verification
│   ├── html_report_generator.py           # HTML report generation
│   ├── pdf_report_generator.py            # PDF report generation
│   └── nova_rules/                        # LLM analysis rule definitions
│       ├── hidden_instruction_rules.nov   # Rules for hidden instruction detection
│       └── variable_poisoning_rules.nov   # Rules for variable poisoning detection
│
└── figs/                            # Images and assets
    ├── demo.gif                     # Demo animation
    ├── eSentire Labs - Logo (FULL).png  # Company logo (PNG)
    └── eSentire Labs - Logo (FULL).svg  # Company logo (SVG)
```

### Core Components

#### **main.py**
- **Purpose**: Application entry point and command-line interface
- **Responsibilities**:
  - Argument parsing (`--config`, `--output`, `--pdf`)
  - Configuration loading and management
  - Server discovery and scanning coordination
  - Report generation orchestration
  - User interaction for additional configuration files

#### **server_scanner.py**
- **Purpose**: Core MCP server analysis engine
- **Key Functions**:
  - `scan_server()`: Main server scanning function with timeout handling
  - `scan_server_capabilities()`: Extracts tools, prompts, and resources
  - `parse_mcp_config()`: Parses MCP configuration files
- **Integration**: Coordinates all security analyzers and aggregates results

#### **config_manager.py**
- **Purpose**: Configuration file discovery and management
- **Features**:
  - Auto-detection of Claude Desktop and Cursor configurations
  - Multi-platform path resolution (macOS, Windows, Linux)
  - Configuration merging and validation
  - Interactive configuration file addition

### Security Analyzer Modules

#### **Authentication & Network Security**
- **`auth_analyzer.py`**: Detects authentication mechanisms (API keys, OAuth, browser auth)
- **`cross_origin_analyzer.py`**: Identifies inappropriate server references in descriptions

#### **Content Analysis**
- **`feature_description_poisoning_analyzer.py`**: Uses LLM analysis to detect malicious descriptions
- **`feature_variables_analyzer.py`**: Analyzes variable names and descriptions for security risks
- **`prompt_injection_analyzer.py`**: Tests prompts for injection vulnerabilities

#### **Behavioral Analysis**
- **`rug_pull_analyzer.py`**: Detects tools/resources/prompts that violate user consent by changing post-approval
- **`installer_spoofing_analyzer.py`**: Verifies installation source legitimacy

#### **Collision Detection**
- **`feature_name_collision_analyzer.py`**: Identifies conflicting feature names
- **`server_name_collision_analyzer.py`**: Detects server name conflicts

### Report Generation

#### **`html_report_generator.py`**
- Interactive HTML reports with security status indicators
- Color-coded threat levels and detailed explanations
- Responsive design with collapsible sections

#### **`pdf_report_generator.py`**
- Professional PDF reports suitable for executive summaries
- Corporate branding support with logo integration
- Structured security assessment documentation

### Rule-Based Analysis

#### **`nova_rules/`**
- **`hidden_instruction_rules.nov`**: Patterns for detecting hidden malicious instructions
- **`variable_poisoning_rules.nov`**: Rules for identifying dangerous variable patterns
- **Format**: Custom rule definition language for LLM-based analysis
