Skip to main content
Glama
aaker
by aaker
README.md
# OpenAPI MCP Server (JavaScript)

A pure JavaScript implementation of a Model Context Protocol (MCP) server that transforms OpenAPI 3.x specifications into MCP tools, enabling Large Language Models (LLMs) to interact with REST APIs through the standardized MCP protocol.

## Features

- **Pure JavaScript**: Built with Node.js and ES modules
- **OpenAPI 3.x Support**: Automatically converts OpenAPI specifications into MCP tools
- **Bearer Token Authentication**: Supports bearer token authentication for API requests
- **All HTTP Methods**: Supports GET, POST, PUT, DELETE, PATCH, OPTIONS, and HEAD
- **Configurable Base URL**: Accept custom API base URLs
- **Parameter Validation**: Validates tool parameters against OpenAPI schemas
- **Error Handling**: Comprehensive error handling and reporting
- **CLI Interface**: Easy-to-use command-line interface

## Installation

```bash
npm install
```

## Usage

### Quick Start

1. **Validate your OpenAPI specification:**
```bash
node src/index.js validate -s UserQueueList.json
```

2. **Start the MCP server:**
```bash
node src/index.js serve -s UserQueueList.json -b https://api.example.com -t your-bearer-token
```

### Command Line Options

#### `serve` - Start the MCP server
```bash
node src/index.js serve [options]

Options:
  -s, --spec <path>       Path to OpenAPI specification file (required)
  -b, --base-url <url>    Base URL for API requests
  -t, --token <token>     Bearer token for authentication
  --timeout <ms>          Request timeout in milliseconds (default: 30000)
  --transport <type>      Transport type (stdio or http, default: stdio)
  --http-port <port>      HTTP server port (when using http transport, default: 3000)
  --http-host <host>      HTTP server host (when using http transport, default: localhost)
```

#### `validate` - Validate OpenAPI specification
```bash
node src/index.js validate -s <path-to-spec>
```

#### `info` - Show server information
```bash
node src/index.js info
```

### Environment Variables

You can use environment variables instead of command-line arguments:

```bash
export OPENAPI_BASE_URL=https://api.example.com
export OPENAPI_BEARER_TOKEN=your-bearer-token
node src/index.js serve -s UserQueueList.json

node src/index.js serve -s UserQueueList.json --transport=http --http-port=8020

```

## Configuration

### OpenAPI Specification Requirements

- Must be OpenAPI 3.x format
- JSON format (`.json` extension)
- Must contain at least one path/operation
- Bearer token authentication should be defined in security schemes

### Example OpenAPI Security Configuration

```json
{
  "components": {
    "securitySchemes": {
      "bearer": {
        "type": "http",
        "scheme": "bearer"
      }
    }
  },
  "security": [
    {
      "bearer": []
    }
  ]
}
```

## Tool Generation

The server automatically converts OpenAPI operations into MCP tools:

### Tool Naming
1. Uses `operationId` if available
2. Falls back to operation `summary` (sanitized)
3. Last resort: `{method}_{path}` (sanitized)

### Parameter Mapping
- **Path parameters**: Required string parameters
- **Query parameters**: Optional parameters based on OpenAPI schema
- **Header parameters**: Prefixed with `header_`
- **Request body**: Object properties or `requestBody` parameter

### Example Tool
For the UserQueueList.json specification:

```javascript
// Tool: ListUsers (GET /domains/~/users/list)
{
  "name": "ListUsers",
  "description": "List Basic Info on Users in Domain",
  "inputSchema": {
    "type": "object",
    "properties": {},
    "required": []
  }
}

// Tool: ListCallqueues (GET /domains/~/callqueues/list)
{
  "name": "ListCallqueues", 
  "description": "Read Basic info on Call Queues in Domain",
  "inputSchema": {
    "type": "object",
    "properties": {},
    "required": []
  }
}
```

## MCP Integration

### Using with Claude Desktop

#### Stdio Transport (Default)
Add to your Claude Desktop configuration (`~/Library/Application Support/Claude/claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "openapi-server": {
      "command": "node",
      "args": [
        "/path/to/your/project/src/index.js",
        "serve",
        "-s", "/path/to/UserQueueList.json",
        "-b", "https://your-api-domain.com",
        "-t", "your-bearer-token"
      ]
    }
  }
}
```

#### HTTP Transport
For HTTP transport, configure the server URL instead:

```json
{
  "mcpServers": {
    "openapi-server": {
      "url": "http://localhost:3000/message"
    }
  }
}
```

Then start the server separately:
```bash
node src/index.js serve -s UserQueueList.json --transport http --http-port 3000
```

### Tool Responses

The server returns structured JSON responses:

**Success Response:**
```json
{
  "status": 200,
  "statusText": "OK",
  "data": {
    // API response data
  }
}
```

**Error Response:**
```json
{
  "error": true,
  "status": 404,
  "statusText": "Not Found",
  "message": "Domain not found",
  "data": {
    "code": 404,
    "message": "Domain example does not exist"
  }
}
```

## Transport Protocols

### Stdio Transport
- **Default transport method**
- Uses standard input/output streams for communication
- Best for integration with Claude Desktop and other MCP clients
- Automatic process management

### HTTP Transport  
- Uses HTTP Server-Sent Events (SSE) for communication
- Allows remote connections and debugging
- Useful for development and testing
- Configurable host and port

## API Examples

Based on the UserQueueList.json specification:

### List Users
```javascript
// Tool call
{
  "name": "ListUsers",
  "arguments": {}
}

// Response: Array of user objects with basic information
```

### List Call Queues
```javascript
// Tool call  
{
  "name": "ListCallqueues",
  "arguments": {}
}

// Response: Array of call queue objects with configuration
```

## Development

### Project Structure
```
src/
├── index.js              # CLI entry point
├── server.js             # MCP server implementation
├── openapi-processor.js  # OpenAPI specification processor
├── http-client.js        # HTTP client for API requests
└── utils.js              # Utility functions
```

### Key Components

- **MCPServer**: Main MCP server class handling tool registration and execution
- **OpenAPIProcessor**: Parses OpenAPI specs and generates tool definitions
- **HttpClient**: Handles HTTP requests with authentication and error handling
- **CLI**: Command-line interface with validation and configuration options

## Error Handling

The server provides comprehensive error handling:

- **Validation Errors**: Parameter validation against OpenAPI schemas
- **HTTP Errors**: Proper handling of API error responses
- **Authentication Errors**: Clear messages for auth failures
- **Network Errors**: Timeout and connectivity error handling

## Security Considerations

- Bearer tokens are handled securely and not logged
- Request validation prevents injection attacks
- Error messages don't expose sensitive information
- HTTPS is recommended for all API communications

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

MIT License - see LICENSE file for details

## Troubleshooting

### Common Issues

1. **"Tool not found" errors**: Check that your OpenAPI spec is valid and contains the expected operations
2. **Authentication failures**: Verify your bearer token is correct and has proper permissions  
3. **Network timeouts**: Increase timeout or check API endpoint availability
4. **Schema validation errors**: Ensure your OpenAPI spec follows 3.x standards

### Debug Mode

For detailed logging, you can modify the server to enable debug output:

```bash
# The server logs to stderr for MCP compatibility
node src/index.js serve -s UserQueueList.json -b https://api.example.com -t token 2>debug.log
```

### Validation

Always validate your OpenAPI specification before use:

```bash
node src/index.js validate -s UserQueueList.json
```

This will show:
- ✅ Validation status
- 📄 Specification details  
- 🔧 Available tools
- 🔐 Security schemes
- 🌐 Base URL information