MCP Code Mode

Set up MCP servers in CODE mode for context-efficient AI agent usage with 3 meta-tools.

CODE mode replaces individual tools with 3 meta-tools that keep the initial context small. Instead of exposing dozens of separate tools, CODE mode gives AI agents a search → read → execute workflow that loads API details on demand.

This is the recommended starting point for broad agent workspaces. Agents do not preload hundreds of schemas; they discover the right integration, inspect typed declarations only when needed, and execute multi-step workflows in one call.

Why Code Mode?

Traditional MCP servers expose every integration action as a separate tool. With 10 integrations and 50 actions, that's 50 tools competing for the AI agent's context window — most of which won't be used in any given request.

Code Mode flips this: instead of listing tools, it gives the agent a programming environment. The agent discovers what's available on demand, reads typed APIs, then writes code to accomplish its goal — often calling multiple integrations in a single execution.

The result:

  • A smaller initial tool surface for broad agent workspaces
  • Multi-step workflows in a single call (read from Sheets → process → post to Slack)
  • Type-safe — TypeScript declarations guide the agent to correct usage
  • Observable — every integration call is traced with duration and status

The Three Meta-Tools

ToolPurpose
weavz_searchDiscover available integrations and actions by keyword. Results include compact parameter signatures for quick one-off calls
weavz_read_apiGet detailed TypeScript declarations for an integration or alias, with hidden/defaulted inputs omitted
weavz_executeExecute JavaScript code in a managed execution environment using weavz.*

The AI agent follows a natural workflow:

  1. Search for the right integration and action
  2. Read the typed API to understand input parameters and return types
  3. Execute code that calls one or more actions — including multi-step compositions

Create a CODE Mode Server

1

Navigate to MCP Servers

Open the dashboard and go to MCP Servers in the sidebar.

2

Create a new server

Click Create MCP Server. Enter a name and optional description.

3

Select CODE mode

Choose CODE as the server mode.

4

Set approval wait behavior

Optionally set how long approval continuation calls should wait while a Human Gate is still pending. Leave it at 0 to return approval_pending immediately.

5

Save and copy the endpoint

Click Create. Copy the MCP endpoint. New servers use MCP OAuth by default, so OAuth-capable clients will ask the user to sign in through Weavz when they connect.

Add Integrations

Add integrations to the workspace first. Workspace integrations sync into MCP servers automatically, and in CODE mode their actions become available under the weavz.* namespace. Use stable aliases for repeated integrations or built-ins, because those aliases become the names agents call.

Manual MCP tool registration is still available when you need a small server-specific override, but the default path for agent workspaces is workspace integrations first. Built-in workspace integrations such as files, state, HTTP, data transformation, web reading, and managed code execution are especially useful because agents can use them without external account setup.

For a dedicated walkthrough, see Using Built-In Workspace Integrations.

1

Open your workspace

Go to the workspace attached to the MCP server.

2

Add workspace integrations

Open Integrations, add the integrations the agent should use, and set aliases, connection strategy, enabled actions, and any built-in persistence or sandbox settings.

3

Confirm MCP sync

Open the MCP server and confirm the workspace integrations are available. Utility and built-in integrations with no external authentication can be added without a connection.

Manual MCP tool registration is still available through POST /api/v1/mcp/servers/:id/tools when one server needs an override that should not affect the workspace. Use workspace integrations for the normal path so API calls, SDK calls, Playground, and MCP all share the same aliases, connection strategy, enabled actions, partials, and built-in settings.

Connect an AI Client

Connect to a CODE mode server the same way as TOOLS mode. OAuth-capable clients can connect with just the MCP endpoint; the AI client will see 3 tools instead of dozens.

In Claude, add a custom connector and paste the MCP endpoint:

text
https://api.weavz.io/mcp/srv_abc123def456

If your MCP client cannot run OAuth, create or update the server with authMode: "bearer" or authMode: "oauth_and_bearer" and pass the returned mcp_ token:

json
{
  "mcpServers": {
    "weavz": {
      "type": "http",
      "url": "https://api.weavz.io/mcp/srv_abc123def456",
      "headers": {
        "Authorization": "Bearer mcp_your_static_token"
      }
    }
  }
}

For provisioned clients, create a bearer-enabled server and issue one token per end user:

bash
curl -X POST https://api.weavz.io/api/v1/mcp/servers/abc123def456/access-tokens \
  -H "Authorization: Bearer wvz_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"endUserId": "user_123", "scopes": ["mcp:tools", "mcp:code"]}'

Use the returned bearerToken as the Authorization: Bearer mcp_... header. For CODE mode, omit mcp:code only if the token should not be allowed to call weavz_execute.

How Code Mode Works

Once connected, the AI agent uses the 3 meta-tools in sequence:

Search for available integrations and actions by keyword. Search results include compact callable signatures, so simple calls often do not need a separate API read:

text
Agent calls: weavz_search({ query: "hash" })
 
Returns:
## Hash & Encode (hash)
Integration: `hash-encode` | Alias: `hash`
 
- `hash({ text: string, algorithm?: "sha256" | "sha1", encoding?: "hex" | "base64" })` — Generate a cryptographic hash of text.

Use weavz_read_api when the action has nested input, dynamic options, or when you need precise return types and field descriptions.

weavz_read_api

Read the TypeScript declarations for an integration's actions:

text
Agent calls: weavz_read_api({ integration: "hash" })
 
Returns:
  declare namespace weavz {
    namespace hash {
      function generate_uuid(input: {
        count?: number;
      }): Promise<
        { success: true; uuid: string } |
        { success: true; uuids: string[]; count: number } |
        { success: false; error: string }
      >;
    }
  }

Declarations include concrete return types when an action has a declared return contract. Broad third-party API passthrough actions may intentionally return unknown.

weavz_execute

Execute JavaScript code in a managed execution environment. All registered integrations are available under the weavz namespace:

javascript
// Single action
const result = await weavz.slack.send_channel_message({
  channel: '#general',
  text: 'Hello from AI!',
})
 
// Connectionless utility action
const parsed = await weavz.datetime.parse_date({
  dateString: '2026-05-18',
})
 
// Multi-action composition
const channels = await weavz.slack.list_channels({})
const issues = await weavz.github.list_issues({ repo: 'my-org/my-repo' })
 
// Chain results between services
const sheet = await weavz.google_sheets.read_sheet({
  spreadsheetId: 'abc123',
  range: 'A1:B10',
})
for (const row of sheet.values) {
  await weavz.slack.send_channel_message({
    channel: '#updates',
    text: `Row: ${row.join(', ')}`,
  })
}

Some actions have dropdown fields (e.g. selecting a Slack channel by ID). Use weavz.$options to discover valid values inside weavz_execute:

javascript
// Get available Slack channels
const channels = await weavz.$options('slack', 'send_channel_message', 'channel')
// Returns: [{ label: '#general', value: 'C01ABCDEF' }, ...]
 
// Optional: pass alias when the same action exists under multiple aliases
const botChannels = await weavz.$options('slack', 'send_channel_message', 'channel', {}, 'slack_bot')
 
// Use the value in an action
await weavz.slack.send_channel_message({
  channel: channels[0].value,
  text: 'Hello!',
})

weavz.$options() takes the original integration name (with hyphens), not the underscore version used in the namespace. For example, use weavz.$options('google-sheets', ...) even though the namespace is weavz.google_sheets.

If an action is registered under multiple aliases on one server, pass the alias as the 5th argument: weavz.$options(integration, action, property, context?, alias).

Validation errors

Code Mode validates action inputs before execution. If the code passes an unknown key, omits a required key, or uses an invalid enum value, weavz_execute returns an actionable error in the tool result:

text
Invalid input for datetime.parse_date: unknown key "date"; missing required key "dateString". Expected: dateString, timezone.
text
Invalid input for hash.hash: invalid value "SHA-256" for "algorithm". Allowed: "sha256", "sha1".

Fix the input and retry the weavz_execute call. In MCP clients, these errors are returned as tool errors rather than generic server failures.

Real-World Example: Weekly Report Bot

An AI agent uses Code Mode to generate a weekly report from multiple sources:

javascript
// 1. Fetch open issues from GitHub
const issues = await weavz.github.list_issues({
  repo: 'acme/backend',
  state: 'open',
})
 
// 2. Get latest metrics from Google Sheets
const metrics = await weavz.google_sheets.read_sheet({
  spreadsheetId: 'abc123',
  range: 'Metrics!A1:D10',
})
 
// 3. Build a summary
const summary = [
  `Weekly Report — ${new Date().toLocaleDateString()}`,
  `\nOpen Issues: ${issues.length}`,
  `Critical: ${issues.filter(i => i.labels.includes('critical')).length}`,
  `\nKey Metrics:`,
  ...metrics.values.map(row => `  ${row[0]}: ${row[1]}`),
].join('\n')
 
// 4. Post to Slack
await weavz.slack.send_channel_message({
  channel: '#engineering',
  text: summary,
})
 
return { issueCount: issues.length, posted: true }

This runs as a single weavz_execute call — the agent wrote one script that orchestrates 3 integrations. In TOOLS mode, this would require at minimum 3 separate tool calls with the agent manually threading data between them.

Execution Tracing

Every weavz_execute call returns a readable result with console output and a trace of every integration action called:

md
## Result
```json
{
  "issueCount": 12,
  "posted": true
}
```
 
## Console Output
```
Fetched 12 issues
Read 10 metric rows
```
 
## Actions Executed
- github/list_issues: OK [340ms]
- google_sheets/read_sheet: OK [180ms]
- slack/send_channel_message: OK [95ms]
 
_Duration: 650ms_

This gives full observability into what happened — useful for debugging, auditing, and understanding agent behavior.

Context Usage

The context savings compared to TOOLS mode depend on the MCP client, model, enabled integrations, action schema size, and prompt context. These examples show why CODE mode is useful for broad workspaces:

ScenarioTOOLS ModeCODE ModeSavings
10 integrations, 50 actionsLarge schema load3 meta-tools firstHigh
5 integrations, 20 actionsMedium schema load3 meta-tools firstHigh
3 integrations, 10 actionsSmaller schema load3 meta-tools firstModerate

CODE mode keeps the initial tool surface to the 3 meta-tools and loads API details only when the agent asks for them.

weavz_search and weavz_read_api are metadata reads. weavz_execute consumes Code Mode execution usage when the run starts. Each successful weavz.* integration action inside that run counts as one action execution; helper probes such as weavz.$schema, weavz.$validate, and weavz.$options do not count as actions.

When to Use CODE vs TOOLS Mode

FactorTOOLS ModeCODE Mode
Number of actionsFew (< 10)Many (10+)
Context window usageHigherSmall initial surface
Multi-step workflowsOne action per callMultiple actions per call
Setup complexitySimplerRequires code execution
AI agent capabilityAny MCP clientNeeds code-capable agent

Choosing by scenario

  • Building a chatbot with a few integrations → TOOLS (simple, focused)
  • Building an AI assistant that handles 20+ services → CODE (context efficiency)
  • Multi-step data pipelines (fetch → transform → send) → CODE (compose in one call)
  • AI agent chaining results between APIsCODE (natural data flow)
  • Simple single-action tools (search, lookup) → TOOLS (lower overhead)

Use CODE mode when you have many integrations, token efficiency matters, or workflows require chaining multiple actions together.

Use TOOLS mode when you have a small, focused set of tools and simplicity is preferred. See the TOOLS mode guide.

End-User MCP Servers

For per-user integrations, use MCP OAuth when the client can complete sign-in. For provisioned clients that cannot run OAuth, create a bearer-enabled server and issue one mcp_ bearer token per end user. Both paths keep the server attached to the workspace and resolve weavz.* calls to a specific end user's connections.

bash
curl -X POST https://api.weavz.io/api/v1/mcp/servers \
  -H "Authorization: Bearer wvz_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "User Code Agent",
    "workspaceId": "550e8400-e29b-41d4-a716-446655440000",
    "mode": "CODE",
    "authMode": "oauth_and_bearer",
    "endUserAccess": "restricted"
  }'
 
curl -X POST https://api.weavz.io/api/v1/mcp/servers/{serverId}/access-tokens \
  -H "Authorization: Bearer wvz_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"endUserId": "user_123", "scopes": ["mcp:tools", "mcp:code"]}'

When a weavz_execute call fails because the end user hasn't connected the required integration, the error includes a setup URL. Share this URL with the end user — they open it, connect their account, and the agent can retry.

If a Human Gates policy matches a Code Mode run, the MCP result includes an authenticated approval URL and an approvalId instead of executing the code. Approve it from the Weavz review view or the approvals API, then call weavz_execute with only the approval ID:

json
{ "approvalId": "apr_..." }

Do not resend the original code. Weavz resumes the stored batch once, applies the approval across the action sequence inside that exact run, and returns the cached result if the agent asks again. If the MCP server tools changed after the review, the continuation is rejected so the reviewer can approve the current tool surface.

For Code Mode servers, settings.codeMode.approvalWaitSeconds can keep an approvalId continuation call open briefly while the Human Gate is still pending. This is useful when an agent calls back before the reviewer has clicked approve. If the wait expires, Weavz returns approval_pending and the agent should call weavz_execute with the same approvalId again after approval. See Human Gates.