npm package: @longcipher/openapi-mcp
Description: Convert OpenAPI specifications to MCP (Model Context Protocol) servers
Latest version: 1.0.1

# openapi-mcp

[![npm version](https://badge.fury.io/js/%40longcipher%2Fopenapi-mcp.svg)](https://www.npmjs.com/package/@longcipher/openapi-mcp)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

Convert OpenAPI specifications to MCP (Model Context Protocol) servers. This tool automatically generates MCP tools from your OpenAPI spec, allowing AI assistants like Claude to interact with your APIs.

## Features

- 🔄 **Automatic Tool Generation** - Converts OpenAPI operations to MCP tools
- 📁 **Multiple Input Sources** - Load specs from local files or URLs
- 📋 **Format Support** - JSON, YAML, and TOML formats
- 🔧 **Flexible Configuration** - Override base URLs, add headers, set timeouts
- 🚀 **Zero Configuration** - Works out of the box with sensible defaults
- 💻 **Easy Integration** - Compatible with Claude Desktop, VS Code, and any MCP client

## Installation

### Using npm

```bash
npm install -g @longcipher/openapi-mcp
```

### Using Bun

```bash
bun add -g @longcipher/openapi-mcp
```

### From source

```bash
git clone https://github.com/longcipher/openapi-mcp.git
cd openapi-mcp
bun install
bun run build
```

## Quick Start

### Basic Usage

```bash
# From a local file
openapi-mcp ./api.yaml

# From a URL
openapi-mcp https://petstore3.swagger.io/api/v3/openapi.json

# With custom base URL
openapi-mcp ./api.yaml --base-url https://api.example.com/v2

# With authentication header
openapi-mcp ./api.yaml --header "Authorization: Bearer token123"

# With verbose logging
openapi-mcp ./api.yaml --verbose
```

### CLI Options

```
Usage: openapi-mcp [options] <source>

Convert OpenAPI specifications to MCP servers

Arguments:
  source                      OpenAPI spec file path or URL (supports JSON, YAML, TOML)

Options:
  -V, --version               output the version number
  -b, --base-url <url>        Override the base URL for API requests
  -H, --header <header...>    Add custom headers (format: 'Name: Value')
  -t, --timeout <ms>          Request timeout in milliseconds (default: "30000")
  -n, --name <name>           Server name (default: "openapi-mcp")
  -v, --verbose               Enable verbose logging
  -h, --help                  display help for command
```

## Integration with MCP Clients

### Claude Desktop

Add to your Claude Desktop configuration (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):

```json
{
  "mcpServers": {
    "petstore": {
      "command": "openapi-mcp",
      "args": [
        "https://petstore3.swagger.io/api/v3/openapi.json"
      ]
    },
    "my-api": {
      "command": "openapi-mcp",
      "args": [
        "/path/to/my-api.yaml",
        "--base-url", "https://api.myservice.com",
        "--header", "Authorization: Bearer ${API_TOKEN}"
      ],
      "env": {
        "API_TOKEN": "your-token-here"
      }
    }
  }
}
```

### VS Code with Copilot

Add to your VS Code settings or `.vscode/mcp.json`:

```json
{
  "mcp": {
    "servers": {
      "petstore": {
        "command": "openapi-mcp",
        "args": ["https://petstore3.swagger.io/api/v3/openapi.json"]
      }
    }
  }
}
```

### Using with npx

You can run without installing globally:

```json
{
  "mcpServers": {
    "my-api": {
      "command": "npx",
      "args": [
        "-y",
        "@longcipher/openapi-mcp",
        "https://example.com/api.yaml"
      ]
    }
  }
}
```

## Supported OpenAPI Features

### Operations

- All HTTP methods: GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD
- Operation IDs are converted to snake_case tool names
- Fallback to `{method}_{path}` when operationId is missing

### Parameters

- **Path parameters** - Automatically substituted in URLs
- **Query parameters** - Added as URL query string
- **Header parameters** - Added as request headers
- **Request body** - Sent as JSON or form data

### Schemas

- Primitive types (string, number, integer, boolean)
- Arrays and objects
- Enums
- Format hints (email, date-time, etc.)
- Required field validation

## Examples

### Petstore API

```bash
openapi-mcp examples/petstore.yaml
```

This exposes tools like:
- `add_pet` - Add a new pet to the store
- `find_pets_by_status` - Find pets by their status
- `get_pet_by_id` - Get a pet by its ID
- `delete_pet` - Delete a pet

### HTTPBin API

```bash
openapi-mcp examples/httpbin.json
```

This exposes tools like:
- `http_get` - Make a GET request
- `http_post` - Make a POST request
- `get_ip` - Get your IP address
- `get_uuid` - Generate a UUID

## Development

### Prerequisites

- [Bun](https://bun.sh) v1.0 or later

### Setup

```bash
# Clone the repository
git clone https://github.com/longcipher/openapi-mcp.git
cd openapi-mcp

# Install dependencies
bun install

# Build
bun run build

# Run tests
bun test

# Lint & format
bun run lint
bun run format
```

### Project Structure

```
openapi-mcp/
├── src/
│   ├── index.ts           # Main entry point
│   ├── cli.ts             # CLI implementation
│   ├── logger.ts          # Logging utilities
│   ├── errors.ts          # Error definitions
│   ├── loader/            # Spec loading module
│   │   ├── types.ts       # OpenAPI type definitions
│   │   ├── parser.ts      # Format detection & parsing
│   │   ├── file-loader.ts # Local file loading
│   │   ├── url-loader.ts  # URL loading
│   │   └── index.ts       # Module exports
│   ├── adapter/           # OpenAPI to MCP adapter
│   │   ├── types.ts       # MCP type definitions
│   │   ├── openapi-adapter.ts
│   │   └── index.ts
│   └── server/            # MCP server implementation
│       ├── mcp-server.ts
│       └── index.ts
├── tests/                 # Test files
├── examples/              # Example OpenAPI specs
└── docs/                  # Documentation
```

## How It Works

1. **Load** - Reads OpenAPI spec from file or URL
2. **Parse** - Detects format (JSON/YAML/TOML) and validates the spec
3. **Convert** - Transforms OpenAPI operations into MCP tool definitions
4. **Serve** - Starts an MCP server over STDIO transport
5. **Execute** - When a tool is called, makes the actual HTTP request

## Troubleshooting

### Common Issues

**"Tool not found" error**
- Check that the operationId matches (converted to snake_case)
- Run with `--verbose` to see available tools

**Connection timeouts**
- Increase timeout with `--timeout 60000` (60 seconds)
- Check network connectivity to the API

**Authentication errors**
- Add auth headers with `--header "Authorization: Bearer token"`
- Ensure the token is valid and not expired

**Invalid spec error**
- Ensure the spec is valid OpenAPI 3.0.x
- Check for syntax errors in YAML/JSON/TOML

### Debug Mode

Run with verbose logging to see detailed information:

```bash
openapi-mcp ./api.yaml --verbose
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

Apache License 2.0 - see [LICENSE](LICENSE) for details.