Skip to main content
Glama
rafalswiderski

Dynamic Code Executor MCP Server

README.md
# ๐Ÿš€ Dynamic Code Executor MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue)](https://www.typescriptlang.org/)
[![MCP](https://img.shields.io/badge/MCP-Compatible-purple)](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

A4/5.0

Scored across 9 tools

Disambiguation5/5

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.

Naming Consistency5/5

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.

Tool Count5/5

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.

Completeness4/5

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

ActivitySlowing
ResponsivenessNo issues