MCP Code Execution: A New Paradigm for Building High‑Efficiency Agents (98.7% Token Savings)

The article analyzes how loading thousands of tool definitions overwhelms an agent's context window, and demonstrates that letting the agent generate code to call MCP tools reduces token consumption from 150,000 to 2,000 (a 98.7% improvement) while also improving privacy, state persistence, and control‑flow flexibility.

Xiaolong Cloud Tech Team
Xiaolong Cloud Tech Team
Xiaolong Cloud Tech Team
MCP Code Execution: A New Paradigm for Building High‑Efficiency Agents (98.7% Token Savings)

Why Direct Tool Calls Exhaust Tokens

When an AI agent is connected to thousands of tools, loading every tool definition into the model’s context can require hundreds of thousands of tokens, causing latency and cost spikes. Anthropic observed token usage of up to 150 k for a single request and proposed a simpler solution: let the agent write code that calls the tools, cutting token consumption to about 2 k (98.7% reduction). This idea underlies Claude Code’s Skills feature and Cloudflare’s “Code Mode”.

Model Context Protocol (MCP) Overview

MCP is an open standard that unifies how agents interact with external systems. Previously, each tool required custom integration, leading to fragmented, repetitive code and poor scalability. By implementing MCP once, developers can access an entire ecosystem of tools via a single protocol. Since its launch in November 2024, thousands of MCP servers and SDKs for major programming languages have been released.

Two Main Sources of Token Bloat

Tool definitions occupy large portions of the context window.

Intermediate tool results are re‑injected into the model, inflating token usage.

Example tool definitions:

gdrive.getDocument
    Description: Retrieves a document from Google Drive
    Parameters:
        documentId (required, string): The ID of the document to retrieve
        fields (optional, string): Specific fields to return
    Returns: Document object with title, body content, metadata, permissions, etc.

salesforce.updateRecord
    Description: Updates a record in Salesforce
    Parameters:
        objectType (required, string): Type of Salesforce object (Lead, Contact, Account, etc.)
        recordId (required, string): The ID of the record to update
        data (required, object): Fields to update with their new values
    Returns: Updated record object with confirmation

When an agent calls these tools directly, the full transcript of a two‑hour sales meeting must be passed twice, adding roughly 50 k tokens and increasing the chance of errors.

Code Execution as a Solution

Instead of direct calls, the agent treats MCP servers as code APIs. The server’s tool set is generated as a file tree, and the agent imports only the files it needs.

servers
├── google-drive
│   ├── getDocument.ts
│   ├── ... (other tools)
│   └── index.ts
├── salesforce
│   ├── updateRecord.ts
│   ├── ... (other tools)
│   └── index.ts
└── ... (other servers)

Each tool file contains a thin wrapper around callMCPTool. Example ( ./servers/google-drive/getDocument.ts):

import { callMCPTool } from "../../../client.js";

interface GetDocumentInput {
    documentId: string;
}

interface GetDocumentResponse {
    content: string;
}

export async function getDocument(input: GetDocumentInput): Promise<GetDocumentResponse> {
    return callMCPTool<GetDocumentResponse>('google_drive__get_document', input);
}

The original Google‑Drive‑to‑Salesforce scenario becomes:

// Read transcript from Google Docs and add to Salesforce prospect
import * as gdrive from './servers/google-drive';
import * as salesforce from './servers/salesforce';

const transcript = (await gdrive.getDocument({ documentId: 'abc123' })).content;
await salesforce.updateRecord({
    objectType: 'SalesMeeting',
    recordId: '00Q5f000001abcXYZ',
    data: { Notes: transcript }
});

Progressive Disclosure

The agent can explore the ./servers/ directory, list available servers (e.g., google-drive, salesforce), and read only the needed tool files, reducing token usage from 150 k to 2 k.

Context‑Efficient Tool Results

For large datasets, the agent can filter data in the execution environment before returning anything to the model. Example filtering a 10,000‑row sheet to only pending orders:

// Without code execution – all rows flow through context
TOOL CALL: gdrive.getSheet(sheetId: 'abc123') → returns 10,000 rows in context to filter manually

// With code execution – filter in the execution environment
const allRows = await gdrive.getSheet({ sheetId: 'abc123' });
const pendingOrders = allRows.filter(row => row["Status"] === 'pending');
console.log(`Found ${pendingOrders.length} pending orders`);
console.log(pendingOrders.slice(0, 5)); // Only log first 5 rows

Only five rows are sent to the model, avoiding context blow‑up.

More Powerful Control Flow

Loops, conditionals, and error handling can be expressed in familiar programming constructs. Example of a while‑loop that polls Slack until a deployment message appears:

let found = false;
while (!found) {
    const messages = await slack.getChannelHistory({ channel: 'C123456' });
    found = messages.some(m => m.text.includes('deployment complete'));
    if (!found) await new Promise(r => setTimeout(r, 5000));
}
console.log('Deployment notification received');

Privacy‑Preserving Operations

Intermediate results stay in the execution environment, so sensitive data never reaches the model. For tasks that involve PII, the controller can tokenize data before returning it. Example of importing contacts while masking email and phone:

const sheet = await gdrive.getSheet({ sheetId: 'abc123' });
for (const row of sheet.rows) {
    await salesforce.updateRecord({
        objectType: 'Lead',
        recordId: row.salesforceId,
        data: {
            Email: row.email,   // tokenized or masked
            Phone: row.phone,   // tokenized or masked
            Name: row.name
        }
    });
}
console.log(`Updated ${sheet.rows.length} leads`);

The MCP client can later de‑tokenize the data when it is passed to another tool, ensuring PII never appears in the LLM context.

State Persistence and Skills

Code execution gives the agent file‑system access, allowing it to write intermediate results and resume later. Example of saving a CSV of leads and reading it back:

const leads = await salesforce.query({ query: 'SELECT Id, Email FROM Lead LIMIT 1000' });
const csvData = leads.map(l => `${l.Id},${l.Email}`).join('
');
await fs.writeFile('./workspace/leads.csv', csvData);
// Later…
const saved = await fs.readFile('./workspace/leads.csv', 'utf-8');

Saved functions can be packaged as reusable “skills”, enabling the model to call them across different tasks.

Trade‑offs

Running generated code requires a sandboxed environment with resource limits, monitoring, and security controls. These operational costs must be weighed against the token savings, latency reduction, and richer tool composition that code execution provides.

Conclusion

MCP supplies a universal protocol for agents to connect to diverse tools, but token consumption grows sharply with many tools. By executing code on the MCP server, agents can load only the necessary definitions, filter results before they reach the model, protect privacy, and persist state. The approach brings mature software‑engineering patterns to agent development, offering substantial efficiency gains while introducing additional operational considerations.

MCP client interaction diagram
MCP client interaction diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AI AgentsMCPprivacy protectioncontext managementcode executionstate persistencetoken optimization
Xiaolong Cloud Tech Team
Written by

Xiaolong Cloud Tech Team

Xiaolong Cloud Tech Team

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.