mcp-openapi-server
v1.0.0
Published
MCP Server that exposes OpenAPI specifications as tools
Downloads
51
Maintainers
Readme
MCP OpenAPI Server
MCP Server that dynamically exposes OpenAPI specifications as tools for Claude and other AI assistants.
Features
✅ Phase 1 (MVP) - Implemented
- Parse OpenAPI 3.0+ specifications from files or URLs
- Generate MCP tools from GET operations
- API Key authentication (header & query)
- Path and query parameters support
- HTTP request execution with Axios
- Configurable timeout and base URL
- Tool filtering by tags and operations
✅ Phase 2 (Full Features) - Implemented
- All HTTP methods support (POST, PUT, PATCH, DELETE)
- Request body handling (application/json, multipart/form-data)
- Multiple authentication types:
- API Key (header & query)
- Bearer Token
- Basic Authentication
- OAuth2 (configuration support)
- Advanced execution features:
- Automatic retry with exponential backoff
- Response size limiting
- Connection pooling with keep-alive
- Configurable retry policies
- Enhanced error handling
- Strict mode for validation
- Sensitive data sanitization in logs
✅ Phase 3 (Observability) - Implemented
- Prometheus metrics (tool calls, HTTP requests, retries)
- Distributed tracing (W3C Trace Context, OTLP export)
- Health checks (Kubernetes liveness/readiness probes)
- Structured logging (module-specific levels, auto-redaction)
- Metrics HTTP server with
/metricsand/healthendpoints
✅ Phase 4 (Security) - Implemented
- Rate limiting (token bucket algorithm)
- Global, per-tool (glob patterns), and per-client limits
- Configurable burst allowance
- Input validation & sanitization
- SQL injection, XSS, and path traversal detection
- Body size limits and content-type validation
- Custom deny patterns
- Role-Based Access Control (RBAC)
- Role definitions with glob-based tool permissions
- Multi-level role inheritance
- Default role configuration
- Audit trail
- Full structured logging of all tool calls
- Access denied / rate limited event tracking
- Queryable in-memory buffer with export support
- Pluggable secrets management
- Environment variable provider (built-in)
- Caching wrapper with TTL and auto-refresh
- Extension points for Vault, AWS SM, Azure KV
✅ Phase 5 (Developer Experience) - Implemented
- Interactive CLI (
mcp-openapibinary)init— interactive config wizardvalidate— config + OpenAPI spec validationtest-connection— API connectivity checklist-tools— table/JSON output of all toolscall <tool>— test tool executiongenerate-types— TypeScript.d.tsgeneration
- Hot Reload
- File watching with debounce for config and spec files
- Graceful drain of active requests before apply
- Validation-before-apply with automatic rollback on error
- Mock Mode
- Strategy chain: fixture → recording → example → schema
- Schema-based random data generation (all JSON Schema types/formats)
- Configurable delay simulation and error rate
- Response recording & replay
- Fixture file loading with argument matching
- Documentation Generator
- Markdown export with TOC, parameter tables, usage examples
- Interactive HTML docs (Swagger UI-like)
- Diff-based changelog generation
- VS Code Support
- JSON Schema for
mcp-config.jsonintellisense - Snippets for common configurations
- JSON Schema for
- VS Code Extension (
vscode-extension/)- TextMate grammar for syntax highlighting (section keys, env vars, auth types)
- CodeLens actions (Register for Copilot, Start Server, Validate, Test Connection, List Tools, Toggle Mock Mode)
- Explorer sidebar tree view with tools grouped by tag
- Inline documentation via hover (sections, properties, env vars, strategies)
- Server management (start/stop in integrated terminal)
- GitHub Copilot integration (auto-generates
.vscode/mcp.json) - 67 tests across 6 test suites
Installation
npm install
npm run buildConfiguration
Create a configuration file (e.g., mcp-config.json):
{
"server": {
"name": "petstore-api",
"version": "1.0.0",
"description": "Petstore API MCP Server"
},
"openapi": {
"source": "./examples/petstore-spec.yaml",
"type": "file"
},
"authentication": {
"type": "apiKey",
"config": {
"location": "header",
"name": "X-API-Key",
"value": "${PETSTORE_API_KEY}"
}
},
"execution": {
"timeout": 10000,
"baseURL": "https://petstore.swagger.io/v2"
},
"filtering": {
"includeTags": ["pet"],
"excludeOperations": ["deletePet"]
}
}Configuration Options
Authentication Types
API Key Authentication
{
"authentication": {
"type": "apiKey",
"config": {
"location": "header", // or "query"
"name": "X-API-Key",
"value": "${API_KEY}"
}
}
}Bearer Token Authentication
{
"authentication": {
"type": "bearer",
"config": {
"token": "${API_TOKEN}",
"prefix": "Bearer" // optional, defaults to "Bearer"
}
}
}Basic Authentication
{
"authentication": {
"type": "basic",
"config": {
"username": "${API_USERNAME}",
"password": "${API_PASSWORD}"
}
}
}OAuth2 Configuration
{
"authentication": {
"type": "oauth2",
"config": {
"clientId": "${CLIENT_ID}",
"clientSecret": "${CLIENT_SECRET}",
"tokenUrl": "https://auth.example.com/token",
"scopes": ["read", "write"],
"grantType": "client_credentials"
}
}
}Execution Configuration
{
"execution": {
"timeout": 10000, // Request timeout in ms
"baseURL": "https://api.example.com", // Override API base URL
"maxResponseSize": 10485760, // Max response size (10MB default)
"retry": {
"maxRetries": 3, // Max retry attempts
"retryDelay": 1000, // Initial delay in ms
"retryableStatusCodes": [408, 429, 500, 502, 503, 504]
},
"keepAlive": true, // Enable HTTP keep-alive
"maxSockets": 50 // Max sockets per host
}
}Filtering Configuration
{
"filtering": {
"includeTags": ["users", "posts"], // Only include these tags
"excludeTags": ["admin"], // Exclude these tags
"includeOperations": ["getUser"], // Include specific operations
"excludeOperations": ["deleteUser"], // Exclude specific operations
"strictMode": true // Throw errors on missing operationId
}
}Security Configuration
All security features are optional and disabled by default. Add a security block to your config:
{
"security": {
"rateLimiting": {
"enabled": true,
"global": {
"requestsPerMinute": 100,
"burstSize": 20
},
"perTool": {
"create_*": { "requestsPerMinute": 10 },
"delete_*": { "requestsPerMinute": 5 }
},
"perClient": {
"requestsPerMinute": 30
}
},
"inputValidation": {
"sanitizeStrings": true,
"pathTraversalProtection": true,
"maxBodySize": 1048576,
"rejectUnknownFields": false,
"allowedContentTypes": ["application/json", "multipart/form-data"]
},
"rbac": {
"enabled": true,
"roles": {
"reader": {
"tools": ["get_*", "list_*", "find_*"]
},
"writer": {
"inherits": "reader",
"tools": ["create_*", "update_*"]
},
"admin": {
"inherits": "writer",
"tools": ["delete_*"]
}
},
"defaultRole": "reader"
},
"audit": {
"enabled": true,
"destination": "logger",
"includeRequest": false,
"includeResponse": false
},
"secrets": {
"provider": "env",
"config": { "prefix": "MCP_" },
"cacheTtl": 300
}
}
}Environment Variables
API keys and sensitive values can use environment variable substitution:
{
"authentication": {
"type": "apiKey",
"config": {
"value": "${API_KEY}"
}
}
}Set the environment variable before running:
export API_KEY=your-secret-keyUsage
Development Mode
npm run dev examples/petstore.config.jsonProduction Mode
npm start examples/petstore.config.jsonWith Claude Desktop
Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"petstore": {
"command": "node",
"args": [
"/Users/szymonwalczak/dev/mcp/dist/index.js",
"/Users/szymonwalczak/dev/mcp/examples/petstore.config.json"
],
"env": {
"PETSTORE_API_KEY": "your-api-key-here"
}
}
}
}With VSCode (GitHub Copilot)
- Create
.vscode/mcp.jsonin your workspace (this file is gitignored to protect API keys):
{
"servers": {
"openapi-petstore": {
"command": "node",
"args": [
"/absolute/path/to/mcp-openapi-server/dist/index.js",
"/absolute/path/to/mcp-openapi-server/examples/petstore.config.json"
],
"env": {
"PETSTORE_API_KEY": "your-api-key-here"
}
}
}
}Restart the MCP server:
- Open Command Palette (Cmd+Shift+P / Ctrl+Shift+P)
- Type "MCP: Restart Server"
- Select your server (e.g., "openapi-petstore")
The OpenAPI endpoints will be available as tools in GitHub Copilot Chat
Important Notes:
- Use absolute paths in the configuration
.vscode/mcp.jsonshould be in.gitignoreto prevent committing API keys- Environment variables in the config file (like
${PETSTORE_API_KEY}) are substituted when the server starts - Set
MCP_LOG_LEVEL=errorinenvto reduce log verbosity in VSCode output panel
How It Works
- Parse: Load and validate OpenAPI specification
- Convert: Generate MCP tools from operations (GET, POST, PUT, PATCH, DELETE)
- Execute: Handle tool calls by building and executing HTTP requests with retry logic
- Respond: Return results in MCP format
Example Tools Generated
GET Operation:
GET /pet/{petId} → MCP Tool: "get_pet_by_id"
Input Schema:
{
"type": "object",
"properties": {
"petId": {
"type": "integer",
"description": "ID of pet to return [PATH]"
}
},
"required": ["petId"]
}POST Operation:
POST /pet → MCP Tool: "add_pet"
Input Schema:
{
"type": "object",
"properties": {
"body": {
"type": "object",
"properties": {
"name": { "type": "string" },
"status": { "type": "string", "enum": ["available", "pending", "sold"] }
},
"required": ["name"]
}
},
"required": ["body"]
}PUT Operation:
PUT /pet → MCP Tool: "update_pet"
Input Schema:
{
"type": "object",
"properties": {
"body": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"status": { "type": "string" }
},
"required": ["id"]
}
},
"required": ["body"]
}Development
# Install dependencies
npm install
# Run in development mode
npm run dev
# Build
npm run build
# Lint
npm run lint
# Format code
npm run format
# Clean build
npm run clean
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with UI
npm run test:ui
# Generate coverage report
npm run test:coverageTesting
The project uses Vitest for testing with 697 comprehensive tests (630 core + 67 VS Code extension) and 83%+ coverage.
Test coverage includes:
Phase 1 Tests
- Config Loader: Configuration loading, validation, and environment variable substitution
- Tool Naming: Tool name generation, description formatting, parameter sanitization
- Schema Converter: OpenAPI to JSON Schema conversion, parameter handling
- Request Builder: HTTP request building, parameter validation, URL construction
- Authentication: API Key authentication in headers and query parameters
Phase 2 Tests
- Multiple Auth Types: Bearer Token, Basic Auth, OAuth2 configuration and application
- Request Bodies: JSON and multipart/form-data handling for POST/PUT/PATCH
- Retry Logic: Exponential backoff, retryable status codes, max retries
- Response Limits: Size limiting, streaming prevention, OOM protection
- Connection Pooling: HTTP/HTTPS agents with keep-alive configuration
- Error Handling: Validation errors, network errors, timeout handling
- Strict Mode: Missing operationId detection and error reporting
Phase 3 Tests (Observability)
- Metrics: Prometheus metrics collector, counter/histogram/gauge operations
- Tracing: Distributed tracing, W3C Trace Context propagation, span builder
- Health Checks: Liveness/readiness probes, background checks, degraded states
- Metrics Server: HTTP endpoints for metrics and health
Phase 4 Tests (Security)
- Rate Limiter: Token bucket algorithm, global/per-tool/per-client limits, burst, refill, reset
- Input Validator: SQL injection (7 patterns), XSS (12 patterns), path traversal (9 patterns), body size limits, custom deny patterns, deep object sanitization
- RBAC: Role definitions, glob matching, multi-level inheritance, circular dependency detection, default roles
- Audit Trail: Tool call/access denied/rate limited/server lifecycle recording, entry filtering, buffer management
- Secrets Manager: EnvSecretsProvider, InMemorySecretsProvider, CachingSecretsProvider with TTL
Phase 5 Tests (Developer Experience)
- CLI: Type generation tests
- Hot Reload: File watcher and reload manager tests
- Mock Mode: Data generator, mock generator, fixture loader, recorder tests
- Documentation Generator: Markdown, HTML, changelog generation tests
- VS Code Extension: CodeLens, hover, tree view providers, config parser, tool loader, extension lifecycle tests
Test Statistics
- Total Tests: 697 (630 core + 67 VS Code extension)
- Coverage: 83%+ across all modules
- Test Files: 27 test suites (21 core + 6 extension)
- Assertions: 1500+ assertions
Run the test suite:
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:ui # Interactive UI
npm run test:coverage # With coverage reportTests are co-located with source files (*.test.ts files next to implementation files) for easy navigation and maintenance. This approach provides:
- Better organization: Tests are right next to the code they test
- Easier navigation: No switching between
src/andtests/directories - Simpler imports: Shorter relative paths (
./module.jsinstead of../src/module.js) - Easier refactoring: Moving a module automatically moves its tests
Test files are excluded from TypeScript compilation and production builds.
Project Structure
mcp-openapi-server/
├── src/
│ ├── config/ # Configuration loading & validation
│ │ ├── loader.ts
│ │ ├── loader.test.ts
│ │ └── schema.ts # Zod schemas (including security)
│ ├── openapi/ # OpenAPI parsing
│ │ └── parser.ts
│ ├── converter/ # OpenAPI → MCP Tool conversion
│ │ ├── naming.ts
│ │ ├── schema-converter.ts
│ │ └── tool-mapper.ts
│ ├── executor/ # HTTP execution
│ │ ├── auth.ts
│ │ ├── request-builder.ts
│ │ └── http-client.ts
│ ├── observability/ # Metrics, tracing, health checks
│ │ ├── metrics.ts
│ │ ├── metrics-server.ts
│ │ ├── tracing.ts
│ │ └── health.ts
│ ├── security/ # Security layer (Phase 4)
│ │ ├── index.ts # SecurityManager orchestrator
│ │ ├── rate-limiter.ts # Token bucket rate limiting
│ │ ├── input-validator.ts # Injection & XSS protection
│ │ ├── rbac.ts # Role-based access control
│ │ ├── audit.ts # Audit trail logging
│ │ └── secrets.ts # Pluggable secrets management
│ ├── types/ # TypeScript type definitions
│ │ ├── config.types.ts
│ │ ├── security.types.ts
│ │ ├── openapi.types.ts
│ │ ├── mcp.types.ts
│ │ └── error.types.ts
│ ├── utils/ # Utilities (logger, errors)
│ ├── cli/ # Interactive CLI (init, validate, call, etc.)
│ ├── hot-reload/ # File watching & graceful reload
│ ├── mock/ # Mock mode (data gen, fixtures, recorder)
│ ├── docs-generator/ # Markdown, HTML, changelog export
│ ├── server.ts # MCP Server implementation
│ └── index.ts # Entry point
├── monitoring/ # Prometheus & Grafana configs
├── vscode-extension/ # VS Code Extension
│ ├── src/
│ │ ├── extension.ts # Extension entry point
│ │ ├── providers/ # CodeLens, TreeView, Hover
│ │ ├── utils/ # Config parser, tool loader
│ │ └── __mocks__/ # VS Code API mock for testing
│ ├── syntaxes/ # TextMate grammar
│ ├── snippets/ # Code snippets
│ ├── schemas/ # JSON validation schemas
│ └── package.json # Extension manifest
├── .wiki/ # Architecture docs & roadmap
│ ├── architecture/ # 11 architecture documents (00-10)
│ └── todo/ # Roadmap & phase tracking
└── examples/ # Example configurationsVS Code Extension
The project includes a dedicated VS Code extension (vscode-extension/) that provides rich editor support for mcp-config.json files.
Features
- Syntax Highlighting — TextMate grammar for section keys, environment variables, auth types, HTTP methods, URLs
- CodeLens Actions — Inline actions above config sections: Register for Copilot, Start Server, Validate Config, Test Connection, List Tools, Toggle Mock Mode, and info lenses for server, execution, filtering, observability, security settings
- Explorer Tree View — Sidebar panel showing config status and tools grouped by tag with method icons
- Hover Documentation — Inline docs for section keys, properties, auth types, mock strategies, environment variables
- JSON Schema Validation — Auto-validation and IntelliSense for
mcp-config.json - Snippets — Quick-insert templates for common configuration patterns
- Server Management — Start/stop MCP server from the editor via integrated terminal
- GitHub Copilot Integration — One-click generation of
.vscode/mcp.jsonwith auto-detected binary path and env vars
Using the Extension
Option 1: Development Mode (F5)
The quickest way to try the extension during development:
cd vscode-extension
npm install
npm run compileThen open the vscode-extension/ folder in VS Code and press F5 to launch an Extension Development Host with the extension loaded.
Option 2: Install as .vsix Package
Package the extension and install it locally:
cd vscode-extension
npm install
npm run compile
npx @vscode/vsce package # Creates mcp-openapi-tools-0.1.0.vsix
code --install-extension mcp-openapi-tools-0.1.0.vsixShare the .vsix file with your team — they can install it via Extensions → ⋯ → Install from VSIX… or using the CLI command above.
Option 3: Publish to VS Code Marketplace
To make the extension publicly available:
- Create a publisher account at Visual Studio Marketplace
- Generate a Personal Access Token (PAT) in Azure DevOps with Marketplace (Manage) scope
- Publish:
cd vscode-extension
npx @vscode/vsce login <your-publisher-id>
npx @vscode/vsce publishAfter publishing, users can install it directly from the VS Code Extensions panel by searching for MCP OpenAPI Tools.
Option 4: Open VSX Registry
For VSCodium, Gitpod, and other open-source editors:
cd vscode-extension
npx ovsx publish mcp-openapi-tools-0.1.0.vsix -p <your-token>Get your token from open-vsx.org.
Extension Development
cd vscode-extension
npm install # Install dependencies
npm run compile # Build the extension
npm test # Run 67 extension tests
npm run lint # Lint extension codeRoadmap
✅ Phase 1 (MVP) - Completed December 2025
- GET operations with path, query, header parameters
- API Key authentication (header & query)
- Basic error handling and logging
- OpenAPI 3.0+ parsing
- 95 tests, 85%+ coverage
✅ Phase 2 (Full Features) - Completed January 2026
- All HTTP methods: POST, PUT, PATCH, DELETE
- Multiple authentication types: Bearer, Basic, OAuth2
- Request body handling (JSON, multipart/form-data)
- Retry logic with exponential backoff
- Response size limiting (10MB default)
- Connection pooling with keep-alive
- Strict mode for validation
- 248 tests, 90%+ coverage
✅ Phase 3 (Observability) - Completed January 2026
- Prometheus metrics (tool calls, HTTP requests, retries)
- Distributed tracing (W3C Trace Context, OTLP export)
- Health checks (Kubernetes liveness/readiness probes)
- Structured logging (module-specific levels, auto-redaction)
- Metrics HTTP server with
/metricsand/healthendpoints - 352 tests, 88%+ coverage
✅ Phase 4 (Security) - Completed February 2026
- Rate limiting (token bucket: global, per-tool, per-client)
- Input validation & sanitization (SQL injection, XSS, path traversal)
- Role-Based Access Control with glob patterns and inheritance
- Full audit trail for compliance
- Pluggable secrets management (env, caching, extension points)
- 475 tests, 83%+ coverage
✅ Phase 5 (Developer Experience) - Completed February 2026
- Interactive CLI (6 commands: init, validate, tools, test, serve, docs)
- Hot Reload with file watching and debouncing
- Mock Mode (random, fixed, recorded, fixture strategies)
- Documentation Generator (Markdown & HTML export)
- VS Code support (JSON Schema, snippets)
- VS Code Extension (syntax highlighting, CodeLens, tree view, hover docs, server management, Copilot integration)
- 697 tests (630 core + 67 extension), 85%+ coverage
🔜 Phase 6 (Advanced Integration) - Planned Q3 2026
- Multi-spec aggregation
- Webhook support
- Plugin system
- Performance optimizations
See .wiki/todo/001-roadmap-overview.md for the full roadmap.
License
MIT
