使用说明
OpenAPI MCP服务器
一个通用的模型上下文协议(MCP)服务器,它动态地将OpenAPI定义的REST API作为MCP工具公开。这使得像Claude这样的大型语言模型能够通过标准化的MCP协议发现任何符合OpenAPI的API并与之交互。
✨ 主要特点
- 🔄 动态工具生成:自动将OpenAPI操作转换为MCP工具
- 🔐 灵活的身份验证:静态标头、动态提供程序、令牌刷新
- 📊 高级过滤:按标签、资源、操作或显式列表筛选工具
- 🌐 多个传输:用于Claude Desktop的Stdio,用于web应用程序的HTTP
- 📝 智能工具命名:智能缩写,长度≤64个字符
- � 元工具:内置API探索和动态端点调用
- 🏗 基于接口的体系结构:类型安全、模块化设计,具有全面的接口
- 📥 多种输入法:URL、文件、stdin或内联OpenAPI规范
🚀 快速开始
CLI用法(推荐)
# Install globally
npm install -g @lucid-spark/openapi-mcp-server
# Use with any OpenAPI-compliant API
openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--transport stdio
Docker使用(生产就绪)
# Run with HTTP transport
docker run --rm -p 3000:3000 \
-e API_BASE_URL=https://petstore.swagger.io/v2 \
-e OPENAPI_SPEC_PATH=https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json \
-e TRANSPORT_TYPE=http \
reallv/openapi-mcp-server:latest
# Run with stdio transport (for Claude Desktop)
docker run --rm -i \
-e API_BASE_URL=https://api.example.com \
-e OPENAPI_SPEC_PATH=https://api.example.com/openapi.json \
reallv/openapi-mcp-server:latest
# Use docker-compose for multiple APIs
docker-compose up -d
图书馆使用情况
npm install @lucid-spark/openapi-mcp-server
import { OpenAPIServer } from "@lucid-spark/openapi-mcp-server";
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "https://api.example.com/openapi.json",
transportType: "stdio",
});
await server.start();
📖 文档
有关MCP协议的详细信息,请参阅 模型上下文协议.io.
📋 目录
🏗 建筑
OpenAPI MCP服务器采用模块化、基于接口的架构,以实现最大的灵活性和类型安全性:
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ OpenAPI Server │ │ Configuration │ │ Type System │
│ │ │ │ │ │
│ • Orchestration │◄──►│ • Validation │◄──►│ • Interface-based │
│ • MCP Protocol │ │ • Defaults │ │ • Type Safety │
│ • Lifecycle Mgmt │ │ • Environment Vars │ │ • Extensibility │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ OpenAPI Spec │ │ Tools Manager │ │ Authentication │
│ Loader │ │ │ │ System │
│ │ │ • Tool Creation │ │ │
│ • Multiple Inputs │ │ • Filtering │ │ • Static Headers │
│ • $ref Resolution │ │ • Lookup & Cache │ │ • Dynamic Providers │
│ • Schema Processing │ │ • Meta-tools │ │ • Token Refresh │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ Tool System │ │ API Client │ │ Transport Layer │
│ │ │ │ │ │
│ • ID Generation │ │ • HTTP Requests │ │ • Stdio (Claude) │
│ • Name Abbreviation │ │ • Auth Integration │ │ • HTTP (Web Apps) │
│ • Schema Mapping │ │ • Error Handling │ │ • Session Mgmt │
└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
关键组件
- 类型系统(
types/):确保类型安全和模块化的接口定义 - 配置系统:验证设置、应用默认值、支持环境变量
- OpenAPI规范加载器:以$ref分辨率处理多个输入法
- 工具管理器:从OpenAPI操作中创建和过滤MCP工具
- 验证系统:支持静态标头和动态身份验证提供程序
- API客户端:使用重试逻辑执行经过身份验证的HTTP请求
- 传输层:用于Claude Desktop的Stdio,用于web应用程序的HTTP
- 工具实用程序:ID生成、名称缩写、模式处理
用户指南
本节介绍如何使用Claude Desktop、Cursor或其他MCP兼容工具作为最终用户使用MCP服务器。
概述
此MCP服务器有两种使用方式:
- CLI工具:使用
npx @lucid-spark/openapi-mcp-server 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
- 在macOS上:
-
添加以下配置:
{
"mcpServers": {
"openapi": {
"command": "npx",
"args": ["-y", "@lucid-spark/openapi-mcp-server", "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的基本URLOPENAPI_SPEC_PATH:指向OpenAPI规范的URL或路径API_HEADERS:逗号分隔的密钥:API身份验证标头的值对
选项2:与HTTP客户端一起使用(HTTP传输)
要将服务器与HTTP客户端一起使用:
- 无需安装!使用npx直接运行包:
npx @lucid-spark/openapi-mcp-server 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
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"
📦 安装
先决条件
- Node.js:18.0.0或更高
- npm:8.0.0或更高
- TypeScript5.3.0或更高(用于开发)
全局安装(CLI)
npm install -g @lucid-spark/openapi-mcp-server
本地安装(库)
npm install @lucid-spark/openapi-mcp-server
开发安装
git clone https://github.com/lucivuc/openapi-mcp-server.git
cd openapi-mcp-server
npm install
npm run build
🐳 Docker使用
Docker快速入门
运行OpenAPI MCP服务器最简单的方法是使用Docker。无需安装本地Node.js!
# Pull the latest image
docker pull reallv/openapi-mcp-server:latest
# Run with Petstore API example
docker run --rm -p 3000:3000 \
-e API_BASE_URL=https://petstore.swagger.io/v2 \
-e OPENAPI_SPEC_PATH=https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json \
-e TRANSPORT_TYPE=http \
reallv/openapi-mcp-server:latest
Docker Compose(推荐)
对于生产部署和多个API服务器:
# Clone and configure
git clone https://github.com/lucivuc/openapi-mcp-server.git
cd openapi-mcp-server
cp docker-env-example.txt .env
# Edit .env with your API configuration
# Start the server
docker-compose up -d
# Start with example APIs
docker-compose --profile examples up -d
# View logs
docker-compose logs -f
MCP工具包目录集成
此服务器旨在包含在Docker的MCP Toolkit目录中。这 mcp-server.json 文件提供:
- 标准化配置:所有选项的完整架构
- 使用示例:通用API的即用型配置
- Docker集成:预构建图像和编写文件
- 多种运输支持:stdio和HTTP传输
- 生产就绪:安全强化的非根容器
环境配置
通过环境变量进行配置(非常适合Docker):
# Required
API_BASE_URL=https://api.example.com
OPENAPI_SPEC_PATH=https://api.example.com/openapi.json
# Authentication
API_HEADERS="Authorization:Bearer token,X-API-Key:key"
# Transport
TRANSPORT_TYPE=http
HTTP_PORT=3000
HTTP_HOST=0.0.0.0
# Tool filtering
TOOLS_MODE=all
INCLUDE_TAGS=public,users
INCLUDE_OPERATIONS=GET,POST
看 Docker使用指南 获取完整的文档、部署模式和生产最佳实践。
⚙️ 配置
完整的配置界面
interface IOpenAPIServerConfig {
// Required
apiBaseUrl: string; // Base URL for API endpoints
// OpenAPI Specification
openApiSpec?: string; // Path, URL, or inline content
specInputMethod?: SpecInputMethod; // 'url' | 'file' | 'stdin' | 'inline'
// Server Identity
name?: string; // Server name (default: 'openapi-mcp-server')
version?: string; // Server version (default: '1.0.3')
namespace?: string; // Namespace for the MCP server tools
// Authentication (choose one)
headers?: Record<string, string>; // Static headers
authProvider?: IAuthProvider; // Dynamic authentication
// Transport
transportType?: TransportType; // 'stdio' | 'http' (default: 'stdio')
httpPort?: number; // HTTP port (default: 3000)
httpHost?: string; // HTTP host (default: '127.0.0.1')
endpointPath?: string; // HTTP endpoint (default: '/mcp')
// Tool Management
toolsMode?: ToolsMode; // 'all' | 'dynamic' | 'explicit'
includeTools?: string[]; // Specific tools to include
includeTags?: string[]; // OpenAPI tags to include
includeResources?: string[]; // Resource paths to include
includeOperations?: string[]; // HTTP methods to include
// Options
disableAbbreviation?: boolean; // Disable tool name abbreviation
debug?: boolean; // Enable debug logging
}
环境变量
所有配置选项都可以通过环境变量进行设置:
# Required
export API_BASE_URL="https://api.example.com"
# OpenAPI Spec
export OPENAPI_SPEC_PATH="./api-spec.yaml"
export OPENAPI_SPEC_FROM_STDIN="true"
export OPENAPI_SPEC_INLINE='{"openapi":"3.0.0",...}'
# Authentication
export API_HEADERS="Authorization:Bearer token,X-API-Key:key"
# Server
export SERVER_NAME="my-api-server"
export SERVER_VERSION="2.0.0"
export NAMESPACE="my-namespace"
# Transport
export TRANSPORT_TYPE="http"
export HTTP_PORT="8080"
export HTTP_HOST="0.0.0.0"
export ENDPOINT_PATH="/mcp"
# Tool Management
export TOOLS_MODE="all"
export DISABLE_ABBREVIATION="true"
命令行参数
npx @lucid-spark/openapi-mcp-server 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
🎯 使用示例
基本示例
公共API(无身份验证)
openapi-mcp-server \
--api-base-url https://jsonplaceholder.typicode.com \
--openapi-spec https://jsonplaceholder.typicode.com/openapi.json
带身份验证的API
openapi-mcp-server \
--api-base-url https://api.github.com \
--openapi-spec https://api.github.com/openapi.json \
--headers "Authorization:Bearer ghp_xxxxxxxxxxxx,Accept:application/vnd.github.v3+json"
当地API开发
openapi-mcp-server \
--api-base-url http://localhost:8080 \
--openapi-spec ./local-api-spec.yaml \
--debug
高级示例
过滤的API子集
openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json \
--tag public \
--operation GET \
--operation POST \
--resource users
Web应用程序的HTTP传输
openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec ./api-spec.yaml \
--transport http \
--port 3000 \
--host 0.0.0.0
仅限动态元工具
openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec ./api-spec.yaml \
--tools dynamic
🖥 Claude桌面集成
基本配置
添加到您的Claude Desktop配置文件中:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
视窗: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"my-api": {
"command": "npx",
"args": [
"@lucid-spark/openapi-mcp-server",
"openapi-mcp-server",
"--api-base-url",
"https://api.example.com",
"--openapi-spec",
"https://api.example.com/openapi.json"
]
}
}
}
通过身份验证
{
"mcpServers": {
"github-api": {
"command": "npx",
"args": [
"@lucid-spark/openapi-mcp-server",
"openapi-mcp-server",
"--api-base-url",
"https://api.github.com",
"--openapi-spec",
"https://api.github.com/openapi.json",
"--headers",
"Authorization:Bearer ${GITHUB_TOKEN},Accept:application/vnd.github.v3+json"
],
"env": {
"GITHUB_TOKEN": "your-github-token-here"
}
}
}
}
🔐 认证
静态标头(简单)
非常适合具有长期令牌或API密钥的API:
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
headers: {
Authorization: "Bearer your-long-lived-token",
"X-API-Key": "your-api-key",
Accept: "application/json",
},
});
动态身份验证(高级)
非常适合具有需要刷新的短期令牌的API:
class GitHubAuthProvider implements IAuthProvider {
private accessToken: string;
private tokenExpiry: Date;
async getAuthHeaders(): Promise<Record<string, string>> {
if (this.isTokenExpired()) {
throw new Error("Token expired. Please authenticate again.");
}
return {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/vnd.github.v3+json",
"User-Agent": "OpenAPI-MCP-Server",
};
}
async handleAuthError(error: AxiosError): Promise<boolean> {
if (error.response?.status === 401) {
// GitHub tokens don't refresh automatically
// In a real implementation, you might redirect to OAuth flow
throw new Error(
"GitHub authentication failed. Please update your token.",
);
}
return false;
}
private isTokenExpired(): boolean {
return !this.tokenExpiry || this.tokenExpiry <= new Date();
}
}
🛠 工具管理
工具ID系统
使用处理复杂OpenAPI路径的强大ID系统来识别工具:
- 格式:
METHOD::pathPart - 路径编码:使用双下划线(
__)分隔路径段和三段划线(---)指示路径参数 - 例子:
GET::users→GET /usersPOST::api__v1__users→POST /api/v1/usersGET::users__123__posts→GET /users/123/postsGET::users__---userId---→GET /users/{userId}PUT::api__v1__users__---id---__profile→PUT /api/v1/users/{id}/profile
工具名称生成
工具名称会自动生成,并带有智能缩写:
- 长度限制:≤64个字符
- 格式:
[a-z0-9-]+ - 智能缩写:删除常用词,使用标准缩写
- 例子:
getUserDetails→get-user-detailsServiceUsersManagementController_updateUser→svc-usrs-mgmt-upd-usr-a1b2
元工具
服务器为动态API探索提供了三个内置元工具:
1. list-api-endpoints
列出具有可选筛选的所有可用API终结点:
{
"name": "list-api-endpoints",
"arguments": {
"tag": "users",
"method": "GET"
}
}
2. get-api-endpoint-schema
获取特定终结点的详细架构信息:
{
"name": "get-api-endpoint-schema",
"arguments": {
"toolId": "GET::users__123"
}
}
3. invoke-api-endpoint
直接调用任何API端点:
{
"name": "invoke-api-endpoint",
"arguments": {
"toolId": "POST::users",
"parameters": {
"name": "John Doe",
"email": "john@example.com"
}
}
}
🌐 运输类型
标准传输(默认)
针对Claude Desktop和其他MCP客户端进行了优化:
const server = new OpenAPIServer({
// ... config
transportType: "stdio",
});
HTTP传输
启用基于web的MCP客户端:
const server = new OpenAPIServer({
// ... config
transportType: "http",
httpPort: 3000,
httpHost: "0.0.0.0",
endpointPath: "/mcp",
});
图书馆使用情况
本节介绍如何在您自己的应用程序中将该包用作库。
安装
在项目中安装该包:
npm install @lucid-spark/openapi-mcp-server
基本用法
import { OpenAPIServer } from "@lucid-spark/openapi-mcp-server";
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "https://api.example.com/openapi.json",
transportType: "stdio",
});
await server.start();
高级配置
import {
OpenAPIServer,
IOpenAPIServerConfig,
IAuthProvider,
validateConfig,
} from "@lucid-spark/openapi-mcp-server";
// Custom authentication provider
class CustomAuthProvider implements IAuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
return {
Authorization: `Bearer ${await this.getValidToken()}`,
"X-Custom-Header": "custom-value",
};
}
async handleAuthError(error: any): Promise<boolean> {
// Handle authentication errors
if (error.response?.status === 401) {
await this.refreshToken();
return true; // Retry request
}
return false;
}
private async getValidToken(): Promise<string> {
// Implementation depends on your auth system
return "your-token";
}
private async refreshToken(): Promise<void> {
// Refresh token logic
}
}
// Complete server configuration
const config: IOpenAPIServerConfig = {
apiBaseUrl: "https://api.example.com",
openApiSpec: "./api-spec.yaml",
specInputMethod: "file",
name: "my-custom-server",
version: "2.0.0",
namespace: "my-api",
authProvider: new CustomAuthProvider(),
transportType: "http",
httpPort: 8080,
httpHost: "0.0.0.0",
endpointPath: "/mcp",
toolsMode: "all",
includeTags: ["users", "posts"],
includeOperations: ["GET", "POST"],
disableAbbreviation: false,
debug: true,
};
// Validate configuration before use
const validatedConfig = validateConfig(config);
// Create and start server
const server = new OpenAPIServer(validatedConfig);
await server.start();
// Get server statistics
const stats = server.getStats();
console.log(`Server running with ${stats.toolCount} tools`);
// Test connection
const isConnected = await server.testConnection();
console.log(`API connection: ${isConnected ? "OK" : "Failed"}`);
// Stop server when done
await server.stop();
自定义工具筛选
import { OpenAPIServer, ToolsManager } from "@lucid-spark/openapi-mcp-server";
// Example: Only include tools for user management
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "./api-spec.yaml",
toolsMode: "explicit",
includeTools: [
"GET::users",
"POST::users",
"GET::users__123",
"PUT::users__123",
"DELETE::users__123",
],
});
集成示例
Express.js集成
import express from "express";
import { OpenAPIServer } from "@lucid-spark/openapi-mcp-server";
const app = express();
const mcpServer = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "./api-spec.yaml",
transportType: "http",
httpPort: 3001, // Different port from Express
httpHost: "127.0.0.1",
});
// Start MCP server alongside Express
app.listen(3000, async () => {
console.log("Express server running on port 3000");
await mcpServer.start();
console.log("MCP server running on port 3001");
});
CLI工具集成
#!/usr/bin/env node
import { Command } from "commander";
import { OpenAPIServer, validateConfig } from "@lucid-spark/openapi-mcp-server";
const program = new Command();
program
.name("my-mcp-tool")
.description("Custom MCP server for My API")
.requiredOption("--token <token>", "API authentication token")
.option("--port <port>", "HTTP port", "3000")
.action(async (options) => {
const config = validateConfig({
apiBaseUrl: "https://my-api.com",
openApiSpec: "https://my-api.com/openapi.json",
headers: {
Authorization: `Bearer ${options.token}`,
},
transportType: "http",
httpPort: parseInt(options.port),
});
const server = new OpenAPIServer(config);
await server.start();
console.log(`MCP server running on port ${options.port}`);
// Graceful shutdown
process.on("SIGINT", async () => {
console.log("Shutting down...");
await server.stop();
process.exit(0);
});
});
program.parse();
错误处理
import { OpenAPIServer } from "@lucid-spark/openapi-mcp-server";
try {
const server = new OpenAPIServer({
apiBaseUrl: "https://api.example.com",
openApiSpec: "invalid-spec.json",
});
await server.start();
} catch (error) {
if (error.message.includes("OpenAPI specification")) {
console.error("Failed to load OpenAPI spec:", error.message);
} else if (error.message.includes("API connection")) {
console.error("Failed to connect to API:", error.message);
} else {
console.error("Server startup failed:", error.message);
}
}
TypeScript支持
该包包括全面的TypeScript定义:
import {
OpenAPIServer,
IOpenAPIServerConfig,
IAuthProvider,
ITool,
IToolsFilter,
ToolsMode,
TransportType,
SpecInputMethod,
HttpMethod,
validateConfig,
generateToolId,
parseToolId,
generateToolName,
DEFAULT_CONFIG,
} from "@lucid-spark/openapi-mcp-server";
// All types are fully typed for excellent IDE support
📚 API文档
TypeScript接口导出
// Core server
export { OpenAPIServer } from "@lucid-spark/openapi-mcp-server";
// Configuration
export {
validateConfig,
DEFAULT_CONFIG,
} from "@lucid-spark/openapi-mcp-server";
// Authentication
export {
StaticAuthProvider,
isAuthError,
} from "@lucid-spark/openapi-mcp-server";
// OpenAPI specification handling
export { OpenAPISpecLoader } from "@lucid-spark/openapi-mcp-server";
// Tool creation and management
export {
createToolFromOperation,
createMetaTools,
} from "@lucid-spark/openapi-mcp-server";
export { ToolsManager } from "@lucid-spark/openapi-mcp-server";
// HTTP client
export { ApiClient } from "@lucid-spark/openapi-mcp-server";
// Tool utilities
export {
generateToolId,
parseToolId,
sanitizeForToolId,
extractResourceName,
isValidToolId,
isValidHttpMethod,
HTTP_METHODS,
generateToolName,
isValidToolName,
} from "@lucid-spark/openapi-mcp-server";
// Transport layer
export {
BaseTransportHandler,
StdioTransportHandler,
HttpTransportHandler,
createTransportHandler,
} from "@lucid-spark/openapi-mcp-server";
// Logging utilities
export { Logger, logger, setDebugMode } from "@lucid-spark/openapi-mcp-server";
// MCP SDK types
export type { Tool } from "@modelcontextprotocol/sdk/types.js";
// All interface definitions from types directory
export * from "@lucid-spark/openapi-mcp-server";
核心方法
OpenAPIServer
class OpenAPIServer {
constructor(config: IOpenAPIServerConfig);
async start(): Promise<void>;
async stop(): Promise<void>;
getStats(): ServerStats;
async testConnection(): Promise<boolean>;
}
配置
function validateConfig(config: IOpenAPIServerConfig): IOpenAPIServerConfig;
const DEFAULT_CONFIG: Partial<IOpenAPIServerConfig>;
认证
interface IAuthProvider {
getAuthHeaders(): Promise<Record<string, string>>;
handleAuthError(error: AxiosError): Promise<boolean>;
}
class StaticAuthProvider implements IAuthProvider {
constructor(headers: Record<string, string>);
}
🧪 发展
设置开发环境
# Clone repository
git clone https://github.com/lucivuc/openapi-mcp-server.git
cd openapi-mcp-server
# Install dependencies
npm install
# Build project
npm run build
# Run development server with CryptoMkt API
npm run dev:cryptomkt
可用脚本
# Build TypeScript
npm run build
# Development with different APIs
npm run dev:bible # Bible API with authentication
npm run dev:cryptomkt # CryptoMkt API
npm run dev:petstore:v2:json # Petstore API v2.0 JSON
npm run dev:petstore:v2:yaml # Petstore API v2.0 YAML
npm run dev:petstore:v3:json # Petstore API v3.0 JSON
npm run dev:petstore:v3:yaml # Petstore API v3.0 YAML
npm run dev:petstore:v3.1:json # Petstore API v3.1 JSON
npm run dev:petstore:v3.1:yaml # Petstore API v3.1 YAML
# Run MCP Inspector with different APIs
npm run inspect:bible
npm run inspect:cryptomkt
npm run inspect:petstore:v2:json
npm run inspect:petstore:v2:yaml
npm run inspect:petstore:v3:json
npm run inspect:petstore:v3:yaml
npm run inspect:petstore:v3.1:json
npm run inspect:petstore:v3.1:yaml
# Testing
npm run test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage
npm run test:verbose # Run tests with verbose output
# Code quality
npm run format # Format code with Prettier
npm run format:staged # Format staged files
# Development tools
npm run cli -- --help # Run CLI with help
npm run depcheck # Check for unused dependencies
npm start # Start built server
项目结构
openapi-mcp-server/
├── src/ # Source code
│ ├── types/ # TypeScript interface definitions
│ │ ├── core.ts # Core type definitions
│ │ ├── config.ts # Configuration interfaces
│ │ ├── auth.ts # Authentication interfaces
│ │ ├── api.ts # API client interfaces
│ │ ├── openapi.ts # OpenAPI specification interfaces
│ │ ├── tools.ts # Tool management interfaces
│ │ ├── transport.ts # Transport interfaces
│ │ └── index.ts # Type exports
│ ├── core/ # Core server implementation
│ │ ├── config.ts # Configuration validation and defaults
│ │ ├── server.ts # Main OpenAPI MCP Server class
│ │ └── index.ts # Core exports
│ ├── auth/ # Authentication providers
│ │ ├── providers.ts # Static auth provider and utilities
│ │ └── index.ts # Auth exports
│ ├── api/ # HTTP client
│ │ ├── client.ts # ApiClient implementation
│ │ └── index.ts # API exports
│ ├── tools/ # Tool management system
│ │ ├── creation.ts # Tool creation from OpenAPI operations
│ │ ├── manager.ts # ToolsManager for filtering and caching
│ │ ├── utils/ # Tool utilities (ID generation, etc.)
│ │ └── index.ts # Tools exports
│ ├── transport/ # Transport implementations
│ │ ├── base.ts # Base transport handler and factory
│ │ ├── stdio.ts # Stdio transport for Claude Desktop
│ │ ├── http.ts # HTTP transport for web applications
│ │ └── index.ts # Transport exports
│ ├── openapi/ # OpenAPI specification handling
│ │ ├── spec-loader.ts # OpenAPISpecLoader with multiple input methods
│ │ └── index.ts # OpenAPI exports
│ ├── utils/ # Utility functions
│ │ ├── logger.ts # Logging system with debug support
│ │ └── index.ts # Utils exports
│ ├── cli.ts # Command-line interface
│ └── index.ts # Library entry point
├── examples/ # Usage examples
├── docs/ # Documentation website
├── test/ # Test files
├── coverage/ # Test coverage reports
├── dist/ # Compiled JavaScript
└── package.json # Project configuration
📁 例子
这 examples/ 目录包含全面的使用示例:
basic-jsonplaceholder.ts:简单的JSONPlaceholder API,带有内联OpenAPI规范、stdio传输、调试日志记录example.ts:演示基本服务器设置和启动生命周期的最小HTTP服务器示例dynamic-auth.ts:使用自定义IAuthProvider进行高级身份验证、令牌刷新和使用httpbin.org进行错误处理http-filtering.ts:使用Petstore API的HTTP传输,通过标签/方法进行全面过滤,服务器统计cli-usage.ts:带有彩色输出、环境变量和Claude Desktop配置的交互式CLI文档cli-examples.md:完整的CLI使用参考,包括真实的API示例、身份验证模式和故障排除
有关详细的实现模式,请参阅各个示例文件,有关全面的使用文档,请参阅CLI示例markdown。
看 示例README 详细文档。
🐛 故障排除
常见问题
OpenAPI规范加载失败
症状:从URL/文件加载规范时出错 解决方案:
- 验证URL可访问性:
curl -I https://api.example.com/openapi.json - 检查文件权限:
ls -la ./api-spec.yaml - 验证JSON/YAML语法:
json_verify < spec.json - 使用
--debug详细错误信息标志
2.未生成工具
症状:服务器已启动,但没有可用的工具 解决方案:
- 确保OpenAPI规范有效
paths章节 - 检查筛选条件(标签、操作、资源)
- 验证
operationId或summary字段存在 - 使用
--tools dynamic始终有可用的元工具
3.身份验证错误
症状:来自API的401/403响应 解决方案:
- 独立验证API凭据:
curl -H "Authorization: Bearer token" https://api.example.com/test - 检查令牌过期和格式
- 验证标头名称和值
- 在中实施适当的错误处理
IAuthProvider
调试模式
启用全面日志记录:
openapi-mcp-server --debug --api-base-url https://api.example.com --openapi-spec ./spec.yaml
调试输出包括:
- 配置验证详细信息
- OpenAPI规范加载进度
- 工具创建和过滤步骤
- 身份验证标头应用程序
- API请求/响应详细信息
- 传输层操作
📄 许可证
MIT许可证-请参阅 许可证 文件以获取详细信息。
🤝 贡献
欢迎投稿!请阅读我们的 贡献指南 有关我们的行为准则和提交pull请求流程的详细信息。
🙏 致谢
- 模型上下文协议 -协议规范
- OpenAPI倡议 -OpenAPI规范
- Anthropic -Claude桌面集成
- TypeScript -类型安全开发
由...制作❤️ 对于MCP生态系统
3. Replace the environment variables with your actual API configuration:
- `API_BASE_URL`: The base URL of your API
- `OPENAPI_SPEC_PATH`: URL or path to your OpenAPI specification
- `API_HEADERS`: Comma-separated key:value pairs for API authentication headers
### Option 2: Using with HTTP Clients (HTTP Transport)
To use the server with HTTP clients:
1. No installation required! Use npx to run the package directly:
```bash
npx @lucid-spark/openapi-mcp-server 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标头的值对SERVER_NAME-MCP服务器的名称(默认:“openapi-MCP服务器”)SERVER_VERSION-服务器版本(默认:“1.0.3”)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个字符时,这可能会引发错误)
命令行参数
npx @lucid-spark/openapi-mcp-server 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
OpenAPI规范加载
MCP服务器支持多种加载OpenAPI规范的方法,为不同的部署场景提供了灵活性:
1.URL加载(默认)
从远程URL加载OpenAPI规范:
npx @lucid-spark/openapi-mcp-server openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec https://api.example.com/openapi.json
2.本地文件加载
从本地文件加载OpenAPI规范:
npx @lucid-spark/openapi-mcp-server openapi-mcp-server \
--api-base-url https://api.example.com \
--openapi-spec ./path/to/openapi.yaml
3.标准输入加载
从标准输入中读取OpenAPI规范(适用于管道或容器化环境):
# Pipe from file
cat openapi.json | npx @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server openapi-mcp-server \
--api-base-url https://api.example.com
4.内联规格
直接将OpenAPI规范内容作为命令行参数提供:
npx @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server 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|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等)。可以多次使用。
示例:
# Load only dynamic meta-tools
npx @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server 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 @lucid-spark/openapi-mcp-server openapi-mcp-server
--api-base-url https://api.example.com
--openapi-spec https://api.example.com/openapi.json
--operation post
运输类型
标准传输(默认)
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传输验证Origin标头以防止DNS重新绑定攻击
- 默认情况下,HTTP传输仅绑定到localhost(127.0.0.1)
- 如果暴露给其他主机,请考虑实施额外的身份验证
调试
要查看调试日志,请执行以下操作:
-
在Claude Desktop中使用stdio传输时:
- 日志显示在Claude Desktop日志中
-
使用HTTP传输时:
npx @lucid-spark/openapi-mcp-server openapi-mcp-server --transport http &2>debug.log
图书馆使用情况
本节面向希望将此包用作库来创建自定义MCP服务器的开发人员。
🚀 用作图书馆
通过导入和配置为特定API创建专用MCP服务器 OpenAPIServer 类。这种方法非常适合:
- 自定义身份验证:使用实现复杂的身份验证模式
AuthProvider接口 - API特定的优化:过滤端点,自定义错误处理,并针对特定用例进行优化
- 分布:将服务器打包为独立的npm模块,便于共享
- 整合:将服务器嵌入大型应用程序或添加自定义中间件
基本库使用
import { OpenAPIServer } from "@lucid-spark/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
};
使用AuthProvider进行高级身份验证
对于具有令牌过期、刷新要求或复杂身份验证的API:
import { OpenAPIServer, IAuthProvider } from "@lucid-spark/openapi-mcp-server";
import { AxiosError } from "axios";
class MyAuthProvider implements IAuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
// Called before each request - return fresh headers
if (this.isTokenExpired()) {
await this.refreshToken();
}
return { Authorization: `Bearer ${this.token}` };
}
async handleAuthError(error: AxiosError): Promise<boolean> {
// 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<Record<string, string>>;
/**
* 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<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; // Retry with fresh token
}
return false;
}
}
手动令牌管理(例如Beatport)
class ManualTokenAuthProvider implements AuthProvider {
async getAuthHeaders(): Promise<Record<string, string>> {
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<Record<string, string>> {
return { "X-API-Key": this.apiKey };
}
async handleAuthError(error: AxiosError): Promise<boolean> {
throw new Error("API key authentication failed. Please check your key.");
}
}
📖 有关详细的身份验证模式和示例,请参阅 示例/ 目录
OpenAPI模式处理
指代消解
此MCP服务器实现了健壮的OpenAPI引用($ref)确保准确表示API模式的解决方案:
- 参数引用:完全解决
$ref指向OpenAPI规范中参数组件的指针 - 架构引用:处理参数和请求体中的嵌套架构引用
- 递归引用:通过检测和处理循环引用来防止无限循环
- 嵌套属性:保留复杂的嵌套对象和数组结构及其所有属性
输入模式组合
服务器智能地将参数和请求体合并到每个工具的统一输入模式中:
- 参数+请求正文合并:将路径、查询和正文参数组合到一个架构中
- 碰撞处理:通过在与参数名称冲突的正文属性前加前缀来解决命名冲突
- 类型保存:维护所有架构元素的原始类型信息
- 元数据保留:保留描述、格式、默认值、枚举和其他架构属性
复杂模式支持
MCP服务器处理各种OpenAPI模式复杂性:
- 基本体类型:将非对象请求体包装在“body”属性中
- 物体主体:将对象属性平铺到工具的输入模式中
- 阵列体:正确处理数组模式及其嵌套项定义
- 所需属性:跟踪并保留所需的参数和属性
开发者信息
对于开发者
开发工具
npm run build-构建TypeScript源代码npm run test-使用Jest运行测试套件npm run test:watch-在监视模式下运行测试npm run test:coverage-运行具有覆盖率报告的测试npm run format-使用Prettier格式化代码npm run format:staged-仅格式化暂存文件npm run dev:cryptomkt-使用CryptoMkt API运行开发服务器npm run inspect:cryptomkt-使用CryptoMkt API运行MCP检查器
开发工作流程
- 克隆仓库
- 安装依赖项:
npm install - 启动开发环境:
npm run dev:cryptomkt或npm run inspect:cryptomkt - 对中的TypeScript文件进行更改
src/ - 运行测试:
npm run test - 格式代码:
npm run format
贡献
- 克隆该仓库
- 创建要素分支
- 进行更改
- 运行测试:
npm run test - 格式代码:
npm run format - 提交拉取请求
📖 有关全面的开发人员文档和贡献指南,请参阅 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: 如何为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: 请参阅 开发者指南 获取有关架构、关键概念、开发工作流程和贡献指南的全面文档。
许可证
麻省理工学院
