从MCP到代码执行
将您的MCP(模型上下文协议)服务器转化为高效的代码执行技能,并实现 99%+代币减少 跟随 Anthropic的代码执行模式.
传统MCP的问题
传统的MCP架构有两个关键的局限性:
- 上下文过载:所有工具定义都是预先加载的(在处理开始之前,大约有100000多个令牌)
- 中间代币浪费:每个工具结果都通过模型的上下文传递(例如,50000个令牌转录本两次通过上下文)
现实世界的影响:使用传统MCP,复杂的工作流程可能会消耗150000多个令牌。
解决方案:代码执行
代理不直接调用MCP工具,而是:
- 写入代码 直接与API/数据库交互
- 在本地执行 -数据从不进入上下文
- 返回摘要 -只有基本的结果才能符合上下文
结果:同一工作流现在使用约2000个令牌。这是一个 减少98.7%.
快速开始
选项1:使用技能
调用 code-execution-creator 克劳德代码技能:
skill: code-execution-creator然后指定要转换的MCP服务器:
Convert the magic-ui MCP server to a Code Execution skill选项2:使用代理
要实现更自主的转换,请使用专用代理:
agent: mcp-to-code-execution代理人将:
- 分析MCP服务器暴露的所有工具
- 确定最佳策略(直接连接、MCP网桥或混合)
- 实现一个具有完整功能覆盖的TypeScript客户端
- 创建全面的SKILL.md文档
- 使用HTML报告生成可验证的测试
- 如果结果是100%迁移或混合,请明确沟通
转换策略
策略1:直接连接(首选)
通过直接连接到底层API或数据库,完全绕过MCP。
// Instead of calling MCP tools...
const result = await mcp__magic-ui__get_component({ name: 'marquee' });
// ...fetch directly from the API
const response = await fetch('https://magicui.design/r/marquee.json');
const component = await response.json();最适合:REST API、具有本机驱动程序的数据库、具有公共端点的服务
结果:用户可以卸载MCP服务器
策略2:MCP桥
当需要MCP服务器逻辑但仍希望节省令牌时。
import { callMCPTool } from './client.js';
// Wrap MCP calls but process results locally
const data = await callMCPTool('server__complex_operation', params);
const summary = processLocally(data);
console.log(summary); // Only this enters context最适合:复杂的业务逻辑,内部MCP服务器
策略3:混合动力
一些工具通过代码执行复制,另一些则委托给MCP。
// Use Code Exec for data fetching (99% token savings)
const components = await getComponents(['button', 'form', 'input']);
// Use MCP for AI-powered operations (requires LLM)
// Tool: mcp__shadcn-vue-mcp__requirement-structuring最适合:配备人工智能工具的MCP服务器
结果:用户必须安装MCP服务器
你可以转换什么
已安装的MCP服务器
转换您的MCP服务器 claude_desktop_config.json:
Convert my installed supabase-self-hosted MCP to Code Execution优点:
- 释放上下文窗口
- 维护所有功能
- 执行速度更快(无MCP开销)
未安装的MCP服务器
提供任何MCP服务器(npm包、GitHub仓库),技能将:
- 分析服务器的工具定义
- 反向工程底层API
- 创建独立的代码执行技能
Create a Code Execution skill for @anthropic/mcp-server-github项目结构
.claude/
├── agents/
│ └── mcp-to-code-execution # Autonomous conversion agent
└── skills/
├── code-execution-creator/ # Skill creation guide & templates
├── supabase-code-exec/ # PostgreSQL direct connection
├── magic-ui-code-exec/ # REST API direct fetch
├── stack-auth-code-exec/ # Documentation API (110+ docs)
├── stripe-code-exec/ # Payments API with sandbox support
├── neon-code-exec/ # Serverless Postgres API
├── posthog-code-exec/ # Analytics & Feature Flags API (42 tools)
├── sentry-code-exec/ # Error Tracking & Monitoring API
└── shadcn-vue-code-exec/ # Hybrid (Code Exec + MCP)包含的技能
| 技能 | 策略 | 代币减少 | 需要MCP |
|---|---|---|---|
| 补充 | 直接连接 | 99%+ | 否 |
| magic用户界面代码执行器 | 直接连接 | 99%+ | 否 |
| 堆栈身份验证代码exec | 直接连接 | 99%+ | 否 |
| 条纹代码执行器 | 直接连接 | 99%+ | 否 |
| 霓虹灯代码执行官 | 直接连接 | 99%+ | 否 |
| posthog代码执行器 | 直接连接 | 99%+ | 否 |
| 哨兵代码执行器 | 直接连接 | 99%+ | 否\* |
| shadcn-vue代码执行 | 混合动力 | ~80% | 是 |
\*注:Sentry的人工智能搜索和Seer功能需要MCP服务器。所有标准REST API操作都已完全迁移。
Supabase(100%迁移)
直接PostgreSQL连接,无需MCP开销。
import { executePostgresql, getSchemas, getTables } from './client-pg.js';
// Direct database queries
const schemas = await getSchemas();
const users = await executePostgresql('SELECT * FROM users LIMIT 10');代币减少: 99%+ 需要MCP:没有
Magic UI(100%迁移)
直接从API获取动画UI组件。
import { getComponent, getComponents, searchComponents } from './client-magicui.js';
// Fetch components directly
const marquee = await getComponent('marquee');
const buttons = searchComponents('button');代币减少: 99%+ 需要MCP:没有
堆栈身份验证(100%迁移)
通过即时本地搜索和按需获取访问Stack Auth文档。
import {
listDocs, searchDocs, getDocById, getSetupInstructions,
listCategories, listDocsByCategory, getQuickReference
} from './client-stack-auth.js';
// Instant local search (no network)
const results = searchDocs('oauth google');
const categories = listCategories();
// Fetch only what you need (network)
const doc = await getDocById('/docs/getting-started/setup');
const setup = await getSetupInstructions();代币减少: 99%+ 需要MCP:没有 覆盖:110多页文档,13个类别
条纹(100%迁移)
带测试模式(沙箱)和实时模式支持的API全条访问。
import {
createCustomer, createPaymentIntent, confirmPaymentIntent,
createSubscription, listProducts, createRefund,
isTestMode, getTestCard, getSandboxSetupGuide,
TEST_CARDS, TEST_PAYMENT_METHODS
} from './client-stripe.js';
// Check mode before operations
if (isTestMode(process.env.STRIPE_API_KEY)) {
console.log('Safe to test!');
}
// Use test cards in sandbox
const card = getTestCard('visa'); // 4242424242424242
// Full payment flow
const customer = await createCustomer({ email: 'test@example.com' });
const intent = await createPaymentIntent({ amount: 2000, currency: 'usd' });
await confirmPaymentIntent(intent.id, { payment_method: 'pm_card_visa' });代币减少: 99%+ 需要MCP:没有 覆盖:22+MCP工具,60+API功能,46个测试卡场景
霓虹灯(100%迁移)
用于项目管理、分支和SQL执行的完整Neon无服务器Postgres API访问。
import {
listProjects, createProject, createBranch, deleteBranch,
runSql, runSqlTransaction, explainSql,
getTables, getTableSchema, listSlowQueries,
getConnectionString, listRegions,
} from './client-neon.js';
// List your projects
const { projects } = await listProjects();
console.log('Projects:', projects.map(p => p.name));
// Create a new project
const result = await createProject({
name: 'my-app',
region_id: 'aws-us-east-1',
pg_version: 16
});
// Execute SQL queries
const users = await runSql({
projectId: result.project.id,
sql: 'SELECT * FROM users LIMIT 10'
});
// Branch-based development (Neon's killer feature)
const devBranch = await createBranch(result.project.id, {
name: 'feature/new-schema'
});
await runSql({
projectId: result.project.id,
branchId: devBranch.branch.id,
sql: 'ALTER TABLE users ADD COLUMN preferences JSONB'
});代币减少: 99%+ 需要MCP:没有 覆盖:27个MCP工具、50+API功能、分支管理、SQL执行
PostHog(100%迁移)
PostHog API的完整访问,用于分析、功能标志、实验、错误跟踪等。
import {
createPostHogClient,
getPostHogConfigFromEnv
} from './client-posthog.js';
// Initialize client
const posthog = createPostHogClient(getPostHogConfigFromEnv());
// Feature Flags
const { results: flags } = await posthog.getFeatureFlags();
await posthog.createFeatureFlag({
key: 'new-feature',
name: 'New Feature',
active: true,
rollout_percentage: 50
});
// Analytics & Insights
const { results: insights } = await posthog.getInsights({ limit: 20 });
const result = await posthog.runQuery({
query: {
kind: 'HogQLQuery',
query: 'SELECT properties.$current_url, count() FROM events GROUP BY properties.$current_url'
}
});
// Error Tracking
const { results: errors } = await posthog.listErrors({ status: 'active' });
const errorDetails = await posthog.getErrorDetails(errorId);
// Experiments
await posthog.createExperiment({
name: 'Button Color Test',
feature_flag_key: 'button-color',
metrics: [{ type: 'primary', query: { kind: 'TrendsQuery' } }]
});
// Surveys
await posthog.createSurvey({
name: 'Product Feedback',
type: 'popover',
questions: [
{ type: 'rating', question: 'How satisfied are you?' },
{ type: 'open', question: 'What could we improve?' }
]
});代币减少: 99%+ 需要MCP:没有 覆盖:42个MCP工具,涵盖所有PostHog功能(仪表板、功能标志、实验、见解、错误跟踪、调查、组织管理)
哨兵(100%迁移\*)
完整的Sentry API访问,用于错误跟踪、问题管理、发布和监控。
import {
createSentryClient,
getSentryConfigFromEnv
} from './client-sentry.js';
// Initialize client
const sentry = createSentryClient(getSentryConfigFromEnv());
// List unresolved errors
const issues = await sentry.listIssues({
query: 'is:unresolved level:error',
statsPeriod: '24h',
sort: 'freq'
});
issues.forEach(issue => {
console.log(`${issue.title} - ${issue.count} occurrences`);
console.log(`Users affected: ${issue.userCount}`);
console.log(issue.permalink);
});
// Get issue details
const issue = await sentry.getIssue('12345');
console.log(`Culprit: ${issue.culprit}`);
// Update issue status
await sentry.updateIssue('12345', { status: 'resolved' });
// Bulk operations
await sentry.bulkUpdateIssues(
['12345', '12346', '12347'],
{ status: 'resolved' }
);
// Releases
const release = await sentry.createRelease({
version: '1.2.3',
projects: ['my-project'],
commits: [
{ id: 'abc123', message: 'Fix critical bug' }
]
});
// Projects & Teams
const projects = await sentry.listProjects();
const teams = await sentry.listTeams();
// DSN Management
const keys = await sentry.listProjectKeys('my-project');
const newKey = await sentry.createProjectKey('my-project', {
name: 'Production Key'
});
// Statistics
const stats = await sentry.getOrganizationStats({
stat: 'received',
since: Date.now() / 1000 - 86400, // Last 24h
resolution: '1h'
});代币减少: 99%+ 需要MCP:否\*(AI搜索和Seer需要MCP) 覆盖:组织、项目、团队、问题、事件、发布、DSN、统计数据
\*注:人工智能搜索(search_events, search_issues)和Seer集成需要具有OpenAI API密钥的MCP服务器。所有标准REST API操作都已完全迁移,以实现最大效率。
shadcn-vue(混合动力)
用于获取的代码执行,用于AI驱动分析的MCP。
// Code Exec: Fast component fetching
const components = await getComponents(['button', 'form']);
// MCP: AI-powered requirement analysis (still needs MCP)
// mcp__shadcn-vue-mcp__requirement-structuring代币减少:约80%用于获取操作 需要MCP:是(针对AI工具)
技能输出结构
每个生成的技能都遵循一个自包含的结构:
.claude/skills/-code-exec/
├── SKILL.md # Documentation with setup & usage
└── scripts/
└── client-.ts # TypeScript clientSKILL.md内容
- 前台:Claude代码发现的名称和描述
- 设置:一次性安装步骤
- 用法:所有操作的代码示例
- 功能表:完整的API参考
- 推荐图案:令牌高效使用
- 故障排除:常见问题和解决方案
- 混合动力警告 (如适用):仍需要哪些MCP工具
可验证测试
生成的技能包括产生有形产出的测试:
test/
├── test--skill.ts
└── output/
├── test-report.html # Visual report (open in browser)
├── single-fetch.json # Real API response
├── batch-fetch.json # Batch results
└── catalog.json # Exported catalog何时不使用代码执行
某些MCP服务器无法完全迁移:
- AI驱动的工具:使用内部LLM处理的工具
- 有状态的操作:维护会话状态的工具
- 复杂的身份验证:OAuth流,刷新令牌
- 专有协议:非HTTP通信
这些结果导致 混合 某些操作使用代码执行,而其他操作委托给MCP的技能。
需求
- 克劳德代码 命令行界面
- Node.js 18+
- TypeScript
参考文献
- Anthropic:使用MCP执行代码 -原始模式文档
- 人类学:建立有效的代理人 -代理设计原则
- 模型上下文协议 -MCP规范
许可证
麻省理工学院
______________________________________________________________________
Created by MAXYMIZE
Maximize efficiency. Minimize tokens.
