Swagger MCP服务
🔄 Automatically Transform Any OpenAPI/Swagger API into MCP (Model Context Protocol) Tools
______________________________________________________________________
🌟 概述
Swagger MCP服务 是一个强大的零代码解决方案,可以自动将任何OpenAPI/Swagger规范转换为MCP(模型上下文协议)工具。这使得大型语言模型(LLM)能够与现有的REST API无缝交互,而无需编写任何自定义集成代码。
主要特点
- 🚀 零代码集成 -只需提供一个OpenAPI规范URL,系统就会处理所有事情
- 🔄 动态工具生成 -自动解析API端点并生成MCP工具
- 🤖 LLM就绪 -通过LangChain与OpenAI GPT模型开箱即用
- 📋 智能解析 -支持Swagger UI、ReDoc和直接OpenAPI JSON端点
- ⚙️ 高度可配置的 -通过YAML自定义工具名称、过滤器、系统提示等
- 🔌 多服务器支持 -同时连接到多个MCP服务器(OpenAPI+第三方)
- 🆕 自动工具发现 -自动从第三方MCP服务器获取工具描述
- 🧩 可扩展架构 -服务器、客户端和解析器组件之间的清晰分离
- 🌐 漂亮的Web界面 -具有实时流式响应的现代聊天用户界面
- 📊 综合录井 -带有性能指标的彩色控制台日志
______________________________________________________________________
🏗️ 建筑
┌──────────────────────────────────────────────────────────────────────────┐
│ Swagger MCP Service │
├──────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌────────────────┐ │
│ │ Browser │───────▶│ Web Interface │ (SSE Streaming) │
│ │ /User │◀───────│ (web_server.py)│ │
│ └─────────────┘ └────────┬───────┘ │
│ │ │
│ ┌─────────────┐ │ │
│ │ CLI │────┐ │ FastAPI + LangGraph │
│ │ (run.py) │ │ │ │
│ └─────────────┘ │ ▼ │
│ │ ┌──────────────┐ ┌──────────────────────┐ │
│ └───▶│ MCP Client │────▶│ LLM (GPT-4) │ │
│ │ (client.py) │◀────│ via LangChain │ │
│ └──────┬───────┘ └──────────────────────┘ │
│ │ │
│ │ stdio (multiple connections) │
│ ┌──────────┴──────────┐ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ MCP Server │ │ 3rd Party MCP │ │
│ │ (server.py) │ │ (mcp-server-*) │ │
│ └──────┬───────┘ └──────────────────┘ │
│ │ │
│ │ Dynamic Tool Registration │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ OpenAPI Parser │ │
│ │ (openapi_parser.py) │ │
│ └─────────┬───────────┘ │
│ │ │
│ │ Parse & Transform │
│ ▼ │
│ ┌──────────────────────┐ │
│ │ OpenAPI/Swagger │ │
│ │ Specification │ │
│ └──────────┬───────────┘ │
│ │ │
└──────────────────────┼────────────────────────────────────────────────────┘
│ HTTP Requests
▼
┌──────────────┐
Web Server** | `web_server.py` | 🌐 Beautiful web chat interface with real-time streaming responses |
| ** │ Target API │
│ Server │
└──────────────┘组件概述
| 组件 | 文件 | 描述 |
|---|---|---|
| 运行脚本 | run.py | CLI的入口点,用于验证、列出工具和运行服务 |
| MCP服务器 | server.py | 从OpenAPI规范中动态注册MCP工具并处理API调用 |
| MCP客户端 | client.py | 通过LangChain连接到LLM,并提供交互式聊天界面 |
| OpenAPI解析器 | openapi_parser.py | 从URL或文件解析OpenAPI/Swagger规范,提取端点 |
| 配置 | config.yaml | API源、LLM设置和自定义的中心配置 |
______________________________________________________________________
📦 安装
先决条件
- Python 3.10或更高版本
- OpenAI API密钥(用于LLM客户端)
步骤1:克隆存储库
git clone https://github.com/yourusername/swagger_mcp_service.git
cd swagger_mcp_service步骤2:安装依赖项
pip install -r requirements.txt步骤3:配置环境变量
创建一个 .env 项目根目录中的文件:
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-4.1-mini # Optional: override model from config______________________________________________________________________
⚙️ 配置
所有配置都是通过 generic_mcp/config.yaml。以下是关键部分的细分:
API配置
api:
# OpenAPI specification source (choose one)
openapi_url: "http://localhost:8000/openapi.json" # Direct URL
# openapi_url: "http://localhost:8000/docs" # Swagger UI page (auto-detected)
# openapi_file: "./openapi.json" # Local file (takes priority)
# Base URL for API calls (used if not defined in OpenAPI spec)
base_url: "http://localhost:8000"
# Request timeout in seconds
timeout: 30MCP服务器配置(支持多服务器)
mcp_servers:
# OpenAPI/Swagger type server
- name: "My API Service"
type: "openapi"
enabled: true
openapi:
openapi_url: "http://localhost:8000/openapi.json"
base_url: "http://localhost:8000"
tool_generation:
include_all: true
snake_case_names: true
# Third-party MCP server (auto tool discovery!)
- name: "Fetch"
type: "external"
enabled: true
command: "uvx"
args: ["mcp-server-fetch"]
# 🆕 No need to write description/tools_description!
# They are automatically fetched from the MCP server第三方MCP服务器
您可以连接到任何第三方MCP服务器。 工具描述会自动发现!
mcp_servers:
# Example: mcp-server-fetch
- name: "Fetch"
type: "external"
enabled: true
command: "uvx"
args: ["mcp-server-fetch"]
# Example: Filesystem server
- name: "Filesystem"
type: "external"
enabled: true
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
# Example: GitHub server with environment variables
- name: "GitHub"
type: "external"
enabled: true
command: "npx"
args: ["-y", "@modelcontextprotocol/server-github"]
env:
GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_TOKEN}"
# Optional: Override auto-discovered descriptions
- name: "Custom Server"
type: "external"
enabled: true
command: "my-mcp-server"
args: []
description: "Custom description (optional)"
tools_description: | # Optional - overrides auto-discovery
- **tool_name**: Custom tool description工具生成选项
tool_generation:
include_all: true # Include all endpoints
exclude_endpoints: [] # Exclude specific endpoints
snake_case_names: true # Convert names to snake_case
simplified_names: true # Simplify tool names
# tool_prefix: "myapi_" # Optional prefix for all toolsLLM配置
llm:
provider: "openai"
model: "gpt-4.1-mini"
temperature: 0系统提示定制
system_prompt:
template: |
You are an AI assistant with access to the following API tools...
Available Variables:
- {api_name}: API title from OpenAPI spec
- {api_description}: API description
- {tools_summary}: Auto-generated tool documentation______________________________________________________________________
🚀 用法
快速开始
选项1:Web界面(推荐)🌐
- 启动您的目标API服务器 (或使用附带的示例):
cd api_swagger_example
uvicorn api_server:app --reload- 配置OpenAPI源代码 在
generic_mcp/config.yaml:
api:
openapi_url: "http://localhost:8000/openapi.json"
base_url: "http://localhost:8000"- 启动web服务器:
cd generic_mcp
python web_server.pyWeb服务器
# Launch web interface with default config
python web_server.py
# Use custom configuration file
python web_server.py /path/to/my-config.yaml
# Set custom port (default: 8080)
export MCP_WEB_PORT=3000
python web_server.py
# Override LLM model
export OPENAI_MODEL=gpt-4o
python web_server.pyCLI客户端
网络界面
网络界面提供了一个美丽、现代的聊天体验,包括:
- 💬 实时流媒体 -观看响应逐个生成令牌
- 🔧 工具调用可视化 -查看何时以及如何调用API工具
- 🎨 深色主题 -视觉舒适,与克劳德的界面相似
- 📝 Markdown支持 -格式丰富,代码突出显示
- 📊 会话管理 -多种对话环境
CLI接口
- 打开浏览器 访问:http://localhost:8080
选项2:命令行界面
- 运行交互式客户端:
cd generic_mcp
python run.py命令行选项
# Run interactive client (default)
python run.py
# Use custom configuration file
python run.py --config /path/to/my-config.yaml
# Validate configuration and OpenAPI spec
python run.py --validate
# List all available tools
python run.py --list-tools
# Run server only (for debugging)
python run.py --server-only交互示例
============================================================
🤖 Procurement System API
============================================================
Enterprise procurement management system...
👤 You: Show me recent purchase history
🤖 Assisweb_server.py # 🌐 Web chat interface (FastAPI + SSE)
│ ├── run.py # CLI entry point
│ ├── server.py # MCP server implementation
│ ├── client.py # MCP client with LangChain
│ ├── openapi_parser.py # OpenAPI specification parser
│ ├── config.yaml # Configuration file
│ └── templates/
│ └── index.html # Web UI templat-----------|
| PH001 | Laptop (Dell) | 10 | NT$ 42,000 | Digital Co |
| PH002 | Laptop (Lenovo) | 5 | NT$ 52,000 | Tech Corp |
------------------------------------------------------------
👤 You: Check inventory for Dell laptops
🤖 Assistant:
Dell Latitude 5540 Inventory Status:
- Available: 3 units
- Reserved: 2 units
- Location: Main Warehouse______________________________________________________________________
📁 项目结构
swagger_mcp_service/
├── README.md # This file
├── requirements.txt # Python dependencies
├── LICENSE # MIT License
│
├── generic_mcp/ # Core MCP service
│ ├── __init__.py
│ ├── run.py # CLI entry point
│ ├── server.py # MCP server implementation
│ ├── client.py # MCP client with LangChain
│ ├── openapi_parser.py # OpenAPI specification parser
│ └── config.yaml # Configuration file
│
└── api_swagger_example/ # Example API server
└── api_server.py # FastAPI demo server4.Web界面流媒体
web服务器使用服务器发送事件(SSE)进行实时流式传输:
- 令牌流 -LLM响应逐字符流
- 工具事件 -
on_tool_start和on_tool_end事件显示API调用 - 会话管理 -具有唯一ID的多个对话上下文
- 彩色日志 -带有时间戳和日志级别的后端日志
- 错误处理 -在UI中显示优美的错误消息
______________________________________________________________________
🔧 运作原理
1.OpenAPI解析
这 OpenAPIParser 类别:
- 从URL(包括Swagger UI页面)或本地文件加载OpenAPI规范
- 自动检测并从文档页面中提取OpenAPI JSON
- 支持OpenAPI 3.x和Swagger 2.0格式
2.动态刀具生成
对于每个API端点,系统生成一个MCP工具:
OpenAPI Endpoint → MCP Tool
───────────────────────────────────────────────────
operationId / path+method → tool name (function name)
summary / description → tool description (docstring)
path parameters → required parameters (in="path")
query parameters → query parameters (in="query")
request body properties → body parameters3.运行时执行
当调用工具时:
- 参数分类(路径、查询、正文)
- URL中的路径参数被替换
- 向目标API发出HTTP请求
- 响应以JSON格式返回给LLM
______________________________________________________________________
🧪 API服务器示例
这 api_swagger_example/ 该目录包含一个完整的FastAPI演示服务器,模拟企业采购系统。它包括:
- 📋 购买历史 -查询过去的采购记录
- 📦 库存管理 -检查库存并索取物品
- 🏢 供应商管理 -查询供应商信息
- 🛒 产品目录 -浏览产品和价格
- 📝 采购申请 -创建和管理采购请求
- 📄 采购订单 -生成采购订单
运行示例
cd api_swagger_example
uvicorn api_server:app --reload --host 0.0.0.0 --port 8000访问Swagger用户界面:http://localhost:8000/docs
______________________________________________________________________
🔌 与其他系统集成
与外部API一起使用
只需更新 config.yaml 指向任何符合OpenAPI的API:
mcp_servers:
- name: "External API"
type: "openapi"
enabled: true
openapi:
openapi_url: "https://api.example.com/openapi.json"
base_url: "https://api.example.com"组合多个MCP服务器
您可以将OpenAPI服务器与第三方MCP服务器结合使用:
mcp_servers:
# Your internal API
- name: "Internal API"
type: "openapi"
enabled: true
openapi:
openapi_url: "http://localhost:8000/openapi.json"
# Web content fetching
- name: "Fetch"
type: "external"
enabled: true
command: "uvx"
args: ["mcp-server-fetch"]
# File system access
- name: "Filesystem"
type: "external"
enabled: true
command: "npx"
args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"]连接到企业系统
该服务可以与以下内容集成:
- SAP系统(带OpenAPI网关)
- Salesforce API
- 具有OpenAPI规范的AWS服务
- 任何带有Swagger/OpenAPI文档的REST API
- 来自社区的第三方MCP服务器
______________________________________________________________________
🛡️ 错误处理
该系统提供稳健的错误处理:
- 连接错误:当无法访问API服务器时清除消息
- HTTP错误:带有状态代码的详细错误响应
- 解析错误:无法解析OpenAPI规范时的有用建议
- 验证模式:飞行前检查
--validate旗帜
______________________________________________________________________
📝 定制示例
筛选特定端点
tool_generation:
include_all: false
include_endpoints:
- "get_purchase_history"
- "create_purchase_order"排除端点
tool_generation:
include_all: true
exclude_endpoints:
- "delete_all_data"
- "/admin/*"添加工具前缀
tool_generation:
tool_prefix: "procurement_"
# Results in: procurement_get_inventory, procurement_create_order, etc.______________________________________________________________________
🤝 贡献
欢迎投稿!请随时提交拉取请求。
- 分叉存储库
- 创建功能分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add some AmazingFeature') - 推到分支(
git push origin feature/AmazingFeature) - 打开拉取请求
______________________________________________________________________
📄 许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
______________________________________________________________________
🙏 致谢
- 模型上下文协议(MCP) -使这成为可能的协议
- FastMCP -简化的MCP服务器实现
- LangChain -LLM应用框架
- 快速API -现代Python web框架
______________________________________________________________________
Made with ❤️ for seamless API-to-LLM integration
