Why Code Mode?
Based on Anthropic’s research on code execution with MCP, code mode provides:- Better efficiency: Batch multiple operations in a single code execution
- Reduced context: Less back-and-forth between agent and tools
- Complex logic: Enable sophisticated data processing and transformations
- Natural workflow: Agents write code the way developers do
Execution Modes
VM Executor (Default)
Local execution with basic sandboxing. Good for:- Development and testing
- Trusted environments
- Fast local execution
E2B Executor (Recommended for Production)
Cloud-based sandboxing with strong isolation. Best for:- Production deployments
- Untrusted code execution
- Enhanced security requirements
Quick Start
Basic Setup (VM Executor)
The simplest way to enable Code Mode with local execution:E2B Setup (Cloud Sandbox)
For production or untrusted code, use E2B for stronger isolation:VM with Custom Timeout
Customize the VM executor timeout:Architecture
Code Mode uses a layered architecture to provide flexible code execution with MCP tool access:Flow
- Agent discovers tools using
search_tools - Agent writes code that calls tools as async functions
- Code executes in VM or E2B sandbox
- Tools are called either directly (VM) or via bridge (E2B)
- Results are returned to the agent
Executor Types
Code Mode supports three executor types:VM Executor (Default)
Local execution using Node.jsvm module. Fast and simple, suitable for trusted environments.
Advantages:
- Zero latency - direct function calls
- No external dependencies
- Immediate execution
- No cost
- Basic isolation (not suitable for untrusted code)
- Limited to Node.js built-ins
- Shares host resources
E2B Executor
Remote execution in E2B cloud sandboxes. Provides strong isolation for production use. Advantages:- True isolation in cloud sandbox
- Full Linux environment
- Network and filesystem access
- Persistent sandboxes
- Suitable for untrusted code
- Network latency overhead
- Requires E2B API key and billing
- More complex debugging
- Install dependency:
- Get API key: Visit e2b.dev and create an account to get your API key.
- Configure client:
- Set environment variable:
Custom Executor
Implement your own execution logic for specialized requirements. Custom Function:How Agent Code Works
When Code Mode is active, the agent writes JavaScript code that has access to:1. Tool Namespaces
Tools are exposed asserverName.toolName(args) async functions:
2. Tool Discovery
Usesearch_tools() to discover available tools at runtime:
3. Standard JavaScript
Full access to JavaScript built-ins for data processing:Complete Example
Here’s how an agent might write code to analyze GitHub issues:Advanced Topics
Timeout Configuration
Control execution timeouts at different levels:Error Handling
Code execution errors are captured in the result:Tool Discovery Patterns
Different ways to discover tools based on your needs:Resource Cleanup
Always clean up resources when done:Security Considerations
VM Executor Security
The VM executor uses Node.jsvm module for isolation:
Allowed:
- Standard built-ins:
Array,Object,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise - Standard functions:
parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,setTimeout,clearTimeout - Console methods:
console.log,console.error,console.warn,console.info - MCP tools via namespaced functions
requireandimportstatementsprocess,fs,child_process, and other Node.js modulesevalandFunctionconstructor- Access to host filesystem (except via MCP tools)
- Use VM executor only in trusted environments
- Validate and sanitize any user input used in code
- Set reasonable timeout limits
- Monitor execution logs for suspicious activity
E2B Executor Security
The E2B executor provides stronger isolation:- Code runs in isolated cloud sandbox
- Full Linux environment with network access
- Sandboxes are ephemeral and destroyed after use
- Tool calls are proxied back to host via secure channel
- No direct access to host system
- Use E2B for production and multi-tenant systems
- Keep API keys secure and rotate regularly
- Monitor E2B usage and costs
- Set appropriate timeout limits
- Review execution logs for debugging
API Reference
MCPClientOptions
ExecutionResult
MCPClient Methods
ToolSearchResponse
BaseCodeExecutor (for custom executors)
Complete Examples
VM Executor Example
Seeexamples/client/code_mode_example.ts for a complete working example using the default VM executor with the filesystem MCP server.
Key points:
- Simple configuration with
codeMode: true - Uses
PROMPTS.CODE_MODEfor agent instructions - Demonstrates tool discovery and usage
- Shows cleanup with
agent.close()
E2B Executor Example
Seeexamples/client/code_mode_e2b_example.ts for a complete working example using E2B cloud sandboxes.
Key points:
- E2B API key from environment variable
- Error handling for missing API key
- E2B-specific configuration
- Resource cleanup for cloud sandboxes
Troubleshooting
”Code execution mode is not enabled”
Make sure you initialized the client withcodeMode: true:
“@e2b/code-interpreter is not installed”
Install the E2B dependency:“Script execution timed out”
Increase the timeout:Tools not available in code
Make sure MCP servers are configured and connected:E2B sandbox issues
- Verify API key is correct and valid
- Check E2B account has sufficient credits
- Review E2B dashboard for sandbox logs
- Ensure network connectivity to E2B API
Further Reading
- Anthropic: Code Execution with MCP - Research and motivation
- MCP Specification - MCP protocol details
- E2B Documentation - E2B sandbox platform
- Executor Architecture - Technical implementation details