Skip to main content

ARCHITECTURE

Architecture

MCP Generator architecture and design decisions.

Overview

┌─────────────────────────────────────────────────────────┐
│                     MCP Generator                        │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  ┌──────────┐   ┌───────────┐   ┌──────────┐          │
│  │ Scanner  │──>│ Generator │──>│ Registry │          │
│  └──────────┘   └───────────┘   └──────────┘          │
│       │              │                │                 │
│       │              │                │                 │
│       v              v                v                 │
│  Find Specs    Convert Ops    Build Registry          │
│  Parse YAML    Create Tools   Export TS/JSON          │
│  Validate      Gen Schemas    Statistics               │
│                                                          │
└─────────────────────────────────────────────────────────┘
                          │
                          v
                  ┌──────────────┐
                  │  Generated   │
                  │  MCP Tools   │
                  └──────────────┘

Components

1. Scanner ([object Object])

Responsibility: Find and parse OpenAPI specifications

Key Features:

  • Recursive directory scanning
  • Pattern matching (glob)
  • YAML parsing and validation
  • Service name extraction
  • Operation counting

Flow:

Directory Path
    ↓
Find Files (glob patterns)
    ↓
Read YAML Files
    ↓
Parse OpenAPI Spec
    ↓
Validate Structure
    ↓
Extract Metadata
    ↓
Return ParsedOpenAPISpec[]

Design Decisions:

  • Uses glob for efficient file discovery
  • Validates OpenAPI structure before parsing
  • Extracts service name from spec title or directory
  • Handles errors gracefully (continues on parse failures)

2. Generator ([object Object])

Responsibility: Convert OpenAPI operations to MCP tool definitions

Key Features:

  • Operation → Tool mapping
  • Input schema generation
  • Handler function generation
  • Authentication extraction
  • Metadata creation

Flow:

OpenAPI Operation
    ↓
Extract Operation ID
    ↓
Generate Tool Name (service_operationId)
    ↓
Build Input Schema
  ├─ Path parameters
  ├─ Query parameters
  ├─ Headers
  └─ Request body
    ↓
Generate Handler Template
    ↓
Extract Metadata
    ↓
Return MCPToolDefinition

Design Decisions:

  • Tool names: {serviceName}_{operationId} (globally unique)
  • Input schema combines all parameter types
  • Handlers are templates (can be customized via inheritance)
  • Metadata includes all operational context

3. Registry ([object Object])

Responsibility: Organize tools and export in multiple formats

Key Features:

  • Service-based organization
  • Multiple export formats (TS, JSON)
  • Individual service modules
  • Statistics and querying

Flow:

ParsedOpenAPISpec[]
    ↓
For each spec:
  Generate Tools
  Create ServiceTools
  Add to Registry
    ↓
Export TypeScript
  ├─ registry.ts (all tools)
  └─ services/*.ts (per-service)
    ↓
Export JSON
  └─ registry.json
    ↓
Return Statistics

Design Decisions:

  • Services are first-class organization unit
  • TypeScript exports include types and runtime handlers
  • JSON exports for runtime/dynamic use
  • Statistics for monitoring and debugging

4. CLI ([object Object])

Responsibility: Command-line interface

Commands:

  • scan - Find OpenAPI specs
  • generate - Generate MCP tools
  • list - View generated tools
  • validate - Validate OpenAPI specs

Design Decisions:

  • Uses commander for CLI framework
  • Interactive spinners (ora) for feedback
  • Colorized output (chalk) for readability
  • Structured error handling

Data Flow

Complete Generation Flow

User Command
    ↓
CLI Parse Arguments
    ↓
Scanner: Find Specs
    ↓
Generator: Create Tools
    ↓
Registry: Organize & Export
    ↓
Files Written
    ↓
Statistics Displayed

Type Flow

OpenAPI 3.1 Spec (YAML)
    ↓
ParsedOpenAPISpec (runtime)
    ↓
OpenAPIOperation[] (extracted)
    ↓
MCPToolDefinition[] (generated)
    ↓
MCPServiceTools (organized)
    ↓
MCPToolRegistry (complete)
    ↓
TypeScript/JSON Files (exported)

Type System

Core Types

// Input: Parsed OpenAPI spec ParsedOpenAPISpec { filePath: string spec: OpenAPI3 serviceName: string version: string } // Output: MCP Tool MCPToolDefinition { name: string description: string inputSchema: JSONSchema handler: (args) => Promise<result> metadata: MCPToolMetadata } // Organization: Service Tools MCPServiceTools { serviceName: string version: string baseUrl: string tools: MCPToolDefinition[] sourceSpec: string } // Complete: Registry MCPToolRegistry { version: string generated: ISO8601 services: Record<serviceName, MCPServiceTools> }

Extension Points

1. Custom Scanner

class CustomScanner extends OpenAPIScanner { // Override service name extraction protected extractServiceName(path, spec): string { // Custom logic } }

2. Custom Generator

class CustomGenerator extends MCPToolGenerator { // Override handler generation protected generateHandler(...): Handler { return async (args) => { // Custom HTTP client // Custom error handling // Custom auth }; } }

3. Custom Registry

class CustomRegistry extends MCPRegistryBuilder { // Override export format async exportCustomFormat(path: string) { // Custom format logic } }

Performance

Optimization Strategies

  1. Parallel Scanning

    • All files scanned in parallel
    • Parse operations are independent
  2. Lazy Loading

    • Specs parsed on-demand
    • Tools generated only when needed
  3. Caching

    • Parsed specs cached in memory
    • Registry built incrementally

Scalability

  • Small Projects (<10 specs): < 1 second
  • Medium Projects (10-50 specs): 1-5 seconds
  • Large Projects (50-200 specs): 5-20 seconds

Memory usage: ~5-10MB per 100 operations

Error Handling

Strategy

  1. Graceful Degradation

    • Continue on individual spec failures
    • Collect errors for reporting
    • Never crash on bad input
  2. Validation Layers

    • File existence checks
    • YAML parsing validation
    • OpenAPI structure validation
    • Schema validation
  3. Error Context

    • File path included
    • Line numbers when available
    • Actionable error messages

Error Types

// Parse errors { file: string error: string context?: { line, column } } // Validation errors { spec: string field: string expected: string received: string } // Generation errors { operation: string reason: string suggestion?: string }

Testing Strategy

Unit Tests

  • Scanner: Parse correctness, error handling
  • Generator: Schema generation, handler templates
  • Registry: Organization, export formats

Integration Tests

  • End-to-end generation
  • Multiple specs
  • Error scenarios

Coverage Goals

  • Lines: 80%+
  • Branches: 80%+
  • Functions: 80%+

Security Considerations

Input Validation

  • YAML bomb protection (size limits)
  • Path traversal prevention
  • Schema validation
  • Safe file operations

Output Safety

  • No code execution in generated handlers
  • Template injection prevention
  • File permission checks

Authentication

  • API keys in environment variables
  • Never hardcode credentials
  • Support for token rotation

Future Enhancements

  1. OpenAPI 3.2+ Support
  2. Swagger 2.0 Conversion
  3. GraphQL Schema Support
  4. Custom Template System
  5. Plugin Architecture
  6. Hot Reload for Development
  7. Distributed Registry
  8. Versioning Support

Dependencies

Production

  • openapi-typescript: OpenAPI parsing
  • yaml: YAML parsing
  • zod: Runtime validation
  • commander: CLI framework
  • chalk: Terminal colors
  • ora: Progress indicators
  • glob: File pattern matching
  • ts-morph: TypeScript code generation

Development

  • typescript: Type system
  • jest: Testing framework
  • ts-jest: Jest TypeScript support
  • eslint: Linting
  • prettier: Code formatting

Build & Distribution

Build Process

npm run build

Output:

  • dist/ - Compiled JavaScript
  • dist/types/ - TypeScript declarations

Package Distribution

npm publish

Publishes to npm registry as @bluefly/mcp-generator

Installation

npm install @bluefly/mcp-generator

Or global:

npm install -g @bluefly/mcp-generator

License

MIT