Skip to main content
Glama

Code Executor MCP Server

by aberemia24

Code Executor MCP Server

Universal MCP server for executing TypeScript and Python code with progressive disclosure - reduces token usage by 98% compared to exposing all tools directly.

License: MIT TypeScript Node.js Tests

Based on Anthropic's official guide to Code Execution with MCP

⚠️ Built for Claude Code: This MCP server was developed and tested exclusively with Claude Code. While it follows MCP standards, no testing has been performed on other MCP clients (Claude Desktop, Cline, Roo, etc.). Use with other clients at your own risk.

🎯 The Problem

Tired of constantly toggling MCPs on and off in Claude Code? Need filesystem access, so you enable it. Done with that, now need zen for code review? Disable filesystem, enable zen. It's tedious and wastes context on unused tools.

With many MCP servers enabled simultaneously, you can easily hit context limits just loading tool definitions - leaving little room for actual work.

✨ The Solution: One MCP to Rule Them All

Keep ALL your MCPs disabled. Enable ONLY code-executor.

Based on Anthropic's code execution pattern, code-executor exposes up to 2 tools (executeTypescript, executePython) that can access all your other MCPs on-demand. No more toggling. No context bloat.

Progressive Disclosure: Instead of Claude directly accessing 47 tools (consuming ~150k tokens), Claude writes code that accesses those tools when needed (~1.6k tokens = 98% reduction).

Note: executeTypescript requires Deno. Without Deno, only executePython is available (still works, just Python-only).

How It Works

  1. LLM calls with code + allowed tools whitelist

  2. Code executes in sandbox (Deno for TypeScript, subprocess for Python)

  3. Code can call to access other MCP servers

  4. Results returned to LLM with audit trail

// LLM executes this code to access zen MCP server const result = await callMCPTool('mcp__zen__codereview', { code: myCode, language: 'typescript' }); console.log(result);

Token savings: 47 tools @ ~3,000 tokens each = 141,000 tokens saved!

πŸ€” When to Use This (and When NOT to)

βœ… Use code-executor when you have:

  • Multiple MCPs (5+) causing token bloat and context exhaustion

  • Mix of local + remote tools - filesystem + Linear API + code review services

  • Complex orchestration - multi-step workflows with state management

  • Security requirements - need allowlisting, audit logs, rate limiting

  • Existing MCP servers you want to orchestrate without rebuilding

❌ Don't use this if you only need:

  • Simple filesystem operations β†’ Use Node.js fs module or shell commands directly

  • Basic git commands β†’ Use child_process.exec('git ...')

  • Single database queries β†’ Use psql, mysql CLI directly

  • One or two MCPs β†’ Just enable them directly, no need for orchestration

Philosophy: Use the simplest tool that works. code-executor solves a specific problem: orchestrating many MCPs without context bloat. If you don't have that problem, you probably don't need this tool.

πŸ’‘ Real-World Example (The Sweet Spot)

// Heterogeneous orchestration - local + remote + governance: // 1. Read local file const code = await callMCPTool('mcp__filesystem__read_file', { path: '/app/src/api/users.ts' }); // 2. Call remote AI code review service const review = await callMCPTool('mcp__zen__codereview', { code, language: 'typescript', styleGuide: 'airbnb' }); // 3. Create Linear issue via API (OAuth handled by MCP) if (review.issues.length > 0) { await callMCPTool('mcp__linear__create_issue', { title: `Code review: ${review.issues[0].title}`, description: review.issues[0].details, teamId: 'ENG', priority: 2 }); } // 4. Post to Slack await callMCPTool('mcp__slack__post_message', { channel: '#code-reviews', text: `Review complete: ${review.summary}` }); console.log('Orchestrated 4 different services with unified interface!');

This workflow mixes local filesystem, remote AI service, Linear API (with OAuth), and Slack - all with one interface, centralized auth, and audit logging.

πŸš€ Features

βœ… Executors

  • TypeScript/JavaScript - Deno sandbox with fine-grained permissions (requires Deno)

  • Python - Subprocess execution with MCP access (enabled via config)

βœ… Security

  • Sandbox execution - Deno for TypeScript, subprocess for Python

  • Tool allowlist - Only explicitly allowed tools can be called

  • Dangerous pattern detection - Blocks eval(), exec(), __import__(), pickle.loads(), etc.

  • Path validation - File system access restricted to allowed projects

  • Network restrictions - Default: localhost only

  • Rate limiting - Token bucket algorithm (optional, 30 req/min default)

  • Comprehensive audit logging - All executions logged with code hash, memory usage

βœ… Configuration

  • Auto-discovery - Searches .code-executor.json in project/user/XDG directories

  • Environment variables - Override any setting

  • Secret management - env:VAR_NAME pattern for secure config

  • MCP integration - Auto-connects to all MCP servers in .mcp.json

  • Safe defaults - Localhost-only network, no write access, 30s timeout

βœ… Quality

  • Type safe - Full TypeScript definitions, Zod validation

  • Connection pooling - Limit concurrent executions (max 100)

  • Error handling - Graceful degradation, clear error messages

  • Well tested - 105 tests passing, 90%+ coverage

πŸ“¦ Installation

Option 1: Docker (Recommended for Production)

Production-grade containerized deployment with security hardening.

# 1. Build the image locally cd code-executor-mcp npm run build # Build TypeScript first docker build -t code-executor-mcp:1.3.0 . # 2. Run with docker-compose (recommended) docker-compose up -d # 3. Or run manually with security options docker run -d \ --name code-executor \ --read-only \ -v /tmp/code-executor \ -m 512m \ --cpus="0.5" \ --pids-limit=100 \ --security-opt=no-new-privileges \ --cap-drop=ALL \ code-executor-mcp:1.3.0

Docker Security Features:

  • βœ… Non-root user (UID 1001)

  • βœ… Read-only root filesystem

  • βœ… Resource limits (memory, CPU, PIDs)

  • βœ… Network isolation (no external access by default)

  • βœ… All capabilities dropped

  • βœ… Custom seccomp profile (syscall filtering)

  • βœ… Tini init system (zombie process reaping)

Testing Docker Security:

# Run comprehensive security test suite ./test-docker-security.sh

See DOCKER_TESTING.md for detailed testing procedures.

Option 2: NPM (Development/Local)

# Install globally npm install -g code-executor-mcp # Or install locally for development git clone https://github.com/aberemia24/code-executor-MCP.git cd code-executor-mcp npm install npm run build

Running the Server

After global install:

code-executor-mcp

Local development:

npm run server # Build + start # or npm start # Start (requires build first)

Link for local CLI testing:

npm link # Creates global symlink code-executor-mcp # Run from anywhere

Prerequisites

For NPM installation:

  • Node.js 22.x or higher (required)

  • Deno (recommended, enables TypeScript execution) - Install from deno.land

    # Quick install (Linux/macOS) curl -fsSL https://deno.land/install.sh | sh # Or use your package manager brew install deno # macOS choco install deno # Windows
  • Python 3.9+ (optional, enables Python execution)

Note: Without Deno, only executePython tool will be available. TypeScript execution (executeTypescript) requires Deno.

For Docker installation:

  • Docker 20.10+ and Docker Compose 2.0+

  • All dependencies (Node.js, Deno, Python) are included in the image

πŸ”§ Configuration

Docker Configuration

When running in Docker, configure via docker-compose.yml:

services: code-executor: image: code-executor-mcp:1.3.0 environment: # Security ALLOWED_PROJECTS: "/app/projects" ENABLE_AUDIT_LOG: "true" AUDIT_LOG_PATH: "/app/audit.log" # Executors DENO_PATH: "/usr/bin/deno" PYTHON_PATH: "/usr/bin/python3" # MCP Configuration (optional) MCP_CONFIG_PATH: "/app/.mcp.json" volumes: # Mount your project (read-only) - ./my-project:/app/projects:ro # Mount MCP config if using other servers - ./.mcp.json:/app/.mcp.json:ro # Writable temp directory - /tmp/code-executor # Security constraints read_only: true mem_limit: 512m cpus: 0.5 pids_limit: 100 cap_drop: - ALL security_opt: - no-new-privileges - seccomp=./seccomp-profile.json

Note: The Docker image includes a default .mcp.json with zero servers (standalone mode). Mount your own .mcp.json to enable MCP tool access.

Local Configuration

Create .code-executor.json in your project root:

{ "version": 1, "security": { "allowRead": ["/home/user/projects/my-project"], "allowWrite": false, "allowNetwork": ["localhost", "127.0.0.1"], "defaultTimeoutMs": 30000, "maxTimeoutMs": 300000, "enableAuditLog": true, "auditLogPath": "./audit.log", "rateLimit": { "enabled": true, "maxRequests": 30, "windowMs": 60000 } }, "executors": { "typescript": { "enabled": true, "denoPath": "deno" }, "python": { "enabled": false, "pythonPath": "python3" } }, "mcpConfigPath": "./.mcp.json" }

Configuration Discovery

The server searches for configuration in this order (first found wins):

  1. CODE_EXECUTOR_CONFIG_PATH environment variable

  2. ./.code-executor.json (project root)

  3. ~/.code-executor.json (user home)

  4. ~/.config/code-executor/config.json (XDG config)

Environment Variables

Override any setting with environment variables:

# Security export ALLOWED_PROJECTS="/home/user/project1:/home/user/project2" export ENABLE_AUDIT_LOG=true export AUDIT_LOG_PATH="/var/log/code-executor.log" # Executors export DENO_PATH="/usr/local/bin/deno" export PYTHON_PATH="/usr/bin/python3" # MCP Configuration export MCP_CONFIG_PATH="/path/to/custom/mcp.json" # Explicit config file export CODE_EXECUTOR_CONFIG_PATH="/etc/code-executor/config.json"

Secret Management

Use env:VAR_NAME pattern in configuration files to reference environment variables:

{ "security": { "allowRead": ["env:PROJECT_ROOT"], "auditLogPath": "env:AUDIT_LOG_PATH" } }

πŸ“– Usage

Add to MCP Configuration (Claude Code)

Add to your .mcp.json (tested with Claude Code only):

{ "mcpServers": { "code-executor": { "command": "node", "args": ["/path/to/code-executor-mcp/dist/index.js"], "env": { "ALLOWED_PROJECTS": "/home/user/my-project" } } } }

MCP Transport Types

Code-executor supports two transport types for connecting to other MCP servers:

1. STDIO (Local Servers)

For local MCP servers spawned as child processes:

{ "mcpServers": { "zen": { "command": "npx", "args": ["-y", "zen-mcp-server"], "env": { "GEMINI_API_KEY": "your-key-here" } } } }

2. HTTP/SSE (Remote Servers)

For remote HTTP-based MCP servers (Linear, GitHub, etc.) with authentication:

{ "mcpServers": { "linear": { "type": "http", "url": "https://mcp.linear.app/mcp", "headers": { "Authorization": "Bearer your-api-token-here" } }, "github": { "type": "http", "url": "https://api.github.com/mcp", "headers": { "Authorization": "token ghp_your_token_here", "Accept": "application/vnd.github.v3+json" } } } }

How it works:

  • Code-executor tries StreamableHTTP first (modern, bidirectional)

  • Falls back to SSE (Server-Sent Events) if StreamableHTTP unavailable

  • Supports authentication via HTTP headers (Authorization, custom headers)

Use cases:

  • βœ… Linear MCP (project management via HTTP)

  • βœ… GitHub MCP (repository operations via API)

  • βœ… Any OAuth/token-authenticated MCP service

  • βœ… Internal company MCP servers

⚠️ Important: Code-executor reads MCP servers from the project-level file (configured via mcpConfigPath in .code-executor.json). It does NOT read from user-level MCP configs like ~/.config/claude/claude_desktop_config.json. All MCP servers must be defined in your project's .mcp.json.

Authentication Flow for SSE/HTTP MCPs (Claude Code)

For SSE MCPs that require OAuth (Linear, GitHub, etc.):

  1. Enable MCP - Type /mcp in Claude Code to open MCP management

  2. Authenticate - Complete OAuth flow from Claude Code's MCP interface (browser will open)

  3. Disable MCP - Type /mcp or @mcp and press Enter to disable the MCP in Claude Code

  4. Code-executor takes over - The MCP is now authenticated and available to code-executor, but disabled in Claude Code to prevent duplicate loading

⚠️ Critical: Do NOT delete the MCP from .mcp.json - just disable it via /mcp. If you delete it, code-executor won't have access anymore. The MCP must remain in the config file (disabled state).

πŸ“ Note: This authentication flow is for Claude Code only. The entire code-executor MCP server has been developed and tested exclusively with Claude Code. Other MCP clients have not been tested and may not work correctly.

Execute TypeScript

// LLM calls this tool { "code": ` const files = await callMCPTool('mcp__filesystem__list_directory', { path: '/src' }); console.log('Files:', files.length); for (const file of files) { if (file.endsWith('.ts')) { const content = await callMCPTool('mcp__filesystem__read_file', { path: file }); console.log(\`\${file}: \${content.length} bytes\`); } } `, "allowedTools": [ "mcp__filesystem__list_directory", "mcp__filesystem__read_file" ], "timeoutMs": 30000, "permissions": { "read": ["/home/user/my-project/src"], "net": ["localhost"] } }

Execute Python (Optional)

Enable Python in config, then:

# LLM calls this tool { "code": """ import json # Call MCP tool from Python result = call_mcp_tool('mcp__zen__thinkdeep', { 'problem': 'How to optimize this algorithm?', 'model': 'gemini-2.5-pro' }) print(json.dumps(result, indent=2)) """, "allowedTools": ["mcp__zen__thinkdeep"], "timeoutMs": 120000 }

Health Check

// Check server status { // No parameters } // Returns: { "healthy": true, "auditLog": { "enabled": true }, "mcpClients": { "connected": 47 }, "connectionPool": { "active": 0, "waiting": 0, "max": 100 }, "uptime": 3600.5, "timestamp": "2025-01-09T12:00:00.000Z" }

πŸ› οΈ Creating MCP Tool Wrappers

Why We Don't Ship Wrappers

MCP servers update independently. Their APIs can change at any time without warning.

Real example:

  • Zen MCP changed parameter names: cli_name β†’ model, query β†’ step

  • Changed data types: findings: [] β†’ findings: ''

  • If we shipped wrappers, they'd be broken ❌

The solution: You create and maintain wrappers that match YOUR installed MCP server versions.

Copy-Paste Templates

We provide battle-tested templates instead of shipped code:

// Copy template to your project cp node_modules/code-executor-mcp/docs/examples/zen-wrapper-template.ts \ src/lib/mcp/zen.ts // Adapt to your environment export async function zenThinkDeep(question: string) { const result = await callMCPTool('mcp__zen__thinkdeep', { // Update params to match YOUR zen version step: question, step_number: 1, total_steps: 1, next_step_required: false, findings: '', model: 'gemini-2.5-pro' }); return typeof result === 'string' ? JSON.parse(result) : result; } // Use it import { zenThinkDeep } from './lib/mcp/zen'; const analysis = await zenThinkDeep('How to optimize this?');

Available Templates

  • docs/examples/zen-wrapper-template.ts - AI analysis tools (thinkdeep, codereview, etc.)

  • docs/examples/filesystem-wrapper-template.ts - File operations (read, write, search)

  • docs/examples/CREATING_WRAPPERS.md - Complete guide for creating your own

Benefits of This Approach

βœ… Your wrappers match YOUR MCP server versions βœ… You update when YOU update MCP servers βœ… No dependency on our release schedule βœ… No "broken package" issues βœ… Full TypeScript autocomplete in your IDE

Quick Start

1. Copy template:

cp docs/examples/zen-wrapper-template.ts src/lib/mcp/zen.ts

2. Adapt to your environment:

// You own this file - update when zen updates export async function zenThinkDeep(question: string) { /* ... */ }

3. Use throughout your project:

import { zenThinkDeep } from './lib/mcp/zen'; const result = await zenThinkDeep('question');

See


πŸ”’ Security Model

Multi-Layer Defense Strategy

Code-executor implements defense-in-depth with multiple security layers:

  1. Path Traversal Protection (CWE-22)

    • Symlink resolution with fs.realpath()

    • Canonical path validation before access

    • Prevents directory escape attacks

  2. SSRF Protection (CWE-918)

    • Comprehensive IP blocklist (localhost, RFC 1918 private networks)

    • Cloud metadata endpoint filtering (AWS, GCP, Azure)

    • Hostname and resolved IP validation

  3. HTTP Proxy Authentication (CWE-306)

    • Cryptographically secure bearer tokens (32 bytes)

    • All sandbox-to-MCP communication authenticated

    • Prevents unauthorized tool access

  4. Temp File Integrity (CWE-345)

    • SHA-256 hash verification after write

    • Detects tampering before execution

    • Race condition prevention

  5. Container Isolation (Docker)

    • Non-root user execution (UID 1001)

    • Read-only root filesystem

    • Network isolation (no external access)

    • Resource limits (memory, CPU, PIDs)

    • Syscall filtering (seccomp profile)

Principle of Least Privilege

  1. Default: Deny All - No file system or network access by default

  2. Explicit Allowlist - Each execution specifies allowed tools

  3. Path Validation - File paths must be within allowRead/allowWrite

  4. Pattern Detection - Dangerous code patterns blocked before execution

  5. Sandbox Isolation - Deno/subprocess provide OS-level isolation

  6. Rate Limiting - Token bucket algorithm prevents abuse

Dangerous Patterns Blocked

JavaScript/TypeScript:

  • eval(), Function(), new Function(), .constructor.constructor()

  • require(), import() (dynamic imports)

  • child_process, Deno.run, Deno.Command

  • setTimeout('code'), setInterval('code')

Python:

  • exec(), __import__(), compile()

  • pickle.loads() (deserialization RCE)

  • os.system(), subprocess.run/call/Popen

  • globals(), locals(), __builtins__

  • open(..., 'w') (write mode)

Audit Logging

All executions are logged with:

  • Timestamp (ISO 8601)

  • Executor type (typescript/python)

  • Code hash (SHA-256)

  • Code length (bytes)

  • Allowed tools (whitelist)

  • Tools called (actual usage)

  • Execution time (milliseconds)

  • Memory usage (bytes)

  • Success/error status

  • Client identifier (for rate limiting)

Example audit log entry:

{ "timestamp": "2025-01-09T12:00:00.000Z", "executor": "typescript", "codeHash": "a1b2c3d4e5f6...", "codeLength": 1234, "allowedTools": ["mcp__filesystem__read_file"], "toolsCalled": ["mcp__filesystem__read_file"], "executionTimeMs": 150, "success": true, "clientId": "default", "memoryUsage": 12345678 }

Rate Limiting

Optional token bucket rate limiter:

{ "security": { "rateLimit": { "enabled": true, "maxRequests": 30, "windowMs": 60000 } } }

Features:

  • Token bucket algorithm - Smooth limiting with burst capacity

  • Per-client limiting - Default: single "default" client (MCP servers run locally)

  • Automatic cleanup - Stale buckets removed every 5 minutes

  • Graceful errors - Clear messages with retry timing

πŸ“Š Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ LLM (Claude, GPT-4, etc.) β”‚ β”‚ - Calls executeTypescript/executePython β”‚ β”‚ - Provides code + allowlist β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Code Executor MCP Server β”‚ β”‚ β”œβ”€ Security Validator (pattern detection, allowlist) β”‚ β”‚ β”œβ”€ Rate Limiter (token bucket, optional) β”‚ β”‚ β”œβ”€ Connection Pool (max 100 concurrent) β”‚ β”‚ └─ Config Discovery (.code-executor.json, env vars) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Deno Sandbox β”‚ β”‚ Python Subprocessβ”‚ β”‚ (TypeScript) β”‚ β”‚ (Python 3.9+) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ callMCPTool()β”‚ β”‚ call_mcp_tool() β”‚ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ MCP Proxy Server (HTTP, localhost-only) β”‚ β”‚ β”œβ”€ Allowlist Validator β”‚ β”‚ β”œβ”€ Tool Call Tracker β”‚ β”‚ └─ Error Normalization β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β” β”‚ MCP Client β”‚ β”‚ MCP Client β”‚ β”‚ MCP β”‚ β”‚... β”‚ β”‚ (zen) β”‚ β”‚ (filesystem)β”‚ β”‚(fetcher)β”‚ β”‚ 47 β”‚ β”‚ thinkdeep β”‚ β”‚ read_file β”‚ β”‚fetch_urlβ”‚ β”‚toolsβ”‚ β”‚ codereview β”‚ β”‚ write_file β”‚ β”‚ β”‚ β”‚totalβ”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”˜

πŸš€ Production Deployment

Docker Deployment (Recommended)

1. Build Production Image

# Install dependencies and build npm ci npm run build # Build Docker image docker build -t code-executor-mcp:1.3.0 . # Tag for registry (optional) docker tag code-executor-mcp:1.3.0 your-registry/code-executor-mcp:1.3.0

2. Deploy with Docker Compose

# Start service docker-compose up -d # View logs docker-compose logs -f code-executor # Stop service docker-compose down

3. Security Checklist

  • βœ… Run as non-root (UID 1001)

  • βœ… Enable read-only filesystem

  • βœ… Set resource limits (512MB RAM, 0.5 CPU)

  • βœ… Drop all capabilities

  • βœ… Use seccomp profile

  • βœ… Network isolation (default)

  • βœ… Mount projects read-only

  • βœ… Enable audit logging

4. Health Monitoring

# Health check via Docker docker exec code-executor node -e "console.log('healthy')" # Check container status docker ps --filter name=code-executor # View resource usage docker stats code-executor

Production Configuration

# docker-compose.yml for production services: code-executor: image: code-executor-mcp:1.3.0 restart: unless-stopped read_only: true mem_limit: 512m cpus: 0.5 pids_limit: 100 environment: NODE_ENV: production ENABLE_AUDIT_LOG: "true" AUDIT_LOG_PATH: "/app/audit.log" volumes: # Projects (read-only) - /var/projects:/app/projects:ro # Audit logs (persistent) - ./logs:/app/logs # Temp directory - /tmp/code-executor cap_drop: - ALL security_opt: - no-new-privileges - seccomp=./seccomp-profile.json networks: - isolated networks: isolated: driver: bridge internal: true # No external network access

πŸ§ͺ Development

Setup

git clone https://github.com/aberemia24/code-executor-MCP.git cd code-executor-MCP npm install

Commands

npm run build # Build TypeScript npm test # Run tests (105 passing) npm run typecheck # Type check only npm run dev # Watch mode # Docker development npm run docker:build # Build Docker image npm run docker:test # Run security tests

Testing

# Run all tests npm test # Watch mode npm run test:watch # Coverage report npm run test:coverage

Current Status: βœ… 105 tests passing | βœ… 90%+ coverage | βœ… Clean TypeScript build

πŸ“ˆ Progressive Disclosure Pattern

Traditional Approach (❌ ~150,000 tokens)

  • Load all 47 MCP tool definitions upfront

  • Wasted context on unused tools

  • Tools: 47 Γ— ~3,000 tokens = ~141,000 tokens

  • Overhead: ~9,000 tokens (descriptions, schemas)

  • Total: ~150,000 tokens

Progressive Disclosure (βœ… ~1,600 tokens)

  • Load only 2-3 code-executor tool definitions

  • Tools loaded on-demand via callMCPTool()

  • Tools: 2-3 Γ— ~500 tokens = ~1,000-1,500 tokens

  • Overhead: ~100 tokens

  • Total: ~1,600 tokens

Savings: 98% reduction (148,400 tokens saved!)

Real-World Example

// Instead of exposing 47 tools, the LLM writes code that discovers and uses them: const allTools = await callMCPTool('mcp__code-executor__health', {}); console.log(`Available: ${allTools.mcpClients.connected} tools`); // Then uses tools as needed for (const file of files) { const content = await callMCPTool('mcp__filesystem__read_file', { path: file }); const review = await callMCPTool('mcp__zen__codereview', { code: content }); if (review.issues.length > 0) { await callMCPTool('mcp__filesystem__write_file', { path: `${file}.review.md`, content: JSON.stringify(review, null, 2) }); } }

🀝 Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

Code Quality Standards

  • βœ… TypeScript strict mode

  • βœ… 90%+ test coverage on business logic

  • βœ… All tests passing

  • βœ… ESLint + Prettier

  • βœ… Meaningful commit messages

πŸ“„ License

MIT License - see LICENSE for details.

πŸ” Security

Current Security Status:

  • βœ… Path traversal protection (symlink resolution)

  • βœ… SSRF mitigation (IP blocklist)

  • βœ… HTTP proxy authentication (bearer tokens)

  • βœ… Temp file integrity (SHA-256 verification)

  • βœ… Docker containerization (multi-layer isolation)

  • βœ… Comprehensive audit logging

Found a security vulnerability? See SECURITY.md for:

  • Documented vulnerabilities and mitigations

  • Responsible disclosure process

  • Security audit history

Please do not open public issues for security vulnerabilities.

Testing Security:

# Run comprehensive Docker security tests ./test-docker-security.sh # View audit logs tail -f audit.log # Check security configuration docker inspect code-executor | jq '.[0].HostConfig.SecurityOpt'

πŸ™ Acknowledgments

  • Model Context Protocol (MCP) - Anthropic's standard for LLM-tool communication

  • Deno - Secure TypeScript runtime with fine-grained permissions

  • Progressive Disclosure Pattern - UI/UX principles applied to LLM context management

πŸ“š Related

MCP & Code Execution:

Security:

Algorithms & Patterns:

Project Documentation:


**Made with ❀️ for anyone really. this has always been a pain point. i am sure that anthropic will release an official something for this, until then, hope this helps.

-
security - not tested
A
license - permissive license
-
quality - not tested

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Universal MCP server for executing TypeScript and Python code with progressive disclosure, reducing token usage by 98% by enabling on-demand access to all other MCP tools through code execution rather than loading tool definitions directly.

  1. 🎯 The Problem
    1. ✨ The Solution: One MCP to Rule Them All
      1. How It Works
    2. πŸ€” When to Use This (and When NOT to)
      1. βœ… Use code-executor when you have:
      2. ❌ Don't use this if you only need:
      3. πŸ’‘ Real-World Example (The Sweet Spot)
    3. πŸš€ Features
      1. βœ… Executors
      2. βœ… Security
      3. βœ… Configuration
      4. βœ… Quality
    4. πŸ“¦ Installation
      1. Option 1: Docker (Recommended for Production)
      2. Option 2: NPM (Development/Local)
      3. Running the Server
      4. Prerequisites
    5. πŸ”§ Configuration
      1. Docker Configuration
      2. Local Configuration
      3. Configuration Discovery
      4. Environment Variables
      5. Secret Management
    6. πŸ“– Usage
      1. Add to MCP Configuration (Claude Code)
      2. MCP Transport Types
      3. Execute TypeScript
      4. Execute Python (Optional)
      5. Health Check
    7. πŸ› οΈ Creating MCP Tool Wrappers
      1. Why We Don't Ship Wrappers
      2. Copy-Paste Templates
      3. Available Templates
      4. Benefits of This Approach
      5. Quick Start
    8. πŸ”’ Security Model
      1. Multi-Layer Defense Strategy
      2. Principle of Least Privilege
      3. Dangerous Patterns Blocked
      4. Audit Logging
      5. Rate Limiting
    9. πŸ“Š Architecture
      1. πŸš€ Production Deployment
        1. Docker Deployment (Recommended)
        2. Production Configuration
      2. πŸ§ͺ Development
        1. Setup
        2. Commands
        3. Testing
      3. πŸ“ˆ Progressive Disclosure Pattern
        1. Traditional Approach (❌ ~150,000 tokens)
        2. Progressive Disclosure (βœ… ~1,600 tokens)
        3. Real-World Example
      4. 🀝 Contributing
        1. Code Quality Standards
      5. πŸ“„ License
        1. πŸ” Security
          1. πŸ™ Acknowledgments
            1. πŸ“š Related

              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/aberemia24/code-executor-MCP'

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