Example on GitHub
Full working example with SecureExecExecutor and tool dispatch.
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.
Why Code Mode
- Fewer round-trips: Chain multiple tool calls, conditionals, and data transformations in a single execution
- Lower token usage: Intermediate results stay in the sandbox instead of passing back through the LLM context
- Better tool handling: LLMs manage more tools and greater complexity when presented as TypeScript APIs vs. raw tool definitions
Status
Code Mode support in Secure Exec is early. Today you need to copy theSecureExecExecutor adapter from the example into your project. We’re planning official first-party support.
Further reading
- Cloudflare Code Mode blog post
@cloudflare/codemodepackage- AI Agent Code Exec for simpler single-tool execution patterns