Swagger MCP Adapter

Swagger MCP Adapter

A TypeScript-based MCP server that integrates with Swagger/OpenAPI specifications to expose API endpoints as tools for Large Language Models (LLMs), enabling natural language interaction with any OpenAPI-compliant API.

Category
访问服务器

README

Swagger MCP Adapter

A TypeScript-based MCP (Model Context Protocol) server that integrates with Swagger/OpenAPI specifications to expose API endpoints as tools for Large Language Models (LLMs).

Quick Start

  1. Install dependencies:

    npm install
    
  2. Build the project:

    npm run build
    
  3. Set environment variables:

    export SWAGGER_PATH="./path/to/your/swagger.json"
    export BASE_URL="https://api.example.com"  # Optional
    
  4. Run the server with hot reloading:

    npm run dev          # Hot reload enabled
    npm run dev:verbose  # Hot reload with verbose output
    
  5. Test with inspector:

    npm run inspect      # MCP inspector with hot reload
    
  6. Run tests:

    npm run test         # Run tests once
    npm run test:watch   # Run tests in watch mode
    

Features

  • Load and parse OpenAPI/Swagger specifications from URLs or local files
  • Expose API endpoints as MCP tools for seamless LLM integration
  • Structured request/response validation with Zod schemas
  • Comprehensive error handling and logging with Pino
  • Intelligent caching system with TTL-based expiration
  • Clean markdown formatting for better readability
  • TypeScript-first development with full type safety
  • Production-ready builds with optimized bundling
  • Claude Desktop integration for easy deployment

Development

Hot Reloading

The project supports hot reloading during development:

# Start development server with hot reload
npm run dev

# Development server with verbose output (no screen clearing)
npm run dev:verbose

# MCP inspector with hot reload
npm run inspect

# Run tests in watch mode
npm run test:watch

File Watching

  • Server files: Automatically restart when src/ files change
  • Configuration: Reloads when .env file changes
  • Tests: Re-run tests when test files or source files change
  • Inspector: Hot reloads MCP server while inspector stays connected

Development Workflow

  1. Start development server:

    npm run dev
    
  2. Make changes to any .ts file in src/

  3. Server automatically restarts with your changes

  4. Test your changes using the inspector or direct API calls

Available MCP Tools

  • list_services: List all available API services with clean markdown formatting
  • get_service_information: Retrieve detailed information about a specific API service including parameters, request/response schemas, and example usage
  • get_all_service_information: Retrieve comprehensive information about all API services from a Swagger/OpenAPI specification
  • get_cache_information: Monitor cache status including cached specifications, expiration times, and performance metrics

Claude Desktop Integration

The Swagger MCP Adapter can be easily integrated with Claude Desktop for seamless API exploration:

  1. Build the project:

    npm run build
    
  2. Update Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json):

    {
      "mcpServers": {
        "Swagger MCP Adapter": {
          "command": "node",
          "args": ["/path/to/your/swagger-mcp-adapter/dist/index.js"]
        }
      }
    }
    
  3. Restart Claude Desktop to load the new MCP server

  4. Start using the tools:

    Hey Claude, can you list the services from this Swagger spec: https://petstore.swagger.io/v2/swagger.json
    
    Hey Claude, tell me about the cache status of my Swagger MCP Adapter
    
    Hey Claude, can you create all services for my React project with zod schema validation for the axios instance from this Swagger spec: https://petstore.swagger.io/v2/swagger.json
    
    Hey Claude, can you create the get_pet_findByTags service for my React project with zod schema validation for the axios instance from this Swagger spec: https://petstore.swagger.io/v2/swagger.json
    

Configuration

Variable Description Default
SWAGGER_PATH Path to OpenAPI/Swagger file ./swagger.json
BASE_URL Base URL for API calls From OpenAPI spec
TIMEOUT Request timeout in ms 30000
LOG_LEVEL Logging level info
CACHE_TTL Cache time-to-live in ms 300000 (5 min)

Cache Configuration

The MCP server includes an intelligent caching system:

  • Automatic cache invalidation based on TTL
  • Memory-efficient storage of parsed specifications
  • Concurrent access handling for multiple requests
  • Cache monitoring tools for performance insights

GitHub Copilot Instructions for Swagger MCP Adapter

Architecture & Structure

Based on best practices for TypeScript/Node.js projects, this project follows a modular structure optimized for maintainability and scalability:

my-mcp-openapi/
├─ src/
│  ├─ index.ts             # MCP server entrypoint
│  ├─ server.ts            # MCP server setup (SDK integration)
│  ├─ swagger/
│  │   ├─ loader.ts        # Load & validate swagger/openapi files
│  │   ├─ parser.ts        # Parse specifications into normalized endpoints
│  │   └─ types.ts         # TypeScript type definitions from OpenAPI
│  ├─ commands/
│  │   ├─ listServices.ts  # MCP command to list available services
│  │   └─ callService.ts   # MCP command to call a specific service
│  ├─ http/
│  │   ├─ client.ts        # HTTP client wrapper (axios/fetch)
│  │   └─ validator.ts     # Request/response validation with Zod
│  ├─ utils/
│  │   └─ logger.ts        # Structured logging utility
│  └─ config.ts            # Configuration management
├─ test/
│  ├─ swagger.mock.json    # Mock OpenAPI specification for testing
│  └─ server.test.ts       # Unit and integration tests
├─ package.json             # Project dependencies and scripts
├─ tsconfig.json            # TypeScript configuration
├─ README.md                # Project documentation

Directory Guidelines

/src - Source Code

  • Contains all TypeScript source files
  • Organized by feature/domain for better maintainability
  • Entry point is index.ts for the MCP server

/src/swagger - OpenAPI/Swagger Handling

  • loader.ts: Handles loading OpenAPI specs from files or URLs
  • parser.ts: Parses specifications into normalized data structures
  • types.ts: Generated TypeScript interfaces from OpenAPI schemas

/src/commands - MCP Commands

  • Implements MCP protocol commands as tools for LLMs
  • listServices.ts: Returns available API endpoints
  • callService.ts: Executes API calls with provided parameters

/src/http - HTTP Client & Validation

  • client.ts: Generic HTTP client for making API requests
  • validator.ts: Schema validation using Zod based on OpenAPI specs

/src/utils - Utilities

  • Shared utility functions and helpers
  • Logging, error handling, and common operations

/test - Test Files

  • Unit tests for individual modules
  • Integration tests for MCP server functionality
  • Mock data for testing without external dependencies

TypeScript Modules & Dependencies

  • Use npm for dependency management (package.json)
  • Module should use ESM ("type": "module" in package.json)
  • Keep dependencies minimal and regularly updated
  • Use npm audit and npm update for security and updates
  • Export main functionality through package.json exports field

TypeScript Development Standards

Code Style & Formatting

  • Always use eslint and prettier for code formatting and linting
  • Follow TypeScript naming conventions: camelCase for variables/functions, PascalCase for classes/interfaces
  • Use meaningful variable names; avoid abbreviations
  • Keep functions small and focused on a single responsibility
  • Prefer const over let, use let only when reassignment is necessary

Error Handling

  • Always handle errors appropriately after async operations
  • Use try/catch blocks for synchronous errors
  • Return errors as rejected Promises for async operations
  • Create custom error classes for domain-specific errors
  • Use structured logging for error details with context
// Good
try {
  const result = await service.callEndpoint(params);
  return result;
} catch (error) {
  logger.error("Failed to call endpoint", { error, params });
  throw new APIError("Service call failed", { cause: error });
}

MCP Server Setup

  • Use the official @modelcontextprotocol/sdk for MCP implementation
  • Implement proper tool definitions with schemas
  • Handle MCP protocol messages correctly
  • Support graceful shutdown with signal handlers
  • Validate all inputs according to MCP specifications

HTTP Requests & Validation

  • Use Axios or native fetch for HTTP requests
  • Implement proper timeout and retry logic
  • Validate request parameters against OpenAPI schemas using Zod
  • Handle different content types (JSON, form-data, etc.)
  • Return normalized responses to LLMs

Schema Validation & Type Safety

  • Use Zod for runtime validation of OpenAPI schemas
  • Generate TypeScript types from OpenAPI specifications
  • Validate both incoming parameters and outgoing responses
  • Provide clear error messages for validation failures

Testing

  • Write unit tests for all modules using Vitest
  • Use mock servers for integration testing
  • Test error scenarios and edge cases
  • Maintain high test coverage (>80%)
  • Run tests in CI/CD pipeline

Project-Specific Guidelines

Configuration Management

  • Use environment variables for configuration
  • Provide sensible defaults for all configuration values
  • Validate configuration on startup
  • Support multiple environments (development, staging, production)
  • Make OpenAPI source configurable (file path or URL)

API Integration

  • Support both JSON and YAML OpenAPI specifications
  • Handle authentication requirements (API keys, OAuth, etc.)
  • Implement rate limiting to prevent API abuse
  • Cache responses when appropriate to reduce load
  • Provide fallback mechanisms for API failures

Security & Validation

  • Validate all inputs to prevent injection attacks
  • Implement proper CORS handling if needed
  • Use HTTPS for all external API calls
  • Sanitize and validate OpenAPI specifications
  • Implement request/response size limits

Logging & Monitoring

  • Use structured logging with Pino for consistent log format
  • Log important events: API calls, errors, performance metrics
  • Include contextual information in logs (request IDs, user info)
  • Monitor MCP server health and performance
  • Alert on critical errors or performance degradation

Development Workflow

  1. Project Setup

    • Initialize Node.js + TypeScript project with proper tooling
    • Set up ESLint, Prettier, and Vitest for development
  2. Swagger/OpenAPI Parser

    • Implement loader for JSON/YAML specifications
    • Parse endpoints and generate TypeScript interfaces
    • Normalize service metadata for MCP exposure
  3. MCP Server Implementation

    • Set up MCP server with SDK
    • Implement listServices and callService commands
    • Handle LLM tool invocations properly
  4. Request/Response Handling

    • Create generic HTTP client with error handling
    • Implement schema validation with Zod
    • Normalize responses for LLM consumption
  5. Best Practices Implementation

    • Add configurable OpenAPI source support
    • Implement comprehensive error handling
    • Add structured logging throughout
    • Ensure strong typing across the codebase
  6. Testing Strategy

    • Write unit tests for all core functionality
    • Create contract tests with mock APIs
    • Implement end-to-end tests with mock OpenAPI specs
  7. Release Preparation

    • Configure package.json for ESM and exports
    • Set up GitHub Actions for automated publishing
    • Create comprehensive documentation

Technology Stack

  • Core: TypeScript 5.6+, Node.js (ESM)
  • MCP SDK: @modelcontextprotocol/sdk 1.17.4
  • OpenAPI/Swagger: swagger-parser 10.0.4, openapi-typescript 7.0+
  • Validation: zod 3.23+
  • HTTP Client: axios 1.7+
  • Testing: vitest 2.0+
  • Logging: pino 9.0+
  • Build: tsup 8.2+, Biome 2.2.2
  • Dev Tools: tsx 4.19+

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选