mcpresso-openapi-generator

Transform OpenAPI 3.0 specifications into fully functional MCPresso servers with type-safe Zod schemas

šŸ“¦ Open Source •License: MIT •Version: 1.0.0 •Requirements: Node.js 18+, TypeScript 4.5+

šŸ”§ OpenAPI 3.0 • ⚔ Code Generation • šŸ”’ Type Safety • šŸ“ Zod Schemas • šŸš€ MCPresso Integration

Installation

Global InstallationBash
# npm
npm install -g mcpresso-openapi-generator

# yarn  
yarn global add mcpresso-openapi-generator

# pnpm
pnpm add -g mcpresso-openapi-generator

# Or run directly with npx
npx mcpresso-openapi-generator generate --help

šŸ’” Dependencies: Automatically installs mcpresso, zod, axios, and TypeScript dependencies in generated projects. Node.js 18+ required for generation and runtime.

Usage

CLI Usage

Generate a MCPresso server from an OpenAPI specification:

CLI CommandsBash
# Generate from local OpenAPI file
mcpresso-openapi-generator generate \
  --source ./api-spec.json \
  --output ./generated-server \
  --name my-api-server \
  --verbose

# Generate from remote OpenAPI URL
mcpresso-openapi-generator generate \
  --source https://api.example.com/openapi.json \
  --output ./my-server \
  --name example-api

# With custom configuration
mcpresso-openapi-generator generate \
  --source ./openapi.yaml \
  --output ./server \
  --name my-server \
  --base-url https://api.example.com \
  --auth-token ${API_TOKEN}

Programmatic Usage

Use the generator in your Node.js scripts:

generate.tsTYPESCRIPT
import { generateFromOpenAPI } from 'mcpresso-openapi-generator';

// Generate server programmatically
await generateFromOpenAPI({
  source: './api-spec.json',
  outputDir: './generated-server',
  serverName: 'my-api-server',
  baseUrl: 'https://api.example.com',
  verbose: true,
  options: {
    includeExamples: true,
    generateReadme: true,
    customTemplates: './templates'
  }
});

console.log('āœ… MCPresso server generated successfully!');

šŸŽÆ What gets generated?

  • Complete MCPresso Server: Ready-to-run server with all endpoints
  • Type-safe Schemas: Zod validation for all OpenAPI types
  • HTTP Handlers: Axios-based API client with error handling
  • Resource Structure: Organized MCPresso resources by API paths
  • Documentation: README with setup and usage instructions

Key Features

šŸ—ļø Clean Architecture

Modular, maintainable code split into focused components. Each part has a single responsibility for maximum clarity.

šŸ”’ Type Safety

Full TypeScript support with Zod schema validation. Catch errors at compile time and runtime.

šŸ“‹ OpenAPI 3.0 Support

Handles complex OpenAPI specifications including schemas, parameters, responses, and authentication.

šŸ”Œ MCPresso Integration

Generates MCP-compliant resources and methods that work seamlessly with AI agents.

šŸ“ Smart Organization

Clean file structure with separate schema and resource files for maintainable codebases.

Schema Conversion Example

"See how OpenAPI schemas are turned into type-safe Zod schemas and used to generate MCP server resources."

OpenAPI SchemaJSON
{
  "components": {
    "schemas": {
      "User": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "name": { "type": "string" },
          "email": { 
            "type": "string", 
            "format": "email" 
          },
          "age": { 
            "type": "integer", 
            "minimum": 0,
            "maximum": 120
          }
        },
        "required": ["id", "name", "email"]
      }
    }
  }
}
→
resources/usersResource.tsTYPESCRIPT
// 🚨 This file is auto-generated by mcpresso-openapi-generator
import { z } from 'zod';
import { createResource } from 'mcpresso';
import apiClient from '../apiClient'; // hypothetical HTTP client

// Zod schema generated from OpenAPI
export const User = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
  age: z.number().int().min(0).max(120).optional()
});

// MCP resource generated from OpenAPI operation
export const usersResource = createResource({
  name: 'users',
  schema: User,
  uri_template: 'users/{id}',
  methods: {
    get: {
      inputSchema: z.object({ id: z.string() }),
      handler: async ({ id }) => {
        const res = await apiClient.get(`/users/${id}`);
        return res.data;
      },
    },
  },
});

šŸŽÆ Advanced Features

  • Circular References: Handles complex schemas with lazy evaluation
  • Path Parameters: Automatic substitution in HTTP requests
  • Query Parameters: Type-safe parameter handling
  • Authentication: Support for API keys, OAuth, and custom auth
  • Error Handling: Comprehensive error mapping and recovery
  • Resource Grouping: Smart organization by API endpoints

Generated Output

The generator creates a complete, production-ready MCPresso server with this file structure:

Generated File StructureBash
generated-server/
ā”œā”€ā”€ server.js              # Main MCPresso server entry point
ā”œā”€ā”€ types.ts               # TypeScript type exports
ā”œā”€ā”€ package.json           # Dependencies and npm scripts
ā”œā”€ā”€ README.md              # Setup and usage documentation
ā”œā”€ā”€ apiClient.ts           # Configured axios HTTP client
ā”œā”€ā”€ schemas/               # Generated Zod validation schemas
│   ā”œā”€ā”€ User.ts           #   User type schema and validation
│   ā”œā”€ā”€ Product.ts        #   Product type schema and validation
│   ā”œā”€ā”€ Order.ts          #   Order type schema and validation
│   └── index.ts          #   Schema exports
└── resources/             # MCPresso resource definitions
    ā”œā”€ā”€ UserResource.ts   #   User CRUD operations
    ā”œā”€ā”€ ProductResource.ts #   Product management
    ā”œā”€ā”€ OrderResource.ts  #   Order processing
    └── index.ts          #   Resource exports

Generated Files Overview

šŸš€ server.js

Main MCPresso server that imports and configures all resources

Generated ServerJAVASCRIPT
import { createMCPServer } from 'mcpresso';
import { userResource } from './resources/UserResource.js';
import { productResource } from './resources/ProductResource.js';

const server = createMCPServer({
  name: 'my-api-server',
  resources: [userResource, productResource],
  metadata: {
    version: '1.0.0',
    description: 'Generated from OpenAPI spec'
  }
});

server.listen(3080);

šŸ“‹ Schema Files

Individual Zod schema files for each OpenAPI type definition

schemas/User.tsTYPESCRIPT
import { z } from 'zod';

export const userSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
  createdAt: z.string().datetime(),
  profile: z.object({
    bio: z.string().optional(),
    avatar: z.string().url().optional()
  }).optional()
});

export type User = z.infer<typeof userSchema>;

šŸ”Œ Resource Files

MCPresso resource definitions with HTTP handlers

resources/UserResource.tsTYPESCRIPT
import { createResource } from 'mcpresso';
import { userSchema } from '../schemas/User.js';
import apiClient from '../apiClient.js';

export const userResource = createResource({
  name: "user",
  schema: userSchema,
  uri_template: "users/{id}",
  methods: {
    list: {
      description: "Get all users",
      handler: async (args) => {
        const response = await apiClient.get('/users');
        return response.data;
      }
    },
    get: {
      description: "Get user by ID",
      handler: async ({ id }) => {
        const response = await apiClient.get(`/users/${id}`);
        return response.data;
      }
    }
  }
});

🌐 API Client

Configured axios client with authentication and error handling

apiClient.tsTYPESCRIPT
import axios from 'axios';

const apiClient = axios.create({
  baseURL: process.env.API_BASE_URL || 'http://localhost:3000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.API_TOKEN}`
  }
});

// Response interceptor for error handling
apiClient.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', error.message);
    throw new Error(`API request failed: ${error.message}`);
  }
);

export default apiClient;

āœ… Ready to Run

All generated servers are immediately runnable with npm start. Just configure your environment variables and you're ready to go!

Configuration

Environment Variables

.env ConfigurationBash
# Required for generated server
API_BASE_URL=https://api.example.com
API_TOKEN=your_api_token_here
PORT=3080

# Optional authentication
OAUTH_CLIENT_ID=your_client_id
OAUTH_CLIENT_SECRET=your_client_secret

CLI Options

  • --source: OpenAPI spec file or URL
  • --output: Output directory for generated server
  • --name: Server name for package.json
  • --base-url: API base URL for HTTP client
  • --auth-token: Default authentication token
  • --verbose: Enable detailed logging

šŸš€ Next Steps

Ready to transform your APIs? Start with npx mcpresso-openapi-generator generate --helpor check out our MCP Implementation Guide for advanced patterns.

Ready to revolutionize your AI operations?

Get early access to build and deploy production-ready AI agents with enterprise-grade security and governance