Code Mode - JavaScript Sandbox Execution
Execute JavaScript code with access to all MCP tools in a secure sandbox.
Code Mode
Code Mode is an advanced feature that allows LLM clients to execute JavaScript code with access to all configured MCP tools. Instead of exposing raw tools directly, Code Mode exposes two meta-tools that enable programmatic tool orchestration.
Why Code Mode?
| Benefit | Description |
|---|---|
| Reduced Context Window | Expose 2 meta-tools instead of 100+ individual tools |
| Complex Workflows | Chain multiple tool calls in a single execution |
| Conditional Logic | Implement if/else, loops, and error handling |
| Secure Execution | Code runs in a WebAssembly sandbox (QuickJS) |
Configuration
{
"codeMode": {
"enabled": true,
"timeout": 30000,
"allowFetch": true
},
"mcpServers": {
// Your MCP servers...
}
}| Option | Default | Description |
|---|---|---|
enabled | false | Enable Code Mode |
timeout | 30000 | Max execution time in ms |
allowFetch | true | Allow fetch() API in sandbox |
Meta-Tools
When Code Mode is enabled, the gateway exposes these tools instead of raw upstream tools:
routermcp.listTools
Lists all available MCP tools with TypeScript type definitions. Use this to discover what tools are available before writing code.
Input:
filter(optional): Filter tools by name or description
Output: TypeScript declarations for all available tools
declare const github: {
create_issue: (args: { owner: string; repo: string; title: string; body?: string }) => Promise<any>;
list_issues: (args: { owner: string; repo: string; state?: "open" | "closed" }) => Promise<any>;
};
declare const filesystem: {
read_file: (args: { path: string }) => Promise<any>;
};
declare function fetch(url: string, init?: RequestInit): Promise<Response>;
declare const console: { log: (...args: any[]) => void; error: (...args: any[]) => void };routermcp.executeCode
Executes JavaScript code in a secure sandbox with access to all MCP tools.
Input:
code(required): JavaScript code to execute
Output:
success: Whether execution completed without errorsresult: Return value from the codelogs: Console outputerrors: Any errors that occurredtoolCalls: List of MCP tools that were calledduration: Execution time in milliseconds
Code Examples
Simple Tool Call
const issues = await github.list_issues({
owner: "microsoft",
repo: "vscode",
state: "open"
});
console.log(`Found ${issues.length} open issues`);
return issues.slice(0, 5);Chaining Multiple Tools
const content = await filesystem.read_file({ path: "/path/to/bug-report.md" });
const issue = await github.create_issue({
owner: "myorg",
repo: "myproject",
title: "Bug Report",
body: content
});
return { issueUrl: issue.html_url };Conditional Logic
const issues = await github.list_issues({ owner: "org", repo: "repo", state: "open" });
const criticalIssues = issues.filter(i =>
i.labels.some(l => l.name === "critical")
);
if (criticalIssues.length > 0) {
console.log(`Found ${criticalIssues.length} critical issues!`);
return { status: "alert", issues: criticalIssues };
} else {
return { status: "ok", message: "No critical issues" };
}Using fetch()
When allowFetch is enabled:
const response = await fetch("https://api.github.com/rate_limit");
const rateLimit = await response.json();
const issues = await github.list_issues({ owner: "org", repo: "repo" });
return {
rateLimit: rateLimit.rate.remaining,
issueCount: issues.length
};Security
Code Mode uses QuickJS compiled to WebAssembly for secure sandboxed execution:
| Protection | Description |
|---|---|
| No filesystem access | Code cannot read/write files directly |
| No process access | Cannot spawn processes or access env vars |
| Timeout enforcement | Execution terminates after timeout |
| Network isolation | fetch() can be disabled |
| Memory limits | WebAssembly sandbox has memory constraints |
Even with these protections, Code Mode gives LLMs significant capabilities through MCP tools. Only enable it when you trust your upstream MCP servers.
Code Mode vs Direct Tools
| Aspect | Direct Tools | Code Mode |
|---|---|---|
| Tools exposed | All configured | 2 meta-tools |
| Context window | Large | Small |
| Workflow complexity | Single calls | Multi-step |
| Error handling | Client-side | In-code try/catch |
| Conditional logic | Not possible | Full JavaScript |
| Best for | Simple operations | Complex orchestration |
When to Use Code Mode
Use Code Mode when:
- You have many tools and want to reduce context window usage
- You need complex multi-step workflows
- You want conditional logic or loops
- You need to aggregate data from multiple tool calls
Use Direct Tools when:
- You have few tools
- Operations are simple and independent
- You want maximum transparency of tool calls
- You don't need programmatic control flow