Skip to main content
Glama
MCP Code Sanitizer

MCP Code Sanitizer

by notasandy

🔍 mcp-code-sanitizer

Un revisor de código estricto impulsado por IA que ejecuta tu código a través de Groq LLM directamente desde Claude Desktop, Cursor o cualquier agente compatible con MCP.

Python FastMCP Groq License

Claude Desktop  ──MCP──►  code-sanitizer  ──REST──►  Groq API
                            (server.py)               (llama-3.3-70b)

✨ Características

Herramienta

Descripción

analyze_code

Revisión de código estricta: errores, vulnerabilidades, puntuación 0–100

compare_code

Compara dos versiones, encuentra regresiones, recomienda fusionar/solicitar cambios

explain_code

Explicación paso a paso para audiencia junior/intermedia/senior

generate_tests

Genera pruebas pytest/jest/go con casos de éxito, casos límite y pruebas de seguridad

analyze_file

Analiza un archivo completo desde el disco con fragmentación paralela

generate_report

Crea un hermoso informe HTML a partir de cualquier resultado de análisis

cache_info

Estadísticas de caché y limpieza

Ejemplo de respuesta

{
  "summary": "Critical SQL injection and secret exposed in logs",
  "score": 23,
  "issues": [
    {
      "severity": "critical",
      "line": 2,
      "title": "SQL Injection",
      "description": "f-string directly interpolates user_id into query",
      "fix": "cursor.execute('SELECT * FROM users WHERE id = %s', (user_id,))"
    }
  ],
  "warnings": [{"title": "No exception handling", "description": "..."}],
  "suggestions": ["Consider using an ORM instead of raw SQL"]
}

Related MCP server: Claude Code Review MCP

🚀 Inicio rápido

1. Clonar el repositorio

git clone https://github.com/YOUR_USERNAME/mcp-code-sanitizer
cd mcp-code-sanitizer

2. Crear entorno virtual e instalar dependencias

python -m venv venv

# macOS / Linux
source venv/bin/activate

# Windows
venv\Scripts\activate

pip install -r requirements.txt

3. Añadir tu clave API de Groq

Obtén una clave gratuita en console.groq.com/keys

cp .env.example .env
# Open .env and set GROQ_API_KEY=gsk_...

4. Probar el servidor

python server.py

El silencio significa que está funcionando: el servidor está escuchando solicitudes MCP a través de stdio.


🔌 Conectar a Claude Desktop

Busca tu archivo de configuración y añade la sección mcpServers:

SO

Ruta de configuración

macOS

~/Library/Application Support/Claude/claude_desktop_config.json

Windows

%APPDATA%\Claude\claude_desktop_config.json

Linux

~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "code-sanitizer": {
      "command": "/full/path/to/venv/bin/python",
      "args": ["/full/path/to/server.py"],
      "env": {
        "GROQ_API_KEY": "gsk_your_key_here"
      }
    }
  }
}

Reinicia Claude Desktop: verás el icono 🔧 en el chat.


🔌 Conectar a Cursor

Crea .cursor/mcp.json en la raíz de tu proyecto:

{
  "mcpServers": {
    "code-sanitizer": {
      "command": "/full/path/to/venv/bin/python",
      "args": ["/full/path/to/server.py"],
      "env": {"GROQ_API_KEY": "gsk_your_key_here"}
    }
  }
}

🧪 Pruebas mediante MCP Inspector

source venv/bin/activate  # or venv\Scripts\activate on Windows
fastmcp dev inspector server.py

Se abrirá una interfaz de usuario en el navegador con la interfaz completa de pruebas de herramientas.


💬 Uso en el chat

Después de conectar a Claude Desktop, simplemente escribe:

Review this code for vulnerabilities:

def get_user(user_id):
    query = f"SELECT * FROM users WHERE id = {user_id}"
    return db.execute(query)

O llama explícitamente a una herramienta:

Use analyze_file on /path/to/my_script.py
Generate tests for this function: ...
Compare these two versions and tell me if it got better: ...

🏗️ Arquitectura

mcp-code-sanitizer/
├── server.py          # FastMCP entry point (39 lines)
├── config.py          # Constants — keys, limits, mappings
├── groq_client.py     # Groq API client with auto-retry on rate limits
├── cache.py           # In-memory cache with TTL
├── prompts.py         # System prompts for all tools
└── tools/
    ├── analyze.py     # analyze_code
    ├── compare.py     # compare_code
    ├── explain.py     # explain_code
    ├── tests.py       # generate_tests
    ├── file_tool.py   # analyze_file (chunking + parallel analysis)
    ├── cache_tool.py  # cache_info
    └── report.py      # generate_report (HTML)

⚙️ Configuración

Todos los ajustes a través de variables de entorno o .env:

Variable

Predeterminado

Descripción

GROQ_API_KEY

—

Requerido. Obténla en console.groq.com

GROQ_MODEL

llama-3.3-70b-versatile

Modelo de Groq

CACHE_TTL

3600

TTL de caché en segundos

CACHE_MAX

200

Entradas máximas de caché

Modelos de Groq disponibles

Modelo

Velocidad

Calidad

llama-3.3-70b-versatile

⚡⚡

⭐⭐⭐⭐⭐ (predeterminado)

llama-3.1-8b-instant

⚡⚡⚡

⭐⭐⭐

mixtral-8x7b-32768

⚡⚡

⭐⭐⭐⭐


📦 Requisitos

fastmcp>=2.3.0
httpx>=0.27.0
python-dotenv>=1.0.0

🤝 Contribución

¡Las PRs y los Issues son bienvenidos! Especialmente interesados en:

  • Soporte para otros proveedores de LLM (OpenAI, Anthropic)

  • Nuevas herramientas (auditoría de seguridad, verificación de dependencias, análisis de complejidad)

  • Mejoras en los prompts


📄 Licencia

MIT: haz lo que quieras. Se agradecería una estrella en GitHub ⭐


🔗 Enlaces

Available Tools

7 tools
analyze_codeC

Strict analysis of a code fragment using Groq LLM.

Inputs: code (required), language, context. Returns: result

analyze_fileA

Analyzes a whole code file from disk. Automatically detects language by file extension. Large files are split into chunks and analyzed in parallel.

Inputs: file_path (required), language, context. Returns: result

cache_infoA

Shows cache statistics or clears the cache Args: clear: True - clears the cache, False - shows statistics.

Returns: JSON with cache stats or clear result.

Inputs: clear. Returns: result

compare_codeA

Compares two versions of code and evaluates whether the change is an improvement.

Performs a structured diff analysis: identifies what improved, what regressed, and what changed neutrally. Returns a merge recommendation based on the findings. Useful for code review, refactoring validation, and AI-generated code verification.

Inputs: code_before (required), code_after (required), language, context. Returns: result

explain_codeA

Explains what code does - step by step and clearly. Args: code: Code to explain. language: Programming language. audience: Target audience level - junior, middle, or senior. Returns: JSON with step-by-step explanation, key concepts, and gotchas.

Inputs: code (required), language, audience. Returns: result

generate_reportA

Generates a beautiful HTML report from analyze_code or analyze_file results. Args: analysis_json: JSON string from analyze_code or analyze_file. output_path: Path to save the HTML file (optional). source_name: File/fragment name for the report title. Returns: JSON with fields: html, saved_to, length.

Inputs: analysis_json (required), output_path, source_name. Returns: result

generate_testsA

Generates tests for the provided code. Args: code: Code to generate tests for. language: Programming language. framework: Test framework (optional - pytest, jest, unittest, etc.). Returns: JSON with test cases, runnable test code, and coverage estimate.

Inputs: code (required), language, framework. Returns: result

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 7 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: code fragment analysis, whole file analysis, cache management, code comparison, code explanation, report generation, and test generation. No overlap in functionality.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern using snake_case (e.g., analyze_code, generate_tests). No inconsistencies in style.

    Tool Count5/5

    7 tools is a well-scoped set for code analysis and sanitization tasks, covering the core operations without being overwhelming or too sparse.

    Completeness4/5

    The tool surface covers analysis, comparison, explanation, test generation, and reporting. A minor gap is the lack of code transformation or refactoring tools, but the set is reasonable for the stated domain.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A server that enables interaction with PostgreSQL, MySQL, MariaDB, or SQLite databases through Claude Desktop using natural language queries.
      1
      -
    • A
      license
      A
      quality
      D
      maintenance
      Enables comprehensive security scanning of code projects, detecting vulnerabilities in dependencies, code patterns (XSS, eval, etc.), and exposed secrets, with detailed reports in Spanish prioritized by severity.
      4
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      AI-powered code review tool that detects AI-generated code defects invisible to traditional linters — hallucinated packages, deprecated APIs, cross-file contradictions, hidden security anti-patterns, and over-engineering. Works as a standalone CLI, GitHub Action, or MCP server. Supports TypeScript, Python, Java, Go, and Kotlin. Free for individuals, no API key required.
      4
      41
      Business Source 1.1