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
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
Code Mode uses a layered architecture to provide flexible code execution with MCP tool access: 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: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: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.
E2B Executor Example: See examples/client/code_mode_e2b_example.ts for a complete working example using E2B cloud sandboxes.
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