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., "@MCP Code Execution Serverfilter users over 30 and calculate their average salary from the employee data"
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.
MCP Code Execution Server
A Model Context Protocol (MCP) server that implements efficient code execution, based on concepts from Anthropic's article: Code Execution with MCP.
π Key Features
98.7% Token Reduction: Instead of loading all tool definitions into context, agents write code to interact with tools
Filesystem-Based Tool Discovery: Tools organized in
./servers/directory for easy explorationSecure Sandboxing: Code execution in isolated VM with resource limits
State Persistence: Maintain state across sessions via filesystem
Dynamic Tool Loading: Load only the tools you need
PII Tokenization: Built-in support for handling sensitive data
π Why Code Execution with MCP?
Traditional MCP implementations load all tool definitions directly into the model's context window, consuming excessive tokens. This approach improves efficiency by:
Reducing Context Usage: From 150,000 tokens β 2,000 tokens in typical scenarios
Data Processing in Execution Environment: Process data before passing results to the model
Control Flow Efficiency: Loops and conditionals execute in code, not through sequential LLM calls
Privacy: Sensitive data can be tokenized, flowing between services without going through the model
ποΈ Architecture
mcp-code-execution/
βββ src/
β βββ index.ts # Main MCP server
β βββ execution-engine.ts # Sandboxed code execution
β βββ tool-loader.ts # Filesystem-based tool discovery
β βββ types.ts # Type definitions
βββ servers/ # Tool implementations
β βββ data/
β β βββ json-processor.ts
β β βββ csv-parser.ts
β βββ text/
β β βββ string-utils.ts
β βββ math/
β β βββ statistics.ts
β βββ crypto/
β βββ hash.ts
βββ package.jsonπ οΈ Installation
# Clone the repository
git clone <repository-url>
cd mcp-code-execution
# Install dependencies
npm install
# Build the project
npm run build
# Run the server
npm startπ Usage
Available Tools
1. execute_code
Execute JavaScript/TypeScript code in a secure sandbox. This is the primary tool for efficient MCP interaction.
Example:
// Instead of multiple tool calls, write code that processes data
const data = [
{ name: 'Alice', age: 30, salary: 80000 },
{ name: 'Bob', age: 25, salary: 65000 },
{ name: 'Charlie', age: 35, salary: 95000 }
];
// Filter and calculate in one execution
const highEarners = data.filter(person => person.salary > 70000);
const avgSalary = highEarners.reduce((sum, p) => sum + p.salary, 0) / highEarners.length;
log('High earners:', highEarners);
log('Average salary:', avgSalary);
// Save results for later use
setState('high_earners', JSON.stringify(highEarners));
setState('avg_salary', avgSalary);
return { count: highEarners.length, avgSalary };Available functions in sandbox:
log(...args): Console logginggetState(key): Retrieve persisted statesetState(key, value): Save state for future sessions
2. discover_tools
Discover available tools without loading them into context.
Example:
{
"category": "data"
}Response:
{
"success": true,
"tools": [
{
"path": "data/json-processor.ts",
"name": "data_json-processor",
"category": "data"
},
{
"path": "data/csv-parser.ts",
"name": "data_csv-parser",
"category": "data"
}
],
"count": 2
}3. load_tool
Load a specific tool's implementation to understand how to use it.
Example:
{
"tool_path": "data/csv-parser.ts"
}4. get_state / set_state
Persist and retrieve state across sessions.
Example:
{
"key": "user_preferences",
"value": "{\"theme\": \"dark\", \"language\": \"en\"}"
}π Security Features
Sandboxed Execution
All code runs in an isolated VM with:
Memory Limits: Default 128MB per execution
Timeout Protection: Default 5 seconds max execution time
Module Restrictions: Only allowed modules can be imported
Code Validation: Dangerous patterns are blocked
Blocked Patterns
The execution engine automatically blocks:
require()andimportstatementseval()andFunction()constructor__proto__manipulationConstructor prototype modification
Resource Limits
Configure resource limits per execution:
{
"code": "// your code here",
"timeout": 10000 // 10 seconds
}π Creating Custom Tools
Create new tools by adding TypeScript files to the servers/ directory:
// servers/mytools/example.ts
/**
* Description of what this tool does
* This comment becomes the tool's description
*/
export interface MyToolConfig {
option1?: string;
option2?: number;
}
export async function myFunction(
input: string,
config: MyToolConfig = {}
): Promise<any> {
// Your implementation here
return { result: 'processed data' };
}
// Example usage
export const example = {
usage: `
// In execute_code:
const result = await myFunction('input data', { option1: 'value' });
setState('my_result', result);
`
};Tools are automatically discovered by the tool loader and can be referenced in code execution.
π― Use Cases
1. Data Processing Pipeline
Process large datasets without sending all data through the model:
// Load CSV data
const csvData = `name,age,city
Alice,30,NYC
Bob,25,LA
Charlie,35,Chicago`;
// Parse and analyze
const parsed = parseCSV(csvData, { hasHeader: true });
const avgAge = parsed.reduce((sum, p) => sum + parseInt(p.age), 0) / parsed.length;
const cities = [...new Set(parsed.map(p => p.city))];
setState('processed_data', JSON.stringify({ avgAge, cities }));
return { avgAge, uniqueCities: cities.length };2. PII Tokenization
Handle sensitive data without exposing it to the model:
const userData = "Contact John at john@example.com or call 555-123-4567";
// Tokenize PII
const { tokenized, tokens } = tokenizePII(userData, {
emails: true,
phones: true
});
// Process tokenized data
log('Tokenized:', tokenized);
// Output: "Contact John at {{TOKEN_0}} or call {{TOKEN_1}}"
// Save tokens securely
setState('pii_tokens', JSON.stringify([...tokens.entries()]));
return { tokenized, tokenCount: tokens.size };3. Statistical Analysis
Perform complex calculations in the execution environment:
const salesData = [100, 150, 120, 200, 180, 160, 190];
const stats = calculateStats(salesData);
const ma = movingAverage(salesData, 3);
log('Statistics:', stats);
log('Moving Average:', ma);
setState('sales_stats', JSON.stringify(stats));
return {
mean: stats.mean,
trend: ma[ma.length - 1] > ma[0] ? 'up' : 'down'
};4. Multi-Step Workflows
Combine multiple operations without multiple LLM calls:
// Step 1: Load and parse data
const rawData = getState('raw_sales');
const parsed = JSON.parse(rawData);
// Step 2: Transform
const transformed = parsed.map(item => ({
...item,
revenue: item.quantity * item.price
}));
// Step 3: Aggregate
const totalRevenue = transformed.reduce((sum, item) => sum + item.revenue, 0);
// Step 4: Generate insights
const insights = {
totalRevenue,
averageOrderValue: totalRevenue / transformed.length,
topProduct: transformed.sort((a, b) => b.revenue - a.revenue)[0]
};
// Step 5: Save results
setState('sales_insights', JSON.stringify(insights));
return insights;π§ͺ Testing
Test the server using the MCP Inspector:
npx @modelcontextprotocol/inspector node dist/index.jsπ Performance Benefits
Approach | Tokens Used | Time | Cost |
Traditional MCP (all tools) | ~150,000 | High | High |
Code Execution MCP | ~2,000 | Low | Low |
Savings | 98.7% | ~95% | ~98% |
π€ Contributing
Add new tools to the
servers/directoryOrganize tools by category (data, text, math, etc.)
Include JSDoc comments for descriptions
Export functions that can be called from code execution
Add usage examples in comments
π Resources
π License
MIT
π Acknowledgments
This implementation is based on concepts from Anthropic's "Code Execution with MCP" article, which demonstrates how to achieve significant efficiency improvements in MCP-based systems through code execution rather than direct tool calls.
This server cannot be installed
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.