RouterMCP
RouterMCP CLI

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?

BenefitDescription
Reduced Context WindowExpose 2 meta-tools instead of 100+ individual tools
Complex WorkflowsChain multiple tool calls in a single execution
Conditional LogicImplement if/else, loops, and error handling
Secure ExecutionCode runs in a WebAssembly sandbox (QuickJS)

Configuration

{
  "codeMode": {
    "enabled": true,
    "timeout": 30000,
    "allowFetch": true
  },
  "mcpServers": {
    // Your MCP servers...
  }
}
OptionDefaultDescription
enabledfalseEnable Code Mode
timeout30000Max execution time in ms
allowFetchtrueAllow 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 errors
  • result: Return value from the code
  • logs: Console output
  • errors: Any errors that occurred
  • toolCalls: List of MCP tools that were called
  • duration: 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:

ProtectionDescription
No filesystem accessCode cannot read/write files directly
No process accessCannot spawn processes or access env vars
Timeout enforcementExecution terminates after timeout
Network isolationfetch() can be disabled
Memory limitsWebAssembly 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

AspectDirect ToolsCode Mode
Tools exposedAll configured2 meta-tools
Context windowLargeSmall
Workflow complexitySingle callsMulti-step
Error handlingClient-sideIn-code try/catch
Conditional logicNot possibleFull JavaScript
Best forSimple operationsComplex 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

On this page