Skip to content
Back to search

openapi-mcp-generator

A tool that converts OpenAPI specifications to MCP server

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/harsha-iiiv--openapi-mcp-generator/badge.svg)](/listings/harsha-iiiv--openapi-mcp-generator)

HTML

<a href="/listings/harsha-iiiv--openapi-mcp-generator"><img src="/api/listings/harsha-iiiv--openapi-mcp-generator/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install -g openapi-mcp-generator

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

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 573 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # OpenAPI to MCP Generator (openapi-mcp-generator)
  2. [![npm version](https://img.shields.io/npm/v/openapi-mcp-generator.svg)](https://www.npmjs.com/package/openapi-mcp-generator)
  3. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  4. [![GitHub repository](https://img.shields.io/badge/GitHub-harsha--iiiv/openapi--mcp--generator-blue.svg)](https://github.com/harsha-iiiv/openapi-mcp-generator)
  5. [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/harsha-iiiv/openapi-mcp-generator)
  6. **openapi-mcp-generator is a free, MIT-licensed CLI and library that turns an OpenAPI 3.x
  7. specification into a ready-to-run [Model Context Protocol (MCP)](https://modelcontextprotocol.io/)
  8. server for stdio, SSE, Streamable HTTP or Cloudflare Workers.** You own the generated TypeScript
  9. code, and tool inputs are validated against JSON Schema before any request reaches your API.
  10. **[Docs](https://mcp.pidata.tech/docs)** · **[Quickstart](https://mcp.pidata.tech/docs/quickstart)** ·
  11. **[Browser playground](https://mcp.pidata.tech/playground/)** ·
  12. [Changelog](https://mcp.pidata.tech/docs/changelog)
  13. ```bash
  14. npx openapi-mcp-generator --input ./openapi.json --output ./my-mcp
  15. ```
  16. ---
  17. ## ✨ Features
  18. - 🔧 **OpenAPI 3.x Support**: Converts any OpenAPI 3.0 or 3.1 spec into an MCP-compatible server (convert Swagger 2.0 first).
  19. - 🔁 **Proxy Behavior**: Proxies calls to your original REST API while validating request structure and security.
  20. - 🔐 **Authentication Support**: API keys, Bearer tokens, Basic auth, and OAuth2 supported via environment variables; calls fail closed when required credentials are missing.
  21. - 🧪 **JSON Schema Validation**: Arguments are validated against each tool's JSON Schema 2020-12 input schema (no code generation, no `eval`).
  22. - 🏷️ **Annotations and Structured Output**: Tools carry titles and read-only/destructive/idempotent hints, and JSON object responses come back as `structuredContent` (optionally with a declared `outputSchema`).
  23. - ⚙️ **Typed Server**: Fully typed, maintainable TypeScript code output.
  24. - 🔌 **Multiple Transports**: Communicate over stdio, SSE via Hono, StreamableHTTP, or a deployable Cloudflare Worker.
  25. - 🧰 **Project Scaffold**: Generates a complete Node.js project with `tsconfig.json`, `package.json`, and entry point.
  26. - 🧪 **Built-in HTML Test Clients**: Test API interactions visually in your browser (for web-based transports).
  27. ---
  28. ## 🚀 Installation
  29. ```bash
  30. npm install -g openapi-mcp-generator
  31. ```
  32. > You can also use `yarn global add openapi-mcp-generator` or `pnpm add -g openapi-mcp-generator`
  33. ---
  34. ## ⬆️ Upgrading to 5.0
  35. 5.0 generates servers on the MCP TypeScript SDK v2 and supports MCP 2026-07-28 alongside 2025-era clients. Generated projects change, so upgrade deliberately:
  36. 1. Commit your generated project, then regenerate with the same flags: `npx openapi-mcp-generator@5 -i ./openapi.json -o ./my-mcp --force`. `--force` overwrites generated files, including your edits.
  37. 2. Use Node.js 22.19 or later to run the generator (generated projects need Node.js 22 or later), then run `npm install`. `@modelcontextprotocol/sdk` is replaced by `@modelcontextprotocol/server` (`^2.4.0`), and `zod`, `json-schema-to-zod`, `dotenv` and `uuid` by `@cfworker/json-schema`.
  38. 3. Update customized code to import from `@modelcontextprotocol/server` (stdio helpers from `@modelcontextprotocol/server/stdio`).
  39. 4. Streamable HTTP and Worker servers are stateless: no `mcp-session-id`, and `GET` and `DELETE` on `/mcp` return `405`. Tool calls over `POST` are unaffected.
  40. 5. Missing upstream credentials now fail closed with an error naming the variables to set; `MCP_ALLOW_MISSING_CREDENTIALS=true` restores the old behavior.
  41. 6. An unknown tool name is now a JSON-RPC `-32602` error. Integers stay integers, `readOnly` properties leave request inputs, and schema defaults are no longer injected.
  42. 7. Swagger 2.0 specs are refused: convert them with `npx swagger2openapi swagger.json -o openapi.json`.
  43. 8. Credential variables, Worker secret names, `--inbound-auth`, `--header-passthrough` and `MCP_ALLOWED_ORIGINS` are unchanged.
  44. Not ready yet? Stay on 4.x with `npx openapi-mcp-generator@4`. Full notes: [CHANGELOG.md](./CHANGELOG.md).
  45. ---
  46. ## 🛠 Usage
  47. ```bash
  48. # Generate an MCP server (stdio)
  49. openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir
  50. # Generate an MCP web server with SSE
  51. openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=web --port=3000
  52. # Generate an MCP StreamableHTTP server
  53. openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=streamable-http --port=3000
  54. # Generate a deployable Cloudflare Worker MCP server
  55. openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=cloudflare-worker
  56. ```
  57. The [`examples/`](./examples) folder holds the Swagger Petstore generated with 5.0 for stdio
  58. (`petstore-mcp`), web (`pet-store-sse`) and StreamableHTTP (`pet-store-streamable-http`).
  59. ### CLI Options
  60. | Option | Alias | Description | Default |
  61. | ------------------------ | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
  62. | `--input` | `-i` | Path or URL to OpenAPI specification (YAML or JSON) | **Required** |
  63. | `--output` | `-o` | Directory to output the generated MCP project | **Required** |
  64. | `--server-name` | `-n` | Name of the MCP server (`package.json:name`) | OpenAPI title or `mcp-api-server` |
  65. | `--server-version` | `-v` | Version of the MCP server (`package.json:version`) | OpenAPI version or `1.0.0` |
  66. | `--base-url` | `-b` | Base URL for API requests. Required if OpenAPI `servers` missing or ambiguous. | Auto-detected if possible |
  67. | `--transport` | `-t` | Transport mode: `"stdio"` (default), `"web"`, `"streamable-http"`, or `"cloudflare-worker"` | `"stdio"` |
  68. | `--port` | `-p` | Port for web-based transports | `3000` |
  69. | `--default-include` | | Default behavior for x-mcp filtering. Accepts `true` or `false` (case-insensitive). `true` = include by default, `false` = exclude by default. | `true` |
  70. | `--allow-external-refs` | | Allow resolving external `http(s)` `$ref` references in the spec. Disabled by default to prevent SSRF during parsing. | `false` |
  71. | `--max-tool-name-length` | | Maximum length for generated tool names (Claude Desktop caps at 64). Longer names are truncated with a hash suffix. | `64` |
  72. | `--header-passthrough` | | Comma-separated inbound header names to forward to the upstream API (web, streamable-http, cloudflare-worker). Enables per-user API keys. | _(none)_ |
  73. | `--inbound-auth` | | Inbound auth for HTTP transports: `none` or `bearer`. With `bearer`, clients must send `Authorization: Bearer <token>` (`MCP_AUTH_TOKEN`). | `none` |
  74. | `--insecure` | `-k` | Allow insecure HTTPS connections (skip TLS certificate verification) in the generated server. | `false` |
  75. | `--generate-lib` | | Generate library-style output: export `main()` instead of auto-invoking it, omitting signal/cleanup wiring. | `false` |
  76. | `--custom-auth` | | Generate an editable `src/auth.ts` hook (`applyCustomAuth`) called before built-in auth; return `true` to skip built-in auth. | `false` |
  77. | `--oauth-creds-in-body` | | Send OAuth2 client credentials in the token request body instead of the Basic `Authorization` header. | `false` |
  78. | `--include-tags` | | Comma-separated tags: generate only operations with one of them (case-insensitive). | _(all)_ |
  79. | `--exclude-tags` | | Comma-separated tags: skip operations with any of them. Exclusions win over inclusions. | _(none)_ |
  80. | `--include-operations` | | Comma-separated operationIds or tool names to generate. Combined with `--include-tags` as a union. | _(all)_ |
  81. | `--exclude-operations` | | Comma-separated operationIds or tool names to skip. Exclusions win over inclusions. | _(none)_ |
  82. | `--output-schema` | | Declare each tool's `outputSchema` from its 2xx JSON response schema (objects only) and reject responses that do not match it. | `false` |
  83. | `--force` | | Overwrite existing files in the output directory without confirmation | `false` |
  84. > **Configuring the API base URL at runtime:** the generated server reads
  85. > `API_BASE_URL` from the environment (`.env`), overriding the value baked in
  86. > from the OpenAPI `servers` list. The port resolves from `--port`, then the
  87. > `PORT` env var, then `3000`.
  88. >
  89. > **Per-operation and per-path servers:** an operation's `servers[0]` wins over its path item's,
  90. > which wins over the root server, with server variables set to their defaults. An absolute
  91. > operation or path server is used even when `API_BASE_URL` is set; a relative one resolves
  92. > against the active base URL (`"v2"` appends a segment, `"/v2"` replaces the path).
  93. ## 📦 Programmatic API
  94. The package also exports the parser the CLI uses, so you can turn an OpenAPI document into MCP tool
  95. definitions inside your own Node.js code:
  96. ```typescript
  97. import { getToolsFromOpenApi } from 'openapi-mcp-generator';
  98. // From a local file or a URL
  99. const tools = await getToolsFromOpenApi('./petstore.json', { dereference: true });
  100. // With options
  101. const readOnlyPetTools = await getToolsFromOpenApi(
  102. 'https://petstore3.swagger.io/api/v3/openapi.json',
  103. {
  104. baseUrl: 'https://petstore3.swagger.io/api/v3',
  105. dereference: true,
  106. includeTags: ['pet'],
  107. excludeOperations: ['deletePet'],
  108. filterFn: (tool) => tool.annotations?.readOnlyHint === true,
  109. }
  110. );
  111. for (const tool of readOnlyPetTools) {
  112. console.log(`${tool.name}: ${tool.method.toUpperCase()} ${tool.pathTemplate}`);
  113. }
  114. ```
  115. ### `getToolsFromOpenApi(spec, options?)`
  116. `spec` is a file path, an http(s) URL or an already parsed `OpenAPIV3.Document`. The function
  117. returns `Promise<McpToolDefinition[]>`. Swagger 2.0 documents are rejected; convert them first
  118. (`npx swagger2openapi swagger.json -o openapi.json`).
  119. | Option | Description | Default |
  120. | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------- |
  121. | `baseUrl` | Override the base URL from the spec's `servers` | |
  122. | `dereference` | Resolve `$ref`s before extracting tools. Without it, referenced schemas stay unresolved and a warning is logged for each one | `false` |
  123. | `includeTags` / `excludeTags` | Keep only, or drop, operations with these tags (case-insensitive) | |
  124. | `includeOperations` / `excludeOperations` | Keep only, or drop, these operations (operationId or tool name). Same rules as the CLI flags: includes combine, exclusions win | |
  125. | `excludeOperationIds` | Drop these operationIds (older option, applied after the filters above) | |
  126. | `filterFn` | Custom predicate `(tool) => boolean`, applied last | |
  127. | `defaultInclude` | Whether operations without an `x-mcp` extension are included | `true` |
  128. | `allowExternalRefs` | Allow external http(s) `$ref`s. Off by default so parsing cannot be used for SSRF | `false` |
  129. | `maxToolNameLength` | Maximum generated tool name length (Claude Desktop allows 64) | `64` |
  130. Filters apply after `x-mcp` filtering. To parse the document yourself, pass the result in:
  131. ```typescript
  132. import SwaggerParser from '@apidevtools/swagger-parser';
  133. import type { OpenAPIV3 } from 'openapi-types';
  134. import { getToolsFromOpenApi } from 'openapi-mcp-generator';
  135. const api = (await SwaggerParser.dereference('./openapi.yaml')) as OpenAPIV3.Document;
  136. const tools = await getToolsFromOpenApi(api);
  137. ```
  138. ### Tool definitions
  139. ```typescript
  140. interface McpToolDefinition {
  141. name: string; // unique tool name
  142. title?: string; // x-mcp-title, else the operation summary
  143. description: string;
  144. inputSchema: JSONSchema7 | boolean; // JSON Schema 2020-12 for the tool arguments
  145. method: string; // get, post, ...
  146. pathTemplate: string; // e.g. /pet/{petId}
  147. parameters: OpenAPIV3.ParameterObject[];
  148. executionParameters: { name: string; in: string }[];
  149. requestBodyContentType?: string;
  150. serverUrl?: string; // operation or path-item server, variables resolved
  151. baseUrl?: string; // set by getToolsFromOpenApi: the baseUrl option or root server, else ''
  152. securityRequirements: OpenAPIV3.SecurityRequirementObject[];
  153. operationId: string;
  154. tags?: string[];
  155. deprecated?: boolean;
  156. annotations?: McpToolAnnotations; // readOnlyHint, destructiveHint, idempotentHint, openWorldHint
  157. outputSchema?: JSONSchema7; // lowest 2xx application/json response, when it is an object
  158. }
  159. ```
  160. `inputSchema` keeps `integer` types, turns `example` into `examples` and leaves out `readOnly`
  161. properties. Annotations come from the HTTP method (GET and HEAD are read-only, DELETE is
  162. destructive, PUT and DELETE are idempotent) and can be overridden per operation with
  163. `x-mcp-annotations`. Each tool returned by `getToolsFromOpenApi` carries `baseUrl`: the `baseUrl`
  164. option, else the spec's root server, else an empty string. An operation or path-item server is in
  165. `serverUrl` and takes precedence when calling the API.
  166. More filters:
  167. ```typescript
  168. const spec = './petstore.json';
  169. // Only GET operations
  170. await getToolsFromOpenApi(spec, { dereference: true, filterFn: (tool) => tool.method === 'get' });
  171. // Only operations that require authentication
  172. await getToolsFromOpenApi(spec, {
  173. dereference: true,
  174. filterFn: (tool) => tool.securityRequirements.length > 0,
  175. });
  176. // Read-only user endpoints, without two specific operations
  177. await getToolsFromOpenApi(spec, {
  178. dereference: true,
  179. excludeOperationIds: ['deleteUser', 'updateUser'],
  180. filterFn: (tool) =>
  181. tool.pathTemplate.startsWith('/user') && tool.annotations?.readOnlyHint === true,
  182. });
  183. ```
  184. ---
  185. ## 🧱 Project Structure
  186. The generated project includes:
  187. ```
  188. <output_directory>/
  189. ├── .gitignore
  190. ├── package.json
  191. ├── tsconfig.json
  192. ├── .env.example
  193. ├── src/
  194. │ ├── index.ts
  195. │ └── [transport-specific-files]
  196. └── public/ # web and streamable-http: the browser playground
  197. ├── index.html, playground.js, playground.css, mcp-client.js
  198. └── playground.config.json
  199. ```
  200. Core dependencies:
  201. - `@modelcontextprotocol/server` - MCP protocol implementation (SDK v2)
  202. - `@cfworker/json-schema` - JSON Schema 2020-12 validation of tool arguments (and outputs with `--output-schema`)
  203. - `axios` - HTTP client for API requests
  204. - Transport-specific deps (`hono`, `@hono/node-server`)
  205. `.env` is loaded with Node's built-in `process.loadEnvFile()`; no `dotenv` dependency.
  206. ---
  207. ## 📡 Transport Modes
  208. Generated servers speak **MCP 2026-07-28** (stateless requests, `server/discover`) and keep
  209. serving **2025-era clients** that open with `initialize`, using the MCP TypeScript SDK v2. The
  210. `web` (SSE) transport stays on the 2025-era protocol because the specification deprecates
  211. HTTP+SSE; prefer `streamable-http` for new deployments.
  212. ### Stdio (Default)
  213. Communicates with MCP clients via standard input/output. Ideal for local development or integration with LLM tools.
  214. ### Web Server with SSE
  215. Launches a fully functional HTTP server with:
  216. - Server-Sent Events (SSE) for bidirectional messaging
  217. - REST endpoint for client → server communication
  218. - Browser playground at `/`
  219. - Multi-connection support
  220. - Built with lightweight Hono framework
  221. ### StreamableHTTP
  222. Implements the MCP StreamableHTTP transport which offers:
  223. - Stateless JSON-RPC over HTTP: every request gets a fresh server, so it scales behind any load
  224. balancer
  225. - Serves MCP 2026-07-28 and 2025-era clients (2025-era clients run without sessions; GET and
  226. DELETE answer `405`)
  227. - Proper HTTP response status codes
  228. - Built-in error handling
  229. - Compatibility with MCP StreamableHTTPClientTransport
  230. - Browser playground at `/`
  231. - Built with lightweight Hono framework
  232. ### Cloudflare Worker
  233. Generates a complete, deployable [Cloudflare Workers](https://developers.cloudflare.com/workers/) project that serves the MCP server over **Streamable HTTP at `/mcp`** using `createMcpHandler` from `@modelcontextprotocol/server` (no extra framework dependency). Deploy it to your own Cloudflare account with one command:
  234. ```bash
  235. openapi-mcp-generator --input ./openapi.json --output ./my-mcp-worker --transport cloudflare-worker
  236. cd my-mcp-worker
  237. npm install
  238. npx wrangler secret put API_KEY # set upstream API secrets (see .dev.vars.example)
  239. npx wrangler deploy # Wrangler logs into YOUR Cloudflare account and deploys
  240. ```
  241. Highlights:
  242. - Stateless, runs on the free Workers tier (no Durable Objects or KV). A fresh MCP server is created per request.
  243. - Lean dependencies: just `@modelcontextprotocol/server` and `@cfworker/json-schema` — no extra agent framework.
  244. - 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.
  245. - Workers-native runtime: global `fetch` (no Node `https`), and arguments are validated against the JSON Schema with `@cfworker/json-schema` (no code generation, no `eval`).
  246. - Auth is scheme-aware: API key (header/query/cookie), HTTP basic/bearer, OpenID Connect tokens, and OAuth2 client-credentials are derived from `env` secrets, following OpenAPI security requirement semantics (see [Securing HTTP servers](#-securing-http-servers)).
  247. - `--inbound-auth bearer` protects `/mcp` with a token from `wrangler secret put MCP_AUTH_TOKEN`; `--header-passthrough` forwards per-user upstream keys from the client.
  248. - `--custom-auth`, `--port`, `--insecure`, `--generate-lib`, and `--oauth-creds-in-body` do not apply to this target and are ignored with a warning.
  249. Local development: `cp .dev.vars.example .dev.vars`, uncomment and fill in the secrets you use, then `npm run dev` (serves `http://localhost:8787/mcp`). Connect with the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) or, from Claude Desktop, via [mcp-remote](https://www.npmjs.com/package/mcp-remote).
  250. ### Transport Comparison
  251. | Feature | stdio | web (SSE) | streamable-http | cloudflare-worker |
  252. | ------------------ | ------------------- | ----------------- | ------------------ | ----------------------- |
  253. | Protocol | JSON-RPC over stdio | JSON-RPC over SSE | JSON-RPC over HTTP | Streamable HTTP at /mcp |
  254. | Connection | Persistent | Persistent | Request/response | Request/response |
  255. | Bidirectional | Yes | Yes | Yes (stateless) | Yes |
  256. | Multiple clients | No | Yes | Yes | Yes |
  257. | Browser compatible | No | Yes | Yes | Yes |
  258. | Firewall friendly | No | Yes | Yes | Yes |
  259. | Load balancing | No | Limited | Yes | Yes (edge) |
  260. | Status codes | No | Limited | Full HTTP codes | Full HTTP codes |
  261. | Headers | No | Limited | Full HTTP headers | Full HTTP headers |
  262. | Browser playground | No | Yes | Yes | Yes |
  263. | Hosting | Local | Self-hosted | Self-hosted | Cloudflare (serverless) |
  264. ---
  265. ## 🔐 Environment Variables for Authentication
  266. Configure auth credentials in your environment:
  267. | Auth Type | Variable Format |
  268. | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- |
  269. | API Key | `API_KEY_<SCHEME_NAME>` |
  270. | Bearer | `BEARER_TOKEN_<SCHEME_NAME>` |
  271. | Basic Auth | `BASIC_USERNAME_<SCHEME_NAME>`, `BASIC_PASSWORD_<SCHEME_NAME>` |
  272. | OAuth2 | `OAUTH_TOKEN_<SCHEME_NAME>`, or `OAUTH_CLIENT_ID_<SCHEME_NAME>`, `OAUTH_CLIENT_SECRET_<SCHEME_NAME>`, `OAUTH_SCOPES_<SCHEME_NAME>` |
  273. | OpenID | `OPENID_TOKEN_<SCHEME_NAME>` |
  274. For OAuth2, `OAUTH_TOKEN_<SCHEME_NAME>` is a token you already have and works for every flow.
  275. Otherwise the server fetches a token: with the client ID and secret when the scheme has a client
  276. credentials flow or, when it has only a password flow, with `OAUTH_USERNAME_<SCHEME_NAME>` and
  277. `OAUTH_PASSWORD_<SCHEME_NAME>` (plus the client ID, and the secret for a confidential client, when
  278. the token endpoint needs them).
  279. When an operation lists several security requirements, the first one whose schemes are all
  280. configured is used. If none can be satisfied (a forwarded `--header-passthrough` header counts)
  281. and the operation does not allow anonymous access with an empty `{}` requirement, the tool
  282. **fails closed**: it does not call the API and returns an error naming what to set, for example
  283. `Missing credentials for 'getPet': set API_KEY_PETSTORE_AUTH.` Set
  284. `MCP_ALLOW_MISSING_CREDENTIALS=true` (a Worker var for Workers) to send such requests without
  285. credentials instead. OAuth2 tokens are requested with the operation's scopes unless
  286. `OAUTH_SCOPES_<SCHEME_NAME>` overrides them. The Cloudflare Worker target reads the same
  287. credentials from Wrangler secrets named `<SCHEME_NAME>_API_KEY`, `<SCHEME_NAME>_TOKEN`,
  288. `<SCHEME_NAME>_USERNAME`/`_PASSWORD` and `<SCHEME_NAME>_CLIENT_ID`/`_CLIENT_SECRET` (see the
  289. generated `.dev.vars.example`). For OAuth2, `<SCHEME_NAME>_TOKEN` holds a token you already have
  290. and works for every flow; the Worker fetches a token from the client ID and secret only when the
  291. scheme declares a client credentials flow.
  292. ---
  293. ## 🧩 Generated tools
  294. - **Input schemas** are JSON Schema 2020-12 mapped from your OpenAPI schemas: `integer`, `format`,
  295. `pattern`, enums and `allOf`/`anyOf`/`oneOf` are kept, `nullable` becomes a `null` type, `example`
  296. becomes `examples`, and `readOnly` properties are left out of request inputs.
  297. - **Validation:** arguments are checked against that schema before any request is sent. Problems come
  298. back as a tool error the model can fix, for example
  299. `Invalid arguments for tool 'getPet': /petId: Instance type "string" is invalid. Expected "integer".`
  300. Arguments are passed through as given: schema defaults are not injected.
  301. - **Errors:** invalid arguments, missing credentials and upstream failures are tool errors
  302. (`isError: true`); an unknown tool name is a JSON-RPC `-32602` protocol error, as the MCP
  303. 2026-07-28 specification requires.
  304. - **Titles and annotations:** the title is the operation's `x-mcp-title`, else its summary. Hints follow
  305. the HTTP method: `GET`/`HEAD`/`OPTIONS` are read-only; `POST` is not destructive and not idempotent;
  306. `PUT` and `DELETE` are destructive and idempotent; `PATCH` is destructive and not idempotent; all are
  307. open-world. Override individual hints per operation:
  308. ```yaml
  309. paths:
  310. /pets/{id}:
  311. delete:
  312. x-mcp-title: Remove a pet
  313. x-mcp-annotations:
  314. destructiveHint: false # a soft delete
  315. ```
  316. - **Structured output:** a JSON response that is an object is also returned as `structuredContent`.
  317. With `--output-schema`, each tool declares the schema of its lowest 2xx `application/json` response
  318. as `outputSchema` (object schemas only, `writeOnly` properties removed) and every response is
  319. validated against it; a response that does not match becomes a tool error that still shows the raw
  320. body. Leave it off if your spec does not describe real responses accurately.
  321. - **Server instructions:** the spec's `info.description` (trimmed, up to 2000 characters) is sent to
  322. clients as the server instructions.
  323. ---
  324. ## 🔒 Securing HTTP servers
  325. Generated `web`, `streamable-http` and `cloudflare-worker` servers expose a network endpoint.
  326. If they also hold upstream credentials, anyone who reaches the endpoint can spend them, so the
  327. generator warns when you generate such a server without protection.
  328. **Require a token** with `--inbound-auth bearer`:
  329. ```bash
  330. openapi-mcp-generator -i openapi.json -o my-mcp -t streamable-http --inbound-auth bearer
  331. openssl rand -hex 32 # put the value in .env as MCP_AUTH_TOKEN (Workers: wrangler secret put MCP_AUTH_TOKEN)
  332. ```
  333. - Every MCP request must send `Authorization: Bearer <token>`; others get `401` before any tool
  334. runs. `/health` stays public.
  335. - Tokens are read at runtime, never written into generated files, and compared in constant time.
  336. Rotate without downtime with `MCP_AUTH_TOKENS=new-token,old-token`.
  337. - With no token configured the server fails closed with `503`.
  338. - SSE sessions are bound to the token that opened them; replaying a session ID with another
  339. token is answered `404`. Streamable HTTP is stateless and checks the token on every request.
  340. - Clients that accept custom headers (Claude Code, Cursor, VS Code, MCP Inspector, `mcp-remote`)
  341. send the token directly. Claude.ai and ChatGPT connectors use OAuth or no auth; put those
  342. behind an OAuth-capable gateway.
  343. **Let each user bring their own upstream key** with `--header-passthrough X-API-Key`: the listed
  344. headers are forwarded per request, so the server stores no shared secret. A forwarded header
  345. satisfies the security scheme whose credential travels in it, so the other schemes of an AND
  346. requirement are still applied from server configuration. Passthrough cannot forward
  347. `Authorization` while `--inbound-auth bearer` is on, because that header carries the MCP token.
  348. **Browser origins.** Node HTTP servers reject browser requests whose `Origin` is not loopback
  349. or listed in `MCP_ALLOWED_ORIGINS` (comma-separated), which blocks DNS-rebinding attacks on
  350. servers running on your machine. MCP clients that send no `Origin` header are unaffected.
  351. `--inbound-auth` has no effect on `stdio`: a stdio server has no network endpoint, and only the
  352. process that launches it can talk to it.
  353. Found a vulnerability? See [SECURITY.md](./SECURITY.md).
  354. ---
  355. ## 🔎 Filtering Endpoints with OpenAPI Extensions
  356. 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.
  357. - Extension: `x-mcp: true | false`
  358. - Default: `true` (include by default)
  359. - Precedence: operation > path > root (first non-undefined wins)
  360. - CLI option: `--default-include false` to change default to exclude by default
  361. Examples:
  362. ```yaml
  363. # Optional root-level default
  364. x-mcp: true
  365. paths:
  366. /pets:
  367. x-mcp: false # exclude all ops under /pets
  368. get:
  369. x-mcp: true # include this operation anyway
  370. /users/{id}:
  371. get:
  372. # no x-mcp -> included by default
  373. ```
  374. This uses standard OpenAPI extensions (x-… fields). See the [OpenAPI Extensions guide](https://swagger.io/docs/specification/v3_0/openapi-extensions/) for details.
  375. 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.
  376. ### Filtering from the command line
  377. Large APIs can be curated without editing the spec:
  378. ```bash
  379. openapi-mcp-generator -i openapi.json -o my-mcp \
  380. --include-tags pets,store --exclude-operations deletePet
  381. ```
  382. - `--include-tags` / `--exclude-tags` match operation tags case-insensitively.
  383. - `--include-operations` / `--exclude-operations` match the operationId or the generated tool name.
  384. - Filters apply after `x-mcp` and `--default-include`, so they never bring back an excluded
  385. operation. Include lists combine (an operation is kept if it matches any), and exclusions always win.
  386. - The programmatic API accepts the same filters: `includeTags`, `excludeTags`, `includeOperations`,
  387. `excludeOperations`.
  388. ---
  389. ## ▶️ Running the Generated Server
  390. ```bash
  391. cd path/to/output/dir
  392. npm install
  393. # Run in stdio mode
  394. npm start
  395. # Run in web server mode
  396. npm run start:web
  397. # Run in StreamableHTTP mode
  398. npm run start:http
  399. ```
  400. ### 🧪 Browser playground
  401. Servers generated for `web`, `streamable-http` and `cloudflare-worker` serve a playground at `/`
  402. (`http://localhost:<port>/`, or `http://localhost:8787/` with `npm run dev` for a Worker). It lists
  403. the tools, builds a form for each one from its input schema, runs it and shows every JSON-RPC
  404. message, with copy-as-curl and ready-made configs for Claude Code, Cursor and VS Code. If the server
  405. was generated with `--inbound-auth bearer`, paste the value of `MCP_AUTH_TOKEN`; it stays in the
  406. browser tab.
  407. - The page is served from the server's own origin with a strict Content-Security-Policy, so local
  408. testing needs no CORS or `MCP_ALLOWED_ORIGINS` changes. Server output is always rendered as text.
  409. - The page also has Resources, Prompts (with argument completion), Logs and Raw JSON-RPC tabs, shows
  410. progress with a Cancel button for long tool calls, and answers server requests: elicitation forms,
  411. sampling (you type the reply) and roots.
  412. - The same open-source page is hosted at [mcp.pidata.tech/playground](https://mcp.pidata.tech/playground)
  413. and connects to any remote MCP server with nothing to install: custom headers, OAuth sign-in
  414. (discovery, Client ID Metadata Documents or dynamic registration, PKCE) and an optional
  415. [open-source relay](relay/README.md) for servers that block browser requests. Generated Workers
  416. answer CORS so it (and other browser clients) can reach them directly; for Node servers, add the
  417. page's origin to `MCP_ALLOWED_ORIGINS`.
  418. - Set `MCP_PLAYGROUND=off` (Node) or the `MCP_PLAYGROUND` var to `"off"` (Worker) to stop serving it,
  419. for example in production.
  420. - stdio servers have no HTTP endpoint; test them with the
  421. [MCP Inspector](https://github.com/modelcontextprotocol/inspector).
  422. ---
  423. ## ⚠️ Requirements
  424. - Node.js 22.19 or later to run the generator; generated projects require Node.js 22 or later (Node 20 reached end of life in April 2026)
  425. ---
  426. ## Star History
  427. <a href="https://star-history.dera.page/#harsha-iiiv/openapi-mcp-generator&Date">
  428. <picture>
  429. <source media="(prefers-color-scheme: dark)" srcset="https://star-history.dera.page/svg?repos=harsha-iiiv/openapi-mcp-generator&type=Date&theme=dark" />
  430. <source media="(prefers-color-scheme: light)" srcset="https://star-history.dera.page/svg?repos=harsha-iiiv/openapi-mcp-generator&type=Date" />
  431. <img alt="Star History Chart" src="https://star-history.dera.page/svg?repos=harsha-iiiv/openapi-mcp-generator&type=Date" />
  432. </picture>
  433. </a>
  434. ## 🤝 Contributing
  435. Contributions are welcome!
  436. 1. Fork the repo
  437. 2. Create a feature branch: `git checkout -b feature/amazing-feature`
  438. 3. Run `npm run format.write` to format your code
  439. 4. Commit your changes: `git commit -m "Add amazing feature"`
  440. 5. Push and open a PR
  441. 📌 Repository: [github.com/harsha-iiiv/openapi-mcp-generator](https://github.com/harsha-iiiv/openapi-mcp-generator)
  442. ---
  443. ## 📄 License
  444. MIT License — see [LICENSE](./LICENSE) for full details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.