OpenAPI MCP桥接服务

一个通用的MCP服务器,可将任何OpenAPI/Swagger规范暴露为MCP工具,允许AI助手搜索、探索和执行任何REST API。

  • by samuellawrence
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 samuellawrence/openapi-mcp-bridge

使用说明

OpenAPI MCP桥

一个通用的MCP服务器,采用任何OpenAPI/Swagger规范并将其公开为MCP工具,允许AI助手搜索、探索和执行任何REST API。

建筑学

                                    +------------------+
                                    |   Claude / AI    |
                                    +--------+---------+
                                             |
                                             | MCP Protocol
                                             v
+------------------------------------------------------------------+
|                      OpenAPI MCP Bridge                          |
|                                                                  |
|  +-------------+    +-------------+    +------------------+      |
|  |   Config    |    |   Parser    |    |    Registry      |      |
|  | (apis.json) |--->| (OpenAPI)   |--->| (API endpoints)  |      |
|  +-------------+    +-------------+    +------------------+      |
|                                                 |                |
|  +-------------+    +-------------+    +--------v---------+      |
|  | Guardrails  |    |   Search    |    |    Executor      |      |
|  | (safety)    |    |  (fuzzy)    |    |    (httpx)       |      |
|  +-------------+    +-------------+    +------------------+      |
|                                                 |                |
+------------------------------------------------------------------+
                                                  |
                                                  v
                                    +------------------+
                                    |    REST APIs     |
                                    | (Petstore, etc)  |
                                    +------------------+

快速开始

安装

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

# Install with uv
uv sync --all-extras

# Or with pip
pip install -e ".[dev]"

注册API

编辑 config/apis.json 添加您的API:

{
  "apis": [
    {
      "name": "my-api",
      "spec_url": "https://api.example.com/openapi.json",
      "base_url": "https://api.example.com",
      "auth": {
        "type": "bearer",
        "token": "$MY_API_TOKEN",
        "header_name": "Authorization"
      },
      "settings": {
        "default_page_size": 20,
        "confirm_destructive": true
      }
    }
  ]
}

Xquik API示例

对于真正经过验证的OpenAPI 3.1 API,请复制 config/xquik.apis.example.json 到您的活动配置和设置 XQUIK_API_KEY该示例为X/Twitter注册了Xquik的公共规范 自动化、趋势、推特搜索、媒体、监控和webhook端点。

运行服务器

# Run with fuzzy search (default)
python -m src.server

# Run with embedding search (better semantic understanding)
python -m src.server --search-provider embedding

# Or set via environment variable
SEARCH_PROVIDER=embedding python -m src.server

安装嵌入搜索(可选)

为了使用句子转换器进行更好的语义搜索:

# With uv
uv pip install "sentence-transformers>=2.2.0" "numpy>=1.24.0"

# Or with pip
pip install sentence-transformers numpy

配置参考

API配置

字段 类型 必填 描述
name string Yes API的唯一标识符
spec_url string 是 OpenAPI规范的URL或本地路径
base_url string 是 API请求的基本URL
auth object 否 身份验证配置
settings 对象 否 特定于API的设置

身份验证类型

类型 描述 示例
bearer 授权标头中的承载令牌 Authorization: Bearer <token>
api_key 标头或查询参数中的API键 X-API-Key: <token>
basic 基本身份验证(base64编码) Authorization: Basic <base64>
none 无身份验证 -

环境变量可以用引用 $VAR_NAME 语法。

设置

设置 默认值 说明
default_page_size 20 列表响应的默认限制
max_batch_size 50 批处理执行中的最大请求数
rate_limit_per_second 5 请求的速率限制
confirm_destructive true 需要确认删除/放置/粘贴

搜索提供程序

模糊搜索(默认)

用途 thefuzz 用于字符串匹配的库。快速且无需额外依赖即可工作。

python -m src.server --search-provider fuzzy

最适合: 精确的关键字匹配、操作ID、路径名。

嵌入搜索

用途 sentence-transformers 为了语义相似性。更好地理解同义词和意图。

python -m src.server --search-provider embedding

最适合: 自然语言查询、同义词匹配、语义相似度。

比较:

查询 模糊 嵌入
“查找所有宠物” 高度自信 高度自信
“有什么动物可用” 信心低 高度自信
“买宠物” 结果喜忧参半 查找店铺/订单
“移除特定动物” 结果喜忧参半 查找删除宠物

工具参考

1.列表_apis

列出所有已注册的OpenAPI/Swagger API。

输入: 无

输出:

[
  {
    "name": "petstore",
    "base_url": "https://petstore.example.com",
    "description": "Pet Store API",
    "auth_type": "api_key",
    "endpoint_count": 15
  }
]

2.搜索_积分

按自然语言描述搜索API端点。

输入:

{
  "api": "petstore",
  "query": "find all available pets",
  "limit": 5
}

输出:

{
  "api": "petstore",
  "query": "find all available pets",
  "results": [
    {
      "endpoint": {
        "path": "/pet/findByStatus",
        "method": "GET",
        "summary": "Finds Pets by status",
        "parameters": [...]
      },
      "similarity_score": 0.85,
      "low_confidence": false
    }
  ],
  "total_results": 5
}

3.执行点

执行API终结点。

输入:

{
  "api": "petstore",
  "path": "/pet/{petId}",
  "method": "GET",
  "params": {"petId": 123},
  "limit": 20,
  "offset": 0,
  "confirmed": false
}

输出:

{
  "status_code": 200,
  "data": {"id": 123, "name": "Buddy", "status": "available"},
  "truncated": false,
  "auth_error": false
}

对于破坏性操作(DELETE、PUT、PATCH),设置 confirmed: true.

4.批处理执行器

并行执行多个API端点。

输入:

{
  "api": "petstore",
  "requests": [
    {"path": "/pet/1", "method": "GET"},
    {"path": "/pet/2", "method": "GET"},
    {"path": "/pet/3", "method": "GET"}
  ],
  "parallel": true,
  "confirmed": true
}

输出:

{
  "results": [...],
  "summary": {"total": 3, "succeeded": 3, "failed": 0}
}

使用示例

示例1:简单查询

User: What pets are available in the store?

AI: Let me search for that endpoint and get the data.
    1. search_endpoints(api="petstore", query="find available pets")
    2. execute_endpoint(api="petstore", path="/pet/findByStatus",
                        method="GET", params={"status": "available"})

    Result: Found 6 available pets: Buddy (dog), Whiskers (cat), ...

示例2:创建资源

User: Add a new pet named "Max" to the store.

AI: 1. search_endpoints(api="petstore", query="create new pet")
    2. execute_endpoint(api="petstore", path="/pet", method="POST",
                        body={"name": "Max", "species": "dog", "status": "available"})

    Result: Created pet with ID 15.

示例3:破坏性操作

User: Delete pet #15.

AI: 1. execute_endpoint(api="petstore", path="/pet/{petId}", method="DELETE",
                        params={"petId": 15}, confirmed=false)

    Warning: This is a destructive operation. Set confirmed=true to proceed.

User: Yes, go ahead.

AI: 2. execute_endpoint(..., confirmed=true)

    Result: Pet #15 deleted successfully.

Claude桌面集成

增添 ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "openapi-bridge": {
      "command": "python",
      "args": ["-m", "src.server"],
      "cwd": "/path/to/openapi-mcp-bridge",
      "env": {
        "PETSTORE_KEY": "your-api-key"
      }
    }
  }
}

Claude代码集成

创建 .mcp.json 在项目根目录中:

{
  "mcpServers": {
    "openapi-bridge": {
      "command": "python",
      "args": ["-m", "src.server"],
      "cwd": "/path/to/openapi-mcp-bridge",
      "env": {
        "PETSTORE_KEY": "your-api-key"
      }
    }
  }
}

测试

运行单元测试

pytest tests/test_parser.py tests/test_search.py tests/test_executor.py -v

运行集成测试

# Requires mock server to start automatically
pytest tests/test_integration.py -v

手动启动模拟服务器

cd mock-petstore
./run.sh

发展

项目结构

openapi-mcp-bridge/
├── src/
│   ├── __init__.py
│   ├── server.py          # MCP server with 4 tools
│   ├── config.py          # Configuration loader
│   ├── parser.py          # OpenAPI spec parser
│   ├── registry.py        # API registry
│   ├── executor.py        # HTTP request executor
│   ├── guardrails.py      # Safety checks
│   └── search/
│       ├── base.py        # Search interface
│       ├── fuzzy.py       # Fuzzy search
│       └── embedding.py   # Embedding search (placeholder)
├── config/
│   └── apis.json          # API registrations
├── mock-petstore/         # Test server
├── tests/
└── pyproject.toml

许可证

麻省理工学院