Sponsored by Deepsite.site

Openapi2mcp

Created By
oil-oil6 months ago
OpenAPI2MCP (Model Context Protocol) that allows AI clients to call any OpenAPI-compatible REST API through the MCP interface. This tool converts OpenAPI specifications into MCP tools, enabling AI clients to interact with external APIs seamlessly.
Content

中文

OpenAPI2MCP

OpenAPI2MCP that allows AI clients to call any OpenAPI-compatible REST API through the MCP interface. This tool converts OpenAPI specifications into MCP tools, enabling AI clients to interact with external APIs seamlessly.

Features

  • Universal API Support: Works with any OpenAPI 2.0/3.0 compatible API
  • 🔄 Multiple Transport Modes: STDIO, HTTP, and SSE (Server-Sent Events)
  • 🔐 Flexible Authentication: Support for API keys, Bearer tokens, and custom headers
  • 🔧 Easy Configuration: Support for environment variables and URL parameter configuration
  • 🎯 Smart API Merging: Intelligently merge related API endpoints into unified tools to reduce tool count for AI clients with limitations (e.g., Cursor)
  • 💾 Efficient Caching: Support for OpenAPI specification caching to improve performance

Quick Start

Prerequisites

  • Node.js 18+ and pnpm
  • An OpenAPI specification (JSON or YAML)
  • API credentials (if required)
  • An MCP-compatible client (Claude Desktop, Cursor, Cline, etc.)

Installation and Build

git clone https://github.com/oil-oil/openapi2mcp.git
cd openapi2mcp
pnpm install
pnpm run build

MCP Client Configuration

STDIO Mode

Configure your MCP client by adding the following to your configuration file:

{
  "mcpServers": {
    "openapi2mcp": {
      "command": "npx",
      "args": ["-y", "openapi2mcp"],
      "env": {
        "TRANSPORT_TYPE": "stdio",
        "API_BASE_URL": "https://petstore3.swagger.io/api/v3",
        "OPENAPI_SPEC_URL": "https://petstore3.swagger.io/api/v3/openapi.json",
        "HEADER.Authorization": "Bearer your-token-here",
        "HEADER.Content-Type": "application/json"
      }
    }
  }
}

SSE Mode

First, start the SSE server:

pnpm start:sse

Then configure your MCP client:

{
  "mcpServers": {
    "openapi2mcp": {
      "url": "http://localhost:3000/sse?base_url=https://petstore3.swagger.io/api/v3&openapi_spec=https://petstore3.swagger.io/api/v3/openapi.json&headers.Content-Type=application%2Fjson&message_path=/custom/message"
    }
  }
}

Available SSE Parameters:

  • base_url - API base URL (required)
  • openapi_spec - OpenAPI specification URL (required)
  • message_path - Custom message endpoint path (optional, default: /message)
  • headers.* - Custom headers (optional)
  • merge_api - Enable API merging (optional, default: false)
  • Cache parameters: cache_enabled, cache_ttl, etc.

Testing Your Setup

Once configured, you can test your setup by asking your AI client:

  • "Find pets by status in the pet store"
  • "Get pet by id xxxx"
  • "Add a new pet to the store, name: doggie, photoUrls: [url1]"

Core Features

API Merging Feature

Some AI clients (like Cursor) have limitations on the number of MCP tools they can handle effectively. The API merging feature intelligently combines related API endpoints into unified tools, significantly reducing the total number of tools while maintaining full functionality.

How It Works

When enabled, the OpenAPI2MCP groups API endpoints by resource path and merges them into comprehensive tools. For example, instead of having separate tools for each HTTP method, you get a single tool that handles multiple operations through an object-based parameter structure.

Petstore API Example

Without Merging (8 individual tools):

  • get_pet_petId - GET /pet/{petId}
  • post_pet_petId - POST /pet/{petId}
  • delete_pet_petId - DELETE /pet/{petId}
  • get_pet_findByStatus - GET /pet/findByStatus
  • get_pet_findByTags - GET /pet/findByTags
  • post_pet - POST /pet
  • put_pet - PUT /pet
  • post_pet_petId_uploadImage - POST /pet/{petId}/uploadImage

With Merging Enabled (3 unified tools):

  1. pet_operations - Handles /pet operations:

    {
      "operation": {
        "get": { "status": "available" },
        "post": { "body": { "name": "doggie", "photoUrls": ["url1"] } },
        "put": { "body": { "id": 1, "name": "doggie" } }
      }
    }
    
  2. pet_item_operations - Handles /pet/{petId} operations:

    {
      "operation": {
        "get": { "petId": "1" },
        "post": { "petId": "1", "name": "doggie" },
        "delete": { "petId": "1" }
      }
    }
    
  3. pet_item_uploadImage_operations - Handles /pet/{petId}/uploadImage:

    {
      "operation": {
        "post": { "petId": "1", "body": { "additionalMetadata": "test" } }
      }
    }
    

Caching Feature

The OpenAPI caching feature provides efficient caching for parsed OpenAPI specifications and generated tools in SSE mode, significantly improving performance by avoiding repeated parsing and tool generation when connecting to the same API.

Usage Example

First connection (cache miss):

[Fresh] Loaded OpenAPI 3.0: Swagger Petstore v1.0.17
[Fresh] Found 19 API endpoints
[Cache] Cached OpenAPI spec: https://petstore3.swagger.io/api/v3/openapi.json (expires in 3600s)

Subsequent connections (cache hit):

[Cache] Cache hit for OpenAPI spec: https://petstore3.swagger.io/api/v3/openapi.json
[Cache] Using cached OpenAPI 3.0: Swagger Petstore v1.0.17
[Cache] Found 19 API endpoints, 19 tools

Monitoring

You can monitor cache performance through the health endpoint:

curl http://localhost:3000/health

Configuration

Environment Variables

Basic Configuration

VariableDescriptionDefaultRequired
TRANSPORT_TYPETransport mode: stdio, http, ssestdioNo
SSE_PORTPort for HTTP/SSE server3000No
API_BASE_URLBase URL for API requests-No**
OPENAPI_SPEC_URLURL to fetch OpenAPI spec-Yes*
OPENAPI_SPEC_PATHLocal path to OpenAPI spec file-Yes*

*Either OPENAPI_SPEC_URL or OPENAPI_SPEC_PATH is required. **API_BASE_URL is optional when OpenAPI specification contains servers field. The first server URL will be used automatically.

Request Configuration

VariableDescriptionDefaultRequired
VERIFY_SSLEnable SSL certificate verificationtrueNo
TIMEOUTRequest timeout in milliseconds30000No
HEADER.*Custom headers-No
HEADERSJSON string of headers (legacy)-No

Feature Configuration

VariableDescriptionDefaultRequired
MERGE_APIEnable API merging to reduce tool countfalseNo

Cache Configuration

VariableDescriptionDefaultRequired
CACHE_ENABLEDEnable OpenAPI specification cachingtrueNo
CACHE_TTLCache time-to-live in seconds3600No
CACHE_MAX_SIZEMaximum number of cached entries200No
CACHE_CHECK_INTERVALCache cleanup interval in seconds300No

Header Configuration

{
  "mcpServers": {
    "openapi2mcp": {
      "command": "npx",
      "args": ["-y", "openapi2mcp"],
      "env": {
        "TRANSPORT_TYPE": "stdio",
        "API_BASE_URL": "https://petstore3.swagger.io/api/v3",
        "OPENAPI_SPEC_URL": "https://petstore3.swagger.io/api/v3/openapi.json",
        "HEADER.Authorization": "Bearer your-token-here",
        "HEADER.Content-Type": "application/json",
        "HEADER.X-API-Key": "your-api-key"
      }
    }
  }
}

URL Parameter Format (SSE Mode)

http://localhost:3000/sse?base_url=https://petstore3.swagger.io/api/v3&openapi_spec=https://petstore3.swagger.io/api/v3/openapi.json&headers.Authorization=Bearer%20your-token&headers.Content-Type=application%2Fjson

Note: Headers in URL parameters must be URL encoded (spaces: %20, slashes: %2F)

Legacy JSON Format

{
  "mcpServers": {
    "openapi2mcp": {
      "command": "npx",
      "args": ["-y", "openapi2mcp"],
      "env": {
        "TRANSPORT_TYPE": "stdio",
        "API_BASE_URL": "https://petstore3.swagger.io/api/v3",
        "OPENAPI_SPEC_URL": "https://petstore3.swagger.io/api/v3/openapi.json",
        "HEADERS": "{\"Authorization\":\"Bearer your-token\",\"Content-Type\":\"application/json\"}"
      }
    }
  }
}

Development

Running Tests

pnpm run dev

# Run tests
pnpm test

# Build project
pnpm run build

Docker Deployment

Build and Run

# Build image
docker build -t openapi2mcp .

# Run with environment variables
docker run -e TRANSPORT_TYPE=http \
           -e API_BASE_URL=https://petstore3.swagger.io/api/v3 \
           -e OPENAPI_SPEC_URL=https://petstore3.swagger.io/api/v3/openapi.json \
           -e HEADER.Authorization="Bearer token" \
           -p 3000:3000 \
           openapi2mcp

Server Config

{
  "mcpServers": {
    "petstore": {
      "command": "npx",
      "args": [
        "-y",
        "openapi2mcp"
      ],
      "env": {
        "TRANSPORT_TYPE": "stdio",
        "API_BASE_URL": "https://petstore3.swagger.io/api/v3",
        "OPENAPI_SPEC_URL": "https://petstore3.swagger.io/api/v3/openapi.json",
        "HEADERS": "{\"Authorization\":\"Bearer your-token\",\"Content-Type\":\"application/json\"}"
      }
    }
  }
}
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
ChatWiseThe second fastest AI chatbot™
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
CursorThe AI Code Editor
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
WindsurfThe new purpose-built IDE to harness magic
DeepChatYour AI Partner on Desktop
Tavily Mcp
Playwright McpPlaywright MCP server
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Serper MCP ServerA Serper MCP Server
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Amap Maps高德地图官方 MCP Server