— MIT Licensed — 91+ tests passing

Turn Any OpenAPI into an MCP Server

Production-oriented library that converts OpenAPI specs into Model Context Protocol servers. Generate Tools, Prompts, and Resources. SSE and stdio transports. Admin web UI included.

$npm install @powerduck/openapi-mcp-server
Tools + Prompts + ResourcesSSE & stdioAdmin Web UIAuth MiddlewareHTTP Executor
Quick Start

Build an MCP server in minutes

import express from "express";
import { buildMcpServer, loadOpenApiSpec, attachSseRoutes } from "@powerduck/openapi-mcp-server";

// Load the OpenAPI document once (JSON or YAML)
const spec = await loadOpenApiSpec("./openapi.json");

// SpecProvider: () => Document | null
// ContextProvider: () => ExecutionContext
// BuildMcpServerOptions: { protocol?, name?, version?, pageSize?, instructions? }
const mcp = buildMcpServer(
  () => spec,                              // specProvider (required)
  () => ({                                 // contextProvider (optional)
    baseUrlOverride: "https://api.example.com/v1",
    upstreamHeaders: { "X-Service": "mcp-gateway" },
    requestTimeoutMs: 30000,
    security: { bearerToken: "upstream-token" },
    correlationId: "req-123",
    onLog: (entry) => console.log(entry.level, entry.message),
  }),
  {                                        // BuildMcpServerOptions (optional)
    name: "My API MCP Server",
    version: "1.0.0",
    pageSize: 100,                        // Max tools per list response
    instructions: "Use these tools to interact with the My API.",
  },
);

// Attach SSE routes to an Express app
const app = express();
attachSseRoutes(app, () => spec, () => ({}));
app.listen(3000, () => console.log("MCP SSE server on :3000"));
Features

Production-grade MCP infrastructure

Everything you need to expose your API to AI agents, securely and reliably.

02

Dual Transports

SSE for browser-based clients via attachSseRoutes(). stdio for local AI assistants via startStdioServer(). Both share the same tool registry.

03

Admin Web UI

Built-in dashboard via startAdminServer(). Inspect registered tools, prompts, and resources. Test tool calls directly from the browser.

04

Auth Middleware

createAuthMiddleware() for bearer token, API key, and custom auth strategies. Per-tool permission scopes with Express-compatible middleware.

05

HTTP Executor

executeToolCall() executes generated tools against the real API. buildRequest() constructs HTTP requests from operation definitions with full parameter mapping.

06

Spec Utilities

loadOpenApiSpec(), parseSpecContent(), iterateOperations(), findOperationById(), synthesizeOperationId(), and more for working with OpenAPI documents.

Transports

Two transports, one server

Choose the transport that fits your deployment model.

SSE

Server-Sent Events

HTTP-based transport for remote and browser clients. Ideal for SaaS deployments and web-based AI assistants.

  • attachSseRoutes(app) for Express
  • Event stream for server-to-client
  • POST endpoint for client-to-server
  • Health check endpoints
  • Compatible with MCP Inspector
STDIO

Standard Input/Output

Local process transport for desktop AI assistants. Perfect for Claude Desktop and other local MCP clients.

  • startStdioServer(server)
  • JSON-RPC over stdin/stdout
  • Zero network configuration
  • Works with Claude Desktop config
  • stderr for logging and diagnostics
API Reference

Complete API surface

Click any entry to expand.

functionbuildMcpServer(options)Build a complete MCP server from an OpenAPI spec
Parameter Type Description
options.specrequired object | string OpenAPI document or path to spec file
options.serverName string MCP server display name
options.toolFilter (op) => boolean Filter which operations become tools
options.specProvider SpecProvider Custom spec loading strategy
options.contextProvider ContextProvider Custom request context injection
functionloadOpenApiSpec(source)Load and parse an OpenAPI spec from file path, URL, or inline string

Supports JSON and YAML. Resolves local file paths and remote URLs. Returns a parsed OpenAPI document object.

functiongenerateTools(spec)Generate MCP Tool definitions from OpenAPI operations

Each operation becomes a tool with name, description, and inputSchema derived from parameters and request body. Also available: generateToolsDetailed() and buildBindingIndex().

functiongeneratePrompts(spec)Generate MCP Prompt definitions from OpenAPI tags

Each tag becomes a prompt template. Use resolvePrompt(name, args) to render a prompt with arguments.

functiongenerateResources(spec)Generate MCP Resource definitions from OpenAPI schemas

Schemas and examples become readable resources. Use readResource(uri) to fetch resource content.

functionexecuteToolCall(tool, args)Execute a generated tool against the real API

Builds and sends the HTTP request, returns structured MCP response content. Handles errors gracefully with MCP error format.

functionbuildRequest(operation, args)Build an HTTP request from an OpenAPI operation and arguments

Maps path params, query params, headers, and request body. Returns a normalized request descriptor.

functionattachSseRoutes(app, specProvider, contextProvider?, routeGuard?)Attach MCP SSE transport routes to an Express app
Parameter Type Description
apprequired Express Express application instance
specProviderrequired () => Document Function returning the OpenAPI document (lazy evaluation)
contextProvider () => ExecutionContext Function returning execution context (auth, headers, etc.)
routeGuard RequestHandler Optional Express middleware for route-level auth
functionstartStdioServer(spec, context?, options?)Start an MCP server over stdio transport

Reads JSON-RPC messages from stdin, writes responses to stdout. Logs go to stderr. Options: name, version, instructions. Returns a handle with close() method.

functionstartAdminServer(server, options?)Start the admin web UI for inspecting and testing MCP tools
Parameter Type Description
serverrequired McpServer Built MCP server
options.port number Admin server port default: 3001
options.authMiddleware Middleware Optional auth middleware
functioncreateAuthMiddleware(options)Create Express-compatible auth middleware
Parameter Type Description
options.bearerToken string | string[] Valid bearer token(s)
options.apiKey string | string[] Valid API key(s) via x-api-key header
options.custom (req) => boolean Custom auth function
classServiceRegistryRuntime registry for managing MCP services

Register, unregister, and look up services at runtime. Supports dynamic tool addition and removal.

3
MCP Primitives
2
Transports
1
Admin UI
MIT
License