使用说明
OpenAPI→ MCP发生器(Monorepo)
将OpenAPI规范转换为功能强大的模型上下文协议(MCP)服务器,可与Claude Desktop、IDE和其他MCP兼容客户端一起使用。此monorepo提供了一个用户友好的CLI和一个用于无缝集成的程序库。
需求
- Bun 1.2+本地安装:https://bun.sh
- Node.js 18+(生成项目的运行时兼容性)
Monorepo结构
packages/core:核心生成器库(@aigentools/mcpgen-core)packages/cli:CLI(@aigentools/mcpgen,垃圾箱:mcpgen)packages/tsconfig:共享TS配置turbo.json: 涡轮增压管道biome.json:生物特征配置tsconfig.json:根TS配置
安装
# Clone and setup
git clone https://github.com/beshkenadze/openapi-mcp-generator.git
cd openapi-mcp-generator
bun install
bun run build
替代方案:使用任务(可选)
如果你有 任务 安装后,您可以使用提供的快捷方式:
task install # Same as: bun install
task build # Same as: bun run build
task typecheck # Same as: bun run typecheck
task test # Same as: bun run test
task lint # Same as: bun run lint
快速开始
选择您喜欢的方法从OpenAPI规范生成MCP服务器:
🚀 方法1:使用CLI(建议大多数用户使用)
交互模式(最简单)
# After installation, run in interactive mode
cd packages/cli
bun run dev
# Or using Task shortcut:
task gen:interactive
# The CLI will prompt you for:
# - Path to your OpenAPI spec file
# - Server name (auto-suggested from spec)
# - Output directory
# - Runtime preference (Bun/Node)
命令行模式(用于自动化)
# Generate from a local OpenAPI spec
cd packages/cli
bun run dev --input ./examples/petstore.yaml --out ./servers/petstore --name petstore-mcp --runtime bun --force
# Using Taskfile shortcuts for Petstore example:
task gen:petstore # Generate Petstore MCP server
task install:petstore # Install dependencies in generated server
task prism:inspect:cli # Generate + test with Prism mock server + MCP Inspector
# Generate from URL
bun run dev --input https://petstore.swagger.io/v2/swagger.json --out ./servers/petstore --name petstore-mcp
# Using configuration file
echo "openapi: ./api-spec.yaml
name: my-awesome-api-mcp" > config.yaml
bun run dev --config config.yaml --out ./my-server
🔧 方法2:使用库(用于程序集成)
在项目中安装:
bun add @aigentools/mcpgen-core # or npm install
以编程方式生成服务器:
import { generateServerFromOpenAPI } from "@aigentools/mcpgen-core";
// Simple usage
await generateServerFromOpenAPI(
"./petstore.yaml", // OpenAPI spec path
"./servers/petstore", // Output directory
"petstore-mcp" // Server name
);
// Advanced usage with options
const result = await generateServerFromOpenAPI(
"./api-spec.yaml",
"./custom-server",
"my-api-mcp",
{
runtime: "bun", // or "node"
force: true, // Overwrite existing files
debug: true, // Enable debug logging
skipFormatting: false // Format with Biome
}
);
console.log(`Generated server: ${result.name}`);
console.log(`Location: ${result.outDir}`);
console.log(`Operations: ${result.operations.length}`);
📁 生成的服务器结构
结构取决于所选的运行时:
标准运行时(Bun/Node)
my-server/
├── mcp-server/
│ └── index.ts # Complete MCP server (single file)
├── package.json # Dependencies and scripts
├── .env.example # Environment variables template
└── README.md # Usage instructions
Hono运行时(Web服务器)
my-server/
├── src/
│ └── server.ts # Hono web server with multiple transports
├── package.json # Dependencies and scripts
├── Dockerfile # Docker deployment support
├── biome.json # Code formatting configuration
└── README.md # Usage and transport endpoint documentation
▶️ 运行生成的MCP服务器
标准运行时(Bun/Node)
# Navigate to generated server
cd ./servers/petstore
# Install dependencies (if needed)
bun install
# Start the server
bun run start
# or directly:
bun --bun mcp-server/index.ts
# The server runs via stdio and is ready for MCP clients!
Hono Runtime(具有多种传输的Web服务器)
# Navigate to generated server
cd ./servers/petstore
# Install dependencies
bun install
# Development server with hot reload
bun run dev
# Production server
bun run build && bun run start
# The server provides multiple transport options:
# 🌐 HTTP transport: http://localhost:3000/mcp
# 📡 SSE transport: http://localhost:3000/mcp/sse
# 🔗 Stdio transport: ws://localhost:3000/mcp/stdio
# 🏥 Health check: http://localhost:3000/health
🔌 连接到克劳德桌面
连接方法取决于所使用的运行时:
标准运行时(标准传输)
添加到您的Claude Desktop MCP配置(claude_desktop_config.json):
{
"mcpServers": {
"petstore": {
"command": "bun",
"args": ["--bun", "/path/to/your/server/mcp-server/index.ts"],
"env": {
"API_BASE_URL": "https://petstore.swagger.io/v2"
}
}
}
}
Hono运行时(HTTP传输)
首先,启动您的Hono服务器,然后将Claude Desktop配置为使用HTTP传输:
{
"mcpServers": {
"petstore": {
"transport": {
"type": "http",
"url": "http://localhost:3000/mcp"
},
"env": {
"API_BASE_URL": "https://petstore.swagger.io/v2"
}
}
}
}
备选方案:苏格兰和南方能源运输公司(Hono)
对于流媒体功能,请使用服务器发送事件传输:
{
"mcpServers": {
"petstore": {
"transport": {
"type": "sse",
"url": "http://localhost:3000/mcp/sse"
},
"env": {
"API_BASE_URL": "https://petstore.swagger.io/v2"
}
}
}
}
📚 完整示例
示例1:Petstore API(标准运行时)
# Method 1: Using Taskfile (easiest for Petstore)
task gen:petstore # Generates the Petstore MCP server
task install:petstore # Installs dependencies
task prism:inspect:cli # Tests with Prism mock server + MCP Inspector
# Method 2: Using CLI interactively
cd packages/cli
bun run dev
# When prompted:
# Input file: https://petstore.swagger.io/v2/swagger.json
# Server name: petstore-api (auto-suggested)
# Output dir: ./servers/petstore-api (auto-suggested)
# Runtime: bun (default)
这将使用以下工具创建MCP服务器:
getPetById-通过ID查找宠物addPet-将新宠物添加到商店updatePet-更新现有宠物deletePet-删除宠物
测试生成的服务器:
# Start Prism mock server (in one terminal)
task prism:mock
# Test your server with MCP Inspector (in another terminal)
cd servers/petstore-mcp
API_BASE_URL=http://127.0.0.1:4010 bun --bun mcp-server/index.ts
示例2:Petstore API与Hono运行时(Web服务器)
# Generate Hono-based MCP server with multiple transports
cd packages/cli
bun run dev --input https://petstore.swagger.io/v2/swagger.json --out ./servers/petstore-hono --name petstore-hono --runtime hono
# Navigate and install dependencies
cd ./servers/petstore-hono
bun install
# Start development server with hot reload
bun run dev
Hono服务器提供多个连接端点:
HTTP传输(POST请求):
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
SSE传输(服务器发送事件):
curl -N http://localhost:3000/mcp/sse
# Returns streaming MCP responses
健康检查:
curl http://localhost:3000/health
# {"status":"ok","server":"petstore-hono"}
Docker部署:
# Build and run with Docker
docker build -t petstore-hono .
docker run -p 3000:3000 -e API_BASE_URL=https://petstore.swagger.io/v2 petstore-hono
示例3:GitHub API(高级)
# Download GitHub API spec
curl -o github.json https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json
# Generate with CLI
cd packages/cli
bun run dev --input github.json --out ./servers/github --name github-mcp --runtime bun
# Configure environment
cd ./servers/github
cp .env.example .env
# Edit .env to add:
# API_BASE_URL=https://api.github.com
# GITHUB_TOKEN=your_token_here
示例4:自定义API(编程)
// generate-mcp.ts
import { generateServerFromOpenAPI } from "@aigentools/mcpgen-core";
async function generateMyAPI() {
try {
const result = await generateServerFromOpenAPI(
"./my-api-spec.yaml",
"./generated-servers/my-api",
"my-company-api",
{
runtime: "hono", // Generate Hono web server with multiple transports
force: true,
debug: true
}
);
console.log(`✅ Generated MCP server: ${result.name}`);
console.log(`📁 Location: ${result.outDir}`);
console.log(`🔧 Tools created: ${result.operations.length}`);
// List all generated tools
result.operations.forEach(op => {
console.log(` - ${op.operationId || op.method}: ${op.summary}`);
});
} catch (error) {
console.error("❌ Generation failed:", error);
}
}
// Run it
generateMyAPI();
示例5:现实世界的整合
# Step 1: Generate server
cd packages/cli
bun run dev --input ./specs/company-api.yaml --out ~/mcp-servers/company --name company-api
# Step 2: Test the server
cd ~/mcp-servers/company
bun --bun mcp-server/index.ts
# Step 3: Add to Claude Desktop
# Edit: ~/.claude_desktop_config.json
{
"mcpServers": {
"company-api": {
"command": "bun",
"args": ["--bun", "/Users/username/mcp-servers/company/mcp-server/index.ts"],
"env": {
"API_BASE_URL": "https://api.company.com/v1",
"API_KEY": "your-api-key"
}
}
}
}
# Step 4: Restart Claude Desktop and start using your API tools!
🔧 CLI使用情况
非交互式标志:
--input, -iOpenAPI规范路径(.yaml/.yml/.json)--output, --out, -o输出目录--name, -n服务器名称(默认为规范标题或文件名)--runtime, -r运行时间:bun(默认),node,或hono(HTTP+SSE+标准传输)--force, -f输出目录不为空时覆盖--config, -cYAML配置文件(见下文)--help, -h显示使用情况--version, -v显示版本
交互模式:
- 通过提示收集缺失的标志。
- 名称建议使用规范
info.title如果可用。 - 输出建议:
./servers/<slugified-name>. - 覆盖非空输出目录的确认(跳过
--force).
最小配置文件(--config mcpgen.config.yaml):
openapi: ./path/to/spec.yaml
name: my-mcp
# out dir can still be passed as --out; if omitted, defaults to "output"
发展
此monorepo使用 Turborepo 用于构建编排和缓存。所有命令都会自动处理包依赖关系,并以正确的顺序运行任务。
📦 发布和版本控制
有关发布包、版本管理和发布工作流的信息,请参阅 docs/releasing.md.
标准开发命令
# Build all packages (with dependency management via Turborepo)
bun run build
# Type check all packages
bun run typecheck
# Lint and format all packages (Biome v2)
bun run lint
bun run format
# Run tests across all packages
bun run test
# Target specific packages using Turborepo filters
bunx turbo run build --filter=@aigentools/mcpgen-core # Build core package only
bunx turbo run test --filter=@aigentools/mcpgen # Test CLI package only
bunx turbo run typecheck --filter=@workspace/* # Type check all workspace packages
任务文件快捷方式
如果你有 任务 安装后,使用这些方便的快捷方式:
# Basic development commands
task install # Install all dependencies
task build # Build all packages
task typecheck # Type check all packages
task test # Run all tests
# Package-specific builds (via Turborepo)
task build:core # Build core package only
task build:cli # Build CLI package only
task typecheck:core # Type check core only
task typecheck:cli # Type check CLI only
# Example workflows with Petstore
task gen:petstore # Generate Petstore MCP server
task install:petstore # Install dependencies in generated server
task test:gen:petstore # Generate and verify files exist
# Testing with Prism mock server + MCP Inspector
task prism:mock # Start Prism mock server
task prism:inspect:cli # Full workflow: generate → test with Inspector CLI
task prism:inspect:ui # Full workflow: generate → test with Inspector UI
task prism:smoke # Complete smoke test chain
Turborepo的好处
- 智能缓存:构建输出被缓存并在运行中重用
- 并行执行:任务尽可能并行运行
- 依赖意识:首先自动构建依赖关系
- 增量构建:只重建已更改的内容
# See what Turborepo will run
bunx turbo run build --dry-run
# Run with verbose logging
bunx turbo run test --verbose
# Clear Turborepo cache
bunx turbo prune
测试
- 单元测试在同一地点进行
*.test.ts近源。 - 测试跑步者:Bun测试。
- 运行所有测试:
bun run test. - 示例:
- 核心:YAML/JSON解析、名称建议、服务器生成
- CLI:arg解析、交互式提示流(模拟)、生成捆绑CLI的集成测试
🚀 生成的MCP服务器功能
您生成的MCP服务器包括:
- 🔧 单个MCP工具:每个OpenAPI操作都成为一个可调用的工具
- ✅ Zod验证:自动输入参数验证,并显示详细的错误消息
- 🛡️ 类型安全:具有适当接口的完全TypeScript支持
- 🔗 智能URL构建:自动路径参数替换和查询字符串处理
- 📝 申请机构:对POST/PUT/PATCH操作的JSON请求体支持
- ⚠️ 错误处理:具有有意义响应的全面HTTP错误处理
- 🌐 环境配置:可通过以下方式配置基本URL
API_BASE_URL环境变量 - 🔐 认证:通过标头内置API密钥支持
🌐 传输选项(运行时比较)
根据您的需求选择合适的运行时:
标准运行时(Bun/Node)- 建议用于Claude Desktop
- ✅ 标准运输:通过stdin/stdout直接进行进程通信
- ✅ 单个文件:一个
index.ts带有完整MCP服务器的文件 - ✅ 零设置:可立即与Claude Desktop配合使用
- ✅ 轻量级:最小依赖性
- ❌ 仅限于克劳德:无法通过HTTP/web访问
Hono运行时- 建议用于Web集成
- ✅ HTTP传输:处的RESTful API终结点
/mcp - ✅ SSE 运输:服务器在以下时间发送事件
/mcp/sse用于流媒体播放 - ✅ 标准运输:WebSocket模拟在
/mcp/stdio(实验) - ✅ Web兼容:从浏览器、web应用程序和HTTP客户端访问
- ✅ Docker就绪:包括Dockerfile,便于部署
- ✅ 健康检查:内置
/health监控端点 - ✅ 热重新加载:具有监视模式的开发服务器
- ❌ 复杂的:需要运行web服务器
- ❌ 网络依赖:需要网络连接
何时使用每个运行时:
在以下情况下选择标准(Bun/Node):
- 仅使用克劳德桌面
- 想要最简单的设置和部署
- 需要最少的资源使用
- 处理敏感数据(无网络暴露)
在以下情况下选择Hono:
- 使用MCP集成构建web应用程序
- 需要多个客户端访问(浏览器+Claude)
- 希望将MCP工具公开为HTTP API
- 部署到云/容器环境
- 需要监测和健康检查
🔍 故障排除
常见问题
Q: CLI显示“找不到命令”
# Make sure you've built the CLI first
cd packages/cli
bun run build
# Then use: bun run dev (from source) or node dist/index.js
Q: 生成的服务器无法连接到API
# Check your .env file in the generated server
cd your-generated-server
cat .env
# Make sure API_BASE_URL is correctly set
Q: OpenAPI规范验证失败
# The generator validates specs strictly. Common issues:
# - Missing required fields in OpenAPI spec
# - Invalid JSON/YAML syntax
# - Unsupported OpenAPI version (use 3.0+)
# Test your spec independently:
curl -o spec.json "your-api-spec-url"
# Or validate online: https://editor.swagger.io/
Q: MCP工具未在Claude Desktop中显示
# 1. Check Claude Desktop logs (Help > Developer Tools > Console)
# 2. Verify your claude_desktop_config.json syntax
# 3. Make sure paths are absolute, not relative
# 4. Test server independently:
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | bun --bun your-server/mcp-server/index.ts
Q: 生成的代码中存在TypeScript错误
# If you see TS errors, try:
cd your-generated-server
bun install # Install missing dependencies
# Or regenerate with --force flag
调试模式
启用调试日志以进行故障排除:
// Programmatic usage
await generateServerFromOpenAPI(spec, output, name, { debug: true });
# CLI usage - check console output for detailed logs
cd packages/cli
DEBUG=1 bun run dev --input spec.yaml --out ./output --name debug-server
📖 api参考
核心库功能
// Main generation function
function generateServerFromOpenAPI(
specPath: string,
outputDir: string,
serverName: string,
options?: {
runtime?: 'bun' | 'node';
force?: boolean;
debug?: boolean;
skipFormatting?: boolean;
}
): Promise<{
name: string;
outDir: string;
operations: Array<{
method: string;
path: string;
operationId?: string;
summary?: string;
}>;
}>;
// Utility functions
function slugify(text: string): string;
function suggestNameFromSpec(specPath: string): Promise<string>;
function readTitleFromSpec(specPath: string): Promise<string>;
🤝 贡献
我们欢迎捐款!拜托:
- 分叉存储库 并创建一个特征分支
- 遵循编码标准:
bun run lint # Check code style bun run typecheck # Validate TypeScript bun run test # Run all tests - 添加测试 对于新功能
- 更新文档 根据需要
- 提交拉取请求 描述清晰
开发设置
git clone https://github.com/beshkenadze/openapi-mcp-generator.git
cd openapi-mcp-generator
bun install
bun run build
bun run test # Make sure everything works
📄 许可证
MIT许可证-请参阅 许可证 了解详情。
🙏 致谢
- 内置于 包子 用于快速JavaScript运行时
- 用途 @标量/openapi解析器 用于健壮的OpenAPI解析
- 由...驱动 模型上下文协议 用于AI工具集成
- 通过以下方式生成代码 ts变形 用于精确的TypeScript AST操作