Safe Local Python Executor/Interpreter
Ejecutor local seguro de Python
Un servidor MCP (transporte stdio) que encapsula LocalPythonExecutor de Hugging Face (del framework smolagents ). Es un entorno de ejecución de Python personalizado que proporciona aislamiento y seguridad básicos al ejecutar código Python generado por LLM localmente. No requiere Docker ni VM. Este paquete permite exponer el ejecutor de Python mediante MCP (Protocolo de Contexto de Modelo) como herramienta para aplicaciones LLM como Claude Desktop, Cursor o cualquier otro cliente compatible con MCP. En el caso de Claude Desktop, esta herramienta es una forma sencilla de añadir un intérprete de código faltante (disponible como complemento en ChatGPT desde hace tiempo).
Características
Expone la herramienta
run_pythonEjecución más segura de código Python en comparación con el uso directo de Python
eva()lSe ejecutó mediante uv en Python venv
No se permiten operaciones de E/S de archivos
Lista restringida de importaciones
colecciones
fecha y hora
herramientas de iteración
matemáticas
cola
aleatorio
re
estadística
estadística
tiempo
datos Unicode
Related MCP server: MCP Code Mode
Seguridad
Tenga cuidado con la ejecución del código generado por LLM en su equipo; evite servidores MCP que ejecuten Python mediante la línea de comandos o usando eval() . La opción más segura es usar una máquina virtual o un contenedor Docker, aunque requiere cierta configuración, consume recursos y es más lento. Existen servicios de terceros que ofrecen entorno de ejecución de Python, aunque requieren registro, claves API, etc.
LocalPythonExecutor ofrece un buen equilibrio entre el uso directo del entorno local de Python (que es más fácil de configurar) y la ejecución remota en un contenedor de Dokcer o en una máquina virtual o servicio de terceros (que es seguro). El equipo de Huggingng Face ha invertido tiempo en crear una opción rápida y segura para ejecutar el código generado por LLM que utilizan sus agentes de código. Este servidor MCP se basa en él:
Para añadir una primera capa de seguridad, la ejecución de código en smolagents no la realiza el intérprete de Python estándar. Hemos rediseñado desde cero un LocalPythonExecutor más seguro.
Lea más aquí .
Instalación y ejecución
Instalar
uv(ehbrew install uven macOS o usa la documentación oficial )Clonar el repositorio, cambiar el directorio
cd mcp_safe_local_python_executorEl servidor se puede iniciar a través de la línea de comandos
uv run mcp_server.py, venv se creará automáticamente y se instalarán las dependencias (smollagents, mcp).
Configuración de Claude Desktop
Asegúrate de tener instalado Claude for Desktop (descárgalo desde claude.ai )
Edite su archivo de configuración de Claude for Desktop:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonVentanas:
%APPDATA%\Claude\claude_desktop_config.jsonO abra Claude Desktop -> Configuración -> Desarrollador -> haga clic en el botón "Editar configuración"
Agregue la siguiente configuración:
{
"mcpServers": {
"safe-local-python-executor": {
"command": "uv",
"args": [
"--directory",
"/path/to/mcp_local_python_executor/",
"run",
"mcp_server.py"
]
}
}
}Reiniciar Claude para escritorio
La herramienta ejecutora de Python ahora estará disponible en Claude (verá el ícono del martillo en el campo de entrada del mensaje)
Ejemplos de indicaciones
Una vez configurado, puedes utilizar indicaciones como:
Calcular el factorial de 5 usando Python
"Crea una lista de números primos hasta 100"
"Resuelve esta ecuación (usa Python): x^2 + 5x + 6 = 0"
Desarrollo
Clona el repositorio. Usa uv para crear venv, instalar las dependencias de desarrollo y ejecutar pruebas.
uv venv .venv
uv sync --group dev
python -m pytest tests/Available Tools
1 toolrun_pythonA
Execute Python code in a secure sandbox environment.
This tool allows running simple Python code for calculations and data manipulations.
The execution environment is restricted for security purposes. Make sure you create a single file
that can be executed in one go and it returns a result.
Default allowed imports:
- math
- random
- datetime
- time
- json
- re
- string
- collections
- itertools
- functools
- operator
Args:
code: The Python code to execute. Must be valid Python 3 code. The result must be stored in a variable called `result`. E.g.:
```python
import math
result = math.sqrt(16)
```
Returns:
A dictionary with execution results containing:
- result: The final value or None if no value is returned
- logs: Any output from print statements
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key traits: the secure sandbox environment, restrictions for security, requirement to create a single executable file, and default allowed imports. However, it doesn't cover aspects like execution time limits, memory constraints, or error handling, leaving some behavioral gaps.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured and front-loaded with the core purpose, followed by usage notes, allowed imports, parameter details, and return information. It's appropriately sized for the tool's complexity, but the list of allowed imports and code example add some length that could be streamlined without losing clarity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's complexity (code execution with security constraints), no annotations, and an output schema that documents return values, the description is highly complete. It covers purpose, behavioral traits, parameter semantics with examples, and usage context, leaving minimal gaps for an AI agent to understand and invoke the tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has 0% description coverage, so the description must fully compensate. It adds substantial meaning beyond the schema by detailing the 'code' parameter: it must be valid Python 3 code, require storing results in a variable called 'result', and includes a clear example with syntax and usage. This provides comprehensive semantic context for the single parameter.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: 'Execute Python code in a secure sandbox environment' with specific verbs ('execute', 'run') and resource ('Python code'). It distinguishes the tool's scope by mentioning it's for 'simple Python code for calculations and data manipulations' and operates in a restricted environment, making its function unambiguous even without siblings.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage context by specifying it's for 'simple Python code for calculations and data manipulations' and mentions security restrictions, but it lacks explicit guidance on when to use this tool versus alternatives (e.g., other code execution tools or manual methods). No siblings are listed, so differentiation isn't needed, but general usage context is only partially addressed.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
- First observed
run_python
TDQS
Scored across 1 tool
With only one tool, there is no possibility of confusion or overlap between tools. The single tool 'run_python' has a clearly defined and distinct purpose.
The naming follows a consistent verb_noun pattern with 'run_python'. Since there's only one tool, consistency is inherently perfect with no deviations to assess.
A single tool is too few for the server's purpose as a 'Safe Local Python Executor/Interpreter'. This suggests a thin surface that may lack essential operations like code validation, environment inspection, or error handling, limiting agent functionality.
The tool set is severely incomplete for the domain. While 'run_python' covers execution, there are obvious gaps such as tools for listing allowed imports, checking code safety, managing execution timeouts, or handling errors, which are critical for a secure interpreter.
Maintenance
Related MCP Connectors
Hosted MCP server connecting claude.ai, ChatGPT and other AI apps to your own computer
Security scanner for MCP servers. Detect vulnerabilities, prompt injection, and tool poisoning.
An MCP server that gives your AI access to the source code and docs of all public github repos
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA MCP server for Hide – headless IDE for coding agents.11MIT
- AlicenseAqualityDmaintenanceUniversal Python code execution MCP server that lets LLMs write and run Python for any task, with auto-install packages, streaming output, and automatic file display.91MIT
- FlicenseNot gradedqualityBmaintenanceA Python MCP server that allows ChatGPT to execute commands on your local PC via a secure Cloudflare tunnel.-
- FlicenseAqualityCmaintenanceA minimal MCP server that lets AI hosts execute shell commands in a sandboxed workspace directory.1-