MCP服务器生成器

MCPGen是一个自动化CLI工具,能够从OpenAPI规范生成生产就绪的模型上下文协议(MCP)服务器,支持AI增强文档和示例生成,适用于快速集成AI助手。

  • by Fato07
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 Fato07/MCP-server-generator

使用说明

MCPGen-自动模型上下文协议服务器生成器

MCPGen 是一个生成生产就绪的自动化CLI工具 模型上下文协议(MCP)服务器 来自OpenAPI规范。在几秒钟内将现有的REST API转换为MCP兼容的服务器 人工智能驱动的文档和示例,实现与Claude Desktop、ChatGPT和其他语言模型等人工智能助手的无缝集成。

🚀 快速开始

# Install globally for easy access
npm link

# Generate your first MCP server
mcpgen new my-weather-server \
  --input examples/weather-api.yaml \
  --language typescript

# 🤖 Generate with AI enhancements (NEW!)
export ANTHROPIC_API_KEY="your-api-key"
mcpgen new my-weather-server \
  --input examples/weather-api.yaml \
  --enhance-docs \
  --generate-examples \
  --llm-provider anthropic

# Test the generated server
cd my-weather-server
npm install && npm run build && npm start

📋 目录

✨ 特性

核心能力

  • 🔄 OpenAPI到MCP的转换:将REST API规范转换为MCP服务器
  • 🎯 多语言支持:TypeScript(已准备就绪)、Python和Go(即将推出)
  • 🛠️ 生产就绪:生成的服务器包括正确的错误处理、验证和文档
  • ⚡ 快速生成:在10秒内完成MCP服务器
  • 🔍 全面验证:从OpenAPI合规性到MCP协议合规性的多层验证

🤖 AI智能层(新增!)

  • 📚 增强文档:AI驱动的自述文件、工具文档和API参考资料
  • 💡 MCP特定代码示例:具有正确MCP SDK使用的服务器端实现
  • 🧠 多种LLM支持:OpenAI GPT-4、Anthropic Claude和当地Ollama模型
  • 💰 成本优化:90%以上的令牌减少和语义缓存,可节省30-60%的成本
  • 🔒 隐私选项:与Ollama就敏感项目进行本地推理
  • ⚡ 快速生成:通过智能提示工程在15-30秒内完成
  • 🎯 上下文感知:生成MCP服务器代码,而不是REST客户端代码

生成的功能

  • MCP工具:通过API操作自动生成工具
  • 参数验证:带运行时验证的类型安全参数处理
  • 错误处理:通过有意义的消息进行稳健的错误处理
  • 文档:自动生成的带有工具说明的README
  • Docker支持:容器配置便于部署
  • TypeScript类型:具有生成接口的全类型安全

📦 安装

先决条件

  • Node.js 18+
  • pnpm(推荐)或npm

开发设置

# Clone the repository
git clone https://github.com/your-org/mcp-server-generator.git
cd mcp-server-generator

# Install dependencies
pnpm install

# Build all packages
pnpm build

# Run tests (when available)
pnpm test

全球安装(未来)

# Once published to npm
npm install -g mcpgen
mcpgen --version

🎮 用法

基础世代

# Generate a TypeScript MCP server
node packages/cli/dist/cli.js new my-api-server \
  --input ./my-openapi.yaml \
  --language typescript \
  --output ./servers

# Generate with authentication
node packages/cli/dist/cli.js new secure-api \
  --input ./api-spec.json \
  --auth apikey \
  --template enterprise

🤖 人工智能增强一代

通过AI驱动的文档和示例,将您的API规范转换为专业MCP服务器:

# Enhanced documentation with Anthropic Claude
export ANTHROPIC_API_KEY="your-api-key"
node packages/cli/dist/cli.js new my-api-server \
  --input ./my-openapi.yaml \
  --enhance-docs \
  --llm-provider anthropic

# Full AI enhancement with examples
node packages/cli/dist/cli.js new my-api-server \
  --input ./my-openapi.yaml \
  --enhance-docs \
  --generate-examples \
  --llm-provider anthropic \
  --max-cost 0.50

# Using OpenAI for complex APIs
export OPENAI_API_KEY="your-api-key"
node packages/cli/dist/cli.js new complex-api \
  --input ./complex-spec.yaml \
  --enhance-docs \
  --generate-examples \
  --llm-provider openai \
  --llm-model gpt-4-turbo

# Local AI with Ollama (free and private)
# First: Install Ollama and run 'ollama serve'
node packages/cli/dist/cli.js new my-api-server \
  --input ./my-openapi.yaml \
  --enhance-docs \
  --llm-provider ollama \
  --llm-model codellama

AI功能包括:

  • 📖 专业README 附带安装指南和使用示例
  • 🛠️ 工具文档 附有详细的参数描述和示例
  • 📝 代码示例 具有现实的参数和错误处理
  • 🚨 错误指南 故障排除和最佳实践
  • 📊 api参考 具有全面的端点文档

交互模式

# Use interactive prompts for configuration
node packages/cli/dist/cli.js new my-server --interactive

验证

# Validate an OpenAPI specification
node packages/cli/dist/cli.js validate ./openapi-spec.yaml

# Validate a generated MCP server
node packages/cli/dist/cli.js validate ./generated-server/

# Detailed validation with verbose output
node packages/cli/dist/cli.js validate ./server --verbose --format json

📚 CLI命令

mcpgen new <project-name>

根据OpenAPI规范生成新的MCP服务器。

核心选项:

  • -i, --input <file> -OpenAPI规范文件(JSON或YAML) [必填]
  • -l, --language <lang> -目标语言: typescript, python, go (默认值: typescript)
  • -t, --template <name> -要使用的模板: basic, enterprise, minimal (默认值: basic)
  • -o, --output <dir> -输出目录(默认:当前目录)
  • -a, --auth <type> -身份验证类型: none, oauth, apikey, jwt (默认值: none)
  • --interactive -使用带有提示的交互模式
  • -v, --verbose -启用详细输出

🤖 AI增强选项:

  • --enhance-docs -启用基于AI的文档增强功能
  • --generate-examples -生成AI驱动的代码示例
  • --llm-provider <provider> -LLM提供者: openai, anthropic, ollama (默认值: anthropic)
  • --llm-model <model> -要使用的特定LLM模型(例如。, gpt-4-turbo, claude-3-5-sonnet)
  • --llm-api-key <key> -LLM提供程序的API密钥(或使用环境变量)
  • --enable-cache -启用语义缓存以降低成本(默认值: true)
  • --max-cost <amount> -人工智能功能的最大成本限制(默认值: 1.00)

示例:

# Basic generation
mcpgen new weather-api --input ./weather.yaml

# With authentication and custom output
mcpgen new secure-api \
  --input ./api.json \
  --auth oauth \
  --output ./my-servers \
  --template enterprise

# Interactive mode
mcpgen new my-api --interactive

mcpgen validate [target]

验证OpenAPI规范或MCP服务器项目。

选项:

  • -s, --strict -启用严格验证模式
  • -f, --format <type> -输出格式: table, json (默认值: table)
  • -v, --verbose -显示详细的验证信息

示例:

# Validate OpenAPI specification
mcpgen validate ./openapi.yaml

# Validate generated MCP server
mcpgen validate ./my-server/

# Strict validation with JSON output
mcpgen validate ./api.yaml --strict --format json

mcpgen add <component> <name>

向现有MCP服务器添加组件(即将推出)。

组件:

  • tool -添加新工具
  • resource -添加新资源
  • prompt -添加新提示

mcpgen deploy [options]

生成部署配置(即将推出)。

目标:

  • docker -生成docker文件和docker编写
  • railway -铁路部署配置
  • vercel -Vercel部署配置

mcpgen dev [directory]

使用热重载启动开发服务器(即将推出)。

🆕 最近的改进

版本1.1.0-AI智能层

  • ✅ AI上下文修复:示例现在生成正确的MCP服务器代码,而不是REST客户端代码
  • ✅ 模板修复:生成的服务器现在构建时没有错误(修复了缺失的导入)
  • ✅ 悬而未决的问题已解决:CLI现在可以在AI生成完成后正确退出
  • ✅ 多种LLM支持:添加了OpenAI、Anthropic Claude和Ollama提供商支持
  • ✅ 成本优化:实施语义缓存和令牌减少策略
  • ✅ 提示工程:增强的提示生成上下文感知的MCP服务器实现

1.0.0版本-核心基础

  • ✅ OpenAPI到MCP的转换:完整的转换管道
  • ✅ TypeScript支持:具有生成接口的全类型安全
  • ✅ 验证系统:从OpenAPI到MCP合规性的多层验证
  • ✅ CLI接口:具有交互模式的综合命令行界面

📖 例子

示例1:天气API服务

使用附带的天气API示例:

# Generate weather MCP server
node packages/cli/dist/cli.js new weather-service \
  --input examples/weather-api.yaml \
  --language typescript \
  --auth apikey \
  --output ./examples/generated

cd examples/generated/weather-service
npm install
npm run build
npm start

生成的工具:

  • getCurrentWeather -获取某个地点的当前天气
  • getWeatherForecast -获取多日天气预报
  • getWeatherAlerts -获取活动天气警报
  • searchLocations -按名称搜索位置
  • getWeatherHistory -获取历史天气数据
  • getAirQuality -获取空气质量信息

示例2:电子商务API

# ecommerce-api.yaml
openapi: 3.0.3
info:
  title: E-commerce API
  version: 1.0.0
paths:
  /products:
    get:
      operationId: getProducts
      summary: List products
      parameters:
        - name: category
          in: query
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Products list
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Product'
components:
  schemas:
    Product:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        price:
          type: number
# Generate e-commerce MCP server
mcpgen new ecommerce-api \
  --input ./ecommerce-api.yaml \
  --template enterprise \
  --auth oauth

🏗️ 建筑

MCPGen遵循 微内核体系结构 明确区分关注点:

mcpgen/
├── packages/
│   ├── core/                   # Core generation engine
│   │   ├── src/
│   │   │   ├── parsers/        # OpenAPI parsing logic
│   │   │   ├── generators/     # Code generation
│   │   │   ├── templates/      # Template management
│   │   │   ├── validators/     # Validation logic
│   │   │   └── types/          # Type definitions
│   │   └── package.json
│   ├── cli/                    # CLI interface
│   │   ├── src/
│   │   │   ├── commands/       # CLI commands
│   │   │   └── utils/          # CLI utilities
│   │   └── package.json
│   └── templates/              # Template library
│       ├── src/
│       └── templates/          # Template files
├── examples/                   # Example specifications
└── docs/                       # Documentation

核心组件

OpenAPI解析器 (@mcpgen/core)

  • 解析OpenAPI 3.x规范(JSON/YAML)
  • 解决 $ref 引用和模式定义
  • 提取工具、资源和参数
  • 验证规范合规性

模板引擎 (@mcpgen/core)

  • 基于Handlebars的模板与自定义助手
  • 特定语言代码生成
  • 自定义模板的可扩展插件系统
  • 用于类型转换和验证的内置帮助程序

CLI接口 (@mcpgen/cli)

  • 基于Commander.js的命令结构
  • 交互式和非交互式模式
  • 全面的错误处理和验证
  • 配置文件支持

模板库 (@mcpgen/templates)

  • TypeScript、Python、Go的预构建模板
  • 项目结构模板
  • 组件模板(工具、资源、提示)
  • 部署配置模板

⚙️ 配置

配置文件

创建一个 mcpgen.config.json 项目根目录中的文件:

{
  "language": "typescript",
  "template": "enterprise",
  "plugins": ["@mcpgen/auth-plugin"],
  "validation": {
    "strict": true,
    "mcp_version": "2025-03-26"
  },
  "deployment": {
    "target": "docker",
    "registry": "ghcr.io"
  }
}

环境变量

# Default language for generation
MCPGEN_DEFAULT_LANGUAGE=typescript

# Default template
MCPGEN_DEFAULT_TEMPLATE=basic

# Enable debug logging
MCPGEN_DEBUG=true

🛠️ 发展

项目结构

mcpgen/
├── packages/           # Monorepo packages
├── examples/           # Example OpenAPI specs
├── docs/              # Documentation
├── tests/             # Integration tests
├── pnpm-workspace.yaml
├── package.json
├── tsconfig.json
└── README.md

从源头构建

# Install dependencies
pnpm install

# Build all packages
pnpm build

# Run linting
pnpm lint

# Format code
pnpm format

# Clean build artifacts
pnpm clean

运行测试

# Run all tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Run specific package tests
pnpm --filter @mcpgen/core test

添加新模板

  1. 在中创建模板文件 packages/templates/templates/
  2. 在中注册模板 packages/templates/src/index.ts
  3. 如果需要,添加特定于模板的帮助程序
  4. 更新文档

添加新语言

  1. 在中创建特定语言的生成器 packages/core/src/generators/
  2. 在中添加语言模板 packages/templates/
  3. 更新CLI语言验证
  4. 添加测试和文档

📚 文档

综合指南

快速参考

  • CLI命令:上面记录的所有命令及其示例
  • OpenAPI支持:完全支持OpenAPI 3.0.x规范
  • MCP合规性:生成的服务器遵循MCP协议规范
  • 环境变量:所有功能的配置选项

示例和教程

  • 基本用法:参见 例子 以上章节
  • 高级模式:检查 examples/ 真实世界规格目录
  • 集成示例:如何连接Claude Desktop和其他人工智能助手

Claude代码集成

  • 自定义命令 -Slash命令用于即时项目上下文
  • 发展背景:针对不同工作区域的预配置命令
  • 团队入职培训:为新贡献者快速加载上下文

🤝 贡献

我们欢迎捐款!请查看我们的 贡献指南 了解详情。

开发工作流程

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/amazing-feature
  3. 加载项目上下文:使用 /project:context 在Claude Code中实现即时理解
  4. 进行更改并添加测试
  5. 运行测试套件: pnpm test
  6. 提交您的更改: git commit -m 'Add amazing feature'
  7. 推到分支: git push origin feature/amazing-feature
  8. 打开拉取请求

Claude代码设置

如果您使用的是Claude Code,请利用自定义命令:

# Get complete project context
/project:context

# Working on specific areas
/project:ai      # AI intelligence features
/project:core    # Core generation engine  
/project:cli     # Command-line interface
/project:debug   # Troubleshooting issues
/project:test    # Testing and validation

代码的风格

  • 遵循TypeScript的最佳实践
  • 使用Prettier进行格式化: pnpm format
  • 棉绒编码: pnpm lint
  • 为新功能编写测试
  • 更新面向用户的更改文档

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

🙏 致谢

🔗 链接


MCPGen -弥合现有API和MCP生态系统之间的差距。在几秒钟内生成生产就绪的MCP服务器,而不是几小时。