
Code Mode enables AI agents to interact with MCP tools through code execution instead of direct tool calls. Based on research from Anthropic and Cloudflare, this approach reduces context consumption by up to 98.7% for complex workflows.
Quick Start
Why Code Mode?
Traditional MCP clients load all tool definitions upfront and pass intermediate results through the model context. This creates two problems:- Tool definitions overload context - 150+ tools = 150,000+ tokens before processing any request
- Intermediate results consume tokens - Each tool result flows through the model, even when just passing data between tools
Key Advantages
1. Progressive Disclosure
Agents load only the tools they need, when they need them:2. Context-Efficient Tool Results
Large datasets are processed in the execution environment before returning to the agent:3. More Powerful Control Flow
Loops, conditionals, and error handling use familiar code patterns instead of chaining individual tool calls:4. Privacy-Preserving Operations
Intermediate results stay in the execution environment by default:Real-World Example: File System Exploration
This example demonstrates how Code Mode dramatically simplifies complex workflows. An agent tasked with “list files and rename them” performs the entire operation efficiently.
Discovery: Finding the Right Tools
The agent starts by searching for filesystem tools:Result (16 filesystem tools found)
Code Mode Advantage: The agent discovered 16 tools using ~200 tokens, compared to ~8,000+ tokens if all filesystem tool definitions were pre-loaded into the system prompt.
Execution: Processing Files Efficiently
The agent writes a single Python script to complete the task:Efficiency Comparison
By writing code instead of chaining tool calls, the agent processed the file list locally and only returned the summary. This avoided passing the raw directory listing (and each rename confirmation) through the LLM context.
API Reference
MCPClient
__init__(code_mode=True)
execute_code(code: str, timeout: float = 30.0)
Execute Python code with MCP tool access.
Returns:
search_tools(query: str = "", detail_level: str = "full")
Search available tools across all servers.
Returns: Dictionary with:
meta: Dictionary containingtotal_tools,namespaces, andresult_countresults: List of tool information dictionaries matching the query
"names", "descriptions", "full"
What’s Available in Code
Functions
search_tools(query, detail_level)- Discover toolsserver.tool_name(**kwargs)- Call any MCP tool__tool_namespaces- List of server names
Note: Tool names are automatically sanitized to be valid Python identifiers. For example, a tool namedlist-filesbecomeslist_files.
Builtins
import, open, eval, file I/O
Performance
From Anthropic’s research:Examples
Tool Chaining
Data Processing
Error Handling
Agent Integration
Agents only see 2 tools whencode_mode=True:
execute_code- Execute Python code with tool accesssearch_tools- Discover available tools
References
See Also
- Direct Tool Calls - Traditional tool calling
- Tools - Understanding MCP tools
- Multi-Server Setup - Multiple servers