Skip to main content
Glama
README.md
# 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:**

   ```bash
   npm install
   ```

2. **Build the project:**

   ```bash
   npm run build
   ```

3. **Set environment variables:**

   ```bash
   export SWAGGER_PATH="./path/to/your/swagger.json"
   export BASE_URL="https://api.example.com"  # Optional
   ```

4. **Run the server with hot reloading:**

   ```bash
   npm run dev          # Hot reload enabled
   npm run dev:verbose  # Hot reload with verbose output
   ```

5. **Test with inspector:**

   ```bash
   npm run inspect      # MCP inspector with hot reload
   ```

6. **Run tests:**
   ```bash
   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:

```bash
# 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:**

   ```bash
   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:**

   ```bash
   npm run build
   ```

2. **Update Claude Desktop configuration** (`~/Library/Application Support/Claude/claude_desktop_config.json`):

   ```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

```typescript
// 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+

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