OpenAPI转换工具

将OpenAPI规范转换为MCP(模型上下文协议)服务器,使AI助手能够与API交互。

  • by longcipher
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 longcipher/openapi-mcp

使用说明

openapi mcp

将OpenAPI规范转换为MCP(模型上下文协议)服务器。该工具根据您的OpenAPI规范自动生成MCP工具,允许像Claude这样的AI助手与您的API进行交互。

特性

  • 🔄 自动生成刀具 -将OpenAPI操作转换为MCP工具
  • � API动态注册 -在运行时注册和管理多个API
  • 🔍 语义搜索 -使用自然语言查询查找相关端点
  • 📊 依赖性检测 -自动发现端点依赖关系
  • ⚡ 工作流执行 -使用数据流执行多步骤API工作流
  • 📁 多个输入源 -从本地文件或URL加载规格
  • 📋 格式支持 -JSON、YAML和TOML格式
  • 🔧 灵活的配置 -覆盖基本URL、添加标头、设置超时
  • 🔐 身份验证支持 -API密钥、承载令牌、基本身份验证、OAuth2
  • 💻 轻松集成 -与Claude Desktop、VS Code和任何MCP客户端兼容

安装

使用npm

npm install -g @longcipher/openapi-mcp

使用Bun

bun add -g @longcipher/openapi-mcp

来源

git clone https://github.com/longcipher/openapi-mcp.git
cd openapi-mcp
bun install
bun run build

快速开始

静态模式(单个API)

使用预定义的工具提供单个OpenAPI规范:

# From a local file
openapi-mcp serve ./api.yaml

# From a URL
openapi-mcp serve https://petstore3.swagger.io/api/v3/openapi.json

# With custom base URL
openapi-mcp serve ./api.yaml --base-url https://api.example.com/v2

# With authentication header
openapi-mcp serve ./api.yaml --header "Authorization: Bearer token123"

# With verbose logging
openapi-mcp serve ./api.yaml --verbose

动态模式(多个API)

以动态模式启动,在运行时注册和管理多个API:

# Start in dynamic mode
openapi-mcp dynamic

# With custom data directory
openapi-mcp dynamic --data-dir ~/.my-openapi-mcp

# Using the default command (no source = dynamic mode)
openapi-mcp --dynamic

在动态模式下,服务器公开这些工具:

工具 说明
register_api 注册一个新的OpenAPI规范(解析、索引、创建嵌入)
unregister_api 删除已注册的API
list_apis 列出所有已注册的API
search_endpoints 使用自然语言对端点进行语义搜索
get_endpoint 获取详细的端点信息
expand_dependencies 获取端点及其所需的依赖关系
execute_endpoint 执行单个API调用
execute_workflow 执行多步骤API工作流
set_auth 为API配置身份验证

CLI选项

Usage: openapi-mcp [options] [command] [source]

Commands:
  serve <source>    Start MCP server with a single OpenAPI spec (static mode)
  dynamic           Start MCP server in dynamic mode (register APIs at runtime)

Options:
  -V, --version               output the version number
  -b, --base-url <url>        Override the base URL for API requests
  -H, --header <header...>    Add custom headers (format: 'Name: Value')
  -t, --timeout <ms>          Request timeout in milliseconds (default: "30000")
  -n, --name <name>           Server name (default: "openapi-mcp")
  -v, --verbose               Enable verbose logging
  -d, --dynamic               Start in dynamic mode (no source required)
  --data-dir <path>           Data directory for dynamic mode
  -h, --help                  display help for command

与MCP客户端集成

克劳德桌面

添加到您的Claude Desktop配置(~/Library/Application Support/Claude/claude_desktop_config.json 在macOS上):

静态模式(单个API):

{
  "mcpServers": {
    "petstore": {
      "command": "openapi-mcp",
      "args": [
        "serve",
        "https://petstore3.swagger.io/api/v3/openapi.json"
      ]
    },
    "my-api": {
      "command": "openapi-mcp",
      "args": [
        "serve",
        "/path/to/my-api.yaml",
        "--base-url", "https://api.myservice.com",
        "--header", "Authorization: Bearer ${API_TOKEN}"
      ],
      "env": {
        "API_TOKEN": "your-token-here"
      }
    }
  }
}

动态模式(运行时有多个API):

{
  "mcpServers": {
    "api-hub": {
      "command": "openapi-mcp",
      "args": ["dynamic"]
    }
  }
}

然后使用自然语言进行交互:

  • “从注册Petstore APIhttps://petstore3.swagger.io/api/v3/openapi.json"
  • “搜索端点以创建新宠物”
  • “显示GET/pets/{petId}的依赖关系”
  • “执行POST/pets,名称=‘最大’,状态=‘可用’”

VS代码与副本

添加到您的VS代码设置或 .vscode/mcp.json:

静态模式:

{
  "mcp": {
    "servers": {
      "petstore": {
        "command": "openapi-mcp",
        "args": ["serve", "https://petstore3.swagger.io/api/v3/openapi.json"]
      }
    }
  }
}

动态模式:

{
  "mcp": {
    "servers": {
      "api-hub": {
        "command": "openapi-mcp",
        "args": ["dynamic"]
      }
    }
  }
}

与npx一起使用

您可以在不全局安装的情况下运行:

{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y",
        "@longcipher/openapi-mcp",
        "serve",
        "https://example.com/api.yaml"
      ]
    }
  }
}

动态模式详解

动态模式将openapi-mcp从单API服务器转换为多API编排平台。API在运行时注册,为语义搜索建立索引,并可供执行。

工作流示例

  1. 注册API:

    User: Register the GitHub API from https://api.github.com/openapi.json
    Claude: [calls register_api] ✓ Registered "GitHub API" with 245 endpoints
    
  2. 搜索端点:

    User: Find endpoints to list repository issues
    Claude: [calls search_endpoints] Found:
      - GET /repos/{owner}/{repo}/issues (0.92)
      - GET /repos/{owner}/{repo}/issues/{issue_number} (0.85)
    
  3. 探索依赖关系:

    User: What do I need to call before GET /repos/{owner}/{repo}/issues/{issue_number}?
    Claude: [calls expand_dependencies] Execution order:
      1. GET /repos/{owner}/{repo}/issues (to get issue_number)
      2. GET /repos/{owner}/{repo}/issues/{issue_number}
    
  4. 设置身份验证:

    User: Set my GitHub token
    Claude: [calls set_auth] ✓ Configured bearer authentication for GitHub API
    
  5. 执行:

    User: Get issues for facebook/react
    Claude: [calls execute_endpoint] Retrieved 30 issues...
    

本地嵌入

动态模式通过以下方式使用本地嵌入 @huggingface/transformers 随着 Xenova/all-MiniLM-L6-v2 模型。这意味着:

  • 不需要API密钥 -一切都在本地运行
  • 隐私 -您的API规格永远不会离开您的机器
  • 离线功能 -首次模型下载后无需互联网即可工作
  • 快速 -针对语义搜索优化的384维嵌入

数据存储

默认情况下,数据存储在 ~/.openapi-mcp/:

  • specs/ -原始OpenAPI规范
  • endpoints/ -解析的端点数据
  • graphs/ -依赖关系图
  • vectors/ -嵌入向量

使用 --data-dir 以定制存储位置。

支持的OpenAPI功能

运营

  • 所有HTTP方法:GET、POST、PUT、DELETE、PATCH、OPTIONS、HEAD
  • 操作ID转换为snake_case工具名称
  • 回退到 {method}_{path} 当operationId缺失时

参数

  • 路径参数 -在URL中自动替换
  • 查询参数 -添加为URL查询字符串
  • 标头参数 -作为请求标头添加
  • 请求体 -以JSON或表单数据形式发送

模式

  • 基本类型(字符串、数字、整数、布尔值)
  • 数组和对象
  • 枚举
  • 格式提示(电子邮件、日期时间等)
  • 必填字段验证

例子

API宠物店

openapi-mcp examples/petstore.yaml

这暴露了以下工具:

  • add_pet -将新宠物添加到商店
  • find_pets_by_status -按状态查找宠物
  • get_pet_by_id -通过宠物ID获得宠物
  • delete_pet -删除宠物

API HTTPBin

openapi-mcp examples/httpbin.json

这暴露了以下工具:

  • http_get -发出GET请求
  • http_post -发出POST请求
  • get_ip -获取您的IP地址
  • get_uuid -生成UUID

发展

先决条件

设置

# Clone the repository
git clone https://github.com/longcipher/openapi-mcp.git
cd openapi-mcp

# Install dependencies
bun install

# Build
bun run build

# Run tests
bun test

# Lint & format
bun run lint
bun run format

项目结构

openapi-mcp/
├── src/
│   ├── index.ts           # Main entry point
│   ├── cli.ts             # CLI implementation
│   ├── logger.ts          # Logging utilities
│   ├── errors.ts          # Error definitions
│   ├── types/             # Core type definitions
│   │   └── index.ts       # Endpoint, Graph, Workflow types
│   ├── loader/            # Spec loading module
│   │   ├── types.ts       # OpenAPI type definitions
│   │   ├── parser.ts      # Format detection & parsing
│   │   ├── file-loader.ts # Local file loading
│   │   ├── url-loader.ts  # URL loading
│   │   └── index.ts       # Module exports
│   ├── adapter/           # OpenAPI to MCP adapter
│   │   ├── types.ts       # MCP type definitions
│   │   ├── openapi-adapter.ts
│   │   └── index.ts
│   ├── ingestion/         # API parsing and indexing
│   │   ├── parser.ts      # Enhanced OpenAPI parser
│   │   ├── graph-builder.ts # Dependency graph construction
│   │   ├── embedder.ts    # Local embedding generation
│   │   └── index.ts
│   ├── stores/            # Persistence layer
│   │   ├── spec-store.ts  # API spec storage
│   │   ├── graph-store.ts # Dependency graph storage
│   │   ├── vector-store.ts # Embedding vector storage
│   │   └── index.ts
│   ├── retrieval/         # Search and ranking
│   │   ├── vector-search.ts # Semantic search
│   │   ├── graph-expander.ts # Dependency expansion
│   │   ├── reranker.ts    # Result reranking
│   │   └── index.ts
│   ├── execution/         # API execution
│   │   ├── schema-formatter.ts # Endpoint formatting
│   │   ├── auth-handler.ts # Authentication handling
│   │   ├── http-executor.ts # HTTP request execution
│   │   ├── workflow-executor.ts # Multi-step workflows
│   │   └── index.ts
│   ├── mcp/               # MCP integration
│   │   ├── tools.ts       # Dynamic API tools
│   │   ├── resources.ts   # API resources
│   │   └── index.ts
│   └── server/            # MCP server implementation
│       ├── mcp-server.ts  # Static & dynamic servers
│       └── index.ts
├── tests/                 # Test files
├── examples/              # Example OpenAPI specs
└── docs/                  # Documentation

运作原理

  1. 负载 -从文件或URL读取OpenAPI规范
  2. 解析 -检测格式(JSON/YAML/TOML)并验证规范
  3. 转换 -将OpenAPI操作转换为MCP工具定义
  4. 服务 -通过STDIO传输启动MCP服务器
  5. 执行 -当调用工具时,发出实际的HTTP请求

故障排除

常见问题

“找不到工具”错误

  • 检查operationId是否匹配(转换为snake_case)
  • 与一起跑步 --verbose 查看可用工具

连接超时

  • 增加超时时间 --timeout 60000 (60秒)
  • 检查与API的网络连接

身份验证错误

  • 添加身份验证标头 --header "Authorization: Bearer token"
  • 确保令牌有效且未过期

规格错误无效

  • 确保规范是有效的OpenAPI 3.0.x
  • 检查YAML/JSON/TOML中的语法错误

调试模式

运行详细日志记录以查看详细信息:

openapi-mcp ./api.yaml --verbose

贡献

欢迎投稿!请随时提交拉取请求。

许可证

Apache许可证2.0-请参阅 许可证 了解详情。