AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Mcp Code Execution

skill-archive228-lab-skills-mcp-code-execution · by Archive228

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 lar…

No reviews yet
0 installs
25 views
0.0% view→install

Install

$ agentstack add skill-archive228-lab-skills-mcp-code-execution

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-archive228-lab-skills-mcp-code-execution)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Mcp Code Execution? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

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.
  1. 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:

```typescript // ./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 { return callMCPTool('googledrive_get_document', input); } ```

  1. 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.
  1. Keep intermediate results inside the execution environment. Chain tools in code so payloads move variable-to-variable, not through context:

``typescript 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.

  1. 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:

``typescript const allRows = await gdrive.getSheet({ sheetId: 'abc123' }); const pendingOrders = allRows.filter(row => row["Status"] === 'pending'); console.log(Found ${pendingOrders.length} pending orders); ``

  1. 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).
  1. 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.
  1. 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.
  1. 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.
  1. 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//.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

  • Code execution with MCP: building more efficient agents — https://www.anthropic.com/engineering/code-execution-with-mcp — 2025-11-04

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

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.