Dynamic Code Executor MCP Server

Dynamic Code Executor MCP Server

Enables AI assistants to execute code in isolated sandboxes with support for Python, JavaScript, and TypeScript, featuring intelligent caching and semantic search for code reuse.

Category
访问服务器

README

🚀 Dynamic Code Executor MCP Server

License: MIT Node.js Version TypeScript MCP

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 →


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:#DDA0DD

Interaction 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 scripts

Caching 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:

  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:

{
  "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:

{
  "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

# 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


💡 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:

  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:

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.

  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 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!

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选