Dynamic Code Executor MCP Server
Click on "Install 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 Serverrun 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!
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
Flicense-qualityCmaintenanceEnables 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.155- Alicense-qualityAmaintenanceProvides 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.15MIT
- Alicense-qualityCmaintenanceEnables LLMs to execute Python code securely in a sandboxed environment. Supports configurable restrictions like no network access and returns results including files.MIT
- Flicense-qualityDmaintenanceEnables AI assistants to securely execute Python and JavaScript code in sandboxed environments, with file management and package installation.112
Related MCP Connectors
Execute code in 8 languages (Python, JS, TS, Go, Java, C++, C, Bash) in gVisor sandboxes.
Build, validate, and deploy multi-agent AI solutions from any AI environment.
Git-backed platform for skills, tools, and context for AI agents
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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/rafalswiderski/mcp-code-executor'
If you have feedback or need assistance with the MCP directory API, please join our Discord server