mcp-code-execution
Scaffold the code execution pattern for MCP-based agents. Use when agents call many MCP tools, intermediate data exceeds context, you need loops, or PII must stay out of context.
What this skill does
# MCP Code Execution Pattern
Expert knowledge for designing agent systems that generate and execute code to interact with MCP servers, instead of calling tools directly.
## When to Use This Skill
| Use this skill when... | Use mcp-management instead when... |
|---|---|
| Designing agents that fan out across 10+ MCP servers or 50+ tools | Installing or configuring a single MCP server in `.mcp.json` |
| Intermediate tool results are large (>10K tokens) and would blow context | Operating one or two servers where every result is small enough to inline |
| Workflows need loops, retries, or conditionals across tool calls | Doing a one-shot connection check or linear 2–3-call sequence |
| PII must not reach the model context | Tool responses contain no sensitive data |
## When to Use This Pattern
| Use code execution when... | Use direct tool calls when... |
|----------------------------|-------------------------------|
| Connecting to 10+ MCP servers or 50+ tools | Few servers with handful of tools |
| Intermediate results are large (>10K tokens) | Results are small and all needed by the model |
| Workflows need loops, retries, or conditionals | Linear sequences of 2-3 tool calls |
| PII must not reach the model context | No sensitive data in tool responses |
| Tasks benefit from state persistence across runs | Stateless, one-shot operations |
| You want agents to accumulate reusable skills | Fixed, predefined workflows |
## Core Architecture
### How It Works
Instead of loading all MCP tool definitions into the model context upfront, the agent:
1. **Discovers** available tools by navigating a typed file tree
2. **Generates** TypeScript/Python code that imports and calls typed wrapper functions
3. **Executes** the code in a sandboxed environment
4. **Returns** only filtered/summarized results to the model
This reduces token usage from O(all_tool_definitions) to O(only_relevant_imports).
### File Tree Structure
```
project/
├── servers/
│ ├── google-drive/
│ │ ├── getDocument.ts
│ │ ├── getSheet.ts
│ │ ├── listFiles.ts
│ │ └── index.ts # Re-exports all tools
│ ├── salesforce/
│ │ ├── query.ts
│ │ ├── updateRecord.ts
│ │ └── index.ts
│ └── slack/
│ ├── sendMessage.ts
│ ├── getChannelHistory.ts
│ └── index.ts
├── skills/ # Agent-accumulated reusable functions
│ └── save-sheet-as-csv.ts
├── workspace/ # Persistent state between executions
├── client.ts # MCP client that routes calls to servers
└── sandbox.config.ts # Execution environment configuration
```
### Typed Wrapper Pattern
Each MCP tool gets a typed wrapper function that the agent imports:
```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<GetDocumentResponse> {
return callMCPTool<GetDocumentResponse>("google_drive__get_document", input);
}
```
The agent then writes code that uses these wrappers naturally:
```typescript
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 },
});
```
## Key Patterns
### 1. Progressive Tool Discovery
The agent navigates the filesystem to find relevant tools on demand, instead of loading all definitions upfront.
```
Agent: "I need to read from Google Drive"
→ ls servers/
→ ls servers/google-drive/
→ cat servers/google-drive/getDocument.ts (reads signature + JSDoc)
→ generates code importing only getDocument
```
**Token impact**: 150,000 tokens (all definitions) reduced to ~2,000 tokens (one definition). 98.7% reduction.
### 2. Context-Efficient Data Filtering
Filter large datasets in the execution environment before results reach the model:
```typescript
// Filter in the sandbox — only summary reaches the model
const allRows = await gdrive.getSheet({ sheetId: "abc123" });
const pending = allRows.filter((row) => row["Status"] === "pending");
console.log(`Found ${pending.length} pending orders`);
console.log(pending.slice(0, 5)); // Only first 5 for model review
```
### 3. Native Control Flow
Replace chained tool calls with code-native loops and conditionals:
```typescript
// Polling loop — runs entirely in sandbox
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");
```
### 4. PII Tokenization
The MCP client intercepts responses and tokenizes sensitive data before it reaches the model:
```typescript
// Agent writes this code
for (const row of sheet.rows) {
await salesforce.updateRecord({
objectType: "Lead",
recordId: row.salesforceId,
data: { Email: row.email, Phone: row.phone, Name: row.name },
});
}
console.log(`Updated ${sheet.rows.length} leads`);
```
What the model sees in the execution output:
```
[
{ salesforceId: "00Q...", email: "[EMAIL_1]", phone: "[PHONE_1]", name: "[NAME_1]" },
{ salesforceId: "00Q...", email: "[EMAIL_2]", phone: "[PHONE_2]", name: "[NAME_2]" }
]
Updated 247 leads
```
The actual PII flows between external systems without entering model context.
### 5. State Persistence
Save intermediate results to the workspace for cross-execution continuity:
```typescript
// Execution 1: fetch and save
const leads = await salesforce.query({
query: "SELECT Id, Email FROM Lead LIMIT 1000",
});
await fs.writeFile("./workspace/leads.csv", leads.map((l) => `${l.Id},${l.Email}`).join("\n"));
// Execution 2: resume from saved state
const saved = await fs.readFile("./workspace/leads.csv", "utf-8");
```
### 6. Skill Accumulation
Agents persist reusable functions as skills for future executions:
```typescript
// skills/save-sheet-as-csv.ts
import * as gdrive from "../servers/google-drive";
import * as fs from "fs/promises";
export async function saveSheetAsCsv(sheetId: string): Promise<string> {
const data = await gdrive.getSheet({ sheetId });
const csv = data.map((row) => row.join(",")).join("\n");
const path = `./workspace/sheet-${sheetId}.csv`;
await fs.writeFile(path, csv);
return path;
}
```
Later executions import the skill directly:
```typescript
import { saveSheetAsCsv } from "./skills/save-sheet-as-csv";
const csvPath = await saveSheetAsCsv("abc123");
```
## Scaffolding a New Project
### Step 1: Identify MCP Servers
List the MCP servers the agent needs to interact with. Check `.mcp.json` or the project's MCP configuration:
```bash
cat .mcp.json 2>/dev/null || echo "No MCP config found"
```
### Step 2: Generate Server Directory
For each MCP server, create a directory with typed wrappers. Each tool gets its own file with:
- Input interface
- Output interface
- JSDoc comment describing the tool
- Async function wrapping `callMCPTool`
### Step 3: Create the MCP Client
The client routes `callMCPTool` calls to the appropriate MCP server:
```typescript
// client.ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
const clients = new Map<string, Client>();
export async function callMCPTool<T>(
toolName: string,
input: Record<string, unknown>
): Promise<T> {
const serverName = toolName.split("__")[0];
const client = clients.get(serverName);
if (!client) throw new Error(`No MCP client for server: ${serverName}`);
const result = await client.callTool({ name: toolName, arguments: input });
return result.content as T;
}
```
### Step 4: Configure the Sandbox
The Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.