MCPaC(MCPaC)-- *MCP作为代码*
使用MCP服务器执行Types/JavaScript代码,就像它们是库一样--\ AI代理调用函数,而不是生成原始的MCP JSON。
______________________________________________________________________
⚠️ 安全警告
关键:此工具执行可能与您的系统交互的任意代码。请务必谨慎使用。
- 代码执行风险:代码通过运行
mcpac execute可以访问您的文件系统、网络和系统资源 - MCP服务器风险:MCP服务器可能会根据其配置(文件系统路径、API密钥、HTTP端点等)访问您的系统
- 不受信任的代码:从不执行来自不可信来源的代码
- 敏感数据:当MCP服务器可以看到机密、源代码或生产数据时,要非常小心
- 执行前审查:始终查看:
- 您配置的MCP服务器 - 您授予的权限 --grant - 您要执行的代码
通过使用MCPaC,您承认这些风险并对任何后果承担全部责任。
______________________________________________________________________
概述
MCPaC是一个CLI工具,它:
- 连接到MCP服务器(文件系统、GitHub、HTTP API等)
- 为他们的工具生成TypeScript类型定义
- 执行Types/JavaScript代码,通过特殊的注入调用这些工具
runtime对象
典型用例:
- 让AI编码代理(Claude、Cursor等)调用MCP工具,而不生成MCP JSON
- 通过代码使代理可以使用偶尔使用的MCP服务器,而无需维护完全的直接工具集成
- 在一个小型、隔离的沙箱中尝试使用TypeScript的MCP服务器,而不是手写的MCP JSON
这个项目是Anthropic博客文章中描述的“使用MCP执行代码”思想的一个具体实现:https://www.anthropic.com/engineering/code-execution-with-mcp
定位/范围
MCPaC并不打算取代整个堆栈中传统的MCP直接工具调用。这是一种互补的方法,在以下情况下效果最佳:
- 您希望AI编码代理偶尔使用MCP服务器,而不将所有工具定义加载到上下文中
- 您更喜欢代理编写组成多个工具的小段代码,而不是发出许多单独的直接工具调用
- 您正在试验新的或低频MCP服务器,还不想保持完整的一流集成
对于高频或对延迟敏感的工具,传统的直接MCP工具调用可能仍然更适合。MCPaC被设计为一种附加选项,而不是通用的替代品。
______________________________________________________________________
特性
- 🚀 从MCP服务器生成TypeScript代码\
自动将MCP工具定义转换为类型安全的API
- 💻 代码执行环境\
使用生成的MCP库执行Types/JavaScript
- 🔐 基于能力的权限系统\
工具必须在代码中明确声明,并通过CLI明确授予
- 🔧 服务器管理\
添加、列出、测试和删除MCP服务器(STDIO和HTTP)
- 🌐 多种运输支持
- STDIO:本地进程(npx @modelcontextprotocol/server-*等等) - HTTP:远程MCP服务器
- 🔍 工具探索\
通过CLI发现工具及其参数类型
- 📦 单二进制(有电流限制)\
作为单个可执行文件分发,但在今天的执行时仍然需要Bun——未来的版本旨在消除这种依赖性。
- ⚡ 自动清理\
MCP连接会自动管理和清理
______________________________________________________________________
安装
从以下网址下载最新版本:\ https://github.com/sh1nduu/mcpac/releases
macOS(苹果硅示例)
curl -L https://github.com/sh1nduu/mcpac/releases/download/v0.4.0/mcpac-0.4.0-darwin-arm64 -o mcpac
chmod +x mcpac
sudo mv mcpac /usr/local/bin/
mcpac --version类似的二进制文件可用于Linux(x64)、macOS(Intel)和Windows(x64)。\ 有关确切的文件名和安装路径,请参阅发布页面。
从源代码构建
git clone https://github.com/sh1nduu/mcpac.git
cd mcpac
bun install
bun run build
./mcpac --version______________________________________________________________________
🧠 核心概念
MCPaC围绕4个理念:
- 服务器注册\
您通过以下方式注册MCP服务器 mcpac server add.
- 代码生成\
你跑 mcpac generate 为所有服务器和工具创建TypeScript类型定义。
- 注入运行时间\
当你奔跑时 mcpac execute,MCPaC注射了一种特殊的 runtime 对象到你的代码中。\ 你 不创建或导入 这个对象你自己。
- 基于能力的权限\
你的代码声明了它需要哪些工具,你必须通过匹配 --grant 执行时标记。
如果 已声明的权限 和 授予的权限 不匹配,执行失败,出现明显错误。
______________________________________________________________________
🚀 快速开始
1.添加MCP服务器
示例:允许访问特定目录的文件系统服务器。
mcpac server add filesystem \
--command npx \
--args @modelcontextprotocol/server-filesystem \
--args ./allowed-directory2.生成TypeScript代码
mcpac generate生成的结构:
servers/
├── _mcpac_runtime.ts # Runtime implementation (IPC, capability system)
├── _types.d.ts # Root types for explicit import
├── global.d.ts # MCPaC ambient namespace (for mcpac execute)
└── filesystem/
├── index.d.ts # Server-level types
├── read_file.d.ts # Individual tool definitions (original MCP names)
└── write_file.d.ts3.编写代码
创建 example.ts:
// Recommended: MCPaC ambient namespace (for mcpac execute)
// DO NOT create runtime yourself – it is injected at execution time.
declare const runtime: MCPaC.McpRequires;
// Read file
const readResult = await runtime.filesystem.read_file({ path: 'example.txt' });
const text = readResult.content.find(c => c.type === 'text')?.text;
console.log('File content:', text);
// Write file
await runtime.filesystem.write_file({
path: 'output.txt',
content: 'Hello from MCPaC!'
});4.使用权限执行
mcpac execute -f example.ts \
--grant filesystem.read_file,filesystem.write_file如果请求的工具 McpRequires 与中的工具不匹配 --grant,执行被阻止。
______________________________________________________________________
🧰 类型和运行时:环境命名空间与显式导入
MCPaC以两种方式公开类型:
1.环境命名空间(建议用于 mcpac execute)
// Available only when you run via `mcpac execute` after `mcpac generate`
declare const runtime: MCPaC.McpRequires;这取决于 servers/global.d.ts:
declare namespace MCPaC {
export type McpRequires =
import('./_types.d.ts').McpRequires;
}⚠️ 环境MCPaC命名空间用于mcpac execute只有环境。 如果没有额外的配置,它可能无法在打包器、ts节点或其他工具中按预期工作。
2.显式导入(高级/自定义集成)
import type { McpRequires } from './servers/_types.js';
declare const runtime: McpRequires;如果您想在自己的运行时或代理线束中重用MCPaC生成的类型,并且自己能够轻松地连接MCP连接和功能检查,请使用此样式。主要支持的路径仍然是 mcpac execute;此显式导入样式是一个高级/自定义选项。
______________________________________________________________________
🔐 权限系统
在代码中(声明功能):
declare const runtime: MCPaC.McpRequires;在执行时(授予能力):
mcpac execute -f script.ts \
--grant filesystem.list_directory,filesystem.read_file规则:
- 您的代码只能调用中列出的工具
McpRequires mcpac execute将只允许中列出的工具--grant- 两个列表必须匹配,否则执行失败
______________________________________________________________________
CLI使用情况
入门指南
mcpac getting-started # Interactive setup
mcpac info # Show current configuration & servers
mcpac examples # Show example snippets服务器管理
# Add server (STDIO)
mcpac server add --command --args
# Add server (HTTP)
mcpac server add --type http --url --headers "KEY=VALUE"
# List servers
mcpac server list
# Test server connection
mcpac server test
# Remove server
mcpac server remove 代码生成
# Generate for all servers
mcpac generate
# Generate for a specific server
mcpac generate -s
# Overwrite existing generated files
mcpac generate --force工具探索
# List all tools
mcpac tools list
# List tools for a specific server
mcpac tools list -s
# Show detailed tool description (schema, examples, etc.)
# Use original MCP tool name (e.g., read_file, not readFile)
mcpac tools describe 直接刀具调用(无代码)
# Call tool with flags (use original MCP tool name)
mcpac tools call read_file --path example.txt
# Call with JSON string
mcpac tools call read_file --json '{"path":"example.txt"}'
# Call with JSON from stdin
echo '{"path":"example.txt"}' | mcpac tools call read_file --stdin输出格式:
mcpac tools call read_file --path example.txt --output-format text # Default
mcpac tools call read_file --path example.txt --output-format json # With metadata
mcpac tools call read_file --path example.txt --output-format raw # Raw MCP response额外标志:
--no-validate:跳过参数验证-q/--quiet:抑制非关键输出-v/--verbose:打印调试日志
退出代码:
0:成功1:参数错误/验证失败2:工具执行错误3:服务器连接错误
代码执行
# Execute from file
mcpac execute -f script.ts --grant server.tool1,server.tool2
# Execute inline code
mcpac execute -c "/* code here */" --grant filesystem.read_file
# Execute from stdin
cat script.ts | mcpac execute --stdin --grant filesystem.read_file
# Skip type checking (faster, but less safe)
mcpac execute -f script.ts --no-typecheck --grant filesystem.read_file
# Verbose / quiet
mcpac execute -f script.ts -v --grant filesystem.read_file
mcpac execute -f script.ts -q --grant filesystem.read_file______________________________________________________________________
示例
示例1:文件操作
// Declare required permissions (use original MCP tool names)
declare const runtime: MCPaC.McpRequires;
// List directory
const dir = await runtime.filesystem.list_directory({ path: '.' });
const listText = dir.content.find(c => c.type === 'text')?.text;
console.log('Directory listing:', listText);
// Read file
const file = await runtime.filesystem.read_file({ path: 'README.md' });
const content = file.content.find(c => c.type === 'text')?.text;
console.log('Content length:', content?.length);运行:
mcpac execute -f script.ts \
--grant filesystem.list_directory,filesystem.read_file示例2:GitHub集成
# Add GitHub server
mcpac server add github \
--command npx \
--args @modelcontextprotocol/server-github \
--env GITHUB_TOKEN=your_token_here
# Generate code
mcpac generatedeclare const runtime: MCPaC.McpRequires;
const result = await runtime.github.create_issue({
owner: 'username',
repo: 'repository',
title: 'Bug Report',
body: 'Description of the bug'
});
const text = result.content.find(c => c.type === 'text')?.text;
console.log('Created issue:', text);运行:
mcpac execute -f script.ts --grant github.create_issue示例3:具有循环的多工具工作流
此示例显示了代理如何在循环中协调多个工具。\ 假设你有一个本地JSON文件,定义了要创建的GitHub问题:
[
{ "title": "Bug: login fails", "body": "Steps to reproduce..." },
{ "title": "Feature: dark mode", "body": "It would be nice if..." }
]您可以让代理编写代码,读取此配置并在GitHub上创建问题:
// Use both filesystem and GitHub tools in a loop
declare const runtime: MCPaC.McpRequires;
// Read issue definitions from a local JSON file
const fileResult = await runtime.filesystem.read_file({ path: './issues.json' });
const text = fileResult.content.find(c => c.type === 'text')?.text ?? '[]';
type IssueDef = { title: string; body: string };
const issues = JSON.parse(text) as IssueDef[];
// Create issues on GitHub in a loop
for (const issue of issues) {
const result = await runtime.github.create_issue({
owner: 'username',
repo: 'repository',
title: issue.title,
body: issue.body,
});
const created = result.content.find(c => c.type === 'text')?.text;
console.log('Created issue:', created);
}运行:
mcpac execute -f script.ts --grant filesystem.read_file,github.create_issue在真实的代理工作流中,这种多工具循环完全存在于执行环境中:\ 模型只需要生成一次代码,然后运行时处理所有迭代和工具协调。
______________________________________________________________________
配置
默认配置文件:
./config/mcp-servers.json通过环境变量进行覆盖:
MCPAC_CONFIG_PATH=/custom/path/config.json mcpac server list______________________________________________________________________
建筑
MCPaC由三个主要层组成:
- MCP客户端层\
管理与MCP服务器的STDIO/HTTP连接,并路由请求/响应。
- 代码生成层\
将MCP工具定义转换为TypeScript .d.ts 文件和功能感知运行时。
- 执行层\
使用Bun执行Types/JavaScript代码并注入 runtime 对象。
生成的代码结构:
servers/
├── _mcpac_runtime.ts # Runtime implementation (IPC, capability system)
├── _types.d.ts # Root types (McpServers, McpRequires, etc.)
├── global.d.ts # Ambient MCPaC namespace for mcpac execute
└── /
├── index.d.ts # Server-level type definitions
├── .d.ts # Individual tool definitions
└── .d.ts______________________________________________________________________
发展
先决条件
- 包子 >= 1.0
有用的命令
# Development wrapper
bun run dev
# Type checking
bun run typecheck
# Linting & formatting
bun run check # Auto-fix
bun run check:ci # CI mode
# Tests
bun test # All tests
bun test tests/unit
bun test tests/e2e
# Build
bun run build # Build binary
bun run build:all # Build for all platforms
bun run clean # Clean artifacts______________________________________________________________________
局限性
- 执行的代码当前假定Bun为运行时
- MCP服务器必须在以下两个位置都可以访问:
- 代码生成时间(用于类型生成) - 执行时间(实际通话)
- 当前的MCP协议通常描述输入模式,但不描述工具响应的完整形式(例如嵌入其中的JSON结构
text内容块),因此MCPaC不能总是生成超出范围的精确响应类型ContentBlock;代理可能仍需要从文档或示例中推断或学习响应形状 - HTTP传输尚不支持SSE流
- Windows二进制文件可能会触发防病毒警告(误报)
______________________________________________________________________
故障排除
“找不到服务器”
mcpac server list
mcpac server test 类型检查错误
# Skip type checking (for quick debugging)
mcpac execute -f script.ts --no-typecheck
# Inspect the generated types for a tool
mcpac tools describe 连接问题
# See detailed MCP logs
mcpac execute -f script.ts -v
# Check the MCP server's stderr output______________________________________________________________________
资源
- MCP规范
- 官方MCP服务器
- MCP TypeScript SDK
- Anthropic博客: *使用MCP执行代码:构建更高效的代理*
______________________________________________________________________
许可证
麻省理工学院
______________________________________________________________________
贡献
欢迎投稿!请随时打开问题或提交pull请求。
