Dynamic Code Executor MCP Server
# ๐ Dynamic Code Executor MCP Server
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org/)
[](https://www.typescriptlang.org/)
[](https://modelcontextprotocol.io/)
> **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
---
## ๐ฌ How It Works - Visual Guide
> **๐บ [See full animated workflow โ](docs/VISUAL_GUIDE.md)**
---
### Execution Flow
```mermaid
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:#DDA0DD
```
### Interaction Sequence
```mermaid
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 scripts
```
### Caching Strategy Visualization
```mermaid
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
```mermaid
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:
1. **๐ค Model sends code** via `execute_code` tool
2. **๐ฆ Cache check** - instant return if identical code was run before
3. **โ
Package validation** - verify all packages are in whitelist
4. **๐ Sandbox creation** - isolated temporary directory with full file access
5. **โก Session cache** - reuse pip/npm cache within session for speed
6. **๐ฆ Package installation** - install whitelisted packages
7. **โถ๏ธ Code execution** - run with timeout protection (max 5 min)
8. **๐พ Result caching** - successful executions saved to persistent cache
9. **๐งน Cleanup** - remove temporary files, keep persistent cache
10. **๐ 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`, or `ts`
- `code`: The code to execute
- `packages`: 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:**
```json
{
"success": true,
"output": "execution output",
"executionTime": 1234,
"language": "python",
"cached": false
}
```
### `validate_code`
Validate code syntax without executing.
**Parameters:**
- `language`: Programming language
- `code`: 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:**
```json
{
"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 from `list_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
```bash
# 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`):
```json
{
"mcpServers": {
"code-executor": {
"command": "node",
"args": ["C:\\path\\to\\MCPSELFCODE\\dist\\index.js"]
}
}
}
```
### For GitHub Copilot (VS Code)
See **[VS Code Setup Guide](docs/VSCODE_SETUP.md)** for detailed instructions.
### For Cline + OLLAMA
See **[Setup Guide](docs/SETUP.md)** for detailed instructions.
---
## ๐ Documentation
- **[Setup Guide](docs/SETUP.md)** - Integrate with Cline + OLLAMA
- **[VS Code Setup](docs/VSCODE_SETUP.md)** - GitHub Copilot integration
- **[LICENSE](LICENSE)** - MIT License
---
## ๐ก Usage Examples
### Example 1: Python with Packages
```python
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
```javascript
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
```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
```python
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
```python
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
```python
# 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:**
1. Provide `description` when executing code (e.g., "fetch GitHub API")
2. Next time you need similar functionality: `search_cached_scripts("get data from GitHub")`
3. Get ranked results even if exact code differs
4. Reuse proven solutions without rewriting
---
## ๐ Workspace Access
Code has **full read/write access** to its sandbox directory:
**Python example:**
```python
with open('data.txt', 'w') as f:
f.write('Hello from sandbox!')
with open('data.txt', 'r') as f:
print(f.read())
```
**JavaScript example:**
```javascript
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.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
---
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
## ๐ Acknowledgments
- Built with [Model Context Protocol SDK](https://modelcontextprotocol.io/)
- 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!*
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.