mcp-from-openapi

mcp
Guvenlik Denetimi
Uyari
Health Gecti
  • License — License: Apache-2.0
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Community trust — 12 GitHub stars
Code Uyari
  • fs module — File system access in .github/workflows/create-release-branch.yml
  • process.env — Environment variable access in .github/workflows/prepare-release.yml
  • fs module — File system access in .github/workflows/prepare-release.yml
  • network request — Outbound network request in .github/workflows/prepare-release.yml
Permissions Gecti
  • Permissions — No dangerous permissions requested

Bu listing icin henuz AI raporu yok.

SUMMARY

TypeScript library that converts Swagger 2.0 and OpenAPI 3.0, 3.1 and 3.2 specifications into MCP (Model Context Protocol) tool definitions, with request building, client-specific schemas and SSRF-safe $ref resolution

README.md

mcp-from-openapi

Convert Swagger 2.0 and OpenAPI 3.0, 3.1 and 3.2 specifications into MCP tool definitions with automatic parameter conflict resolution

npm version
npm downloads
CI
coverage
CodeQL
License: Apache 2.0
TypeScript
node
XERJ Corpus Hub contributor

What This Solves

When converting OpenAPI specs to MCP tools, you hit parameter conflicts -- the same name appears in different locations (path, query, body). This library resolves them automatically and gives you an explicit mapper for building HTTP requests.

The Problem:

paths:
  /users/{id}:
    post:
      parameters:
        - name: id # path
          in: path
      requestBody:
        content:
          application/json:
            schema:
              properties:
                id: # body -- CONFLICT!
                  type: string

The Solution:

{
  inputSchema: {
    properties: {
      pathId: { type: "string" },    // Automatically renamed
      bodyId: { type: "string" }     // Automatically renamed
    }
  },
  mapper: [
    { inputKey: "pathId", type: "path", key: "id" },
    { inputKey: "bodyId", type: "body", key: "id" }
  ]
}

Now you know exactly how to build the HTTP request.

Features

  • Swagger 2.0 and OpenAPI 3.0, 3.1 and 3.2 -- Validated with the rules of the version a document declares. From 3.2: the query operation and additionalOperations methods, in: querystring whole-query parameters, style: cookie, streamed responses (itemSchema), $self, and security schemes named by URI; what the library skips or ignores is recorded in getDiagnostics() instead of dropped. A Swagger 2.0 document is converted to OpenAPI 3.0 (upgradeSwagger2, also exported) and its tools are generated from the conversion, with what could not be carried over exactly recorded the same way. The OpenAPI types, version rules and the converter come from openapi-spec, which is checked every week against the official OpenAPI schemas
  • Built-in Request Builder -- buildHttpRequest() applies the full OpenAPI serialization table (form/deepObject/pipeDelimited queries, label/matrix paths, content parameters, per-field Encoding Objects in form and multipart bodies, allowReserved that never lets a value add a query pair, OpenAPI 3.2 whole-query (in: querystring) and style: cookie, multipart, binary, wholeBody) so you never hand-write request assembly
  • Client Compatibility Targets -- target: 'claude' | 'openai' | 'gemini' | 'strict' emits schemas each client actually accepts (inlined refs, closed objects, collapsed unions, demoted formats)
  • Context-Budget Reports -- analyzeToolSet() estimates the token bill per tool and warns at the thresholds where agent accuracy degrades
  • Overlays & Lint -- apply OpenAPI Overlay curation files at load time; lint() flags the spec gaps that hurt tool-calling accuracy
  • Curation-Grade Filtering -- Filter by tag, method, path glob (/admin/**), operationId, a readOnlyOnly safety switch, and x-mcp extension flags with root < path < operation precedence
  • Smart Parameter Handling -- Automatic conflict detection and resolution across path, query, header, cookie, and body; an operation-level parameter overrides a path-level one with the same name and location; allOf bodies flatten, union and binary bodies map cleanly (wholeBody, binary markers)
  • Complete Schemas -- Input schema combines all parameters; output schema from responses (with anyOf unions); streamed responses (itemSchema) reported in metadata.responseStream; clean JSON Schema 2020-12 output (nullable unions, normalized examples)
  • MCP-Native Tools -- title and tool annotations (readOnly/destructive/idempotent hints) inferred from HTTP semantics, overridable via the x-mcp extension family; spec-compliant tool names (64-char cap, stable hash truncation, collision dedup); deterministic tool ordering for prompt-cache friendliness; toSdkTool() for one-line SDK registration
  • Security Resolution -- Framework-agnostic auth for Bearer, Basic, Digest, API Key, OAuth2, OpenID, mTLS, HMAC, AWS Sig V4; per-scheme includeSecurityInInput
  • SSRF Prevention -- Blocks internal IPs, localhost, and cloud metadata endpoints by default during $ref resolution; one-flag secureDefaults posture for untrusted specs; a documented trust model for what a spec can make the library read
  • Multiple Input Sources -- Load from URL, file, YAML string, or JSON object; multi-file specs resolve relative $refs against where the document was loaded from (URL, file or documentUri)
  • Rich Metadata -- Authentication, servers, tags, deprecation, external docs, x-frontmcp extension
  • Production Ready -- Full TypeScript support, validation, structured errors, 100% test coverage (enforced)
  • Runtime Agnostic -- Works on Node and V8 isolates (Cloudflare Workers) alike

Installation

npm install mcp-from-openapi
# or
yarn add mcp-from-openapi
# or
pnpm add mcp-from-openapi

Quick Start

import { OpenAPIToolGenerator } from "mcp-from-openapi";

// Load an OpenAPI spec
const generator = await OpenAPIToolGenerator.fromURL(
  "https://api.example.com/openapi.json",
);

// Generate MCP tools
const tools = await generator.generateTools();

// Each tool has everything you need
tools.forEach((tool) => {
  console.log(tool.name); // "createUser"
  console.log(tool.title); // "Create a user" (from summary/extensions)
  console.log(tool.annotations); // { readOnlyHint: false, destructiveHint: true, ... }
  console.log(tool.inputSchema); // Combined schema for all params
  console.log(tool.outputSchema); // Response schema
  console.log(tool.mapper); // How to build the HTTP request
  console.log(tool.metadata); // Auth, servers, tags, etc.
});

Building Requests

buildHttpRequest() turns a tool plus input values into a ready-to-send request — style/explode serialization, deepObject queries, multipart, binary, and wholeBody handled correctly:

import { buildHttpRequest } from "mcp-from-openapi";

const request = buildHttpRequest(tool, { id: "42", filter: { tag: "news" } });
// { url: 'https://api.example.com/users/42?filter[tag]=news',
//   method: 'GET', headers: {...}, body: undefined, ... }

await fetch(request.url, {
  method: request.method,
  headers: request.headers,
  body: request.body as BodyInit,
});

The mapper array stays public for anyone who needs custom request assembly — see Request Builder and Parameter Conflicts for its contract.

Serving with the Official MCP SDK

import { toSdkTool, buildHttpRequest } from "mcp-from-openapi";
import { fromJsonSchema } from "@modelcontextprotocol/server"; // SDK v2

for (const tool of await generator.generateTools({ target: "claude" })) {
  server.registerTool(...toSdkTool(tool, { fromJsonSchema }), async (input) => {
    const request = buildHttpRequest(tool, input);
    const response = await fetch(request.url, {
      method: request.method,
      headers: request.headers,
      body: request.body as BodyInit,
    });
    return { content: [{ type: "text", text: await response.text() }] };
  });
}

Documentation

Document Description
Getting Started Loading specs (multi-file included), generating tools, building requests
Configuration LoadOptions, GenerateOptions, RefResolutionOptions
OpenAPI Versions Supported versions, Swagger 2.0 conversion, OpenAPI 3.2 features, diagnostics, known gaps
Parameter Conflicts How conflict detection and resolution works
Request Builder buildHttpRequest — full OpenAPI parameter serialization
Client Targets Per-client schema dialects (Claude, OpenAI, Gemini)
Curation Token budgets, overlays, lint, trimming, response hints
Type Signatures TypeScript call contracts for code-execution surfaces
Modern MCP Fields Tool _meta, icons, x-mcp-header, elicitation descriptors
Arazzo Workflows fromArazzo() — Arazzo 1.0 workflows as consolidated MCP tools
Tested Examples Runnable examples, each executed as an e2e test on every CI run
Response Schemas Output schemas, status codes, anyOf unions, streamed responses
Annotations & Extensions Tool title, annotation inference, x-mcp extension family
Security SecurityResolver, all auth types, custom resolvers
SSRF Prevention Ref resolution security, base URIs and $self, trust model
Format Resolution Format-to-schema enrichment (uuid, date-time, email, int32, etc.)
Naming Strategies Custom tool naming and conflict resolvers
SchemaBuilder JSON Schema utility methods
Error Handling Error classes, context, and patterns
x-frontmcp Extension Custom OpenAPI extension for MCP annotations
API Reference Complete types, interfaces, and exports
Examples MCP server, Zod, filtering, security, and more
Architecture System overview, data flow, design patterns
Maintaining OpenAPI Support For maintainers: adding a version, moving the pinned official sources
Releasing For maintainers: the release pull request flow and the npm and repository settings it needs

Requirements

  • Node.js >= 22.19.0
  • TypeScript >= 5.0 (for TypeScript users)
  • Peer dependency: zod@^4.0.0

Contributing

Contributions are welcome! Start with the
contributing guide;
this project follows the
Contributor Covenant.
Bug reports and feature requests go through the
issue templates.

Security

Report vulnerabilities privately — see the
security policy.
When loading untrusted specs, use secureDefaults: true, and do not allow
the file protocol in refResolution.allowedProtocols for a spec you do not
control: it lets the spec read any local file the process can read (see the
trust model).

Related Projects

License

Apache 2.0

Yorumlar (0)

Sonuc bulunamadi