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
globfor 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 specsgenerate- Generate MCP toolslist- View generated toolsvalidate- Validate OpenAPI specs
Design Decisions:
- Uses
commanderfor 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
-
Parallel Scanning
- All files scanned in parallel
- Parse operations are independent
-
Lazy Loading
- Specs parsed on-demand
- Tools generated only when needed
-
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
-
Graceful Degradation
- Continue on individual spec failures
- Collect errors for reporting
- Never crash on bad input
-
Validation Layers
- File existence checks
- YAML parsing validation
- OpenAPI structure validation
- Schema validation
-
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
- OpenAPI 3.2+ Support
- Swagger 2.0 Conversion
- GraphQL Schema Support
- Custom Template System
- Plugin Architecture
- Hot Reload for Development
- Distributed Registry
- Versioning Support
Dependencies
Production
openapi-typescript: OpenAPI parsingyaml: YAML parsingzod: Runtime validationcommander: CLI frameworkchalk: Terminal colorsora: Progress indicatorsglob: File pattern matchingts-morph: TypeScript code generation
Development
typescript: Type systemjest: Testing frameworkts-jest: Jest TypeScript supporteslint: Lintingprettier: Code formatting
Build & Distribution
Build Process
npm run build
Output:
dist/- Compiled JavaScriptdist/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