Skip to main content
Glama

MCP-DOC-MID: MCP Server for OpenAPI and Integration Generation

Enterprise-grade server for the Model Context Protocol (MCP) ecosystem in Node.js (ES Modules), specialized in learning, dereferencing ($ref), and allowing an LLM to query OpenAPI/Swagger specifications and generate production-ready code integrations.

It uses @apidevtools/swagger-parser to resolve all pointers and component schemas in memory at server startup, and exposes a catalog of 8 MCP tools designed for search, inspection, validation, and generation of HTTP clients in multiple languages (TypeScript, Python, JavaScript, cURL, C#).


📚 Detailed Documentation

For specialized guides and complete diagrams, see:


Related MCP server: mcp-swagger

🏛️ Main Features

  1. Automatic Reading and Dereferencing (swaggers/):

    • Recursive scanning of .yml, .yaml, and .json files.

    • Complete resolution of $ref references in components, parameters, and models.

  2. Code Integration Generation for LLMs:

    • generate_integration_code: Generate strongly typed snippets and clients for any endpoint.

    • Support for TypeScript (fetch/axios), JavaScript, Python (httpx/requests), cURL, and C#.

  3. Security Validation and Extraction:

    • validate_payload: Check in advance that a JSON payload meets required types and fields.

    • get_security_schemes: Extract authentication schemes (Bearer tokens, API keys, OAuth2).

  4. Dual Transport:

    • STDIO: Standard integration with Claude Desktop, Antigravity, Cursor, and MCP extensions.

    • SSE / HTTP: Express server with /sse, /messages, /metrics, /health, and /dashboard.

  5. Observability and Security:

    • Logs directed exclusively to process.stderr with Pino.

    • Prometheus metrics (prom-client) at /metrics.

    • Session Binding and protection against Session Hijacking at /messages.


🛣️ The 3-Step Integration Flow (Zero-Code)

To make integrating new APIs 100% scalable, friction-free, and without touching a single line of code, the server implements Auto-discovery and Convention-Based Loading:

flowchart LR
    A["1. Copiar Archivo\n(swaggers/mi-api.json o .yml)"] --> B["2. Auto-Discovery & Caching\n(Hash SHA-256 + Dereference)"]
    B --> C["3. Auto-Diagnóstico\n(npm run self-test)"]
    C --> D["✅ Disponible en las 8 Tools MCP\n(search_docs, get_endpoint_doc, etc.)"]

1️⃣ Step 1: Place the File in swaggers/

Simply save your .json, .yml, or .yaml file into the swaggers/ folder.

The scanner is recursive, so you can organize your files into themed subfolders as the number of APIs grows:

swaggers/
├── middleware-api.json                # API Core Middleware
├── partners/
│   ├── avasa-car-rental.json          # Swagger de Avasa
│   └── iamsa-bus.json                 # Swagger de IAMSA
├── payments/
│   └── openpay-gateway.yml            # OpenAPI de Pasarelas de Pago
└── flights/
    └── viva-booking.yaml              # OpenAPI de Reservaciones Viva

[!TIP] Automatic Identifier (specId):
The system automatically generates the specId from the file's base name:

  • avasa-car-rental.json $\rightarrow$ specId: "avasa-car-rental"

  • openpay-gateway.yml $\rightarrow$ specId: "openpay-gateway"

  • my-api.json $\rightarrow$ specId: "my-api"


2️⃣ Step 2: Verify Integrity with npm run self-test

You don't need to start MCP clients or blindly restart servers. Run in your terminal:

npm run self-test

What does this command do in < 15 ms?

  1. Detect the new file and calculate its SHA-256 hash.

  2. Automatically resolve and dereference all $ref pointers.

  3. Clean up broken or missing references so the server never crashes.

  4. Generate the high‑performance snapshot in .cache/swaggers/.

  5. Show the real‑time summary:

{
  "status": "healthy",
  "checks": {
    "swaggers": {
      "status": "pass",
      "specsCount": 4,
      "endpointsCount": 285,
      "schemasCount": 412
    }
  }
}

3️⃣ Step 3: Ready for Agents and LLMs to Consult

Immediately, the 8 MCP tools learn the new endpoints and schemas with no additional configuration:

  • Global search: search_docs({ query: "renta autos" }) will search across all swaggers at once.

  • Filtered search: search_docs({ query: "renta", specId: "avasa-car-rental" }) queries that API exclusively.

  • Code generation: generate_integration_code({ path: "/v1/cars/book", language: "typescript" }) will generate the typed client.

  • Payload validation: validate_payload({ schemaName: "CarBookingDto", payload: { ... } }) will validate against the new model.


🏆 Best Practices for Maximum Quality in the LLM

So that language models generate the best code and accurate responses when reading your new swaggers:

  1. Declare the Base URL (servers):

    servers:
      - url: https://api.vivaaerobus.com/v1
        description: Ambiente de Producción
  2. Include Examples in the Schemas (example / examples): Examples allow the generate_integration_code tool and the LLM to automatically create realistic test payloads.

  3. Use Clear Tags (tags): Grouping by tags (e.g. [ "CarRental", "Payments", "Security" ]) allows agents to quickly filter endpoint collections with search_docs({ tag: "Payments" }).

  4. Declare the Security (components.securitySchemes): Specify whether it uses bearerFormat: JWT, ApiKey, or OAuth2 so that the get_security_schemes tool exposes the required headers.


🛠️ Available MCP Tools

Tool

Description

Main Parameters

list_specs

Lists all loaded APIs with their versions, servers, and route counts.

None

search_docs

Searches endpoints, models, and descriptions by keywords.

query (req), specId (opt), tag (opt), limit (opt)

get_endpoint_doc

Gets the complete, dereferenced specification of an endpoint.

path (req), method (opt, default: GET), specId (opt)

get_schema_doc

Gets the dereferenced data/schema model.

schemaName (req), specId (opt)

generate_integration_code

Generates production‑ready client code (TS, Python, JS, cURL, C#).

path (req), method (opt), language (opt), clientType (opt)

get_security_schemes

Gets authentication schemes and the required headers.

specId (opt)

validate_payload

Validates a JSON payload against an endpoint's schema before invoking it.

schemaName (req), payload (req), specId (opt)

query_api_knowledge

Synthesizes answers to business or architectural questions about the APIs.

query (req), specId (opt)


⚙️ Environment Variables (.env)

Variable

Description

Default Value

TRANSPORT_MODE

Transport mode (stdio, sse, http)

stdio

PORT

Listening port for SSE/HTTP mode

3000

LOG_LEVEL

Log level (debug, info, warn, error)

info

MCP_API_KEY

Secret key for API authentication

default-mcp-secret-key

ENABLE_AUTH

Enable/disable authentication (true/false)

true

ALLOWED_ORIGINS

Allowed origins for CORS

*

DASHBOARD_USER

User for web dashboard access

admin

DASHBOARD_PASSWORD

Password for web dashboard access

admin

RATE_LIMIT_WINDOW_MS

Time window for Rate Limit in ms

900000 (15 min)

RATE_LIMIT_MAX

Maximum requests per window

1000

STATS_STORAGE_ENABLED

Persist statistics to disk

true

STATS_STORAGE_PATH

Persistence file path

data/stats.json

SWAGGERS_DIR

Folder for OpenAPI specifications

swaggers


🚀 Quick Start

# 1. Instalar dependencias
npm install

# 2. Autodiagnóstico en runtime (<5ms)
npm run self-test

# 3. Iniciar en modo STDIO (predeterminado)
npm start

# 4. Iniciar en modo SSE / HTTP (servidor web)
TRANSPORT_MODE=sse PORT=3000 npm start

🧪 Automated Tests and Benchmarks

The project includes a comprehensive test suite with 116 passing tests (100%) and coverage above 93% in statements:

# 1. Ejecutar suite completa de pruebas unitarias y de integración
npm test

# 2. Reporte de cobertura detallado con Vitest y V8 (>93% Stmts)
npm run test:coverage

# 3. Pruebas de carga de alta concurrencia (100 agentes concurrentes)
npm run test:load

# 4. Benchmark de latencia y throughput (<5ms)
npm run benchmark

# 5. Pipeline de integración continua (CI)
npm run test:ci

🐳 Docker Deployment

# Construir imagen Docker multi-stage
docker build -t mcp-doc-mid:latest .

# Ejecutar contenedor en modo SSE
docker run -p 3000:3000 -e TRANSPORT_MODE=sse mcp-doc-mid:latest

Available Tools

8 tools
generate_integration_codeB

Genera un snippet/cliente de código listo para producción en TypeScript, JavaScript, Python, cURL o C# para un endpoint específico.

Inputs: path (required), method, specId, language, +1 more.

get_endpoint_docB

Obtiene la documentación completa, parámetros, request body y respuestas dereferenciadas de un endpoint específico.

Inputs: path (required), method, specId.

get_schema_docA

Obtiene la definición de un modelo de datos o schema dereferenciado (propiedades, tipos, campos obligatorios y enums).

Inputs: schemaName (required), specId.

get_security_schemesA

Obtiene los esquemas de autenticación y seguridad (Bearer token, API Key, OAuth2) definidos en las especificaciones OpenAPI.

Inputs: specId.

list_specsA

Lista todas las especificaciones OpenAPI/Swagger (.yml y .json) que han sido aprendidas y dereferenciadas en memoria con sus servidores y versiones.

Inputs: no named parameters.

query_api_knowledgeB

Consulta y sintetiza el conocimiento transversal de las APIs OpenAPI aprendidas para resolver dudas de negocio o integración.

Inputs: query (required), specId.

search_docsA

Busca endpoints, operaciones, etiquetas y modelos de datos en todas las especificaciones OpenAPI aprendidas por palabras clave.

Inputs: query (required), tag, limit, specId.

validate_payloadA

Valida si un payload JSON cumple con la estructura, campos obligatorios y tipos de datos del schema OpenAPI antes de generar código.

Inputs: payload (required), schemaName (required), specId.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 8 tools

    Disambiguation4/5

    Each tool targets a distinct operation: list, search, get endpoint/schema, generate code, security, validate, and query knowledge. Some potential overlap exists between search_docs and query_api_knowledge, but descriptions clarify the difference between keyword search and synthesized cross-cutting knowledge.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case, such as list_specs, get_endpoint_doc, and generate_integration_code. There are no mixed casing styles or vague verb variations.

    Tool Count5/5

    With 8 tools, the count is well-scoped for an OpenAPI documentation assistant. Each tool covers a necessary aspect of browsing, validating, and generating code from specs without redundancy.

    Completeness5/5

    The set covers the full document consumption lifecycle: discovering specs, searching content, retrieving endpoint/schema details, understanding security, validating payloads, and generating integration code. No significant gaps are apparent for the server's stated purpose.

    Maintenance

    ActivityStale
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Exposes Swagger/OpenAPI API documentation to AI models, enabling exploration, search, and interaction with endpoints, schemas, and execution of API calls.
      14
      20 npm
      2
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to understand and interact with OpenAPI specifications, providing deep insight into API structures for faster and more accurate API integration.
      9
      16 npm
      1
      MIT