Skip to main content
Glama
mcp-api-pentest

mcp-api-pentest

by josenieto

mcp-api-pentest

Python License: MIT PyPI

An MCP server that lets AI assistants (Claude Desktop, Cursor, Claude Code) perform automated security audits on your APIs. It detects BOLA/IDOR vulnerabilities — the #1 risk in the OWASP API Top 10 — where one user can access another user's data.

Think of it as giving your AI the ability to act like a penetration tester, running requests with different user tokens and comparing the results to find broken authorization logic.


Quickstart in 3 minutes

# 1. Clone and install
git clone https://github.com/josenieto/mcp-api-pentest
cd mcp-api-pentest
uv sync

# 2. Start the mock API (a vulnerable API for safe testing)
uv run mock_api.py

# 3. Start the MCP server
uv run app.py

That's it. The server is now running and waiting for an AI client to connect.


Related MCP server: Security Hunter MCP

What it does

The project acts as a bridge between an AI and your API:

AI (Claude/Cursor)  ←→  MCP Server  ←→  API Target
                           |
                     Generates REPORTE_PENTEST.md

Example attack flow the AI can run:

  1. Create an invoice with Token A → POST /api/v1/invoices

  2. Read the same invoice with Token B → GET /api/v1/invoices/42

  3. Detect the IDOR → both tokens return 200 OK with 94% similar content

  4. Save the finding → "BOLA/IDOR in invoices endpoint — CRITICAL"

  5. Generate a report → REPORTE_PENTEST.md

All of this happens without writing a single line of code — the AI drives the audit through MCP tools.


Features

  • IDOR detection: Compares API responses with privileged vs unprivileged tokens

  • Chained attacks: Create a resource, capture its ID, then attack it with a different user

  • Multi-session state: Cache dynamic values across requests for complex attack flows

  • Smart truncation: Handles massive JSON responses without flooding the AI's context window

  • Rate limiting: Passive delays to avoid being blocked by WAFs

  • Intelligent retry: Detects 429 responses and retries with exponential backoff

  • Multiple auth schemes: Bearer, Basic, API Key (header/query), Cookie

  • Stealth mode: Random delay between requests to evade WAF detection patterns

  • User-Agent rotation: Rotates through a pool of realistic browser User-Agents

  • OpenAPI 3.x + YAML: Parses Swagger 2.0, OpenAPI 3.x in JSON or YAML format

  • Markdown reports: Automatic generation of security audit reports with evidence

  • Mock API sandbox: 9 intentionally vulnerable endpoints for safe testing

  • CLI entry point: Run from the terminal with mcp-api-pentest --target https://api.example.com


Try it now (no AI client needed)

# 1. Start the mock API in the background
uv run mock_api.py &
sleep 2

# 2. Run a quick IDOR test
uv run python -c "
import anyio, json
from mcp_api_pentest.idor_detector.access_analyzer import analyze_access_control
async def test():
    r = await analyze_access_control(
        url='http://localhost:8080/api/v1/facturas/1001',
        privileged_token='admin_secret_token_2026',
        unprivileged_token='user_atacante_token_xyz',
        delay_seconds=0,
    )
    print(json.loads(r)['idor_alert'])
result = anyio.run(test)
"

Example prompts for your AI

After connecting the MCP server to Claude Desktop, Cursor, or Claude Code, paste these into your AI assistant:

Basic IDOR scan:

Audit the API at http://localhost:8080. Use the admin token 'admin_secret_token_2026' and the attacker token 'user_atacante_token_xyz'. Detect IDOR in all invoice endpoints.

Chained attack:

Create an invoice with the victim token 'user_victima_token_abc', capture its ID, then try to read and delete it with the attacker token 'user_atacante_token_xyz'.

Full audit with report:

Run a complete access control audit on http://localhost:8080. Test all endpoints with the three tokens: admin, victim, and attacker. Generate a findings report.


Installation

git clone https://github.com/josenieto/mcp-api-pentest
cd mcp-api-pentest
uv sync

Requirements

  • Python 3.10 or newer

  • uv package manager


How to Use

Option 1: CLI mode (terminal)

Start the MCP server directly:

uv run app.py

With options:

mcp-api-pentest \
  --swagger spec.json \
  --target https://api.example.com \
  --token-admin "admin123" \
  --token-victim "victim456" \
  --token-attacker "attacker789" \
  --output report.md \
  --delay 1.0

Option 2: Connect an AI client

Add this to your MCP client configuration:

Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "api-logic-pentest": {
      "command": "uv",
      "args": ["run", "app.py"],
      "cwd": "/path/to/mcp-api-pentest"
    }
  }
}

Cursor (.cursor/mcp.json):

{
  "mcpServers": {
    "api-logic-pentest": {
      "command": "uv",
      "args": ["run", "app.py"],
      "cwd": "/path/to/mcp-api-pentest"
    }
  }
}

Claude Code (~/.claude/mcp.json):

{
  "mcpServers": {
    "api-logic-pentest": {
      "command": "uv",
      "args": ["run", "app.py"],
      "cwd": "/path/to/mcp-api-pentest"
    }
  }
}

Option 3: Sandbox mode (test locally)

# Starts a vulnerable mock API on port 8080
uv run mock_api.py

The mock API includes 3 test users with tokens:

User

Token

Role

Admin

admin_secret_token_2026

admin

Victim

user_victima_token_abc

user

Attacker

user_atacante_token_xyz

user

Vulnerable endpoints (intentionally broken for testing):

  • GET /api/v1/facturas/{id} — IDOR (no ownership validation)

  • POST /api/v1/invoices — creates invoice, captures ID for chained attacks

  • DELETE /api/v1/invoices/{id} — deletes without ownership check

  • GET /api/v1/users/{id}/profile — reads profile without ownership check

  • PUT /api/v1/users/{id}/profile — mass assignment without ownership (escalate role to admin)

  • GET /api/v1/items — pagination without bounds validation

  • POST /api/v1/items — creates item for chained attacks

  • DELETE /api/v1/items/{id} — deletes without ownership check

  • GET /api/v1/spec.yaml — returns OpenAPI 3.x spec in YAML format


Running Tests

# Run all tests (141 tests, all passing)
uv run pytest

# Run with verbose output
uv run pytest -v

# Run tests for a specific module
uv run pytest src/mcp_api_pentest/idor_detector/tests/

Code quality checks:

# Lint
uv run ruff check .

# Type checking
uv run mypy src/mcp_api_pentest/ --ignore-missing-imports

Available MCP Tools

The AI can use 11 tools to audit APIs:

Tool

What it does

parse_api_spec

Reads an OpenAPI/Swagger file and extracts routes

execute_security_request

Sends HTTP requests with auth headers and rate limiting

analyze_access_control

Compares responses from two tokens to detect IDOR

capture_context

Stores a dynamic value (like a created ID) in memory

get_context

Retrieves a previously stored value

list_context

Lists all stored key-value pairs

clear_context

Resets the session cache

extract_json_value

Extracts a field from a JSON response using dot-notation

save_security_finding

Records a security finding to the audit report

generate_report

Returns the full Markdown audit report

export_report_json

Exports all findings as structured JSON


Architecture

This project follows a Modular Monolith by Features design.

src/mcp_api_pentest/
├── config/               → Global settings and logger
├── shared/               → Reusable utilities (JSON truncation)
├── spec_analyzer/        → OpenAPI/Swagger file parsing
├── http_client/          → HTTP communication with auth providers
├── idor_detector/        → Multi-session authorization comparison
├── audit_context/        → In-memory state for chained attacks
├── report_generator/     → Security finding reports (Markdown + JSON)
├── orchestration/        → Cross-module attack flow coordinator
└── adapters/             → Entry points: MCP server and CLI

Each module is self-contained with its own tests. New detection patterns (like Mass Assignment or Rate Limit testing) are added as new modules without touching existing code.

See docs/adr/ADR-001-modular-monolith-by-features.md for the full architecture decision.


Contributing

  1. Create a branch from integration/master

  2. Write your changes plus tests (we follow RED/GREEN/REFACTOR)

  3. Push — CI runs lint, type check, and tests automatically

  4. When CI passes, the merge happens automatically


License

MIT

Available Tools

11 tools
analyze_access_controlA

Executes the same HTTP request with two different tokens (privileged vs unprivileged) and compares responses to detect authorization failures (BOLA/IDOR). Automatically cleans volatile fields (timestamps, session_ids, etc.) and calculates structural similarity. Marks as 'is_suspicious_success' if both return 200 OK with >85% similarity. When stealth mode is enabled, uses random delay to evade WAF detection patterns. Supports multiple auth types: bearer, basic, api_key_header, api_key_query, cookie.

Inputs: url (required), privileged_token (required), unprivileged_token (required), method, +5 more. Returns: result

capture_contextA

Stores a dynamic value in the session cache. Use after POST/PUT responses to save resource IDs for later use in DELETE/GET requests with a different auth token.

Inputs: key (required), value (required). Returns: result

clear_contextA

Clears all stored values from the session cache. Use at the start of a new audit cycle to avoid stale data contamination.

Inputs: no named parameters. Returns: result

execute_security_requestB

Async resilient HTTP client with anti-blocking (WAF) protection and rate limiting. Supports multiple auth types: bearer, basic, api_key_header, api_key_query, cookie. When stealth mode is enabled, uses random delay between STEALTH_MIN and STEALTH_MAX to evade WAF detection patterns.

Inputs: url (required), method (required), stealth, auth_type, +5 more. Returns: result

export_report_jsonD

Inputs: no named parameters. Returns: result

extract_json_valueA

Extracts a specific value from a JSON response using dot-notation path. Essential for chained attacks where the LLM needs to grab a dynamically created resource ID from a POST response (e.g. 'data.id' → 42).

Inputs: json_path (required), response_json (required). Returns: result

generate_reportD

Inputs: no named parameters. Returns: result

get_contextA

Retrieves a previously stored value from the session cache. Returns not_found if the key does not exist. Use to inject dynamic IDs into attack URLs.

Inputs: key (required). Returns: result

list_contextA

Returns all key-value pairs stored in the session cache. Useful for the LLM to see what dynamic IDs are available for chained attack flows.

Inputs: no named parameters. Returns: result

parse_api_specA

Reads a local OpenAPI/Swagger file (JSON or YAML), auto-detects format, and selectively extracts routes and methods. Strips verbose descriptions to save up to 70% of LLM tokens.

Inputs: spec_path (required). Returns: result

save_security_findingD

Inputs: title (required), severity (required), description (required), affected_url (required), +3 more. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3/5.0

    Scored across 11 tools

    Disambiguation3/5

    Most tools have clear, distinct purposes (e.g., parse_api_spec vs execute_security_request), but generate_report, export_report_json, and save_security_finding lack descriptions, making their boundaries unclear. Additionally, analyze_access_control and execute_security_request both perform HTTP requests, though their intent differs.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun snake_case pattern (extract_json_value, save_security_finding, analyze_access_control, etc.). The naming is predictable and uniform across the set.

    Tool Count5/5

    11 tools is a well-scoped size for an API pentest server. Each tool covers a distinct aspect of the workflow (spec parsing, request execution, access control analysis, context caching, reporting) without excessive overlap or unnecessary additions.

    Completeness4/5

    The tool set covers a complete pentest lifecycle: parse spec, execute requests, analyze access control, manage dynamic values, save findings, and generate/export reports. Minor gaps exist, such as no explicit tool for fuzzing or editing requests, but these can be worked around with execute_security_request and context tools.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables authorized compliance verification and security auditing through natural language, bridging AI assistants with industry-standard security tools for enterprise audits.
      24
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables autonomous AI agents and penetration testers to conduct authorized security audits with persistent cross-session memory, zero-trust secret scrubbing, dynamic OWASP/ASVS checklists, and hallucination-free exploit PoC generation from captured traffic.
      1
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Enables AI coding assistants to scan projects for security issues such as leaked API keys, missing Supabase RLS, open Firebase rules, unauthenticated routes, and hallucinated packages, then fix and verify the results.
      8
      1
      MIT
    • F
      license
      B
      quality
      C
      maintenance
      Enables AI agents to audit web headers and DOM code, API routes, and database queries for vulnerabilities such as XSS, BOLA/IDOR, and SQL/NoSQL injection, returning scored CWE findings. It also automatically synthesizes secure drop-in replacement code with unified git diffs for review.
      24
      -