agentleFS
Archive228Archive228/lab-skills/skills/mcp-code-execution/SKILL.md

mcp-code-execution

Skill8 starsChanged 3 months agoMITView on GitHub

Cut agent token consumption by calling MCP servers through generated code instead of direct tool invocations: present tools as typed wrapper files on a filesystem, discover them progressively, and keep intermediate data in the execution environment (Anthropic measured 150,000 → 2,000 tokens, a 98.7% saving). Trigger when an agent connects to many MCP servers/tools, when tool definitions eat a large share of the context window before work starts, when workflows pipe large intermediate results (transcripts, spreadsheets) between tools, or when sensitive data should not enter model context.

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do NOT use when:

    line 25
  2. Very specific:

    Persist state to files so work can resume: Write intermediate results to the workspace (e.g., ./workspace/leads.csv) and pick up where a …

    line 76

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

MCP via Code Execution — Cut Agent Token Consumption

This skill gives you an operating procedure for replacing direct MCP tool invocations with agent-generated code that calls MCP servers as code APIs. Direct tool calling has two token sinks: every tool definition is loaded into context up front, and every intermediate result flows through the model. Presenting MCP tools as files on a filesystem and writing code against them fixes both. On Anthropic's reference workflow (Google Drive → Salesforce), this cut token usage from 150,000 to 2,000 tokens — a 98.7% saving.

When to use

Switch to code execution with MCP when any of these hold:

  • The agent has access to many tools — developers routinely wire agents into dozens of MCP servers exposing hundreds or thousands of tools. At that scale, definitions alone can consume hundreds of thousands of tokens before the agent reads the request.
  • A workflow chains tools so one tool's output becomes another's input. With direct calls the full payload flows through the model twice (e.g., a 2-hour sales-meeting transcript ≈ an extra 50,000 tokens just to copy it from gdrive.getDocument into salesforce.updateRecord).
  • Tool results are large and mostly irrelevant (10,000-row spreadsheets, long channel histories) and you only need a filtered slice.
  • The workflow needs loops, conditionals, retries, or polling — chaining individual tool calls for these burns tokens and adds latency per round trip.
  • Sensitive data (emails, phones, names) must move between systems without entering model context.

Do NOT use when:

  • You cannot provide a secure execution environment. Running agent-generated code requires sandboxing, resource limits, and monitoring — no sandbox, no code execution.
  • The infrastructure cost outweighs the gain. The source is explicit: code execution "introduces its own complexity"; weigh token/latency savings against implementation cost before adopting.

Rules

  1. Diagnose the two overheads first. (a) Tool definitions loaded up front — with enough MCP servers connected, the agent processes hundreds of thousands of tokens before doing anything. (b) Intermediate results passing through context — each chained call routes the full payload through the model again. If neither applies, direct tool calls are not the bottleneck.
  2. Present each MCP tool as a file in a servers/ tree, one directory per server, one file per tool (e.g., ./servers/google-drive/getDocument.ts, ./servers/salesforce/updateRecord.ts, plus an index.ts per server). Each file exports a typed async function that wraps the MCP call:

    // ./servers/google-drive/getDocument.ts
    import { callMCPTool } from "../../../client.js";
    
    interface GetDocumentInput { documentId: string; }
    interface GetDocumentResponse { content: string; }
    
    /* Read a document from Google Drive */
    export async function getDocument(input: GetDocumentInput): Promise<GetDocumentResponse> {
      return callMCPTool<GetDocumentResponse>('google_drive__get_document', input);
    }
  3. Discover tools progressively, never all at once. "Models are great at navigating filesystems" (Anthropic). List ./servers/ to find available servers, then read only the tool files the current task needs. Alternatively expose a search_tools function with a detail-level parameter — name only; name and description; or full definition with schemas — and load the heavier levels on demand.
  4. Keep intermediate results inside the execution environment. Chain tools in code so payloads move variable-to-variable, not through context:

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

    This is the pattern behind the 150,000 → 2,000 token reduction.

  5. Filter and aggregate before anything reaches the model. Fetching a 10,000-row sheet? Filter in code, log the count, and print only the first 5 rows for review — not the dataset:

    const allRows = await gdrive.getSheet({ sheetId: 'abc123' });
    const pendingOrders = allRows.filter(row => row["Status"] === 'pending');
    console.log(`Found ${pendingOrders.length} pending orders`);
  6. Write control flow as code, not as chained tool calls. Loops, conditionals, and error handling belong in the script — e.g., a while loop polling Slack channel history until a "deployment complete" message appears. This saves tokens per iteration and cuts latency (fewer time-to-first-token round trips).
  7. Use the execution layer for privacy. Intermediate results stay in the sandbox by default. For PII workflows, have the MCP client tokenize sensitive fields before they reach the model ([EMAIL_1], [PHONE_1]) and untokenize them when passing to other MCP tools — real values flow between services without ever entering model context.
  8. Persist state to files so work can resume. Write intermediate results to the workspace (e.g., ./workspace/leads.csv) and pick up where a previous run stopped instead of re-fetching.
  9. Promote proven code into skills. Save working functions in ./skills/ (e.g., ./skills/save-sheet-as-csv.ts) and reuse them. Adding a SKILL.md file to saved functions creates a structured skill the model can reference — capabilities compound across tasks.
  10. Sandbox is non-negotiable. Agent-generated code demands a secure execution environment with appropriate sandboxing, resource limits, and monitoring. Budget for this operational overhead when deciding whether the pattern pays off.

Checklist

  • Confirmed the bottleneck: tool definitions and/or intermediate results dominate token spend
  • Secure sandbox available (isolation, resource limits, monitoring) — otherwise stop, keep direct calls
  • MCP tools generated as typed wrapper files under ./servers/<server>/<tool>.ts wrapping callMCPTool
  • Agent discovers tools by listing ./servers/ or via search_tools with detail levels — no upfront bulk load
  • Chained tool outputs passed variable-to-variable in code, never round-tripped through context
  • Large results filtered/aggregated in code; only counts and small samples (e.g., first 5 rows) logged
  • Loops/polling/retries implemented in the script, not as repeated tool invocations
  • PII tokenized by the MCP client before reaching the model; untokenized only when handed to other MCP tools
  • Intermediate state written to ./workspace/ files for resumability
  • Reusable functions saved to ./skills/, with SKILL.md for structured reuse

Anti-patterns

  • Loading every tool definition up front. With thousands of tools this costs hundreds of thousands of tokens before the request is even read.
  • Copying data between tools through the model. A document fetched then written elsewhere flows through context twice; even larger documents can exceed context-window limits and break the workflow outright.
  • Logging full datasets back to the model. Returning all 10,000 rows when 5 filtered ones suffice defeats the pattern.
  • Implementing polling or loops as repeated direct tool calls. Each iteration pays full context and latency cost.
  • Running generated code without sandboxing, resource limits, and monitoring. The source names this as the pattern's core requirement, not an optional hardening step.
  • Treating the pattern as free. It adds infrastructure complexity; adopt it only where token/latency/composition gains beat the implementation cost.

Source

Distilled from the official document(s) above on 2026-08-12. If this skill and the source disagree, trust the source.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.