Skip to main content
Glama
ozgureyilmaz

MCP Code Execution Server

by ozgureyilmaz

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 exploration

  • Secure 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:

  1. Reducing Context Usage: From 150,000 tokens β†’ 2,000 tokens in typical scenarios

  2. Data Processing in Execution Environment: Process data before passing results to the model

  3. Control Flow Efficiency: Loops and conditionals execute in code, not through sequential LLM calls

  4. 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 logging

  • getState(key): Retrieve persisted state

  • setState(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() and import statements

  • eval() and Function() constructor

  • __proto__ manipulation

  • Constructor 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

  1. Add new tools to the servers/ directory

  2. Organize tools by category (data, text, math, etc.)

  3. Include JSDoc comments for descriptions

  4. Export functions that can be called from code execution

  5. 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.

-
security - not tested
F
license - not found
-
quality - not tested

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ozgureyilmaz/mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server