anthropic-openapi
v3.13.0
Published
An MCP server for Anthropic that allows you to make API requests to an OpenAPI specification
Readme
Anthropic OpenAPI MCP Server
A powerful MCP (Model Context Protocol) server for Anthropic that enables AI models to make API requests to any OpenAPI specification. This package provides a seamless way to integrate external APIs with Anthropic's Claude models through a structured tool interface.
Features
- 🔌 OpenAPI Integration: Automatically generate tools from OpenAPI specifications
- 🛠️ Custom Tools: Create custom tools with JSON Schema validation
- 🔒 Request Approval: Implement custom approval logic for API requests
- 📝 Type Safety: Full TypeScript support with automatic type inference
- 🎯 Flexible Configuration: Include/exclude specific paths, operations, and tags
- ⚡ Easy Setup: Simple configuration and instant integration
Installation
npm install anthropic-openapiQuick Start
Basic Usage
import { OpenAPIMCPServer } from 'anthropic-openapi';
// Configure your API
const apiConfig = {
name: 'example-api',
baseUrl: 'https://api.example.com',
headers: {
'Authorization': 'Bearer your-api-key'
},
openapi: {
specification: {
// Your OpenAPI specification here
openapi: '3.0.0',
info: {
title: 'Example API',
version: '1.0.0'
},
paths: {
'/users': {
get: {
summary: 'Get users',
responses: {
'200': {
description: 'Successful response',
content: {
'application/json': {
schema: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' }
}
}
}
}
}
}
}
}
}
}
}
}
};
// Create the MCP server
const mcpServer = new OpenAPIMCPServer({
apiKey: 'your-anthropic-api-key',
apis: [apiConfig],
});
// Run a conversation with tools
const response = await mcpServer.runOnce({
model: 'claude-3-sonnet-20240229',
max_tokens: 1000,
messages: [
{
role: 'user',
content: 'Get all users from the API'
}
]
});Creating Custom Tools
import { tool } from 'anthropic-openapi';
const getUserTool = tool('getUser', {
description: 'Get a user by ID',
schema: {
type: 'object',
properties: {
userId: { type: 'integer' }
},
required: ['userId']
},
execute: async (input) => {
// Your custom logic here
const user = await fetchUser(input.userId);
return JSON.stringify(user);
}
});Configuration
APIConfig
type APIConfig = {
name: string; // Unique name for the API
baseUrl: string; // Base URL of the API
headers?: Record<string, string>; // Additional headers
openapi: OpenAPIConfig; // OpenAPI configuration
requestApproval?: (request: APIRequestInput) => Promise<boolean> | boolean; // Return false to deny request
}OpenAPIConfig
type OpenAPIConfig = {
description?: string;
specification: OpenAPIV3.Document;
include?: IncludeExcludeConfig;
exclude?: IncludeExcludeConfig;
}Include/Exclude Configuration
type IncludeExcludeConfig = {
tags?: string[];
paths?: string[];
operations?: ('get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'options')[];
}Examples
Weather API Integration
const weatherApiConfig = {
name: 'weather-api',
baseUrl: 'https://api.weatherapi.com/v1',
headers: {
'Authorization': 'Bearer your-weather-api-key'
},
openapi: {
specification: {
openapi: '3.0.0',
info: {
title: 'Weather API',
version: '1.0.0'
},
paths: {
'/current.json': {
get: {
summary: 'Get current weather',
parameters: [
{
name: 'q',
in: 'query',
required: true,
schema: { type: 'string' }
}
],
responses: {
'200': {
description: 'Weather data',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
location: { type: 'object' },
current: { type: 'object' }
}
}
}
}
}
}
}
}
}
},
include: {
operations: ['get'] // Only allow GET requests
}
},
requestApproval: async (request) => {
// Only allow weather queries for specific cities
const city = request.parameters.find(p => p.name === 'q')?.value;
const allowedCities = ['New York', 'London', 'Tokyo'];
return allowedCities.includes(city);
}
};Custom Tool with Validation
const calculateTool = tool('calculate', {
description: 'Perform mathematical calculations',
schema: {
type: 'object',
properties: {
operation: {
type: 'string',
enum: ['add', 'subtract', 'multiply', 'divide']
},
a: { type: 'number' },
b: { type: 'number' }
},
required: ['operation', 'a', 'b']
},
validate: true, // Enable JSON Schema validation
execute: async (input) => {
const { operation, a, b } = input;
switch (operation) {
case 'add': return (a + b).toString();
case 'subtract': return (a - b).toString();
case 'multiply': return (a * b).toString();
case 'divide':
if (b === 0) throw new Error('Division by zero');
return (a / b).toString();
default: throw new Error('Invalid operation');
}
}
});API Reference
OpenAPIMCPServer
The main class for creating an MCP server.
Constructor
new OpenAPIMCPServer(config: OpenAPIMCPServerConfig)Methods
tools(): Returns all available toolsrunOnce(input): Executes a single conversation turn with tools
Tool
A class for creating custom tools.
Constructor
new Tool<T extends JSONSchema>(name: string, config: ToolConfig<T>)Methods
toAnthropicTool(): Converts the tool to Anthropic's tool formatexecute(input): Executes the tool with the given input
Helper Functions
tool(name, config): Factory function for creating tools
TypeScript Support
This package is written in TypeScript and provides full type safety. All types are exported and can be imported:
import type {
OpenAPIMCPServerConfig,
APIConfig,
ToolConfig,
APIRequestInput
} from 'anthropic-openapi';