Skip to main content
Glama

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

Related MCP server: MCP-Typescribe

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+

Available Tools

4 tools
get_all_service_informationA

Get detailed information about all API services from a Swagger/OpenAPI specification including parameters, request/response schemas, and examples

ParametersJSON Schema
NameRequiredDescriptionDefault
swaggerUrlYesURL of the Swagger/OpenAPI specification to load and analyze

TDQS

A3.8/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description conveys the read-only intent through 'Get' and lists the kind of data returned (parameters, schemas, examples). However, it does not disclose whether fetching the spec may have side effects, network requirements, or error behaviors.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, well-structured sentence that front-loads the purpose and includes relevant output content details without any fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple one-parameter input and no output schema, the description provides sufficient context by stating what information is returned. It also differentiates from sibling tools, though it could mention the read-only nature or behavior when the URL is invalid.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The single parameter swaggerUrl is fully described in the schema (100% coverage). The description adds no extra detail about parameter format or constraints, aligning with the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly specifies the verb 'Get' and the resource: detailed information about all API services from a Swagger/OpenAPI spec. The inclusion of 'all' distinguishes it from the sibling tool get_service_information, and the detail level separates it from list_services.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use for retrieving comprehensive data on every service in a spec, but it does not explicitly state when to use this over get_service_information or list_services. No alternatives or exclusions are mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_cache_informationA

Get comprehensive information about the cache status including cached specifications, expiration times, and performance metrics

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description carries the full burden. It gives some behavioral context by listing the types of information returned, but it does not explicitly state that the operation is read-only, or mention any side effects, permissions, or response format. The verb 'get' implies safety, but this is not explicitly disclosed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, well-structured sentence that front-loads the main purpose ('Get comprehensive information about the cache status') and concisely lists the key areas of information. There is no unnecessary verbosity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has no output schema, so the description must convey what the tool returns. It mentions three specific categories (cached specifications, expiration times, performance metrics), which gives a reasonable understanding. However, it does not specify the return format or whether all cache entries are included, leaving some ambiguity. Overall, it is fairly complete for a zero-parameter getter.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so the description is not required to provide parameter semantics. The baseline for 0 params is 4; the schema coverage is 100% trivially, and the description does not need to compensate for missing parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: 'Get comprehensive information about the cache status' with explicit details on what it includes (cached specifications, expiration times, performance metrics). It is distinct from sibling tools (list_services, get_service_information, get_all_service_information) which all concern services, not cache.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies the tool is for retrieving cache-related information, but it does not explicitly state when to use it versus alternatives. Sibling tools are service-focused, so the distinction is implicit, but no direct guidance or exclusions are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_service_informationA

Get comprehensive information about a specific API service including parameters, request/response schemas, and example usage

ParametersJSON Schema
NameRequiredDescriptionDefault
serviceIdYesThe ID of the service to get information about
swaggerUrlYesURL of the Swagger/OpenAPI specification

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It implies a read-only operation via the verb 'Get' and indicates the type of content returned, but does not state authoritative details such as permissions required, potential side effects (though likely none), or return format specifics. This is adequate but not rich.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no unnecessary words. It efficiently communicates the core purpose and scope without repetition.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the tool's main output content but lacks usage guidance, prerequisites (e.g., needing a swaggerUrl from another source), and explicit return structure details. Given the absence of an output schema and annotations, the description is only minimally complete for an agent to confidently invoke the tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Both parameters are fully described in the input schema (100% schema description coverage), so the description adds no additional meaning beyond what the schema already provides. The mention of 'including parameters' is redundant given the schema's thorough descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states a specific verb ('Get') and resource ('comprehensive information about a specific API service'), listing the exact content (parameters, request/response schemas, example usage). This distinguishes it from siblings like list_services (lists all services) and get_cache_information (focuses on cache details).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention that this is for a single service while list_services is for all, or when get_all_service_information might be preferred. No exclusions or prerequisites are noted.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_servicesB

List all available API services from the Swagger/OpenAPI specification and prepare for caching

ParametersJSON Schema
NameRequiredDescriptionDefault
swaggerUrlYesURL of the Swagger/OpenAPI specification to load

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses the 'prepare for caching' side effect but does not explain what this entails, whether it mutates state, or what the response contains.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core action. Every word contributes meaning, with no filler or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool is simple with one well-documented parameter, but the absence of an output schema and annotations leaves gaps about return values and the caching behavior. The description is adequate for basic understanding but vague on important details.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already fully documents the only parameter (swaggerUrl) with a clear description, and the tool description adds no additional parameter semantics. The baseline of 3 applies due to high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('List all available API services') and the source ('Swagger/OpenAPI specification'), and adds a distinct caching preparation aspect. However, it does not explicitly distinguish itself from sibling tools like get_all_service_information.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies a use case (preparing for caching) but provides no explicit guidance on when to use this tool versus alternatives. There are no stated exclusions or comparisons with sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 4 tool updatesv0.1.0
    • First observedget_all_service_information
    • First observedget_cache_information
    • First observedget_service_information
    • First observedlist_services

TDQS

A3.7/5.0

Scored across 4 tools

Disambiguation3/5

There is overlap between list_services and get_all_service_information, as both return information about all services, though one is a list and the other provides detailed info. get_service_information and get_cache_information are distinct. Agents might confuse list_services with get_all_service_information when seeking details.

Naming Consistency4/5

Tool names follow a verb_noun pattern, but mix 'list' (list_services) with 'get' for the others. This is a minor deviation from a fully consistent verb set, but the pattern is still predictable and readable.

Tool Count5/5

Four tools is well-scoped for a Swagger/OpenAPI adapter, covering list, get single, get all, and cache info without unnecessary bloat. The count is within the ideal range and each tool earns its place.

Completeness5/5

The tool set covers the core operations needed for a Swagger adapter: enumerating services, retrieving details for one or all, and managing cache information. No obvious gaps exist for the stated purpose.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    An MCP server that enables LLMs to understand and work with TypeScript APIs they haven't been trained on by providing structured access to TypeScript type definitions and documentation.
    11
    46
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Automatically converts Swagger/OpenAPI specifications into MCP servers, enabling AI agents to interact with any REST API through natural language by exposing endpoints as AI-friendly tools.
    3
    -
  • A
    license
    A
    quality
    D
    maintenance
    A generic MCP server that dynamically exposes any OpenAPI-documented REST API to LLMs by auto-discovering endpoints. It provides tools for exploring API capabilities and making authenticated requests directly through natural language interfaces.
    2
    7
    MIT