OpenAPI MCP服务器
](https://smithery.ai/server/@ivo-toby/mcp-openapi-server)
一个模型上下文协议(MCP)服务器,它将OpenAPI端点作为MCP工具公开,并提供对MCP提示和资源的可选支持。该服务器允许大型语言模型通过MCP协议发现OpenAPI规范定义的REST API并与之交互。
📖 文档
- 用户指南 -对于希望将此MCP服务器与Claude Desktop、Cursor或其他MCP客户端一起使用的用户
- 图书馆使用情况 -对于使用此包作为库创建自定义MCP服务器的开发人员
- 开发者指南 -面向代码库的贡献者和开发人员
- 身份验证提供者指南 -详细的身份验证模式和示例
______________________________________________________________________
用户指南
本节介绍如何使用Claude Desktop、Cursor或其他MCP兼容工具作为最终用户使用MCP服务器。
概述
此MCP服务器有两种使用方式:
- CLI工具:使用
npx @ivotoby/openapi-mcp-server直接使用命令行参数进行快速设置 - 图书馆:导入和使用
OpenAPIServer类在您自己的Node.js应用程序中用于自定义实现
服务器支持两种传输方式:
- 标准运输 (默认):用于与Claude Desktop等通过标准输入/输出管理MCP连接的AI系统直接集成。
- 可流式HTTP传输:用于通过HTTP连接到服务器,允许web客户端和其他支持HTTP的系统使用MCP协议。
用户快速入门
选项1:与Claude桌面一起使用(标准传输)
无需克隆此存储库。只需配置Claude Desktop即可使用此MCP服务器:
- 查找或创建您的Claude Desktop配置文件:
- 在macOS上: ~/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配置:
- API_BASE_URL:API的基本URL - OPENAPI_SPEC_PATH:指向OpenAPI规范的URL或路径 - API_HEADERS:逗号分隔的密钥:API身份验证标头的值对
选项2:与HTTP客户端一起使用(HTTP传输)
要将服务器与HTTP客户端一起使用:
- 无需安装!使用npx直接运行包:
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- 使用HTTP请求与服务器交互:
# Initialize a session (first request)
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"}}}'
# The response includes a Mcp-Session-Id header that you must use for subsequent requests
# and the InitializeResult directly in the POST response body.
# Send a request to list tools
# This also receives its response directly on this POST request.
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"}'
# Open a streaming connection for other server responses (e.g., tool execution results)
# This uses Server-Sent Events (SSE).
curl -N http://localhost:3000/mcp -H "Mcp-Session-Id: your-session-id"
# Example: Execute a tool (response will arrive on the GET stream)
# 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": {}}}'
# Terminate the session when done
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标头的值对CLIENT_CERT_PATH-双向TLS客户端证书PEM文件的路径CLIENT_KEY_PATH-双向TLS客户端私钥PEM文件的路径CA_CERT_PATH-私有/内部CA的自定义CA证书PEM文件的路径CLIENT_KEY_PASSPHRASE-加密客户端私钥的密码REJECT_UNAUTHORIZED-是否拒绝不受信任的服务器证书(默认值:true)SERVER_NAME-MCP服务器的名称(默认:“MCP-openapi服务器”)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-工具加载模式:“全部”(加载所有基于端点的工具)、“动态”(仅加载元工具)或“显式”(includeTools中指定的仅加载工具)(默认值:“所有”)DISABLE_ABBREVIATION-禁用名称优化(当名称超过64个字符时,这可能会引发错误)VERBOSE-启用操作日志记录(true默认情况下;着手false抑制非必要日志)PROMPTS_PATH-用于提示JSON/YAML文件的路径或URLPROMPTS_INLINE-直接以JSON字符串形式提供提示RESOURCES_PATH-资源JSON/YAML文件的路径或URLRESOURCES_INLINE-直接以JSON字符串形式提供资源
命令行参数
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" \
--client-cert ./certs/client.pem \
--client-key ./certs/client-key.pem \
--name "my-mcp-server" \
--server-version "1.0.0" \
--transport http \
--port 3000 \
--host 127.0.0.1 \
--path /mcp \
--disable-abbreviation true \
--verbose false双向TLS(mTLS)
如果您的上游API需要客户端证书身份验证,则可以将TLS凭据直接附加到出站请求。
npx @ivotoby/openapi-mcp-server \
--api-base-url https://secure-api.example.com \
--openapi-spec https://secure-api.example.com/openapi.json \
--client-cert ./certs/client.pem \
--client-key ./certs/client-key.pem \
--headers "Authorization:Bearer token123"这与HTTP级别的身份验证正交,因此mTLS可以与静态标头或 AuthProvider.
TLS相关选项仅在以下情况下适用 --api-base-url 用途 https://.
对于私有CA或加密密钥:
npx @ivotoby/openapi-mcp-server \
--api-base-url https://internal-api.example.com \
--openapi-spec ./openapi.yaml \
--client-cert ./certs/client.pem \
--client-key ./certs/client-key.pem \
--client-key-passphrase "$CLIENT_KEY_PASSPHRASE" \
--ca-cert ./certs/internal-ca.pem \
--reject-unauthorized false--client-cert/CLIENT_CERT_PATH:客户端证书PEM文件--client-key/CLIENT_KEY_PATH:客户端私钥PEM文件--client-key-passphrase/CLIENT_KEY_PASSPHRASE:加密私钥的密码--ca-cert/CA_CERT_PATH:私有/内部证书颁发机构的自定义CA包--reject-unauthorized/REJECT_UNAUTHORIZED:设置为false仅当您有意允许自签名或不受信任的服务器证书时
集 --verbose false 或 VERBOSE=false 如果您希望服务器在脚本或嵌入式环境中保持安静。
OpenAPI规范加载
MCP服务器支持多种加载OpenAPI规范的方法,为不同的部署场景提供了灵活性:
1.URL加载(默认)
从远程URL加载OpenAPI规范:
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json2.本地文件加载
从本地文件加载OpenAPI规范:
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec ./path/to/openapi.yaml3.标准输入加载
从标准输入中读取OpenAPI规范(适用于管道或容器化环境):
# Pipe from file
cat openapi.json | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin
# Pipe from curl
curl -s https://api.example.com/openapi.json | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin
# Using environment variable
export OPENAPI_SPEC_FROM_STDIN=true
echo '{"openapi": "3.0.0", ...}' | npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com4.内联规格
直接将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": {}}'
# Using environment variable
export OPENAPI_SPEC_INLINE='{"openapi": "3.0.0", ...}'
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com支持格式
所有加载方法都支持JSON和YAML格式。服务器会自动检测格式并相应地进行解析。
Docker和容器使用
对于容器化部署,您可以挂载OpenAPI规范或使用stdin:
# Mount local file
docker run -v /path/to/spec:/app/spec.json your-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec /app/spec.json
# Use stdin with docker
cat openapi.json | docker run -i your-mcp-server \
--api-base-url https://api.example.com \
--spec-from-stdin错误处理
服务器为规范加载失败提供详细的错误消息:
- URL加载:HTTP状态代码和网络错误
- 文件加载:文件系统错误(找不到、权限等)
- 标准载荷:空输入或读取错误
- 内联加载:缺少内容错误
- 解析错误:详细的JSON/YAML语法错误消息
验证
一次只能使用一个规范源。服务器将验证是否提供了以下内容之一:
--openapi-spec(URL或文件路径)--spec-from-stdin--spec-inline
如果指定了多个源,服务器将退出并显示错误消息。
工具加载和筛选选项
基于不锈钢文章“我们从将复杂的OpenAPI规范转换为MCP服务器中学到了什么”(https://www.stainless.com/blog/what-we-learned-converting-complex-openapi-specs-to-mcp-servers),添加了以下标志以控制加载了哪些API终结点(工具):
--tools:选择刀具加载模式:
- all (默认):从OpenAPI规范加载所有工具,应用任何指定的过滤器 - dynamic:仅加载动态元工具(list-api-endpoints, get-api-endpoint-schema, invoke-api-endpoint) - explicit:仅加载中明确列出的工具 --tool 选项,忽略所有其他筛选器
--tool:仅导入指定的工具ID或名称。可以多次使用。--tag:仅导入具有指定OpenAPI标签的工具。可以多次使用。--resource:仅导入指定资源路径前缀下的工具。可以多次使用。--operation:仅导入指定HTTP方法的工具(get、post等)。可以多次使用。
示例:
# Load only dynamic meta-tools
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tools dynamic
# Load only explicitly specified tools (ignores other filters)
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
# Load only the GET /users endpoint tool (using all mode with filtering)
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tool GET-users
# Load tools tagged with "user" under the "/users" resource
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --tag user --resource users
# Load only POST operations
npx @ivotoby/openapi-mcp-server --api-base-url https://api.example.com --openapi-spec https://api.example.com/openapi.json --operation post提示和资源
除了将OpenAPI端点公开为 工具,此服务器可以公开 提示 (可重复使用的模板)和 资源 (静态内容)通过MCP协议。
什么是提示和资源?
| 功能 | 目的 | 用例 |
|---|---|---|
| 工具 | 人工智能执行的API端点 | 进行API调用 |
| 提示 | 带参数替换的模板消息 | 可重用的工作流模板 |
| 资源 | 上下文的只读内容 | API文档、架构 |
加载提示
提示可以从文件、URL或内联JSON加载:
# Load from local file
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--prompts ./prompts.json
# Load from URL
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--prompts https://example.com/mcp/prompts.json
# Inline JSON
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--prompts-inline '[{"name":"greet","title":"Greeting","template":"Hello {{name}}!"}]'提示文件格式(JSON):
[
{
"name": "api_request",
"title": "API Request Helper",
"description": "Helps generate API request templates",
"arguments": [
{ "name": "endpoint", "description": "API endpoint path", "required": true },
{ "name": "method", "description": "HTTP method", "required": false }
],
"template": "Create a {{method}} request to {{endpoint}} with proper parameters."
}
]加载资源
资源可以从文件、URL或内联JSON加载:
# Load from local file
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--mcp-resources ./resources.json
# Load from URL
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--mcp-resources https://example.com/mcp/resources.json
# Inline JSON
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--mcp-resources-inline '[{"uri":"docs://readme","name":"readme","text":"# Welcome"}]'资源文件格式(JSON):
[
{
"uri": "docs://api/overview",
"name": "api-overview",
"title": "API Overview",
"description": "Overview of the API",
"mimeType": "text/markdown",
"text": "# API Overview\n\nThis API provides..."
}
]结合工具、提示和资源
npx @ivotoby/openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--prompts ./prompts.json \
--mcp-resources ./resources.json \
--transport http \
--port 3000使用此配置,服务器会通告所有三个功能:
{
"capabilities": {
"tools": { "list": true, "execute": true },
"prompts": {},
"resources": {}
}
}运输类型
标准传输(默认)
stdio传输旨在与Claude Desktop等人工智能系统直接集成,这些系统通过标准输入/输出管理MCP连接。这是最简单的设置,不需要网络配置。
何时使用:与Claude Desktop或支持基于stdio的MCP通信的其他系统集成时。
可流式HTTP传输
HTTP传输允许通过HTTP访问MCP服务器,使web应用程序和其他支持HTTP的客户端能够与MCP协议交互。它支持会话管理、流式响应和标准HTTP方法。
主要特点:
- 使用Mcp会话Id标头进行会话管理
- HTTP响应
initialize和tools/list请求在POST上同步发送。 - 其他服务器到客户端消息(例如。,
tools/execute结果、通知)通过GET连接使用服务器发送事件(SSE)进行流式传输。 - 支持POST/GET/DELETE方法
何时使用:当您需要将MCP服务器暴露给通过HTTP而不是stdio进行通信的web客户端或系统时。
健康检查端点
使用HTTP传输时,可以在以下位置使用健康检查端点 /health 用于监控和服务发现:
# Check server health
curl http://localhost:3000/health
# Response:
# {
# "status": "healthy",
# "activeSessions": 2,
# "uptime": 3600
# }健康响应字段:
status:服务器运行时始终返回“健康”activeSessions:活动MCP会话数uptime:服务器正常运行时间(秒)
主要特点:
- 不要求进行验证
- 适用于任何HTTP方法(GET、POST等)
- 非常适合负载均衡器、Kubernetes探测器和监控系统
集成示例:
# Kubernetes liveness probe
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 3
periodSeconds: 10
# Docker healthcheck
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost:3000/health || exit 1安全注意事项
- HTTP传输验证Origin标头以防止DNS重新绑定攻击
- 默认情况下,HTTP传输仅绑定到localhost(127.0.0.1)
- 如果暴露给其他主机,请考虑实施额外的身份验证
调试
要查看调试日志,请执行以下操作:
- 在Claude Desktop中使用stdio传输时:
- 日志显示在Claude Desktop日志中
- 使用HTTP传输时:
npx @ivotoby/openapi-mcp-server --transport http &2>debug.log______________________________________________________________________
图书馆使用情况
本节面向希望将此包用作库来创建自定义MCP服务器的开发人员。
🚀 用作图书馆
通过导入和配置为特定API创建专用MCP服务器 OpenAPIServer 类。这种方法非常适合:
- 自定义身份验证:使用实现复杂的身份验证模式
AuthProvider接口 - API特定的优化:过滤端点,自定义错误处理,并针对特定用例进行优化
- 分布:将服务器打包为独立的npm模块,便于共享
- 整合:将服务器嵌入大型应用程序或添加自定义中间件
基本库使用
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, // Options: "all", "dynamic", "explicit"
}
const server = new OpenAPIServer(config)
const transport = new StdioServerTransport()
await server.start(transport)工具加载模式
这 toolsMode 配置选项控制从OpenAPI规范加载哪些工具:
// Load all tools from the spec (default)
const config = {
// ... other config
toolsMode: "all" as const,
// Optional: Apply filters to control which tools are loaded
includeTools: ["GET::users", "POST::users"], // Only these tools
includeTags: ["public"], // Only tools with these tags
includeResources: ["users"], // Only tools under these resources
includeOperations: ["get", "post"], // Only these HTTP methods
}
// Load only dynamic meta-tools for API exploration
const config = {
// ... other config
toolsMode: "dynamic" as const,
// Provides: list-api-endpoints, get-api-endpoint-schema, invoke-api-endpoint
}
// Load only explicitly specified tools (ignores other filters)
const config = {
// ... other config
toolsMode: "explicit" as const,
includeTools: ["GET::users", "POST::users"], // Only these exact tools
// includeTags, includeResources, includeOperations are ignored in explicit mode
}配置提示和资源
与API工具一起展示可重复使用的提示和静态资源:
import { OpenAPIServer } from "@ivotoby/openapi-mcp-server"
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,
transportType: "stdio" as const,
toolsMode: "all" as const,
// Define prompts with argument templates
prompts: [
{
name: "api_request",
title: "API Request Helper",
description: "Helps generate API request templates",
arguments: [
{ name: "endpoint", description: "API endpoint path", required: true },
{ name: "method", description: "HTTP method", required: false },
],
template: "Create a {{method}} request to {{endpoint}} with proper parameters.",
},
],
// Define resources with static content
resources: [
{
uri: "docs://api/overview",
name: "api-overview",
title: "API Overview",
description: "Overview of the API capabilities",
mimeType: "text/markdown",
text: "# API Overview\n\nThis API provides...",
},
],
}
const server = new OpenAPIServer(config)动态提示与资源管理
您还可以在服务器创建后动态添加提示和资源:
const server = new OpenAPIServer(config)
// Add prompts dynamically
const promptsManager = server.getPromptsManager()
if (promptsManager) {
promptsManager.addPrompt({
name: "debug_error",
title: "Error Debugger",
template: "Debug this API error: {{error_message}}",
})
}
// Add resources dynamically
const resourcesManager = server.getResourcesManager()
if (resourcesManager) {
resourcesManager.addResource({
uri: "docs://changelog",
name: "changelog",
title: "API Changelog",
mimeType: "text/markdown",
text: "# Changelog\n\n## v1.0.0\n- Initial release",
})
}提示定义格式
interface PromptDefinition {
name: string // Unique identifier
title?: string // Human-readable display title
description?: string // Description of the prompt
arguments?: {
// Template arguments
name: string
description?: string
required?: boolean
}[]
template: string // Template with {{argName}} placeholders
}资源定义格式
interface ResourceDefinition {
uri: string // Unique URI identifier
name: string // Resource name
title?: string // Human-readable display title
description?: string // Description of the resource
mimeType?: string // Content MIME type
text?: string // Static text content
blob?: string // Static binary content (base64)
contentProvider?: () => Promise // Dynamic content
}使用AuthProvider进行高级身份验证
对于具有令牌过期、刷新要求或复杂身份验证的API:
import { OpenAPIServer, AuthProvider } from "@ivotoby/openapi-mcp-server"
import { AxiosError } from "axios"
class MyAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise> {
// Called before each request - return fresh headers
if (this.isTokenExpired()) {
await this.refreshToken()
}
return { Authorization: `Bearer ${this.token}` }
}
async handleAuthError(error: AxiosError): Promise {
// Called on 401/403 errors - return true to retry
if (error.response?.status === 401) {
await this.refreshToken()
return true // Retry the request
}
return false
}
}
const authProvider = new MyAuthProvider()
const config = {
// ... other config
authProvider: authProvider, // Use AuthProvider instead of static headers
}📁 请参阅 示例/ 完整、可运行示例的目录,包括:
- 静态身份验证的基本库用法
- 不同场景的AuthProvider实现
- 现实世界Beatport API集成
- 生产就绪的包装模式
🔐 使用AuthProvider进行动态身份验证
这 AuthProvider 接口支持静态标头无法处理的复杂身份验证场景:
主要特点
- 动态标头:每个请求的新身份验证标头
- 令牌过期处理:自动检测和处理过期令牌
- 身份验证错误恢复:重试可恢复身份验证失败的逻辑
- 自定义错误消息:为用户提供清晰、可操作的指导
身份验证提供者接口
interface AuthProvider {
/**
* Get authentication headers for the current request
* Called before each API request to get fresh headers
*/
getAuthHeaders(): Promise>
/**
* Handle authentication errors from API responses
* Called when the API returns 401 or 403 errors
* Return true to retry the request, false otherwise
*/
handleAuthError(error: AxiosError): Promise
}常见模式
自动令牌刷新
class RefreshableAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise> {
if (this.isTokenExpired()) {
await this.refreshToken()
}
return { Authorization: `Bearer ${this.accessToken}` }
}
async handleAuthError(error: AxiosError): Promise {
if (error.response?.status === 401) {
await this.refreshToken()
return true // Retry with fresh token
}
return false
}
}手动令牌管理(例如Beatport)
class ManualTokenAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise> {
if (!this.token || this.isTokenExpired()) {
throw new Error(
"Token expired. Please get a new token from your browser:\n" +
"1. Go to the API website and log in\n" +
"2. Open browser dev tools (F12)\n" +
"3. Copy the Authorization header from any API request\n" +
"4. Update your token using updateToken()",
)
}
return { Authorization: `Bearer ${this.token}` }
}
updateToken(token: string): void {
this.token = token
this.tokenExpiry = new Date(Date.now() + 3600000) // 1 hour
}
}API密钥验证
class ApiKeyAuthProvider implements AuthProvider {
constructor(private apiKey: string) {}
async getAuthHeaders(): Promise> {
return { "X-API-Key": this.apiKey }
}
async handleAuthError(error: AxiosError): Promise {
throw new Error("API key authentication failed. Please check your key.")
}
}📖 有关详细的AuthProvider文档和示例,请参阅 docs/auth-provider-guide.md
OpenAPI模式处理
参考解析
此MCP服务器实现了健壮的OpenAPI引用($ref)确保准确表示API模式的解决方案:
- 参数引用:完全解决
$ref指向OpenAPI规范中参数组件的指针 - 架构引用:处理参数和请求体中的嵌套架构引用
- 递归引用:通过检测和处理循环引用来防止无限循环
- 嵌套属性:保留复杂的嵌套对象和数组结构及其所有属性
输入模式组合
服务器智能地将参数和请求体合并到每个工具的统一输入模式中:
- 参数+请求正文合并:将路径、查询和正文参数组合到一个架构中
- 碰撞处理:通过在与参数名称冲突的正文属性前加前缀来解决命名冲突
- 类型保存:维护所有架构元素的原始类型信息
- 元数据保留:保留描述、格式、默认值、枚举和其他架构属性
复杂模式支持
MCP服务器处理各种OpenAPI模式复杂性:
- 基本体类型:将非对象请求体包装在“body”属性中
- 物体主体:将对象属性平铺到工具的输入模式中
- 阵列体:正确处理数组模式及其嵌套项定义
- 所需属性:跟踪并保留所需的参数和属性
______________________________________________________________________
开发者信息
面向开发者
开发工具
npm run build-构建TypeScript源代码npm run clean-删除构建工件npm run typecheck-运行TypeScript类型检查npm run lint-运行ESLintnpm run dev-监视源文件并根据更改进行重建npm run inspect-watch-运行检查器,并在更改时自动重新加载
开发工作流程
- 克隆存储库
- 安装依赖项:
npm install - 启动开发环境:
npm run inspect-watch - 对中的TypeScript文件进行更改
src/ - 服务器将自动重建并重新启动
贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 运行测试和梳理:
npm run typecheck && npm run lint - 提交拉取请求
📖 有关全面的开发人员文档,请参阅 docs/developer-guide.md
______________________________________________________________________
常见问题解答
Q: 什么是“工具”? A: 工具对应于从您的OpenAPI规范派生的单个API端点,作为MCP资源公开。
Q: 我如何在自己的项目中使用此包? A: 您可以导入 OpenAPIServer 类,并将其用作Node.js应用程序中的库。这允许您为具有自定义身份验证、过滤和错误处理的特定API创建专用MCP服务器。请参阅 示例/ 完整实现的目录。
Q: 使用CLI和将其用作库有什么区别? A: CLI非常适合快速设置和测试,而库方法允许您为特定API创建专用包,使用 AuthProvider,添加自定义逻辑,并将服务器作为独立的npm模块分发。
Q: 如何处理令牌过期的API? A: 使用 AuthProvider 接口而不是静态标头。AuthProvider允许您通过令牌刷新、过期处理和自定义错误恢复来实现动态身份验证。有关不同的模式,请参阅AuthProvider示例。
Q: 什么是AuthProvider,我什么时候应该使用它? A. AuthProvider 是一个动态身份验证接口,在每次请求之前获取新的标头并处理身份验证错误。当API的令牌过期、需要刷新令牌或需要静态头无法处理的复杂身份验证逻辑时,请使用它。
Q: 如何筛选加载的工具? A: 使用 --tool, --tag, --resource,以及 --operation 旗帜与 --tools all (默认),设置 --tools dynamic 仅适用于元工具,或使用 --tools explicit 仅加载指定的工具 --tool (忽略其他过滤器)。
Q: 我什么时候应该使用动态模式? A: 动态模式提供元工具(list-api-endpoints, get-api-endpoint-schema, invoke-api-endpoint)无需预加载所有操作即可检查端点并与端点交互,这对于大型或不断变化的API非常有用。
Q: 什么是提示和资源? A. 提示 是具有参数占位符的可重用消息模板(例如。, {{name}})可以通过MCP检索 prompts/get 方法。 资源 是可以通过MCP读取的静态或动态内容(文本或二进制) resources/read 方法。两者都是可选功能,您可以与工具一起配置。
Q: 如何从CLI公开提示和资源? A: 使用 --prompts 对于提示和 --resources 资源。您还可以使用 --prompts-inline 和 --resources-inline 用于内联JSON。有关详细信息,请参阅《用户指南》中的“提示和资源”部分。
Q: 如何为API请求指定自定义标头? A: 使用 --headers 旗帜或 API_HEADERS 环境变量 key:value 使用CLI时用逗号分隔的对。对于图书馆使用,请使用 headers 配置选项或实现 AuthProvider 对于动态标头。
Q: 支持哪些运输方式? A: 服务器支持stdio传输(默认)以与AI系统集成,并支持web客户端的HTTP传输(通过SSE进行流式传输)。
Q: 服务器如何处理带有引用的复杂OpenAPI模式? A: 服务器完全解析 $ref 参数和模式中的引用,保留嵌套结构、默认值和其他属性。有关引用解析和模式组合的详细信息,请参阅“OpenAPI模式处理”部分。
Q: 当参数名称与请求正文属性冲突时会发生什么? A: 服务器检测到命名冲突,并自动在正文属性名称前加上前缀 body_ 为了避免冲突,请确保所有属性都是可访问的。
Q: 我可以打包我的MCP服务器进行分发吗? A: 是的!当使用库方法时,您可以为API创建一个专用的npm包。有关可以打包和分发为的完整实现,请参阅Beatport示例 npx your-api-mcp-server.
Q: 我在哪里可以找到发展和贡献指南? A: 请参阅 开发者指南 获取有关架构、关键概念、开发工作流程和贡献指南的全面文档。
许可证
麻省理工学院
