eavz

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 dramatically reduce context usage. Instead of exposing dozens of separate tools, CODE mode gives AI agents a search → read → execute workflow that uses 80–98% fewer tokens.

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:

  • 80–98% fewer tokens consumed per request
  • 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
weavz_read_apiGet detailed TypeScript declarations for an integration's actions
weavz_executeExecute JavaScript code in a sandboxed 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

Save and copy credentials

Click Create. Copy the bearer token and SSE endpoint.

Add Integrations

Register integrations on the server. In CODE mode, each integration's actions become available under the weavz.* namespace.

1

Open your MCP server

Go to MCP Servers and click on the server you created.

2

Add integrations

Click Add Tool. Select integrations and choose which actions to include.

3

Set connections

Assign a connection for each integration to handle authentication.

Connect an AI Client

Connect to a CODE mode server the same way as TOOLS mode — the AI client will see 3 tools instead of dozens.

Add to your Claude Desktop config (claude_desktop_config.json):

json
{
  "mcpServers": {
    "weavz": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://api.weavz.io/api/v1/mcp/servers/mcp_abc123/sse",
        "--header",
        "Authorization:Bearer mcp_token_xyz..."
      ]
    }
  }
}

How Code Mode Works

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

Search for available integrations and actions by keyword:

text
Agent calls: weavz_search({ query: "send slack message" })
 
Returns:
- slack.send_channel_message — Send a message to a Slack channel
- slack.send_direct_message — Send a direct message to a user

weavz_read_api

Read the TypeScript declarations for an integration's actions:

text
Agent calls: weavz_read_api({ integration: "slack" })
 
Returns:
  declare namespace weavz {
    namespace slack {
      function send_channel_message(input: {
        channel: string;
        text: string;
      }): Promise<{ ok: boolean; ts: string }>;
    }
  }

weavz_execute

Execute JavaScript code in a sandboxed 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!',
})
 
// 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).

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 structured output including a trace of every integration action called:

json
{
  "result": { "issueCount": 12, "posted": true },
  "logs": ["Fetched 12 issues", "Read 10 metric rows"],
  "actionsExecuted": [
    { "integration": "github", "action": "list_issues", "duration": 340, "success": true },
    { "integration": "google_sheets", "action": "read_sheet", "duration": 180, "success": true },
    { "integration": "slack", "action": "send_channel_message", "duration": 95, "success": true }
  ],
  "duration": 650
}

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

Context Reduction

The context savings compared to TOOLS mode are dramatic:

ScenarioTOOLS ModeCODE ModeSavings
10 integrations, 50 actions~25,000 tokens~500 tokens98%
5 integrations, 20 actions~10,000 tokens~500 tokens95%
3 integrations, 10 actions~5,000 tokens~500 tokens90%

CODE mode always uses roughly the same ~500 tokens for the 3 meta-tools, regardless of how many integrations are registered.

When to Use CODE vs TOOLS Mode

FactorTOOLS ModeCODE Mode
Number of actionsFew (< 10)Many (10+)
Context window usageHigherMinimal (~500 tokens)
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

You can scope a CODE mode server to a specific end user by passing endUserId when creating the server. The server resolves connections belonging to that end user, so all weavz.* calls use their connected accounts.

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": "proj_abc123",
    "endUserId": "user_123",
    "mode": "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.