Code Mode Template
The Code Mode Template (typescript-code-mode) demonstrates local script orchestration using NitroStack's CodeModeTransform. AI models write standard JavaScript (ES2020) scripts that execute inside an isolated QuickJS WebAssembly sandbox with direct access to an asynchronous callTool() bridge. This allows complex multi-step pipelines to execute in a single network round-trip, eliminating serialized network latency and token overhead.
Table of Contents
- Overview
- What's Included
- Quick Start
- Architecture & Sandboxed Worker Pool
- The 3 Synthetic Meta-Tools
- Multi-Step Script Execution Walkthrough
- Sandboxing & Security Caps
Overview
When an agent needs to perform multi-step data pipelines (such as fetching 100 records, filtering values, calculating an aggregate sum, and formatting a report), traditional MCP requires serialized back-and-forth round-trips over the wire for every tool invocation.
Code Mode transforms this interaction model:
- The tool catalog is collapsed into 3 meta-tools:
search,get_schema, andexecute. - The model searches for required tools and inspects parameter schemas.
- The model sends a JavaScript script containing the complete pipeline to the
executetool. - NitroStack evaluates the script inside an isolated WebAssembly sandbox in a worker thread pool, executing tool calls locally and returning only the final computed summary.
What's Included
- Data Controller: High-frequency micro-tools (
data_filter_records,data_aggregate_sum,data_transform_format). - Inventory Controller: Stock verification and inventory summaries.
- Finance Controller: Ledger auditing and financial summaries.
- Support Controller: System health and diagnostic status.
- QuickJS WASM Engine: Isolated guest runtime compiled to WebAssembly via Emscripten.
- Worker Thread Pool: Pre-warmed Node.js worker pool for concurrent script execution.
- Batch Orchestration Script: Complete runnable example located at
src/scripts/sample-batch.js.
Quick Start
Create Project
# Using the preset alias:
npx @nitrostack/cli init code-orchestrator --preset code-mode
# Or using full template name:
npx @nitrostack/cli init code-orchestrator --template typescript-code-mode
cd code-orchestrator
npm run dev
Project Structure
code-orchestrator/
├── src/
│ ├── controllers/
│ │ ├── data.controller.ts # Data processing micro-tools
│ │ ├── finance.controller.ts # Financial auditing tools
│ │ ├── inventory.controller.ts # Stock management tools
│ │ └── support.controller.ts # System diagnostics
│ ├── scripts/
│ │ └── sample-batch.js # Sample guest sandbox script
│ ├── app.module.ts # @McpApp with CodeModeTransform
│ └── index.ts # Bootstrap entry point
├── tsconfig.json
└── package.json
Architecture & Sandboxed Worker Pool
In src/app.module.ts, CodeModeTransform is configured with strict execution boundaries:
// src/app.module.ts
import {
McpApp,
Module,
CodeModeTransform,
DEFAULT_CODE_MODE_SEARCH_DESCRIPTION,
} from '@nitrostack/core';
import { DataController } from './controllers/data.controller.js';
import { InventoryController } from './controllers/inventory.controller.js';
import { FinanceController } from './controllers/finance.controller.js';
import { SupportController } from './controllers/support.controller.js';
@McpApp({
module: AppModule,
server: {
name: 'code-mode-service',
version: '1.0.0',
},
transforms: [
new CodeModeTransform({
workerPoolSize: 4, // Dedicated worker thread pool
memoryLimitMb: 128, // 128MB memory cap per script
timeoutMs: 15000, // 15-second execution timeout
maxToolCalls: 50, // Maximum 50 tool invocations per script
allowDestructive: false, // Block tools marked destructiveHint: true
searchToolDescription: DEFAULT_CODE_MODE_SEARCH_DESCRIPTION,
alwaysVisible: [
'finance_get_financial_summary',
'finance_audit_ledger',
'inventory_check_stock',
'inventory_report',
'support_get_system_status',
'data_aggregate_sum',
],
}),
],
})
@Module({
name: 'app',
description: 'Code Mode service with QuickJS WebAssembly sandboxing',
controllers: [DataController, InventoryController, FinanceController, SupportController],
})
export class AppModule {}
The 3 Synthetic Meta-Tools
When connecting to the server, the AI model interacts with 3 primary tools:
search: Queries the tool catalog by keywords or task descriptions to discover tool names and descriptions.get_schema: Takes an array of tool names and returns full Zod parameter schemas, input types, and required fields.execute: Takes{ script: string }and runs the script inside the QuickJS sandbox, exposingcallTool(name, args).
Multi-Step Script Execution Walkthrough
The template includes a reference batch script (src/scripts/sample-batch.js) illustrating how the model coordinates micro-tools locally:
// src/scripts/sample-batch.js
async function main() {
console.log('Starting data pipeline execution...');
// Step 1: Filter raw records
const rawValues = [12, 45, 68, 89, 23, 91, 105, 34];
const filterRes = await callTool('data_filter_records', {
values: rawValues,
min: 50,
});
console.log('Filtered values:', filterRes.filtered);
// Step 2: Calculate aggregate metrics
const sumRes = await callTool('data_aggregate_sum', {
values: filterRes.filtered,
});
console.log('Aggregated metrics:', sumRes);
// Step 3: Format output records
const formatRes = await callTool('data_transform_format', {
prefix: 'METRIC',
values: filterRes.filtered,
});
return {
rawCount: rawValues.length,
filteredCount: filterRes.filtered.length,
totalSum: sumRes.sum,
average: sumRes.avg,
records: formatRes.formatted,
};
}
// Sandbox executes this script and captures the return value
return await main();
Execution Flow
Client (LLM) NitroStack Server (CodeMode)
│ │
│─── 1. execute({ script: "..." }) ─────▶│
│ │ Dispatches to Worker Thread
│ │ Initializing QuickJS WASM
│ │
│ │ Script runs locally:
│ │ callTool('data_filter_records')
│ │ callTool('data_aggregate_sum')
│ │ callTool('data_transform_format')
│ │
│◀── 2. Returns final result object ─────│
│ { rawCount: 8, totalSum: 353 } │
Instead of 6 HTTP round-trips transferring intermediate JSON arrays across the network, the entire pipeline executes atomically in under 20 milliseconds.
Sandboxing & Security Caps
The Code Mode runtime enforces multiple layers of isolation:
- WASM Sandboxing: QuickJS runs compiled to WebAssembly. The guest script has zero access to Node.js globals (
process,require,fs,net,child_process). - Memory Hard Cap: If guest script allocations exceed
memoryLimitMb(default: 128MB), the worker terminates and returns an out-of-memory error. - Execution Timeout: If a script enters an infinite loop, the worker thread is terminated after
timeoutMs(default: 15 seconds). - Tool Call Cap: Prevents recursive tool calling loops by capping calls at
maxToolCalls(default: 50). - Destructive Guard: With
allowDestructive: false, any attempt to call tools annotated withdestructiveHint: truethrows a security violation error.