MCP代码执行工具

MCPaC是一个CLI工具,允许通过TypeScript/JavaScript代码调用MCP服务器功能,为AI代理提供安全的代码执行环境。

  • by sh1nduu
  • TypeScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 sh1nduu/mcpac

使用说明

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个理念:

  1. 服务器注册
    您通过以下方式注册MCP服务器 mcpac server add.

  2. 代码生成
    你跑 mcpac generate 为所有服务器和工具创建TypeScript类型定义。

  3. 注入运行时间
    当你奔跑时 mcpac execute,MCPaC注射了一种特殊的 runtime 对象到你的代码中。
    你 不创建或导入 这个对象你自己。

  4. 基于能力的权限
    你的代码声明了它需要哪些工具,你必须通过匹配 --grant 执行时标记。

如果 已声明的权限 和 授予的权限 不匹配,执行失败,出现明显错误。


🚀 快速开始

1.添加MCP服务器

示例:允许访问特定目录的文件系统服务器。

mcpac server add filesystem \
  --command npx \
  --args @modelcontextprotocol/server-filesystem \
  --args ./allowed-directory

2.生成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.ts

3.编写代码

创建 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<['filesystem.read_file', 'filesystem.write_file']>;

// 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<['filesystem.read_file']>;

这取决于 servers/global.d.ts:

declare namespace MCPaC {
  export type McpRequires<T extends readonly string[]> =
    import('./_types.d.ts').McpRequires<T>;
}

⚠️ 环境 MCPaC 命名空间用于 mcpac execute 只有环境。 如果没有额外的配置,它可能无法在打包器、ts节点或其他工具中按预期工作。

2.显式导入(高级/自定义集成)

import type { McpRequires } from './servers/_types.js';

declare const runtime: McpRequires<['filesystem.read_file']>;

如果您想在自己的运行时或代理线束中重用MCPaC生成的类型,并且自己能够轻松地连接MCP连接和功能检查,请使用此样式。主要支持的路径仍然是 mcpac execute;此显式导入样式是一个高级/自定义选项。


🔐 权限系统

在代码中(声明功能):

declare const runtime: MCPaC.McpRequires<[
  'filesystem.list_directory',
  'filesystem.read_file'
]>;

在执行时(授予能力):

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 <name> --command <cmd> --args <args...>

# Add server (HTTP)
mcpac server add <name> --type http --url <url> --headers "KEY=VALUE"

# List servers
mcpac server list

# Test server connection
mcpac server test <name>

# Remove server
mcpac server remove <name>

代码生成

# Generate for all servers
mcpac generate

# Generate for a specific server
mcpac generate -s <server-name>

# Overwrite existing generated files
mcpac generate --force

工具探索

# List all tools
mcpac tools list

# List tools for a specific server
mcpac tools list -s <server-name>

# Show detailed tool description (schema, examples, etc.)
# Use original MCP tool name (e.g., read_file, not readFile)
mcpac tools describe <function_name>

直接刀具调用(无代码)

# 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<[
  'filesystem.list_directory',
  'filesystem.read_file'
]>;

// 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 generate
declare const runtime: MCPaC.McpRequires<['github.create_issue']>;

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<[
  'filesystem.read_file',
  'github.create_issue'
]>;

// 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由三个主要层组成:

  1. MCP客户端层
    管理与MCP服务器的STDIO/HTTP连接,并路由请求/响应。

  2. 代码生成层
    将MCP工具定义转换为TypeScript .d.ts 文件和功能感知运行时。

  3. 执行层
    使用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
└── <serverName>/
    ├── index.d.ts          # Server-level type definitions
    ├── <tool1>.d.ts        # Individual tool definitions
    └── <tool2>.d.ts

发展

先决条件

有用的命令

# Development wrapper
bun run dev <command>

# 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 <name>

类型检查错误

# Skip type checking (for quick debugging)
mcpac execute -f script.ts --no-typecheck

# Inspect the generated types for a tool
mcpac tools describe <function_name>

连接问题

# See detailed MCP logs
mcpac execute -f script.ts -v

# Check the MCP server's stderr output

资源


许可证

麻省理工学院


贡献

欢迎投稿!请随时打开问题或提交pull请求。