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.

If the user is connecting Weavz directly from Claude, ChatGPT, Codex, Cursor, or another remote MCP client, start with the Weavz MCP App. It provisions a Code Mode connector server after the user signs in and chooses a workspace.

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 aliases, apps, and actions by keyword. Results include compact parameter signatures, hidden/enforced key names, and safe destination stubs when applicable
weavz_read_apiGet detailed TypeScript declarations for one or more aliases, with hidden/defaulted inputs omitted and optional action filtering
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, purpose-readable aliases because those aliases become the names agents call, such as weavz.office_slack or weavz.customer_gmail.

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_550e8400-e29b-41d4-a716-446655440000

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_550e8400-e29b-41d4-a716-446655440000",
      "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/550e8400-e29b-41d4-a716-446655440000/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.

Bearer-token scopes default to ["mcp:tools", "mcp:code"] for CODE servers. expiresIn defaults to 30 days and can be set from 5 minutes to 90 days. See Create MCP bearer token.

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: "file download" })
 
Returns:
Code Mode guidance:
- Call `weavz_search` with no args or `{ query: "..." }`; use `weavz_execute` for JavaScript code.
- Read multiple APIs in one `weavz_read_api({ aliases: [...] })` call when a task needs several aliases.
- Compose internal fetch, transform, model, storage, and KV work into one `weavz_execute` call when sensible.
- Split or expect approval for externally visible side effects such as Slack sends.
 
## Storage (files)
Alias: `files` | Namespace: `weavz.files` | App: Storage (`storage`)
 
- `get_download_url({ path: string, expiresInSeconds?: number })` — Create a short-lived download URL for a stored file.

Use weavz_read_api when the action has nested input, dynamic options, or when you need precise return types and field descriptions. If a task needs several aliases, read them in one call with aliases: [...] instead of calling weavz_read_api repeatedly.

weavz_read_api

Read TypeScript declarations for an alias's actions:

text
Agent calls: weavz_read_api({ alias: "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 }
      >;
    }
  }

For multi-integration planning, batch the metadata read:

text
Agent calls: weavz_read_api({ aliases: ["web", "deepseek", "files", "state"] })

For focused work, ask only for the actions you plan to call:

text
Agent calls: weavz_read_api({ alias: "files", actions: ["write_file", "get_download_url"] })

Declarations include concrete return types when an action has a declared return contract. Broad third-party API passthrough actions may intentionally return unknown. Use detail: "signatures" when the agent only needs parameter names and return shapes.

For structured model extraction, prefer JSON-specific actions when they are available. OpenAI, DeepSeek, and AI Toolkit expose ask_json, which returns a parsed json value plus rawText, producedBy, and parse metadata. This avoids agents hand-writing prompt-only JSON parsing and then guessing provider response shapes.

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.office_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.office_slack.list_channels({})
const issues = await weavz.support_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.office_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('office_slack', 'send_channel_message', 'channel')
// Returns: [{ label: '#general', value: 'C01ABCDEF' }, ...]
 
// Pass the alias as the first argument when the same app exists under multiple aliases
const customerChannels = await weavz.$options('customer_slack', 'send_channel_message', 'channel')
 
// Use the value in an action
await weavz.office_slack.send_channel_message({
  channel: channels[0].value,
  text: 'Hello!',
})

weavz.$options() takes the configured integration alias. For example, use weavz.$options('office_slack', ...) for the weavz.office_slack namespace.

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

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.support_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.office_slack.send_channel_message({
  channel: '#engineering',
  text: summary,
})
 
({ issueCount: issues.length, posted: true })

This runs as a single weavz_execute call — the agent wrote one script that orchestrates 3 integrations. Code Mode supports top-level await, top-level return, and final-expression capture, so agents can return compact metadata with either return value or a final expression. 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 and each run can execute for up to 5 minutes. 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 structuredContent.view: "approval_required", a formatted approval link when the policy allows end-user links, 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.