Code Mode
Code Mode is an alternative operating mode for Weavz MCP servers that replaces individual tool definitions with three meta-tools. Instead of exposing every action as a separate MCP tool (which can consume thousands of context tokens), Code Mode gives AI agents a search-read-execute workflow that reduces context usage by 80 to 98 percent.
This is especially valuable when an MCP server exposes many pieces. A server with 10 pieces in TOOLS mode might have 80+ tools, each with a full JSON Schema. In CODE mode, the same server has exactly 3 tools regardless of how many pieces are configured.
The Three Meta-Tools
1. weavz_search
Searches across all available pieces, actions, and triggers. The agent uses this to discover what capabilities are available. Results are compact — just names, descriptions, and piece info, without full parameter schemas.
Input:
query(string, required) — Natural language search term
Output: A list of matching actions and triggers with:
- Piece name and display name
- Action/trigger name and description
- Whether it requires authentication
// Agent: "I need to send notifications"
weavz_search({ query: "send notification message" })
// Result:
// - slack / send_message: Send a message to a Slack channel
// - discord / send_message: Send a message to a Discord channel
// - email / send_email: Send an email via SMTP
// - slack / send_direct_message: Send a DM to a user2. weavz_read_api
Retrieves the full TypeScript type declaration for a specific action or trigger. This gives the agent the complete parameter schema it needs to construct a valid call.
Input:
pieceName(string, required) — The piece to read fromactionNameortriggerName(string, required) — Which action or trigger to read
Output: A TypeScript declaration including:
- Input interface with all properties, types, and descriptions
- Which properties are required vs. optional
- Enum values for static dropdowns
- Annotations for dynamic dropdowns (with
$optionsreferences) - Output interface describing the response shape
weavz_read_api({ pieceName: "slack", actionName: "send_message" })
// Result (TypeScript declaration):
// interface SendMessageInput {
// /** Channel to send the message to */
// channel: string // $options: weavz.$options.slack.channels()
// /** Message text (supports Slack markdown) */
// text: string
// /** Thread timestamp to reply to */
// thread_ts?: string
// /** Send as bot or as user */
// as_user?: boolean
// }
//
// interface SendMessageOutput {
// ok: boolean
// channel: string
// ts: string
// message: { text: string; type: string }
// }3. weavz_execute
Executes a JavaScript code snippet in a sandboxed environment. The code has access to a global weavz object that provides typed methods for every available action and utility functions for dropdown discovery and persistent storage.
Input:
code(string, required) — JavaScript code to execute
Available globals:
weavz.{pieceName}.{actionName}(input)— Execute an actionweavz.$options.{pieceName}.{propertyName}(deps?)— Fetch dropdown optionsweavz.$storage.read(path)— Read from persistent storageweavz.$storage.write(path, data)— Write to persistent storageweavz.$storage.remove(path)— Delete from persistent storage
TypeScript Declaration Generation
Weavz automatically generates TypeScript declarations for all available actions at server startup. These declarations are what weavz_read_api returns, and they serve as the “API documentation” that AI agents use to understand how to call each action.
The declaration generator handles:
- Property types: Maps piece property types (SHORT_TEXT, LONG_TEXT, NUMBER, CHECKBOX, DROPDOWN, STATIC_DROPDOWN, ARRAY, OBJECT, DYNAMIC) to TypeScript types
- Required vs. optional: Properties marked as required in the piece schema become required in the TypeScript interface
- Static dropdowns: Converted to TypeScript union types with all valid values
- Dynamic dropdowns: Annotated with
$optionscomments showing the agent how to discover valid values - Nested objects: Recursively generates sub-interfaces
Sandbox Execution
Code submitted through weavz_execute runs in a sandboxed environment to ensure security. Weavz uses a two-tier sandbox strategy:
Cloudflare Sandbox (Primary)
When running on Cloudflare Workers, code executes in dedicated Cloudflare Sandbox containers. These are isolated JavaScript runtimes with:
- Full JavaScript/Node.js API surface
- Network access (for HTTP requests within the code)
- Filesystem access (within the container)
- Persistent storage via R2
- Resource limits (CPU time, memory)
The container communicates with the main Weavz API through a callback mechanism: when code calls weavz.slack.send_message(...), the container makes an HTTP request back to the API with a one-time token. The API executes the actual action using the stored connection credentials and returns the result to the container.
QuickJS WASM (Fallback)
For Node.js deployments or when Cloudflare Sandbox is unavailable, code executes in a QuickJS WebAssembly sandbox. QuickJS is a lightweight JavaScript engine compiled to WASM, running entirely in-process:
- Fast startup (no container spin-up)
- Zero infrastructure requirements
- Restricted globals (no filesystem, no network)
- Synchronous execution model with deferred promise bridging for async operations
Both sandboxes expose the identical weavz.* API surface, so code written for one sandbox works in the other without changes.
Persistent Storage
Code Mode provides a persistent key-value storage API via weavz.$storage. This allows agents to store and retrieve data across executions — useful for maintaining state, caching API responses, or building multi-step workflows.
// Store data
await weavz.$storage.write("last-sync", {
timestamp: Date.now(),
cursor: "abc123"
});
// Read data
const state = await weavz.$storage.read("last-sync");
if (state) {
console.log("Last sync:", state.timestamp);
}
// Delete data
await weavz.$storage.remove("last-sync");Storage is scoped per organization and MCP server. Data stored by one server is not accessible to other servers, even within the same organization. Under the hood, storage is backed by R2 (Cloudflare Workers) or S3/MinIO (Node.js), with paths following the pattern sandbox/{orgId}/{serverId}/{path}.
Dropdown Discovery
Many actions have dropdown properties whose valid values come from the third-party API (e.g. Slack channels, GitHub repositories). In Code Mode, agents discover these values using weavz.$options:
// List available Slack channels
const channels = await weavz.$options.slack.channels();
// [{ label: "#general", value: "C01ABC" }, ...]
// Dependent dropdowns: pass parent values
const sheets = await weavz.$options.google_sheets.sheets({
spreadsheetId: "abc123"
});The TypeScript declarations returned by weavz_read_api include $options annotations on dropdown properties, so the agent knows which options to call and what dependencies are required.
Complete Example Workflow
Here is how an AI agent typically uses Code Mode to accomplish a task like “post a summary of recent GitHub issues to Slack”:
Step 1: Search for Capabilities
weavz_search({ query: "github issues list" })
// Finds: github / list_issues
weavz_search({ query: "slack send message" })
// Finds: slack / send_messageStep 2: Read the APIs
weavz_read_api({ pieceName: "github", actionName: "list_issues" })
// Returns TypeScript declaration with repo, state, labels, per_page params
weavz_read_api({ pieceName: "slack", actionName: "send_message" })
// Returns TypeScript declaration with channel, text, thread_ts paramsStep 3: Execute the Composed Logic
weavz_execute({
code: `
// Fetch recent open issues
const issues = await weavz.github.list_issues({
repo: "my-org/my-repo",
state: "open",
per_page: 10
});
// Build a summary
const summary = issues.map(i =>
\`- #\${i.number}: \${i.title} (\${i.labels.map(l => l.name).join(", ")})\`
).join("\n");
// Post to Slack
await weavz.slack.send_message({
channel: "#dev-updates",
text: \`*Recent Open Issues (last 10):*\n\${summary}\`
});
return { issueCount: issues.length };
`
})Notice that the agent accomplished a multi-service integration in a single weavz_execute call, without needing to make separate MCP tool calls for each API operation. This is one of Code Mode's key advantages: the agent can write arbitrary composition logic.
Context Reduction Analysis
To illustrate the context savings:
| Scenario | TOOLS Mode Tokens | CODE Mode Tokens | Reduction |
|---|---|---|---|
| 3 pieces, 15 actions | ~8,000 | ~800 | 90% |
| 10 pieces, 60 actions | ~32,000 | ~800 | 97.5% |
| 20 pieces, 120+ actions | ~65,000 | ~800 | 98.8% |
The token count in CODE mode stays roughly constant because it always exposes exactly 3 tools. The agent loads additional context on-demand via weavz_read_api, but only for the specific actions it needs.
Security Model
Code Mode is designed with defense in depth:
- Sandboxed execution: Code runs in an isolated environment with no access to the host process, environment variables, or other tenants' data.
- One-time callback tokens: Each execution generates a unique callback token that expires after use or after 5 minutes. The sandbox cannot reuse tokens or forge new ones.
- Scoped access: The sandbox can only invoke actions for pieces configured on the MCP server. It cannot access other servers, other organizations, or administrative APIs.
- Resource limits: Execution time and memory are bounded to prevent runaway code.
- Storage isolation: Persistent storage is scoped per org and server. Cross-tenant access is not possible.
When to Use Code Mode
Code Mode is the recommended default for most production MCP servers. Use TOOLS mode only when you have a small number of pieces (1–3) and want maximum simplicity.
| Consideration | TOOLS | CODE |
|---|---|---|
| Number of pieces | 1–3 | Any |
| Context efficiency | Low | High |
| Multi-action composition | Multiple tool calls | Single execute call |
| Setup complexity | None | Sandbox required |
| Persistent state | Not available | weavz.$storage |
Related
- MCP Servers — Overview of both TOOLS and CODE modes
- Connections — How credentials are resolved for action execution in the sandbox