Logotipo de Openapi MCP Generator

Openapi MCP Generator

Comunidad
harsha-iiiv

A tool that converts OpenAPI specifications to MCP server

Editorharsha-iiiv
Repositorioopenapi-mcp-generator
IdiomaTypeScript
Forks
85
Estrellas
637
Herramientas disponibles
0
Tipo de transportestdio
LicenciaMIT
Enlaces
  • Conecta herramientas a flujos de trabajo con IA

    Openapi MCP Generator ofrece funciones MCP que pueden usar los clientes y agentes de IA compatibles.

  • 0 herramientas disponibles

    Explora a continuación las acciones que se pueden invocar, con sus nombres y descripciones cuando el servidor los proporcione.

  • Configuración lista para copiar

    Usa los ejemplos de instalación para configurar este servidor en tu cliente MCP preferido.

  • Indicadores de interés en el código abierto

    637 estrellas y 85 forks en el repositorio enlazado.

OpenAPI to MCP Generator (openapi-mcp-generator)

npm version License: MIT GitHub repository Ask DeepWiki

Generate Model Context Protocol (MCP) servers from OpenAPI specifications.

This CLI tool automates the generation of MCP-compatible servers that proxy requests to existing REST APIs—enabling AI agents and other MCP clients to seamlessly interact with your APIs using your choice of transport methods.


✨ Features

  • 🔧 OpenAPI 3.0 Support: Converts any OpenAPI 3.0+ spec into an MCP-compatible server.
  • 🔁 Proxy Behavior: Proxies calls to your original REST API while validating request structure and security.
  • 🔐 Authentication Support: API keys, Bearer tokens, Basic auth, and OAuth2 supported via environment variables.
  • 🧪 Zod Validation: Automatically generates Zod schemas from OpenAPI definitions for runtime input validation.
  • ⚙️ Typed Server: Fully typed, maintainable TypeScript code output.
  • 🔌 Multiple Transports: Communicate over stdio, SSE via Hono, or StreamableHTTP.
  • 🧰 Project Scaffold: Generates a complete Node.js project with tsconfig.json, package.json, and entry point.
  • 🧪 Built-in HTML Test Clients: Test API interactions visually in your browser (for web-based transports).

🚀 Installation

bash
npm install -g openapi-mcp-generator

You can also use yarn global add openapi-mcp-generator or pnpm add -g openapi-mcp-generator


🛠 Usage

bash
# Generate an MCP server (stdio)
openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir

# Generate an MCP web server with SSE
openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=web --port=3000

# Generate an MCP StreamableHTTP server
openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=streamable-http --port=3000

# Generate a deployable Cloudflare Worker MCP server
openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=cloudflare-worker

CLI Options

OptionAliasDescriptionDefault
--input-iPath or URL to OpenAPI specification (YAML or JSON)Required
--output-oDirectory to output the generated MCP projectRequired
--server-name-nName of the MCP server (package.json:name)OpenAPI title or mcp-api-server
--server-version-vVersion of the MCP server (package.json:version)OpenAPI version or 1.0.0
--base-url-bBase URL for API requests. Required if OpenAPI servers missing or ambiguous.Auto-detected if possible
--transport-tTransport mode: "stdio" (default), "web", "streamable-http", or "cloudflare-worker""stdio"
--port-pPort for web-based transports3000
--default-includeDefault behavior for x-mcp filtering. Accepts true or false (case-insensitive). true = include by default, false = exclude by default.true
--allow-external-refsAllow resolving external http(s) $ref references in the spec. Disabled by default to prevent SSRF during parsing.false
--max-tool-name-lengthMaximum length for generated tool names (Claude Desktop caps at 64). Longer names are truncated with a hash suffix.64
--header-passthroughComma-separated inbound header names to forward to the upstream API (web/streamable-http). Enables per-user API keys via MCP client headers.(none)
--insecure-kAllow insecure HTTPS connections (skip TLS certificate verification) in the generated server.false
--generate-libGenerate library-style output: export main() instead of auto-invoking it, omitting signal/cleanup wiring.false
--custom-authGenerate an editable src/auth.ts hook (applyCustomAuth) called before built-in auth; return true to skip built-in auth.false
--oauth-creds-in-bodySend OAuth2 client credentials in the token request body instead of the Basic Authorization header.false
--forceOverwrite existing files in the output directory without confirmationfalse

Configuring the API base URL at runtime: the generated server reads API_BASE_URL from the environment (.env), overriding the value baked in from the OpenAPI servers list. The port resolves from --port, then the PORT env var, then 3000.

📦 Programmatic API

You can also use this package programmatically in your Node.js applications:

javascript
import { getToolsFromOpenApi } from 'openapi-mcp-generator';

// Extract MCP tool definitions from an OpenAPI spec
const tools = await getToolsFromOpenApi('./petstore.json');

// With options
const filteredTools = await getToolsFromOpenApi('https://example.com/api-spec.json', {
  baseUrl: 'https://api.example.com',
  dereference: true,
  excludeOperationIds: ['deletePet'],
  filterFn: (tool) => tool.method.toLowerCase() === 'get',
});

For full documentation of the programmatic API, see PROGRAMMATIC_API.md.


🧱 Project Structure

The generated project includes:

<output_directory>/
├── .gitignore
├── package.json
├── tsconfig.json
├── .env.example
├── src/
│   ├── index.ts
│   └── [transport-specific-files]
└── public/          # For web-based transports
    └── index.html   # Test client

Core dependencies:

  • @modelcontextprotocol/sdk - MCP protocol implementation
  • axios - HTTP client for API requests
  • zod - Runtime validation
  • json-schema-to-zod - Convert JSON Schema to Zod
  • Transport-specific deps (Hono, uuid, etc.)

📡 Transport Modes

Stdio (Default)

Communicates with MCP clients via standard input/output. Ideal for local development or integration with LLM tools.

Web Server with SSE

Launches a fully functional HTTP server with:

  • Server-Sent Events (SSE) for bidirectional messaging
  • REST endpoint for client → server communication
  • In-browser test client UI
  • Multi-connection support
  • Built with lightweight Hono framework

StreamableHTTP

Implements the MCP StreamableHTTP transport which offers:

  • Stateful JSON-RPC over HTTP POST requests
  • Session management using HTTP headers
  • Proper HTTP response status codes
  • Built-in error handling
  • Compatibility with MCP StreamableHTTPClientTransport
  • In-browser test client UI
  • Built with lightweight Hono framework

Cloudflare Worker

Generates a complete, deployable Cloudflare Workers project that serves the MCP server over Streamable HTTP at /mcp using the MCP SDK's WebStandardStreamableHTTPServerTransport directly (no extra framework dependency). Deploy it to your own Cloudflare account with one command:

bash
openapi-mcp-generator --input ./openapi.json --output ./my-mcp-worker --transport cloudflare-worker
cd my-mcp-worker
npm install
npx wrangler secret put API_KEY   # set upstream API secrets (see .dev.vars.example)
npx wrangler deploy               # Wrangler logs into YOUR Cloudflare account and deploys

Highlights:

  • Stateless, runs on the free Workers tier (no Durable Objects or KV). A fresh MCP server + transport is created per request (required by MCP SDK ≥ 1.26).
  • Lean dependencies: just @modelcontextprotocol/sdk and zod — no extra agent framework.
  • Non-secret config (e.g. API_BASE_URL) lives in wrangler.jsonc under vars; secrets are set with wrangler secret put and read from the env binding — never committed.
  • Workers-native runtime: global fetch (no Node https), and argument validation uses build-time-emitted zod (no runtime eval).
  • Auth is scheme-aware: API key (header/query/cookie), HTTP basic/bearer, and OAuth2 client-credentials are derived from env secrets.
  • --header-passthrough, --custom-auth, --port, --insecure, --generate-lib, and --oauth-creds-in-body do not apply to this target and are ignored with a warning.

Local development: cp .dev.vars.example .dev.vars, fill in secrets, then npm run dev (serves http://localhost:8787/mcp). Connect with the MCP Inspector or, from Claude Desktop, via mcp-remote.

Transport Comparison

Featurestdioweb (SSE)streamable-httpcloudflare-worker
ProtocolJSON-RPC over stdioJSON-RPC over SSEJSON-RPC over HTTPStreamable HTTP at /mcp
ConnectionPersistentPersistentRequest/responseRequest/response
BidirectionalYesYesYes (stateful)Yes
Multiple clientsNoYesYesYes
Browser compatibleNoYesYesYes
Firewall friendlyNoYesYesYes
Load balancingNoLimitedYesYes (edge)
Status codesNoLimitedFull HTTP codesFull HTTP codes
HeadersNoLimitedFull HTTP headersFull HTTP headers
Test clientNoYesYesNo (use MCP Inspector)
HostingLocalSelf-hostedSelf-hostedCloudflare (serverless)

🔐 Environment Variables for Authentication

Configure auth credentials in your environment:

Auth TypeVariable Format
API KeyAPI_KEY_<SCHEME_NAME>
BearerBEARER_TOKEN_<SCHEME_NAME>
Basic AuthBASIC_USERNAME_<SCHEME_NAME>, BASIC_PASSWORD_<SCHEME_NAME>
OAuth2OAUTH_CLIENT_ID_<SCHEME_NAME>, OAUTH_CLIENT_SECRET_<SCHEME_NAME>, OAUTH_SCOPES_<SCHEME_NAME>

🔎 Filtering Endpoints with OpenAPI Extensions

You can control which operations are exposed as MCP tools using a vendor extension flag x-mcp. This extension is supported at the root, path, and operation levels. By default, endpoints are included unless explicitly excluded.

  • Extension: x-mcp: true | false
  • Default: true (include by default)
  • Precedence: operation > path > root (first non-undefined wins)
  • CLI option: --default-include false to change default to exclude by default

Examples:

yaml
# Optional root-level default
x-mcp: true

paths:
  /pets:
    x-mcp: false # exclude all ops under /pets
    get:
      x-mcp: true # include this operation anyway

  /users/{id}:
    get:
      # no x-mcp -> included by default

This uses standard OpenAPI extensions (x-… fields). See the OpenAPI Extensions guide for details.

Note: x-mcp must be a boolean or the strings "true"/"false" (case-insensitive). Other values are ignored in favor of higher-precedence or default behavior.


▶️ Running the Generated Server

bash
cd path/to/output/dir
npm install

# Run in stdio mode
npm start

# Run in web server mode
npm run start:web

# Run in StreamableHTTP mode
npm run start:http

Testing Web-Based Servers

For web and StreamableHTTP transports, a browser-based test client is automatically generated:

  1. Start the server using the appropriate command
  2. Open your browser to http://localhost:<port>
  3. Use the test client to interact with your MCP server

⚠️ Requirements

  • Node.js v20 or later

Star History

🤝 Contributing

Contributions are welcome!

  1. Fork the repo
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Run npm run format.write to format your code
  4. Commit your changes: git commit -m "Add amazing feature"
  5. Push and open a PR

📌 Repository: github.com/harsha-iiiv/openapi-mcp-generator


📄 License

MIT License — see LICENSE for full details.

Usa el MCP de Openapi MCP Generator con varios modelos de IA

TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que, una vez conectado Openapi MCP Generator, puedes usarlo con distintos modelos de IA en TypingMind sin tener que configurarlo por separado para cada modelo. Esta integración MCP se ejecuta localmente en tu dispositivo a través del conector MCP de TypingMind.

Guía de configuración para usar el conector local

Usa esta opción si el servidor MCP necesita acceder a archivos locales, aplicaciones o recursos privados de tu ordenador.

1

Abre los ajustes de MCP

En TypingMind, ve a Ajustes, luego a Ajustes avanzados y a Model Context Protocol, y elige Configurar conector.

  1. Abre TypingMind en tu navegador.
  2. Haz clic en el icono de Ajustes.
  3. Ve a Ajustes avanzados.
  4. Abre la sección Model Context Protocol.
  5. Haz clic en Configurar conector y elige Este dispositivo.
Pantalla de configuración del conector MCP de TypingMind con «Este dispositivo» seleccionado
2

Ejecuta el comando del conector

Elige Este dispositivo, copia el comando de TypingMind y ejecútalo en Terminal. Mantén el proceso en ejecución mientras uses MCP.

  1. Copia el comando de configuración que muestra TypingMind.
  2. Abre Terminal en macOS o Windows Terminal en Windows.
  3. Pega y ejecuta el comando.
  4. Acepta la instalación del paquete si Terminal te pide confirmación para continuar.
  5. Mantén el proceso en ejecución en la ventana de Terminal mientras uses las herramientas MCP.
3

Añade Openapi MCP Generator como servidor

Cuando el estado del conector sea «Listo», haz clic en «Edita servidores» y pega la configuración del servidor MCP.

  1. Espera hasta que el estado del conector indique «Listo».
  2. Haz clic en Edita servidores.
  3. Pega la configuración del servidor MCP de Openapi MCP Generator.
  4. Guarda la lista de servidores.
  5. Actualiza para comprobar que el conector sigue listo.
Ajustes de MCP de TypingMind con un servidor activo y el botón «Edita servidores»
{
  "mcpServers": {
    "openapi-mcp-generator": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Úsala con distintos modelos

Guarda la lista de servidores, abre Plugins, activa las herramientas MCP de Openapi MCP Generator y selecciona cualquier modelo de IA compatible en TypingMind para usar las herramientas en el chat o asignárselas a un agente de IA.

  1. Abre la página Plugins en TypingMind.
  2. Activa las herramientas MCP de Openapi MCP Generator.
  3. Inicia un chat y elige el modelo de IA que quieras usar.
  4. Usa las herramientas MCP en el chat o asígnalas a un agente de IA.
  5. Cambia a otro modelo de IA cuando lo necesites sin volver a conectar MCP.
Chat de TypingMind que usa herramientas MCP activadas con un modelo de IA seleccionado
¿Puedes usar Openapi MCP Generator para ayudarme con esta tarea?
Openapi MCP Generator
Claro. Lo he leído.
Esto he encontrado usando Openapi MCP Generator.

Preguntas frecuentes

¿Para qué sirve el servidor MCP Openapi MCP Generator?

Openapi MCP Generator es un servidor MCP que permite a los clientes de IA compatibles conectarse a herramientas y contexto externos. En TypingMind, basta con añadir este servidor MCP una vez para que sus herramientas estén disponibles en tu espacio de trabajo de IA.

¿Puedo usar el servidor MCP Openapi MCP Generator con varios modelos de IA en TypingMind?

Sí. TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que puedes usar Openapi MCP Generator con distintos modelos de IA, como Claude, ChatGPT, Gemini u otros que hayas configurado en TypingMind, sin configurar el servidor MCP por separado para cada modelo.

¿Por qué usar el conector MCP de Openapi MCP Generator con TypingMind?

TypingMind es una de las mejores interfaces de chat con LLM porque reúne varios modelos de IA, prompts, plugins, agentes de IA, claves de API y herramientas MCP en un solo espacio de trabajo. Con Openapi MCP Generator conectado, puedes usar sus herramientas MCP con tus modelos preferidos y mantener organizado tu flujo de trabajo de chat en TypingMind.

¿Cómo conecto el servidor MCP Openapi MCP Generator a TypingMind?

Openapi MCP Generator funciona a través del conector MCP local de TypingMind. Es la mejor opción cuando el servidor MCP necesita acceder a archivos locales, aplicaciones de escritorio, herramientas de línea de comandos o recursos privados de tu ordenador.

¿Qué herramientas ofrece el servidor MCP Openapi MCP Generator en TypingMind?

Openapi MCP Generator ofrece funciones MCP que puedes activar desde la página Plugins de TypingMind y usar en el chat o asignar a agentes de IA.

¿Tengo que compartir mis claves de API con TypingMind para usar el servidor MCP Openapi MCP Generator?

No. TypingMind prioriza el funcionamiento local y te permite mantener el control de tus proveedores de modelos, claves de API, prompts y configuración MCP. Si Openapi MCP Generator requiere autenticación, añade las cabeceras, los ajustes de OAuth o la configuración local necesarios para ese servidor MCP al crear la conexión.

Servidores MCP relacionados

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇