Skip to main content
Glama
neco001

Python Executor MCP Server

by neco001

Python Executor MCP Server

MCP Server Python License: MIT CI

Execute Python code snippets with shell-quoting-free execution via temporary files.

Features:

  • Batch execution - Run multiple snippets in parallel (max 4 workers)

  • Security-first - Size limits, type validation, UUID temp files

  • Helper utilities - chunk_by_count(), suggest_batch_size() for task decomposition

  • Zero dependencies - Only mcp required, uses stdlib for execution

Why Do I Need This?

Ever been frustrated when your AI agent tries to execute a simple one-liner and gets lost in shell quoting hell?

# Agent tries to run this:
print("Hello 'world' with \"quotes\" and $variables")

# Shell interprets quotes, variables, escapes...
# Result: SyntaxError, FileNotFoundError, or worse - unexpected behavior

This server solves the problem by:

  1. Writing code directly to a temp file (no shell interpretation)

  2. Executing the file with Python (clean, predictable)

  3. Returning stdout/stderr/exit_code (full visibility)

Bonus: Batch execution lets you run 20 independent tasks in parallel instead of sequentially.

Related MCP server: mcp-run-isolated-python

Installation

Quick Start

# Clone the repository
git clone https://github.com/neco001/py-executor.git
cd py-executor

# Install dependencies with uv
uv sync

# Run the server
uv run python server.py

Configure with Claude Desktop / Roo / Other MCP Clients

Add to your MCP client configuration:

{
  "mcpServers": {
    "py-executor": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/py-executor",
        "run",
        "python",
        "server.py"
      ]
    }
  }
}

Alternative: Direct Python

{
  "mcpServers": {
    "py-executor": {
      "command": "python",
      "args": ["/path/to/py-executor/server.py"]
    }
  }
}

Tools

run_python - Single Execution

Execute a single Python code snippet. Use for stateful/dependent operations.

Parameters:

  • code: Python code to execute (max 1MB)

  • timeout: Execution timeout in seconds (default 30, max 60)

  • cwd: Optional working directory - uses local .venv if found

When to use:

  • Running a single calculation or analysis

  • When code needs to maintain state between operations

  • When subsequent code depends on previous results

  • For interactive debugging or testing small code snippets

Examples:

# Simple calculation
code = "result = 2 + 2\nprint(f'Result: {result}')"

# Data analysis on single dataset
code = "import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3]})\nprint(df.sum())"

# File processing (single file)
code = "with open('data.txt', 'r') as f:\n    content = f.read()\n    print(len(content))"

run_python_batch - Parallel Execution

Execute multiple Python code snippets in parallel (max 4 workers, max 20 snippets).

Parameters:

  • codes: List of Python code strings to execute (max 20, each max 1MB)

  • timeout: Timeout per snippet in seconds (default 30, max 60)

  • max_workers: Maximum parallel workers (default 4, hard capped at 4)

  • cwd: Optional working directory - uses local .venv if found

When to use:

  • Processing multiple files independently

  • Running parallel data transformations on separate datasets

  • When tasks are completely independent and don't share state

  • For batch processing of similar operations across different inputs

When NOT to use:

  • When code snippets depend on each other's results

  • When maintaining shared state between executions

  • For sequential operations where order matters

Examples:

# Processing multiple files independently
codes = [
    "with open('file1.txt', 'r') as f: print(len(f.read()))",
    "with open('file2.txt', 'r') as f: print(len(f.read()))",
    "with open('file3.txt', 'r') as f: print(len(f.read()))"
]
run_python_batch(codes)

# Parallel data analysis on separate datasets
codes = [
    "import pandas as pd; df = pd.read_csv('data1.csv'); print(df.shape)",
    "import pandas as pd; df = pd.read_csv('data2.csv'); print(df.shape)",
    "import pandas as pd; df = pd.read_csv('data3.csv'); print(df.shape)"
]
run_python_batch(codes)

# Independent calculations
codes = [
    "result = sum(range(1000)); print(result)",
    "import math; result = math.factorial(10); print(result)",
    "import random; result = [random.randint(1, 100) for _ in range(5)]; print(result)"
]
run_python_batch(codes)

Helper Utilities

Internal functions to help agents split large tasks into batch-friendly chunks.

chunk_by_count(items: list, n: int) -> list[list]

Split a list into n approximately equal-sized chunks.

files = ['file1.py', 'file2.py', 'file3.py', 'file4.py']
chunks = chunk_by_count(files, 2)
# Result: [['file1.py', 'file2.py'], ['file3.py', 'file4.py']]

# Use with run_python_batch:
chunks = chunk_by_count(files, 4)
codes = [f"process_files({chunk})" for chunk in chunks]
run_python_batch(codes)

chunk_by_size(code: str, max_bytes: int = 500000) -> list[str]

Split a large code string into smaller chunks based on byte size.

large_code = "process_data('file1')\nprocess_data('file2')\n..."
chunks = chunk_by_size(large_code, 500000)  # 500KB per chunk
run_python_batch(chunks)

suggest_batch_size(total_items: int, complexity: str = "medium") -> int

Suggest an optimal batch size based on total items and task complexity.

files = list_of_100_files
workers = suggest_batch_size(len(files), "low")  # Returns 4 for simple tasks
workers = suggest_batch_size(len(files), "high")  # Returns 2 for heavy tasks

chunks = chunk_by_count(files, workers)
codes = [f"analyze_files({chunk})" for chunk in chunks]
run_python_batch(codes, max_workers=workers)

Complexity levels:

  • "low": Simple operations (e.g., file size checks) → max 4 workers

  • "medium": Moderate operations (e.g., data parsing) → 3 workers

  • "high": Heavy operations (e.g., ML inference) → 2 workers


Performance & Limits

Parameter

Limit

Max workers

4 (hard cap)

Max batch size

20 snippets

Max code size

1MB per snippet

Max timeout

60 seconds per snippet


Architecture

run_python_batch(codes: list[str])
    └── ProcessPoolExecutor(max_workers=4)
            ├── Worker 1: _execute_single_snippet(0, code, timeout, cwd)
            ├── Worker 2: _execute_single_snippet(1, code, timeout, cwd)
            ├── Worker 3: _execute_single_snippet(2, code, timeout, cwd)
            └── Worker 4: _execute_single_snippet(3, code, timeout, cwd)
                    └── UUID temp file → subprocess.run → cleanup
            └── Results collected by index → ordered JSON response

Security

  • UUID-named temp files prevent collisions

  • Input validation: type checking, size limits

  • Timeout enforcement prevents zombie processes

  • ProcessPoolExecutor provides crash containment

  • No shell execution (shell=False) prevents injection

Available Tools

2 tools
run_pythonA

Execute a single Python code snippet. Use for stateful/dependent operations. Use run_python_batch for parallel independent tasks. Max 1MB code, 60s timeout. See README.md for usage examples and helper utilities.

ParametersJSON Schema
NameRequiredDescriptionDefault
cwdNo
codeYes
timeoutNo

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description must carry the full burden. It discloses limits (1MB code, 60s timeout) and the stateful nature of execution, adding valuable context beyond the schema. However, it doesn't mention side effects, return format, or environment specifics, which would be expected for complete transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three sentences, front-loaded with the primary action, then usage context, then constraints and reference. Every sentence earns its place with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has no output schema and no annotations, so the description must compensate. It provides essential usage and constraints, and points to README for more details, but omits return value behavior and other environmental context. The pointer to README assigns completeness, but the description itself is not fully self-contained.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description should explain the parameters. It mentions the code size limit and timeout constraint, but does not clarify the meaning of the 'cwd' parameter or describe the semantics of each field beyond what the schema titles already imply. This is insufficient given the lack of schema-level descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb+resource: 'Execute a single Python code snippet.' It also distinguishes itself from the sibling tool by specifying 'Use for stateful/dependent operations' vs. 'run_python_batch for parallel independent tasks.'

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly provides when-to-use guidance ('Use for stateful/dependent operations') and names the alternative ('Use run_python_batch for parallel independent tasks'). Also states constraints (Max 1MB code, 60s timeout) and points to README for examples.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

run_python_batchA

Execute multiple Python snippets in parallel (max 4 workers, max 20 snippets). Use for independent tasks: file processing, parallel data analysis. Use run_python for stateful/dependent operations. See README.md for examples.

ParametersJSON Schema
NameRequiredDescriptionDefault
cwdNo
codesYes
timeoutNo
max_workersNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden. It discloses parallel execution and limits (max workers, max snippets) but does not explain error handling, result ordering, isolation, or what happens when limits are exceeded, leaving notable 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.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three concise sentences with no fluff: first states the core function, second gives usage context, third names the alternative and points to examples. Information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the primary use case and points to README, but omits important operational details such as timeout behavior, cwd handling, and behavior when max limits are exceeded. The output schema may cover return values, but the tool still feels incomplete for a batch execution tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description does not explain the meaning of cwd, timeout, or max_workers beyond implicit mention of worker/snippet limits. It fails to compensate for the undocumented schema parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Execute multiple Python snippets in parallel' with specific constraints (max 4 workers, max 20 snippets), distinguishing it from the sibling run_python tool by emphasizing the batch/parallel aspect.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explicitly states when to use this tool ('independent tasks: file processing, parallel data analysis') and when not to ('Use run_python for stateful/dependent operations'), providing clear guidance and naming the alternative.

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. Dates show when Glama detected each change.

  1. 2 tool updatesv0.1.0
    • First observedrun_python
    • First observedrun_python_batch

TDQS

A4.2/5.0
Disambiguation5/5

The two tools are clearly distinct: run_python for a single snippet and run_python_batch for parallel execution. Descriptions explicitly state when to use each, eliminating ambiguity.

Naming Consistency5/5

Both tools follow a consistent pattern: 'run_python' and 'run_python_batch', with the second adding a descriptive qualifier. This is predictable and easy to understand.

Tool Count3/5

With only two tools, the server feels minimal. The tools cover the core need, but the count is borderline per calibration standards (1-2 tools is considered thin).

Completeness4/5

For a Python execution server, single and batch execution cover the primary use cases. Minor gaps exist (e.g., no explicit environment management), but the core functionality is well-covered.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables secure execution of Python code in a sandboxed WebAssembly environment using Pyodide and Deno. Automatically handles package management and captures complete execution results including stdout, stderr, and return values.
    194
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables LLMs to execute Python code securely in a sandboxed environment. Supports configurable restrictions like no network access and returns results including files.
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/neco001/py_executor'

If you have feedback or need assistance with the MCP directory API, please join our Discord server