mcp-rest-gateway-adapter
A Model Context Protocol (MCP) endpoint translator that materializes RESTful services, defined via OpenAPI schemas, into discoverable MCP resources for consumption by Large Language Models, streamlining API integration and lifecycle management.
Author

ivo-toby
Quick Info
Actions
Tags
OpenAPI MCP Server Gateway
This specialized Model Context Protocol (MCP) apparatus transforms OpenAPI definitions into accessible MCP artifacts. It empowers Generative AI agents to dynamically enumerate and invoke external REST backends described by the specification, managed entirely through the MCP framework.
📖 Reference Documentation
- End-User Manual - Instructions for integration with AI environments like Claude Desktop or Cursor via MCP clients.
- Library Integration Guide - For software engineers embedding this package as a core component in custom Node.js servers.
- Codebase Development Guide - Details for contributors focused on source code enhancement.
- Authentication Provider Specification - In-depth coverage of advanced authorization strategies.
User Guide
This section guides the operator on deploying and utilizing the MCP gateway with compatible MCP clients (e.g., Claude Desktop, Cursor).
Deployment Modalities
This gateway supports two primary execution styles:
- Standalone CLI Utility: Execution via
npx @ivotoby/openapi-mcp-serverutilizing runtime command-line parameters. - Modular Component: Importing and instantiating the
OpenAPIServerclass within custom Node.js application logic.
The connectivity layer can be configured using either:
- Inter-Process Communication (IPC) via Stdio: The default transport, ideal for direct handoff integration with local AI host processes (like Claude Desktop) over standard I/O streams.
- Web-Accessible HTTP Conduit: A TCP-based transport enabling interaction via standard HTTP requests/responses, facilitating access from web frontends or remote clients.
Initial Configuration for Operators
Mode 1: Integration with AI Local Hosts (Stdio Transport)
No prerequisite repository cloning is necessary. Configure your AI client's MCP server manifest:
-
Locate or generate the configuration file (e.g., for macOS:
~/Library/Application Support/Claude/claude_desktop_config.json). -
Inject the following service definition:
{ "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" } } } }
- Adjust the environment variables to match your target API credentials:
API_BASE_URL: The root Uniform Resource Locator for the external API.OPENAPI_SPEC_PATH: The URI or filesystem path pointing to the OpenAPI schema document.API_HEADERS: A semicolon-delimited series of authentication key-value pairs.
Mode 2: Access via External HTTP Clients (HTTP Transport)
Execute the package directly via npx specifying HTTP parameters:
bash 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
Interact using JSON-RPC 2.0 messages over HTTP POST to the defined endpoint (default /mcp).
Session Establishment and Usage:
- Initialization: Send an MCP
initializerequest via POST. bash 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 server returns the initialization result and sets a required Mcp-Session-Id header for subsequent calls.
-
Tool Listing: Request available functions. bash 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"}'
-
Streaming for Notifications: Establish a persistent connection for asynchronous server responses (like tool execution outputs) using Server-Sent Events (SSE). bash curl -N http://localhost:3000/mcp -H "Mcp-Session-Id: your-session-id"
-
Termination: Close the active session. bash curl -X DELETE http://localhost:3000/mcp -H "Mcp-Session-Id: your-session-id"
Configuration Parameters
Configuration is manageable via environment variables or CLI flags (CLI flags override environment variables):
| Variable/Flag | CLI Argument | Description | Default |
|---|---|---|---|
API_BASE_URL |
--api-base-url |
Root URI for the external API. | N/A |
OPENAPI_SPEC_PATH |
--openapi-spec |
Location (URL or file path) of the OpenAPI definition. | N/A |
OPENAPI_SPEC_FROM_STDIN |
N/A | Set to "true" to read specification content from stdin pipe. | "false" |
OPENAPI_SPEC_INLINE |
--spec-inline |
Raw OpenAPI specification string provided directly. | N/A |
API_HEADERS |
--headers |
Comma-separated list of Key:Value authentication headers. |
Empty |
SERVER_NAME |
--name |
Identifier for this MCP service instance. | "mcp-openapi-server" |
SERVER_VERSION |
--server-version |
Version string for the gateway. | "1.0.0" |
TRANSPORT_TYPE |
--transport |
Communication method: "stdio" or "http". | "stdio" |
HTTP_PORT |
--port |
TCP port utilized for HTTP transport binding. | 3000 |
HTTP_HOST |
--host |
Network interface binding address for HTTP transport. | "127.0.0.1" |
ENDPOINT_PATH |
--path |
URI path for handling HTTP MCP messages. | "/mcp" |
TOOLS_MODE |
--tools |
Loading strategy: "all" (default), "dynamic" (meta-tools only), or "explicit" (only explicitly defined tools). | "all" |
DISABLE_ABBREVIATION |
--disable-abbreviation |
Inhibits internal name optimization, potentially preventing errors on excessively long tool names (> 64 chars). | "false" |
Specification Ingestion Strategies
The gateway offers four distinct mechanisms for loading the required OpenAPI documentation:
1. Remote URI Retrieval (Default)
bash npx @ivotoby/openapi-mcp-server --openapi-spec https://my-service.com/v3/api-docs.json
2. Local Filesystem Reference
bash npx @ivotoby/openapi-mcp-server --openapi-spec ./local/swagger.yaml
3. Standard Input Piping
Useful for container orchestration or CI/CD pipelines where the spec is generated or fetched upstream:
bash
Example: Fetch via curl and pipe directly
curl -s https://api.example.com/openapi.json | npx @ivotoby/openapi-mcp-server --spec-from-stdin
4. Direct Inline Injection
For small, static specifications:
bash npx @ivotoby/openapi-mcp-server --spec-inline '{"openapi":"3.0.0", "info":{"title":"Local Test"}, "paths":{}}'
Format Support: Both OpenAPI JSON and YAML syntax are automatically recognized and parsed.
Source Validation: Exactly one specification source must be active (--openapi-spec, --spec-from-stdin, or --spec-inline). Specifying multiple sources results in a startup failure.
Tool Selection and Scoping Controls
In alignment with best practices for large API definitions, granular control over which endpoints become MCP tools is provided:
--tools <all|dynamic|explicit>: Defines the loading philosophy (default isall).--tool <toolId>: Imports only the specific tool identified by its fully qualified name (e.g.,GET::users). Usable multiple times.--tag <tag>: Restricts loading to operations marked with a specified OpenAPI tag.--resource <resource>: Filters tools based on path prefix matching (e.g., operations under/v1/users).--operation <method>: Includes only tools corresponding to specified HTTP verbs (e.g.,get,put).
Example: Explicit Loading for Safety
bash npx @ivotoby/openapi-mcp-server ... --tools explicit --tool GET::retrieve_user --tool POST::create_order
Transport Mechanism Deep Dive
Stdio Transport (Default IPC)
Optimal for headless execution integrated directly with the execution host process (e.g., AI application running locally).
Streamable HTTP Transport
Provides a network interface for MCP communication. It employs a hybrid request/response model:
- Synchronous:
initializeandtools/listresponses are returned immediately in the POST body. - Asynchronous/Streaming: All subsequent real-time messages (execution results, notifications) are pushed to the client over a long-lived HTTP GET connection utilizing Server-Sent Events (SSE).
Debugging Output
Logging verbosity can be increased:
- HTTP Mode: Redirect standard error to a log file:
npx ... --transport http &> debug.log - Stdio Mode: Review the application logs of the parent AI process.
Library Usage
This section addresses developers constructing specialized server deployments by leveraging the exported OpenAPIServer class.
Core Initialization Pattern
Instantiate the server with a configuration object, then bind it to a transport implementation (e.g., StdioServerTransport or a custom HTTP server wrapper).
typescript import { OpenAPIServer } from "@ivotoby/openapi-mcp-server" import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
const configuration = { name: "custom-api-handler", apiBaseUrl: "https://prod.internal.corp", openApiSpec: "./schemas/production.json", specInputMethod: "file" as const, headers: { "X-Client-ID": "Internal-Tooling" }, transportType: "stdio" as const, toolsMode: "all" as const, };
const serverInstance = new OpenAPIServer(configuration) const ipcTransport = new StdioServerTransport() await serverInstance.start(ipcTransport)
Advanced Authentication with AuthProvider
For dynamic credential requirements, inject an implementation of the AuthProvider interface, superseding static headers configuration.
typescript import { OpenAPIServer, AuthProvider } from "@ivotoby/openapi-mcp-server" import axios, { AxiosError } from "axios"
class TokenRefreshingProvider implements AuthProvider { private currentToken: string | null = null;
async getAuthHeaders(): PromiseBearer ${this.currentToken} };
}
async handleAuthError(error: AxiosError): Promise
const advancedAuth = new TokenRefreshingProvider(); const config = { / ... standard config ... / authProvider: advancedAuth };
Referencing Examples: Comprehensive runnable examples demonstrating various authentication flows and transport configurations are located in the examples/ submodule.
OpenAPI Schema Transformation Logic
The internal parser applies sophisticated logic to ensure LLMs receive accurate representations:
- Reference Resolution: Complete, recursive resolution of all internal and external
$refpointers within parameter definitions and schema objects. - Schema Composition: Intelligent merging of path/query parameters with request body content into a singular, unified input schema for the final tool definition. Collision resolution (naming conflicts between path parameters and body fields) is handled by prepending prefixes to body properties.
- Type Fidelity: Exact preservation of primitive types, complex objects, arrays, required status, descriptions, and enumeration constraints defined in the source specification.
Frequently Asked Queries (FAQ)
Q: What artifact does an OpenAPI endpoint become in the MCP world?
A: Each accessible REST operation maps directly to an MCP Tool that an LLM can invoke.
Q: Why use the library mode over the CLI?
A: Library mode grants granular control over security policies (via AuthProvider), custom pre/post-processing logic, and packaging the server as a dedicated service module.
Q: How is token expiration managed for dynamic access?
A: By implementing the AuthProvider interface, specifically the getAuthHeaders and handleAuthError methods, you gain the capability to automatically refresh credentials upon expiry or upon receiving HTTP 401/403 responses.
Q: Is dynamic tool loading supported?
A: Yes. Setting --tools dynamic exposes only the meta-capabilities required for the LLM to introspect the API schema itself (list-api-endpoints, etc.), suitable for APIs that change frequently.
Q: What is the primary purpose of the HTTP transport configuration? A: It enables the MCP layer to communicate over standard network sockets instead of direct process pipes, allowing interaction from non-local clients or web UIs.
License: MIT
