Dynamic Code Executor MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Dynamic Code Executor MCP Server run this Python code to calculate compound interest"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
๐ Dynamic Code Executor MCP Server
A powerful Model Context Protocol (MCP) server that enables AI assistants to execute code dynamically in isolated sandboxes with intelligent caching and semantic search.
Perfect for GitHub Copilot, Claude Desktop, Cline, and any MCP-compatible AI assistant that needs to run, test, and validate code in real-time.
๐ฏ Why This Project?
Modern AI assistants can write code, but they can't verify it works. Dynamic Code Executor bridges that gap by providing:
๐ฌ Real-time Validation - AI can test code immediately and fix errors
๐ง Semantic Cache - Find and reuse similar solutions without rewriting
โก Lightning Fast - Cached results return instantly
๐ Enterprise Security - Sandboxed execution with package whitelisting
๐ 35+ Scripts Cached - Proven track record in production use
Related MCP server: Code Executor MCP Server
๐ฌ How It Works - Visual Guide
Execution Flow
flowchart TD
A[๐ค AI Assistant sends code] --> B{๐ฆ Check Cache}
B -->|Cache Hit| C[โก Return Cached Result]
B -->|Cache Miss| D[โ
Validate Packages]
D --> E[๐ Create Sandbox]
E --> F[๐ฆ Install Packages]
F --> G[โถ๏ธ Execute Code]
G --> H{โ Success?}
H -->|Yes| I[๐พ Save to Cache]
H -->|No| J[โ Return Error]
I --> K[๐งน Cleanup Temp Files]
J --> K
K --> L[๐ Return Results]
C --> L
style C fill:#90EE90
style I fill:#87CEEB
style J fill:#FFB6C1
style L fill:#DDA0DDInteraction Sequence
sequenceDiagram
participant AI as ๐ค AI Assistant
participant MCP as ๐ง MCP Server
participant Cache as ๐พ Cache
participant Sandbox as ๐ฆ Sandbox
participant Python as ๐ Python/JS/TS
AI->>MCP: execute_code(language, code, packages)
MCP->>Cache: Check if code exists
alt Code in cache
Cache-->>MCP: Return cached result โก
MCP-->>AI: Instant response (0ms)
else Code not cached
MCP->>MCP: Validate packages against whitelist
MCP->>Sandbox: Create isolated workspace
MCP->>Sandbox: Install packages (pip/npm)
MCP->>Python: Execute code with timeout
Python-->>MCP: Output + Exit Code
MCP->>Cache: Save successful execution ๐พ
MCP->>Sandbox: Cleanup temporary files ๐งน
MCP-->>AI: Return results
end
Note over AI,Python: Semantic search enables reuse of similar scriptsCaching Strategy Visualization
graph LR
A[Code Execution] --> B{Exact Match?}
B -->|Yes| C[โก Instant Cache Hit]
B -->|No| D[Execute & Cache]
D --> E[๐พ Persistent Cache]
E --> F[๐ Semantic Search Index]
F --> G[Find Similar Scripts]
style C fill:#90EE90
style E fill:#87CEEB
style F fill:#FFD700
style G fill:#DDA0DDโจ Features
๐ Python support with pip package installation
๐จ JavaScript/Node.js support with npm packages
๐ท TypeScript support with automatic transpilation
๐ Process isolation for security
โฑ๏ธ Timeout protection against infinite loops
๐ฆ Whitelisted package installation - only safe, approved packages
๐พ Persistent caching - successful scripts cached and reusable
๐ Semantic search - find similar scripts by task description
โก Session-based caching - fast package installation within session
๐ Full workspace access - scripts can read/write files in their sandbox
๐งน Automatic cleanup after execution
โ Detailed error reporting with line numbers
๐ Script repository - browse and reuse previously successful scripts
๐ How It Works - Step by Step
stateDiagram-v2
[*] --> ReceiveCode: ๐ค AI sends code
ReceiveCode --> CheckCache: ๐ฆ Check cache
CheckCache --> ReturnCached: โก Cache hit!
CheckCache --> ValidatePackages: Cache miss
ValidatePackages --> CreateSandbox: โ
All packages allowed
CreateSandbox --> InstallPackages: ๐ Isolated workspace
InstallPackages --> ExecuteCode: ๐ฆ pip/npm install
ExecuteCode --> Success: โถ๏ธ Run with timeout
ExecuteCode --> Failed: โ Error
Success --> SaveCache: ๐พ Save to persistent cache
SaveCache --> Cleanup: ๐งน Remove temp files
Failed --> Cleanup
Cleanup --> ReturnResults: ๐ Send output
ReturnCached --> [*]
ReturnResults --> [*]Detailed Steps:
๐ค Model sends code via
execute_codetool๐ฆ Cache check - instant return if identical code was run before
โ Package validation - verify all packages are in whitelist
๐ Sandbox creation - isolated temporary directory with full file access
โก Session cache - reuse pip/npm cache within session for speed
๐ฆ Package installation - install whitelisted packages
โถ๏ธ Code execution - run with timeout protection (max 5 min)
๐พ Result caching - successful executions saved to persistent cache
๐งน Cleanup - remove temporary files, keep persistent cache
๐ Semantic search - model can browse and reuse cached scripts
๐ ๏ธ Available Tools
execute_code
Execute code in an isolated sandbox.
Parameters:
language:python,javascript,js,typescript, ortscode: The code to executepackages: Optional array of packages to install (e.g.,["requests", "numpy"])timeout: Execution timeout in ms (default: 30000ms, max: 300000ms)allowNetworking: Allow network access (default: true)
Returns:
{
"success": true,
"output": "execution output",
"executionTime": 1234,
"language": "python",
"cached": false
}validate_code
Validate code syntax without executing.
Parameters:
language: Programming languagecode: Code to validate
Returns: Syntax validation result with error details if invalid.
list_supported_languages
List all supported programming languages.
Returns: Array of supported languages and their capabilities.
list_allowed_packages
List all whitelisted packages that can be installed.
Parameters:
language: Language to list packages for (or"all")
Returns: List of allowed packages for the specified language.
search_cached_scripts
Search for similar scripts using semantic matching.
Parameters:
query: Description of what you want to do (e.g., "fetch GitHub API", "parse CSV")language: Filter by language (optional)limit: Max results (default: 10)
Returns: Ranked results with similarity scores.
Example:
{
"query": "fetch data from REST API",
"results": 2,
"matches": [
{
"hash": "a1b2c3...",
"score": 0.85,
"description": "fetch GitHub API data",
"language": "python"
}
]
}list_cached_scripts
List recently executed successful scripts (chronological).
Parameters:
language: Filter by language (optional)limit: Maximum number to return (default: 20)
Returns: List of cached scripts with hashes and previews.
get_cached_script
Get full details of a cached script by hash.
Parameters:
hash: Cache hash fromlist_cached_scripts
Returns: Complete script with code, results, and execution stats.
get_cache_stats
Get statistics about the persistent cache.
Returns: Total scripts, size, breakdown by language.
get_execution_limits
Get information about execution limits and constraints.
Returns: Timeout limits, resource constraints, security settings.
๐ฆ Installation
# Clone the repository
git clone https://github.com/yourusername/dynamic-code-executor-mcp.git
cd dynamic-code-executor-mcp
# Install dependencies
npm install
# Build the project
npm run buildโ๏ธ Configuration
For Claude Desktop
Add to your config (%APPDATA%\Claude\claude_desktop_config.json):
{
"mcpServers": {
"code-executor": {
"command": "node",
"args": ["C:\\path\\to\\MCPSELFCODE\\dist\\index.js"]
}
}
}For GitHub Copilot (VS Code)
See VS Code Setup Guide for detailed instructions.
For Cline + OLLAMA
See Setup Guide for detailed instructions.
๐ Documentation
Setup Guide - Integrate with Cline + OLLAMA
VS Code Setup - GitHub Copilot integration
LICENSE - MIT License
๐ก Usage Examples
Example 1: Python with Packages
import requests
response = requests.get('https://api.github.com')
print(f"Status: {response.status_code}")
print(f"Rate Limit: {response.headers.get('X-RateLimit-Remaining')}")Example 2: JavaScript with Packages
const axios = require('axios');
const response = await axios.get('https://api.github.com');
console.log(`Status: ${response.status}`);
console.log(`Headers:`, response.headers);Example 3: TypeScript
interface User {
name: string;
age: number;
email?: string;
}
const users: User[] = [
{ name: "Alice", age: 30, email: "alice@example.com" },
{ name: "Bob", age: 25 }
];
users.forEach(user => {
console.log(`${user.name} (${user.age}): ${user.email || 'No email'}`);
});Example 4: Data Processing with NumPy
import numpy as np
# Create array and perform calculations
data = np.array([1, 2, 3, 4, 5])
print(f"Mean: {np.mean(data)}")
print(f"Std Dev: {np.std(data)}")
print(f"Sum: {np.sum(data)}")Example 5: Web Scraping
from bs4 import BeautifulSoup
import requests
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('title').text
print(f"Page title: {title}")Example 6: File Operations in Sandbox
# Write data to file in sandbox
with open('results.txt', 'w') as f:
f.write('Processing complete!\n')
f.write('Total: 42\n')
# Read it back
with open('results.txt', 'r') as f:
print(f.read())๐ Security
Process Isolation
Each execution runs in a separate isolated process
Timeout protection prevents infinite loops
Automatic cleanup of all temporary files
Sandboxed Workspaces
Each run gets an isolated temporary directory with full access
Package whitelist: Only pre-approved safe packages can be installed
Package isolation: Python uses venv, Node uses local node_modules
No cross-session contamination: Each execution is independent
๐พ Caching Strategy
Session Cache (Temporary)
Created per execution
Speeds up package installation within same session
Automatically cleaned up after execution
Stored in:
%TEMP%/mcp-cache-{sessionId}/
Persistent Cache (Permanent)
Stores successful script executions with hash + description
Exact match: Identical code = instant cached result
Semantic match: Similar task description = suggested cached solution
Survives restarts
Model can search and reuse scripts by description
Stored in:
%USERPROFILE%/.mcp-code-executor/
How semantic caching works:
Provide
descriptionwhen executing code (e.g., "fetch GitHub API")Next time you need similar functionality:
search_cached_scripts("get data from GitHub")Get ranked results even if exact code differs
Reuse proven solutions without rewriting
๐ Workspace Access
Code has full read/write access to its sandbox directory:
Python example:
with open('data.txt', 'w') as f:
f.write('Hello from sandbox!')
with open('data.txt', 'r') as f:
print(f.read())JavaScript example:
const fs = require('fs');
fs.writeFileSync('output.json', JSON.stringify({status: 'ok'}));
console.log(fs.readFileSync('output.json', 'utf-8'));The workspace path is returned in results as workspaceDir (automatically cleaned after execution).
๐ Requirements
Node.js 18+
Python 3.7+ (for Python execution)
npm (for JavaScript/TypeScript execution)
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Fork the repository
Create your feature branch (
git checkout -b feature/AmazingFeature)Commit your changes (
git commit -m 'Add some AmazingFeature')Push to the branch (
git push origin feature/AmazingFeature)Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
Built with Model Context Protocol SDK
Inspired by the need for AI assistants to validate their code in real-time
Thanks to all contributors and users!
Made with โค๏ธ for the AI coding community
Star โญ this repo if you find it useful!
Available Tools
9 toolsexecute_codeA
Execute code in a secure isolated sandbox. Supports Python, JavaScript, and TypeScript.
The code will be executed in a temporary environment that is cleaned up after execution. You can optionally install packages before execution.
Use this when you need to:
Run code to get results or test functionality
Process data dynamically
Validate code behavior
Install and use external packages
Returns execution results including output, errors, and execution time.
Inputs: code (required), language (required), timeout, packages, +3 more.
get_cached_scriptA
Get a specific cached script by its hash.
Returns the full script details including code, result, packages used, and execution stats.
Inputs: hash (required).
get_cache_statsA
Get statistics about the persistent script cache
Inputs: no named parameters.
get_execution_limitsB
Get information about execution limits and constraints
Inputs: no named parameters.
list_allowed_packagesA
List all packages allowed to be installed for each language.
Only whitelisted packages can be installed for security reasons. Use this tool to check which packages are available before writing code that requires external dependencies.
Returns a list of allowed packages for Python, JavaScript, and TypeScript.
Inputs: language.
list_cached_scriptsA
List recently cached scripts (chronological order).
Shows the most recent successful executions. Use search_cached_scripts for finding scripts by task description.
Inputs: limit, language.
list_supported_languagesA
List all supported programming languages with their capabilities and package managers
Inputs: no named parameters.
search_cached_scriptsA
Search for similar cached scripts using semantic search.
Finds previously executed scripts that solve similar problems, even if the exact code differs. Use this when you need to solve a task - there might already be a working solution cached.
Example queries:
"fetch data from REST API"
"parse JSON and extract fields"
"read CSV file and calculate sum"
"scrape webpage content"
Returns ranked results by similarity with scores.
Inputs: query (required), limit, language.
validate_codeA
Validate code syntax without executing it. Performs static analysis to check for syntax errors.
Use this to check code validity before execution or to help debug syntax issues.
Inputs: code (required), language (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 9 tools
Each tool targets a distinct action: validation, execution, listing languages, listing packages, limits, cache search, cache list, cache retrieval, and cache stats. No two tools overlap in purpose, and descriptions clearly differentiate between similar-sounding operations like search_cached_scripts vs list_cached_scripts.
All tool names follow a consistent verb_noun pattern in snake_case (e.g., validate_code, list_supported_languages, get_execution_limits, search_cached_scripts). There is no mixing of conventions or inconsistent verb styles.
9 tools is well-scoped for a code execution service. It covers validation, execution, environment discovery (languages, packages, limits), and a complete cache querying subsystem without redundancy or bloat.
The core domain is well-covered: validate and execute code, discover supported languages/allowed packages/limits, and search/list/retrieve cached scripts. Minor gaps like cache deletion or clearing are absent, but they are not essential for primary use cases.
Maintenance
Related MCP Connectors
Build Apps and run code in 30 languages โ sandboxed, with persistent sessions for agent loops.
Run AI agent tasks in isolated sandboxes with a cost cap, saved workflows and scoped connections.
Backend platform for AI agents: one agentstack.execute tool runs batched steps over +700 actions (hosting, storage, auth, payments, CRM, app builder).
Cloud Linux VMs for your agent: run code, Docker, files and HTTPS previews in a Sandboxer microVM.
Related MCP Servers
FlicenseNot gradedqualityDmaintenanceEnables AI assistants to execute Python, JavaScript, Bash, and Go code in blazing-fast (~0.1ms startup), isolated cloud containers with secure, ephemeral environments that auto-destroy after use.128-- AlicenseNot gradedqualityCmaintenanceProvides sandboxed code execution for AI agents with support for Python, JavaScript, and shell commands. Includes comprehensive safety features like destructive pattern blocking, timeout protection, and restricted file access for secure production use.21 npm43 PyPIMIT
- AlicenseAqualityDmaintenanceEnables AI assistants to securely execute Python and JavaScript code in sandboxed environments, with file management and package installation.792 npmMIT
- AlicenseAqualityCmaintenanceEnables AI assistants to securely execute Python and C++ code snippets inside disposable, isolated Docker containers and receive structured results.31MIT