Skip to content

Inicio Rapido

Esta guia te llevara desde cero hasta tu primer escaneo de seguridad en 5 minutos.


Tabla de Contenidos

  1. Requisitos Previos
  2. Tu Primer Escaneo
  3. Entendiendo los Resultados
  4. Configuracion Basica
  5. Siguiente Nivel

Requisitos Previos

Antes de comenzar, asegurate de tener:

  1. mcp-scan instalado - Ver Instalacion
  2. Un proyecto MCP para escanear - Puede ser tu propio codigo o un ejemplo

Verificar Instalacion

mcp-scan version

Si ves la version, estas listo para continuar.


Tu Primer Escaneo

Opcion 1: Escanear un Proyecto Existente

Si ya tienes un servidor MCP:

# Escanear el directorio actual
mcp-scan scan .

# O especificar una ruta
mcp-scan scan /ruta/a/mi/proyecto

Opcion 2: Crear un Proyecto de Prueba

Vamos a crear un servidor MCP vulnerable para demostrar las capacidades de mcp-scan:

# Crear directorio de prueba
mkdir mcp-ejemplo
cd mcp-ejemplo

# Crear servidor vulnerable de ejemplo
cat > server.py << 'EOF'
"""Servidor MCP de ejemplo con vulnerabilidades intencionales."""
from mcp import Server, tool
import subprocess
import os
import sqlite3

server = Server("demo-server")

@tool
def execute_command(command: str) -> str:
    """Execute a system command.

    WARNING: This is intentionally vulnerable for demonstration.
    """
    # VULNERABLE: Ejecucion directa de comandos (Clase A - RCE)
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout

@tool
def read_file(filepath: str) -> str:
    """Read contents of a file.

    WARNING: This is intentionally vulnerable for demonstration.
    """
    # VULNERABLE: Path traversal (Clase B - Filesystem)
    with open(filepath, 'r') as f:
        return f.read()

@tool
def fetch_url(url: str) -> str:
    """Fetch content from a URL.

    WARNING: This is intentionally vulnerable for demonstration.
    """
    import requests
    # VULNERABLE: SSRF - URL no validada (Clase C)
    response = requests.get(url)
    return response.text

@tool
def query_database(user_input: str) -> str:
    """Query the database.

    WARNING: This is intentionally vulnerable for demonstration.
    """
    conn = sqlite3.connect('data.db')
    cursor = conn.cursor()
    # VULNERABLE: SQL Injection (Clase D)
    cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")
    return str(cursor.fetchall())

# VULNERABLE: Secreto hardcodeado (Clase E)
API_KEY = "sk-1234567890abcdef"
DATABASE_PASSWORD = "super_secret_password_123"

if __name__ == "__main__":
    server.run()
EOF

Ejecutar el Escaneo

mcp-scan scan .

Salida Esperada

MCP-Scan v2.0.0
Scanning: /Users/ejemplo/mcp-ejemplo
Mode: fast
Files: 1

Analyzing...

================================================================================
FINDINGS SUMMARY
================================================================================

CRITICAL: 2
  - MCP-A003: Direct shell command execution (server.py:16)
  - MCP-A004: SQL injection via string concatenation (server.py:43)

HIGH: 2
  - MCP-B002: Potential path traversal (server.py:24)
  - MCP-C002: Unvalidated URL in request (server.py:33)

MEDIUM: 2
  - MCP-E001: Hardcoded secret detected (server.py:47)
  - MCP-E002: Hardcoded secret detected (server.py:48)

================================================================================
SECURITY SCORE
================================================================================

MSSS Score: 32/100
Compliance Level: 0 (Not Compliant)

Category Breakdown:
  A (RCE):        0/22 (-22 points)
  B (Filesystem): 8/13 (-5 points)
  C (SSRF):       5/10 (-5 points)
  D (SQLi):       0/10 (-10 points)
  E (Secrets):    6/10 (-4 points)

================================================================================
MCP SURFACE
================================================================================

Tools: 4
  - execute_command (handler: execute_command)
  - read_file (handler: read_file)
  - fetch_url (handler: fetch_url)
  - query_database (handler: query_database)

SDK: Python Official (mcp)
Transport: Unknown

================================================================================

Total: 6 findings (2 critical, 2 high, 2 medium)
Exit code: 1 (findings exceed threshold)

Entendiendo los Resultados

Estructura del Reporte

El reporte de mcp-scan tiene varias secciones:

1. Resumen de Hallazgos

CRITICAL: 2
  - MCP-A003: Direct shell command execution (server.py:16)
  • Severidad: CRITICAL, HIGH, MEDIUM, LOW, INFO
  • ID de Regla: MCP-A003 (Clase A, regla 003)
  • Descripcion: Que se detecto
  • Ubicacion: archivo:linea

2. Puntuacion MSSS

MSSS Score: 32/100
Compliance Level: 0 (Not Compliant)
  • Score 0-59: Nivel 0 - No Cumple
  • Score 60-79: Nivel 1 - Basico
  • Score 80-89: Nivel 2 - Enterprise
  • Score 90-100: Nivel 3 - Certificado

3. Superficie MCP

Tools: 4
  - execute_command (handler: execute_command)

Lista todos los tools MCP detectados y sus handlers.

Clases de Vulnerabilidades

ID Clase Descripcion Severidad Tipica
A RCE Ejecucion remota de codigo Critical
B Filesystem Acceso no autorizado a archivos High
C SSRF Server-side request forgery High
D SQLi Inyeccion SQL Critical
E Secrets Exposicion de secretos Medium-High
F Auth Problemas de autenticacion High
G Poisoning Envenenamiento de tools Medium-High

Configuracion Basica

Crear Archivo de Configuracion

mcp-scan init

Esto crea .mcp-scan.yaml con valores por defecto:

# Archivos a incluir
include:
  - "**/*.py"
  - "**/*.ts"
  - "**/*.tsx"
  - "**/*.js"
  - "**/*.jsx"

# Archivos a excluir
exclude:
  - "**/node_modules/**"
  - "**/venv/**"
  - "**/.git/**"
  - "**/dist/**"
  - "**/build/**"

# Configuracion del escaneo
scan:
  mode: fast        # fast o deep
  timeout: 5m       # tiempo maximo
  fail_on: high     # severidad minima para fallar

# Configuracion de salida
output:
  redact_snippets: false  # ocultar codigo en reportes

Personalizar Exclusiones

exclude:
  - "**/node_modules/**"
  - "**/venv/**"
  - "**/tests/**"        # Excluir tests
  - "**/examples/**"     # Excluir ejemplos
  - "**/*_test.py"       # Archivos de test Python
  - "**/*.test.ts"       # Archivos de test TypeScript

Configurar Umbral de Fallo

Para CI/CD, configura cuando debe fallar el escaneo:

scan:
  fail_on: high  # Falla en high o critical

Opciones: info, low, medium, high, critical


Siguiente Nivel

Obtener Salida en JSON

mcp-scan scan . --output json > resultado.json

Generar Reporte SARIF (GitHub)

mcp-scan scan . --output sarif > resultado.sarif

Modo Deep (Analisis Profundo)

mcp-scan scan . --mode deep

El modo deep analiza flujos de datos entre funciones.

Ver Superficie MCP

mcp-scan surface .

Muestra todos los tools, resources y prompts detectados.

Crear Baseline

Si tienes hallazgos que no puedes arreglar inmediatamente:

# Generar baseline de hallazgos actuales
mcp-scan scan . --output json > scan.json
mcp-scan baseline generate --from scan.json

# Futuros escaneos ignoraran estos hallazgos
mcp-scan scan . --baseline baseline.json

Ejemplo Completo: Flujo de Trabajo

# 1. Clonar o crear proyecto
cd mi-servidor-mcp

# 2. Inicializar configuracion
mcp-scan init

# 3. Primer escaneo completo
mcp-scan scan . --mode deep --output json > scan-inicial.json

# 4. Ver resultados
cat scan-inicial.json | jq '.summary'

# 5. Crear baseline de hallazgos aceptados
mcp-scan baseline generate --from scan-inicial.json

# 6. Editar baseline (opcional) - remover falsos positivos
# nano baseline.json

# 7. Escaneos futuros con baseline
mcp-scan scan . --baseline baseline.json --fail-on high

# 8. Integrar en CI/CD (ver seccion de CI/CD)

Comandos Utiles

Comando Descripcion
mcp-scan scan . Escaneo basico
mcp-scan scan . --mode deep Escaneo profundo
mcp-scan scan . --output json Salida JSON
mcp-scan scan . --output sarif Salida SARIF
mcp-scan scan . --fail-on high Fallar en severidad alta
mcp-scan surface . Ver superficie MCP
mcp-scan init Crear configuracion
mcp-scan baseline generate Crear baseline
mcp-scan version Ver version

Proximos Pasos

Ahora que has completado tu primer escaneo:

  1. Comandos CLI - Aprende todos los comandos disponibles
  2. Configuracion - Personaliza mcp-scan para tu proyecto
  3. Modos de Analisis - Entiende fast vs deep
  4. Integracion CI/CD - Automatiza en tu pipeline

Limpieza

Si creaste el proyecto de prueba:

cd ..
rm -rf mcp-ejemplo

Anterior: Instalacion | Siguiente: Comandos CLI