Code Execution MCP

Code Execution MCP

Enables efficient AI agent operations through sandboxed Python code execution with progressive tool discovery, PII tokenization, and skills persistence, achieving up to 98.7% token reduction by processing data in a sandbox rather than in context.

Category
Visit Server

README

Code Execution MCP

Implements the patterns from Anthropic's "Code Execution with MCP" article for efficient AI agent operations.

Core Insight

Instead of loading thousands of tool definitions upfront and passing intermediate results through model context, agents write code that:

  1. Discovers tools on-demand (progressive disclosure)
  2. Processes data in a sandbox (not in context)
  3. Returns only summarized/filtered results

Result: Up to 98.7% token reduction compared to direct tool invocation.

Features

1. Sandboxed Code Execution

  • Resource limits (30s timeout, 500MB memory)
  • Restricted builtins (safe subset)
  • Safe modules (json, re, math, datetime, etc.)
  • Workspace file utilities

2. Progressive Tool Discovery

  • Search tools by query without loading definitions
  • Get summaries first, full definitions on-demand
  • Organized by category (security, memory, cluster, etc.)

3. PII Tokenization

  • Auto-detect sensitive data (emails, phones, SSNs, etc.)
  • Replace with tokens before data reaches model
  • Restore when needed for tool calls

4. Skills Persistence

  • Save reusable code snippets
  • Build compound capabilities over time
  • Share across sessions

Tools

Tool Description
execute_code Run Python in secure sandbox
search_tools Progressive tool discovery
get_tool_definition Load full tool details
save_skill Persist reusable code
load_skill Load saved skill
list_skills List all skills
sanitize_pii Tokenize PII in text
restore_pii Restore tokenized PII
write_workspace_file Persist data to workspace
read_workspace_file Read from workspace
list_workspace_files List workspace contents
get_execution_stats Environment statistics

Usage Examples

Efficient Data Processing

# Instead of returning 10,000 rows to context:
code = '''
data = json.loads(read_file("large_dataset.json"))
filtered = [d for d in data if d['status'] == 'active']
result = {
    'total': len(data),
    'active': len(filtered),
    'sample': filtered[:5]
}
'''
execute_code(code)
# Returns only summary, not full dataset

Progressive Tool Discovery

# Find security tools (minimal tokens)
search_tools("vulnerability", category="security", detail_level="summary")

# Load full definition only when needed
get_tool_definition("web_vuln_scanner", category="security")

Privacy-Preserving Operations

# Sanitize before processing
sanitize_pii("Contact john@example.com at 555-123-4567")
# Returns: "Contact [EMAIL_abc123] at [PHONE_def456]"

# Restore when needed
restore_pii("[EMAIL_abc123]")
# Returns: "john@example.com"

Building Skills

# Save a reusable skill
save_skill(
    name="filter_high_risk",
    code="def filter_high_risk(vulns): return [v for v in vulns if v['severity'] in ['high', 'critical']]",
    description="Filter vulnerabilities to high/critical only"
)

# Use in future code execution
code = '''
skill = load_skill("filter_high_risk")
exec(skill)
vulns = json.loads(read_file("scan_results.json"))
result = filter_high_risk(vulns)
'''

Installation

cd /mnt/agentic-system/mcp-servers/code-execution-mcp
pip install -e .

Configuration

Add to ~/.claude.json:

{
  "mcpServers": {
    "code-execution": {
      "command": "/mnt/agentic-system/.venv/bin/python3",
      "args": ["/mnt/agentic-system/mcp-servers/code-execution-mcp/src/code_execution_mcp/server.py"],
      "disabled": false
    }
  }
}

Architecture

code-execution-mcp/
├── workspace/           # Sandboxed file storage
├── skills/              # Persistent skill definitions
├── tools_registry/      # Tool definitions for discovery
│   ├── security/        # Security tools
│   └── memory/          # Memory tools
└── src/
    └── code_execution_mcp/
        └── server.py    # Main MCP server

Security Notes

  • Code runs with restricted builtins (no open, exec, eval on arbitrary input)
  • File access limited to workspace directory
  • Resource limits prevent runaway execution
  • No network access from sandbox

References

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured