OpenAPI转MCP服务器生成器

将OpenAPI规范转换为生产就绪的TypeScript MCP服务器,具备AI代码生成和安全扫描功能。

  • by Matt-MFG
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 Matt-MFG/Magic-MCP

使用说明

🪄 魔法MCP

基于OpenAPI规范生成的企业级MCP服务器

将任何OpenAPI规范转换为生产就绪、完全类型化的TypeScript MCP服务器,利用AI驱动的代码生成和内置的安全扫描功能。

🌟 什么是Magic MCP?

Magic MCP能够自动根据OpenAPI规范生成模型上下文协议(MCP)服务器,从而实现:

  • ✅ 完全类型化的TypeScript代码 具有适当的响应类型和接口
  • ✅ 运行时验证 使用带有适当数组类型的Zod模式z.array(z.string()))
  • ✅(对号,表示正确、确认或完成) 自动化测试生成 使用 Vitest(GitHub API 通过 26 个测试)
  • ✅ OpenAPI 组件名称 保存的(Repository 不是 NestedType1)
  • ✅ 去重后的类型定义 使用 TypeScript 类型别名(代码减少40-60%)
  • ✅(对号,表示正确、确认或完成) 安全扫描 平均分为99/100
  • ✅ 基于人工智能的分析 使用Vertex AI Gemini进行模式洞察

🎯 快速入门

先决条件

  • Node.js 20+(版本)
  • npm 10及以上版本
  • Google Cloud账户(用于AI功能)

安装

# Clone repository
git clone https://github.com/YOUR_USERNAME/Magic-MCP.git
cd Magic-MCP

# Install dependencies
npm install

# Build all packages
npm run build

配置

创建一个 .env 文件:

GOOGLE_CLOUD_PROJECT=your-project-id
GOOGLE_CLOUD_LOCATION=us-central1
VERTEX_AI_MODEL=gemini-2.0-flash-exp
VERTEX_AI_LOCATION=us-central1
LOG_LEVEL=info

配置 Google Cloud:

gcloud config configurations create magic-mcp
gcloud auth login
gcloud config set project your-project-id
gcloud services enable aiplatform.googleapis.com
gcloud auth application-default login

生成您的第一个MCP服务器

# Generate from OpenAPI spec with tests
node packages/cli/dist/cli.js generate \
  examples/github-repos-api.yaml \
  --output my-mcp-server

# Build, test, and run the generated server
cd my-mcp-server
npm install
npm run build
npm test        # Run 26 generated tests!
npm start

🚀 特性

当前(第二阶段F部分已完成)

代码生成

  • ✅ 支持OpenAPI 2.0、3.0、3.1版本
  • ✅ 使用NodeNext解析的TypeScript ES模块
  • ✅ 使用Zod进行运行时验证,支持正确的数组类型(z.array(z.string()))
  • 携带者和API密钥认证
  • ✅ 路径、查询和正文参数处理
  • ✅ 支持请求体(JSON + 表单编码)

类型系统

  • ✅ 使用 TypeScript 接口生成响应类型
  • ✅ 嵌套模式提取(3+个属性)
  • ✅ 全局类型去重(代码减少40-60%)
  • ✅ OpenAPI 组件名称保留
  • ✅ 使用Zod模式提取数组项类型
  • ✅ 从OpenAPI描述中提取JSDoc注释

测试与质量

  • ✅ 自动化Vitest测试生成(为GitHub API生成26个测试)
  • ✅ 对所有端点进行输入验证测试
  • ✅ 参数处理测试(路径、查询、主体)
  • ✅ 错误处理和类型安全测试
  • ✅ 基于AI的模式分析(Vertex AI Gemini)
  • ✅ 安全扫描(涵盖10+类漏洞,平均得分为99/100)
  • ✅ 循环引用处理
  • ✅ 更美观的代码格式化
  • ✅ TypeScript 严格模式编译(100% 成功率)

生成的代码示例

输入带有(或:配以)OpenAPI规范 components/schemas/Repository

输出:

// Component name preserved!
export interface Repository {
  /** Unique identifier of the repository */
  id: number;
  /** The name of the repository */
  name: string;
  /** Simple User */
  owner: { login: string; id: number };
  // ... 20 properties with JSDoc
}

// Array response uses the component type
export type ListForAuthenticatedUserResponse = Repository[];

// Duplicate responses use type aliases (no duplication!)
export type CreateForAuthenticatedUserResponse = Repository;
export type GetResponse = Repository;
export type UpdateResponse = Repository;

// Zod schema for nested type (for validation)
export const RepositorySchema = z.object({
  id: z.number().describe('Unique identifier'),
  name: z.string().describe('The name of the repository'),
  owner: z.object({ login: z.string(), id: z.number() }),
  // ... full validation
});

// Zod validation with enum and array support
const ReposListSchema = z.object({
  visibility: z.enum(['all', 'public', 'private']).optional(),
  tags: z.array(z.string()).optional(),  // Proper array types!
  ids: z.array(z.number()).optional(),
});

// Fully-typed client method
async reposListForAuthenticatedUser(
  params: z.infer<typeof ReposListSchema>
): Promise<ListForAuthenticatedUserResponse> {
  // Implementation with type safety
}

// Generated tests (26 tests for GitHub API)
describe('repos_list_for_authenticated_user', () => {
  it('should validate input schema correctly', () => { ... });
  it('should build query parameters correctly', () => { ... });
  // ... 24 more tests
});

📊 生成质量

经与……一起测试:

  • 宠物商店API(基本的CRUD操作)
  • ✅ GitHub API(1,350个端点)
  • ✅ Stripe API(572个端点,6.8MB规范)

质量指标:

  • TypeScript 编译:100% 成功率
  • 安全评分:平均99/100
  • 代码缩减:通过去重达到40-60%
  • 生成时间:典型API < 15秒

🏗️ 建筑学

packages/
├── cli/              # Command-line interface (Commander.js)
├── parser/           # OpenAPI parser (@apidevtools/swagger-parser)
├── generator/        # Code generator (Handlebars + Vertex AI)
├── security/         # Security scanner (10+ categories)
└── shared/           # Shared types and utilities

数据流:

OpenAPI Spec → Parser → AI Analysis → MCP Spec → Template → Generated Code → Security Scan

🔒 安全

Magic MCP 默认生成安全代码:

  • 输入验证Zod schema 验证所有输入
  • 类型安全完整的 TypeScript 严格模式
  • 认证承载令牌和API密钥支持
  • 安全扫描自动漏洞检测
  • 最佳实践生成的代码遵循MCP SDK的模式

已检查的安全类别:

  • 缺少认证详情
  • 输入验证不足
  • 缺少授权检查
  • 缺乏速率限制
  • 潜在的信息泄露
  • 缺少审计日志记录
  • XSS(跨站脚本)漏洞
  • 跨站请求伪造(CSRF)保护

📚 文档

入门指南:

阶段文档:

📦 包裹

包 描述 状态
@magic-mcp/cli 命令行界面 ✅ 正常工作
@magic-mcp/generator 基于AI的代码生成器 ✅ 正常运行
@magic-mcp/parser OpenAPI 模式解析器 ✅ 正常工作
@magic-mcp/security 安全扫描 ✅ 正常运行
@magic-mcp/shared 共享类型和实用工具 ✅ 正常运行

🗺️ 路线图

✅ 第一阶段:基础(已完成)

  • ✅ 使用 Turborepo 设置单体仓库
  • ✅ OpenAPI 解析器(v2.0、v3.0、v3.1)
  • ✅ 基于模板的代码生成
  • ✅ 命令行界面(CLI)工具

✅ 第二阶段A:人工智能生成质量(已完成)

  • ✅ 正确的Zod类型映射
  • ✅ 路径参数替换
  • ✅ 类名净化
  • ✅ 请求体提取

阶段2B:真实世界API测试(已完成)

  • ✅ Stripe API(572个端点)
  • ✅ GitHub API(1,350个端点)
  • ✅ Zod模式中的枚举支持
  • ✅ 正确的OpenAPI描述

✅ 第二阶段C:响应类型与高级功能(已完成)

  • ✅ TypeScript 响应类型生成
  • ✅ 嵌套模式提取(3+个属性)
  • ✅ 响应类型去重
  • ✅ OpenAPI 组件名称保留
  • ✅ 数组项类型提取
  • ✅ 循环引用处理

🔄 第二阶段D:下一步行动(计划中)

  • [ ] Zod 数组模式(z.array(ItemSchema))
  • [ ] 测试生成(Vitest)
  • [ ] 多云部署(Cloud Run、Lambda、Workers)

🔮 第三阶段:智能平台(未来)

  • [ ] MCP发现与搜索
  • [ ] 差距分析工具
  • [ ] 功能建议和改进

看 claude.md(文件名,可理解为“克劳德的Markdown文件”或保持原样,具体翻译取决于上下文和使用场景) 以了解详细的发展重点。

🤝 贡献(或“参与贡献”)

我们欢迎投稿!请参阅 CONTRIBUTING.md 翻译为中文是:“贡献指南/文件”。这个文件通常用于说明如何向项目贡献代码或内容,包括贡献的流程、规范、要求等 for:

  • 安装说明
  • 测试与评估标准
  • 拉取请求流程
  • 错误报告模板
  • 功能需求指南

快速测试:

npm run build
node packages/cli/dist/cli.js generate examples/github-repos-api.yaml --output test
cd test && npm run build  # Should compile without errors

💻 CLI 参考手册

# Generate MCP server
node packages/cli/dist/cli.js generate <spec-path> [options]

Options:
  --output <dir>     Output directory (default: ./output)
  --name <name>      Custom MCP server name
  --no-tests         Skip test generation
  --project <id>     Google Cloud project ID
  --location <loc>   Vertex AI location (default: us-central1)

# Examples
node packages/cli/dist/cli.js generate https://api.stripe.com/openapi.yaml
node packages/cli/dist/cli.js generate examples/github-repos-api.yaml --output my-server
node packages/cli/dist/cli.js generate spec.json --no-tests --name my-api

🧪 测试

运行评估套件,从 CONTRIBUTING.md 翻译为中文是:“贡献指南.md” 或 “如何贡献.md”,具体翻译可能根据上下文略有调整,但基本意思是指向一个关于如何为项目做出贡献的指南或说明文件:

# 1. Code Generation Quality
npm run build
node packages/cli/dist/cli.js generate examples/github-repos-api.yaml --output test
cd test && npm run build  # Should succeed

# 2. Component Name Preservation
grep "export interface Repository" test/src/index.ts  # Should find

# 3. Type Safety
grep -c "Promise<unknown>" test/src/index.ts  # Should be minimal

# 4. Security Score
# Check CLI output for "Security scan passed (score: XX/100)"

📊 性能

构建时间~1.5秒(使用Turborepo缓存)

世代时间(或繁殖代数时间):

  • 简单API(5个端点):约10秒
  • Medium API(50个端点):~15秒
  • 大型API(500个端点):~30秒

生成的代码大小:

  • 典型API:10-30KB TypeScript
  • 大型API:50-100KB TypeScript
  • 通过去重减少40%-60%

🙏 致谢

构建于:

📄 许可证

MIT 许可证 - 请参阅 许可证 详情如下。

📞 联系方式


当前状态第二阶段C完成 - 准备就绪的TypeScript MCP生成,具备完整的类型安全性、组件名称保留以及企业级安全扫描功能。

用心与Claude代码打造