Example on GitHub
Full working example with SecureExecExecutor and tool dispatch.
Why Code Mode
- 81% less token overhead: With 50 tools, replacing per-call tool descriptions with a single code-execution tool cuts tool description tokens by 81%
- Fewer round-trips: Chain multiple tool calls, conditionals, and data transformations in a single execution
- Real control flow: Loops, branching,
Promise.all— not a chain of isolated tool calls - Drop-in replacement: Your existing tools don’t change at all. Code Mode wraps them transparently.
How it works
- Define your tools (AI SDK
tool(), MCP servers, or both) - Create a
SecureExecExecutorthat runs LLM-generated code in a V8 isolate and proxiescodemode.*calls back to your tool implementations - Give the LLM one tool (“execute code”) with typed API definitions for your tools
- The LLM writes JavaScript that calls your tools via
codemode.*and chains the results
SecureExecExecutor.
Further reading
- Complete Code Mode implementation guide — end-to-end Code Mode walkthrough using MCP Toolkit
- Cloudflare Code Mode blog post
- AI Agent Code Exec for simpler single-tool execution patterns