MCP OpenAPI 服务器添加福利群:解决AI开发者的「MCP实战痛点」这是一个模型上下文协议(MCP)服务器,将 OpenAPI 端点作为 MCP 资源公开。该服务器允许大型语言模型通过 MCP 协议发现并交互由 OpenAPI 规范定义的 REST API。
本节介绍如何作为终端用户将 MCP 服务器与 Claude Desktop、Cursor 或其他兼容 MCP 的工具配合使用。
本 MCP 服务器可通过两种方式使用:
npx @ivotoby/openapi-mcp-server 配合命令行参数快速设置OpenAPIServer 类进行自定义实现服务器支持两种传输方式:
无需克隆此仓库。只需配置 Claude Desktop 使用此 MCP 服务器:
找到或创建您的 Claude Desktop 配置文件:
~/Library/Application Support/Claude/claude_desktop_config.json添加以下配置:
{
"mcpServers": {
"openapi": {
"command": "npx",
"args": ["-y", "@ivotoby/openapi-mcp-server"],
"env": {
"API_BASE_URL": "https://api.example.com",
"OPENAPI_SPEC_PATH": "https://api.example.com/openapi.json",
"API_HEADERS": "Authorization:Bearer token123,X-API-Key:your-api-key"
}
}
}
}

API_BASE_URL:您的 API 基础 URLOPENAPI_SPEC_PATH:OpenAPI 规范的 URL 或路径API_HEADERS:用于 API 认证头的逗号分隔键值对要与 HTTP 客户端使用服务器:
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--headers "Authorization:Bearer token123" \
--transport http \
--port 3000

# 初始化会话(首次请求)
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"curl-client","version":"1.0.0"}}}'
# 响应包含一个 Mcp-Session-Id 头,您必须在后续请求中使用
# 以及 POST 响应体中的 InitializeResult 直接返回
# 发送请求列出工具
# 此请求也会在此 POST 请求上直接接收响应
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-H "Mcp-Session-Id: your-session-id" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# 为其他服务器响应(如工具执行结果)打开流式连接
# 这使用服务器发送事件(SSE)
curl -N http://localhost:3000/mcp -H "Mcp-Session-Id: your-session-id"
# 示例:执行工具(响应将通过 GET 流到达)
# curl -X POST http://localhost:3000/mcp \
# -H "Content-Type: application/json" \
# -H "Mcp-Session-Id: your-session-id" \
# -d '{"jsonrpc":"2.0","id":2,"method":"tools/execute","params":{"name":"yourToolName", "arguments": {}}}'
# 完成后终止会话
curl -X DELETE http://localhost:3000/mcp -H "Mcp-Session-Id: your-session-id"

服务器可以通过环境变量或命令行参数进行配置:
API_BASE_URL - API 端点的基础 URLOPENAPI_SPEC_PATH - OpenAPI 规范的路径或 URLOPENAPI_SPEC_FROM_STDIN - 设置为 "true" 以从标准输入读取 OpenAPI 规范OPENAPI_SPEC_INLINE - 直接以字符串形式提供 OpenAPI 规范内容API_HEADERS - 用于 API 头的逗号分隔键值对SERVER_NAME - MCP 服务器名称(默认:"mcp-openapi-server")SERVER_VERSION - 服务器版本(默认:"1.0.0")TRANSPORT_TYPE - 使用的传输类型:"stdio" 或 "http"(默认:"stdio")HTTP_PORT - HTTP 传输端口(默认:3000)HTTP_HOST - HTTP 传输主机(默认:"127.0.0.1")ENDPOINT_PATH - HTTP 传输的端点路径(默认:"/mcp")TOOLS_MODE - 工具加载模式:"all"(加载所有基于端点的工具)、"dynamic"(仅加载元工具)或 "explicit"(仅加载 includeTools 中指定的工具)(默认:"all")DISABLE_ABBREVIATION - 禁用名称优化(当名称 > 64 个字符时可能会抛出错误)npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--headers "Authorization:Bearer token123,X-API-Key:your-api-key" \
--name "my-mcp-server" \
--server-version "1.0.0" \
--transport http \
--port 3000 \
--host 127.0.0.1 \
--path /mcp \
--disable-abbreviation true

MCP 服务器支持多种加载 OpenAPI 规范的方法,为不同的部署场景提供灵活性:
从远程 URL 加载 OpenAPI 规范:
npx @ivotoby/openapi-mcp-server \ --api-base-url https://api.example.com \ --openapi-spec https://api.example.com/openapi.json
从本地文件加载 OpenAPI 规范:
npx @ivotoby/openapi-mcp-server \ --api-base-url https://api.example.com \ --openapi-spec ./path/to/openapi.yaml
从标准输入读取 OpenAPI 规范(适用于管道或容器化环境):
# 从文件管道
cat openapi.json | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin
# 从 curl 管道
curl -s https://api.example.com/openapi.json | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin
# 使用环境变量
export OPENAPI_SPEC_FROM_STDIN=true
echo '{"openapi": "3.0.0", ...}' | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com

直接以命令行参数形式提供 OpenAPI 规范内容:
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--spec-inline '{"openapi": "3.0.0", "info": {"title": "My API", "version": "1.0.0"}, "paths": {}}'
# 使用环境变量
export OPENAPI_SPEC_INLINE='{"openapi": "3.0.0", ...}'
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com

所有加载方法均支持 JSON 和 YAML 格式。服务器会自动检测格式并进行相应解析。
对于容器化部署,您可以挂载 OpenAPI 规范或使用 stdin:
# 挂载本地文件
docker run -v /path/to/spec:/app/spec.json your-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec /app/spec.json
# 使用 docker 的 stdin
cat openapi.json | docker run -i your-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin

服务器为规范加载失败提供详细的错误消息:
一次只能使用一个规范来源。服务器将验证是否恰好提供了以下之一:
--openapi-spec(URL 或文件路径)--spec-from-stdin--spec-inline如果指定了多个来源,服务器将退出并显示错误消息。
根据 Stainless 文章《将复杂 OpenAPI 规范转换为 MCP 服务器的经验》(https://www.stainless.com/blog/what-we-learned-converting-complex-openapi-specs-to-mcp-servers),添加了以下标志来控制加载哪些 API 端点(工具):
--tools <all|dynamic|explicit>:选择工具加载模式:
all(默认):从 OpenAPI 规范加载所有工具,应用任何指定的过滤器dynamic:仅加载动态元工具(list-api-endpoints、get-api-endpoint-schema、invoke-api-endpoint)explicit:仅加载 --tool 选项中明确列出的工具,忽略所有其他过滤器--tool <toolId>:仅导入指定的工具 ID 或名称。可以多次使用。--tag <tag>:仅导入具有指定 OpenAPI 标签的工具。可以多次使用。--resource <resource>:仅导入位于指定资源路径前缀下的工具。可以多次使用。--operation <method>:仅导入指定 HTTP 方法(get、post 等)的工具。可以多次使用。示例:
# 仅加载动态元工具
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tools dynamic
# 仅加载显式指定的工具(忽略其他筛选条件)
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tools explicit --tool GET::users --tool POST::users
# 仅加载GET /users端点工具(使用全模式筛选)
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tool GET-users
# 加载带有"user"标签且位于"/users"资源下的工具
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tag user --resource users
# 仅加载POST操作
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --operation post

标准输入输出传输专为与Claude Desktop等通过标准输入/输出管理MCP连接的AI系统直接集成而设计。这是最简单的设置,无需网络配置。
使用场景:当需要与Claude Desktop或其他支持基于stdio的MCP通信的系统集成时。
HTTP传输允许通过HTTP访问MCP服务器,使Web应用程序和其他支持HTTP的客户端能够与MCP协议交互。它支持会话管理、流式响应和标准HTTP方法。
主要特性:
initialize和tools/list请求的HTTP响应在POST时同步发送tools/execute结果、通知)通过GET连接使用服务器发送事件(SSE)流式传输使用场景:当需要将MCP服务器暴露给Web客户端或通过HTTP而非stdio通信的系统时。
使用HTTP传输时,可通过/health端点进行健康检查和服务发现:
# 检查服务器健康状态
curl http://localhost:3000/health
# 响应:
# {
# "status": "healthy",
# "activeSessions": 2,
# "uptime": 3600
# }

健康响应字段:
status:服务器运行时始终返回"healthy"activeSessions:活跃MCP会话数uptime:服务器运行时间(秒)主要特性:
集成示例:
# Kubernetes存活探针
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 3
periodSeconds: 10
# Docker健康检查
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost:3000/health || exit 1

查看调试日志:
在Claude Desktop中使用stdio传输时:
使用HTTP传输时:
npx @ivotoby/openapi-mcp-server --transport http &2>debug.log
本节面向希望将此包作为库来创建自定义MCP服务器的开发者。
通过导入和配置OpenAPIServer类,为特定API创建专用的MCP服务器。此方法适用于:
AuthProvider接口实现复杂认证模式import { OpenAPIServer } from "@ivotoby/openapi-mcp-server"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
const config = {
name: "my-api-server",
version: "1.0.0",
apiBaseUrl: "https://api.example.com",
openApiSpec: "https://api.example.com/openapi.json",
specInputMethod: "url" as const,
headers: {
Authorization: "Bearer your-token",
"X-API-Key": "your-api-key",
},
transportType: "stdio" as const,
toolsMode: "all" as const, // 选项:"all"、"dynamic"、"explicit"
}
const server = new OpenAPIServer(config)
const transport = new StdioServerTransport()
await server.start(transport)

toolsMode配置选项控制从OpenAPI规范加载哪些工具:
// 从规范加载所有工具(默认)
const config = {
// ... 其他配置
toolsMode: "all" as const,
// 可选:应用筛选器控制加载哪些工具
includeTools: ["GET::users", "POST::users"], // 仅这些工具
includeTags: ["public"], // 仅带有这些标签的工具
includeResources: ["users"], // 仅这些资源下的工具
includeOperations: ["get", "post"], // 仅这些HTTP方法
}
// 仅加载用于API探索的动态元工具
const config = {
// ... 其他配置
toolsMode: "dynamic" as const,
// 提供:list-api-endpoints、get-api-endpoint-schema、invoke-api-endpoint
}
// 仅加载显式指定的工具(忽略其他筛选条件)
const config = {
// ... 其他配置
toolsMode: "explicit" as const,
includeTools: ["GET::users", "POST::users"], // 仅这些精确工具
// includeTags、includeResources、includeOperations在显式模式下被忽略
}

对于需要令牌过期处理、刷新或复杂认证的API:
import { OpenAPIServer, AuthProvider } from "@ivotoby/openapi-mcp-server"
import { AxiosError } from "axios"
class MyAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
// 每个请求前调用 - 返回最新的头部
if (this.isTokenExpired()) {
await this.refreshToken()
}
return { Authorization: `Bearer ${this.token}` }
}
async handleAuthError(error: AxiosError): Promise<boolean> {
// 出现401/403错误时调用 - 返回true以重试
if (error.response?.status === 401) {
await this.refreshToken()
return true // 重试请求
}
return false
}
}
const authProvider = new MyAuthProvider()
const config = {
// ... 其他配置
authProvider: authProvider, // 使用AuthProvider替代静态头部
}

📁 查看examples/目录获取完整可运行的示例,包括:
AuthProvider接口支持静态头部无法处理的复杂认证场景:
interface AuthProvider {
/**
* 获取当前请求的认证头部
* 每个API请求前调用以获取最新头部
*/
getAuthHeaders(): Promise<Record<string, string>>
/**
* 处理API响应中的认证错误
* 当API返回401或403错误时调用
* 返回true以重试请求,false则否
*/
handleAuthError(error: AxiosError): Promise<boolean>
}

class RefreshableAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
if (this.isTokenExpired()) {
await this.refreshToken()
}
return { Authorization: `Bearer ${this.accessToken}` }
}
async handleAuthError(error: AxiosError): Promise<boolean> {
if (error.response?.status === 401) {
await this.refreshToken()
return true // 使用新令牌重试
}
return false
}
}

class ManualTokenAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
if (!this.token || this.isTokenExpired()) {
throw new Error(
"令牌已过期。请从浏览器获取新令牌:\n" +
"1. 访问API网站并登录\n" +
"2. 打开浏览器开发者工具(F12)\n" +
"3. 从任意API请求复制Authorization头部\n" +
"4. 使用updateToken()更新您的令牌",
)
}
return { Authorization: `Bearer ${this.token}` }
}
updateToken(token: string): void {
this.token = token
this.tokenExpiry = new Date(Date.now() + 3600000) // 1小时
}
}

class ApiKeyAuthProvider implements AuthProvider {
constructor(private apiKey: string) {}
async getAuthHeaders(): Promise<Record<string, string>> {
return { "X-API-Key": this.apiKey }
}
async handleAuthError(error: AxiosError): Promise<boolean> {
throw new Error("API密钥认证失败。请检查您的密钥。")
}
}

📖 详细AuthProvider文档和示例见docs/auth-provider-guide.md
本 MCP 服务器实现了强大的 OpenAPI 引用 ($ref) 解析功能,确保 API 模式的准确表示:
$ref 指针服务器智能地将参数和请求体合并为每个工具的统一输入模式:
MCP 服务器处理各种 OpenAPI 模式复杂性:
npm run build - 构建 TypeScript 源代码npm run clean - 清除构建产物npm run typecheck - 运行 TypeScript 类型检查npm run lint - 运行 ESLintnpm run dev - 监视源文件并在更改时重新构建npm run inspect-watch - 运行检查器并在更改时自动重新加载npm installnpm run inspect-watchsrc/ 中的 TypeScript 文件npm run typecheck && npm run lint📖 完整的开发者文档请参阅 docs/developer-guide.md
问:什么是 "工具"? 答:工具对应于从 OpenAPI 规范派生的单个 API 端点,作为 MCP 资源公开。
问:如何在自己的项目中使用这个包?
答:您可以导入 OpenAPIServer 类并将其作为库用于 Node.js 应用程序。这允许您为特定 API 创建定制的 MCP 服务器,具有自定义身份验证、过滤和错误处理。完整实现请参阅 examples/ 目录。
问:使用 CLI 和作为库使用有什么区别?
答:CLI 适用于快速设置和测试,而库方法允许您为特定 API 创建专用包,使用 AuthProvider 实现自定义身份验证,添加自定义逻辑,并将服务器作为独立的 npm 模块分发。
问:如何处理带有过期令牌的 API?
答:使用 AuthProvider 接口而不是静态标头。AuthProvider 允许您实现动态身份验证,包括令牌刷新、过期处理和自定义错误恢复。不同模式的 AuthProvider 示例请参阅相关文档。
问:什么是 AuthProvider,何时使用它?
答:AuthProvider 是用于动态身份验证的接口,它在每个请求前获取新的标头并处理身份验证错误。当您的 API 有过期令牌、需要令牌刷新或需要静态标头无法处理的复杂身份验证逻辑时使用它。
问:如何过滤加载的工具?
答:使用 --tool、--tag、--resource 和 --operation 标志与 --tools all(默认),设置 --tools dynamic 仅用于元工具,或使用 --tools explicit 仅加载 --tool 指定的工具(忽略其他过滤器)。
问:何时应使用动态模式?
答:动态模式提供元工具(list-api-endpoints、get-api-endpoint-schema、invoke-api-endpoint)来检查和与端点交互,而无需预加载所有操作,这对于大型或变化的 API 非常有用。
问:如何为 API 请求指定自定义标头?
答:对于 CLI 使用,使用 --headers 标志或 API_HEADERS 环境变量,键值对用逗号分隔。对于库使用,使用 headers 配置选项或实现 AuthProvider 以获取动态标头。
问:支持哪些传输方法? 答:服务器支持 stdio 传输(默认)用于与 AI 系统集成,以及 HTTP 传输(通过 SSE 流式传输)用于 Web 客户端。
问:服务器如何处理带有引用的复杂 OpenAPI 模式?
答:服务器完全解析参数和模式中的 $ref 引用,保留嵌套结构、默认值和其他属性。有关引用解析和模式组合的详细信息,请参阅 "OpenAPI 模式处理" 部分。
问:当参数名与请求体属性冲突时会发生什么?
答:服务器检测命名冲突并自动为体属性名添加 body_ 前缀以避免冲突,确保所有属性可访问。
问:我可以打包 MCP 服务器以进行分发吗?
答:可以!使用库方法时,您可以为 API 创建专用的 npm 包。完整实现请参阅 Beatport 示例,可以打包并分发为 npx your-api-mcp-server。
问:在哪里可以找到开发和贡献指南? 答:全面的架构、关键概念、开发流程和贡献指南请参阅 开发者指南。
MIT