convez.ai
MCP ServerIntegração & APIsIntermediário
agentfront

MCP from OpenAPI

agentfront/mcp-from-openapi

Converta OpenAPI specs em ferramentas MCP com resolução automática de conflitos

Ver no GitHub
InicialPluginScore · de 0 a 100

Biblioteca pronta para produção que converte especificações OpenAPI em definições de ferramentas MCP, com resolução automática de conflitos de parâmetros. Detecta e renomeia automaticamente parâmetros duplicados entre path, query, headers, cookies e body, fornecendo um mapeador explícito para construir requisições HTTP.

Instalação

$npx convez-ai agentfront/mcp-from-openapi

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
12
Forks
0
Acompanhando
2
Saúde
62%
Último commit
há 1 dia
Versão
v2.10.0
Issues abertas
1
Contribuidores
1

Casos de uso

  • Integrar APIs REST existentes como ferramentas nativas do MCP
  • Gerar esquemas de entrada/saída automáticos a partir de OpenAPI
  • Resolver conflitos de parâmetros em endpoints complexos

Veredito

Solução sólida e bem arquitetada para o problema real de mapear APIs REST para o ecossistema MCP. Oferece resolução automática de conflitos, suporte a autenticação variada e validação robusta — exatamente o que falta para integração de produção.

README

A tradução para o português deste README ainda está na fila.

mcp-from-openapi

Convert OpenAPI specifications into MCP tool definitions with automatic parameter conflict resolution

npm version License: Apache 2.0 TypeScript Node.js

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

  • Smart Parameter Handling -- Automatic conflict detection and resolution across path, query, header, cookie, and body
  • Complete Schemas -- Input schema combines all parameters; output schema from responses (with oneOf unions)
  • Security Resolution -- Framework-agnostic auth for Bearer, Basic, Digest, API Key, OAuth2, OpenID, mTLS, HMAC, AWS Sig V4
  • SSRF Prevention -- Blocks internal IPs, localhost, and cloud metadata endpoints by default during $ref resolution
  • Multiple Input Sources -- Load from URL, file, YAML string, or JSON object
  • Rich Metadata -- Authentication, servers, tags, deprecation, external docs, x-frontmcp extension
  • Production Ready -- Full TypeScript support, validation, structured errors, 80%+ test coverage
  • MCP Native -- Designed specifically for Model Context Protocol integration

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.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.
});

Using the Mapper

The mapper tells you how to convert tool inputs into an HTTP request:

function buildRequest(tool: McpOpenAPITool, input: Record<string, any>) {
  let path = tool.metadata.path;
  const query = new URLSearchParams();
  const headers: Record<string, string> = {};
  let body: Record<string, any> | undefined;

  for (const m of tool.mapper) {
    const value = input[m.inputKey];
    if (value === undefined) continue;

    switch (m.type) {
      case 'path':
        path = path.replace(`{${m.key}}`, encodeURIComponent(value));
        break;
      case 'query':
        query.set(m.key, String(value));
        break;
      case 'header':
        headers[m.key] = String(value);
        break;
      case 'body':
        if (!body) body = {};
        body[m.key] = value;
        break;
    }
  }

  const baseUrl = tool.metadata.servers?.[0]?.url ?? '';
  const qs = query.toString();

  return {
    url: `${baseUrl}${path}${qs ? '?' + qs : ''}`,
    method: tool.metadata.method.toUpperCase(),
    headers,
    body: body ? JSON.stringify(body) : undefined,
  };
}

Documentation

DocumentDescription
Getting StartedLoading specs, generating tools, building requests
ConfigurationLoadOptions, GenerateOptions, RefResolutionOptions
Parameter ConflictsHow conflict detection and resolution works
Response SchemasOutput schemas, status codes, oneOf unions
SecuritySecurityResolver, all auth types, custom resolvers
SSRF PreventionRef resolution security, blocked IPs and hosts
Format ResolutionFormat-to-schema enrichment (uuid, date-time, email, int32, etc.)
Naming StrategiesCustom tool naming and conflict resolvers
SchemaBuilderJSON Schema utility methods
Error HandlingError classes, context, and patterns
x-frontmcp ExtensionCustom OpenAPI extension for MCP annotations
API ReferenceComplete types, interfaces, and exports
ExamplesMCP server, Zod, filtering, security, and more
ArchitectureSystem overview, data flow, design patterns

Requirements

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

Contributing

Contributions are welcome! Please see our issues page.

Related Projects

License

Apache 2.0

Ver o original no GitHub

Bom para

Relacionados