OpenAPI2MCP is a Python tool that converts OpenAPI specifications into MCP (Model Context Protocol) servers with tools. It allows AI models to interact with APIs defined by OpenAPI specifications through the standardized MCP interface.
pip install openapi2mcpgit clone https://github.com/yourusername/openapi2mcp.git
cd openapi2mcp
pip install -e .OpenAPI2MCP provides two main commands:
serve- Start an MCP server with tools from OpenAPI specsconvert- Convert OpenAPI specs to MCP tools JSON without starting a server
openapi2mcp serve --spec-file /path/to/openapi.yaml --port 8000This will:
- Parse the OpenAPI specification from the specified file
- Extract tools from the specification
- Start an MCP server on the specified port (default: 8000)
openapi2mcp convert --spec-file /path/to/openapi.yaml --output tools.jsonThis will:
- Parse the OpenAPI specification from the specified file
- Extract tools from the specification
- Write the tools to the specified output file in MCP format
OpenAPI2MCP supports OAuth authentication for API calls. To use OAuth authentication, you need to provide credentials either through environment variables or a configuration file.
Create a .env file in your project directory with the following variables:
API_CLIENT_ID=your_client_id
API_CLIENT_SECRET=your_client_secret
API_TOKEN_URL=https://example.com/oauth/token
Or set them directly in your environment:
export API_CLIENT_ID=your_client_id
export API_CLIENT_SECRET=your_client_secret
export API_TOKEN_URL=https://example.com/oauth/tokenYou can also provide credentials through a configuration file:
# auth_config.yaml
client_id: your_client_id
client_secret: your_client_secret
token_url: https://example.com/oauth/tokenAnd load it programmatically when creating an MCP server:
import yaml
from openapi2mcp.server import MCPServer
# Load authentication configuration
with open('auth_config.yaml', 'r') as f:
auth_config = yaml.safe_load(f)
# Create MCP server with authentication
server = MCPServer(spec_files=['openapi.yaml'], auth_config=auth_config)The MCPServer class is the main entry point for creating an MCP server.
from openapi2mcp.server import MCPServer
# Create an MCP server
server = MCPServer(
spec_files=['path/to/openapi.yaml'], # List of OpenAPI specification files
auth_config=None, # Optional authentication configuration
cors_origins=["*"] # Optional CORS origins (default: ["*"])
)
# Get the FastAPI application instance
app = server.get_app()
# Run the server with uvicorn
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)The OpenAPIParser class is responsible for parsing OpenAPI specifications and extracting MCP tools.
from openapi2mcp.openapi_parser import OpenAPIParser
# Parse an OpenAPI specification
parser = OpenAPIParser(spec_dict)
# Extract MCP tools
tools = parser.extract_tools()The OAuthHandler class handles OAuth authentication for API calls.
from openapi2mcp.auth import OAuthHandler
# Create an OAuth handler
auth_handler = OAuthHandler({
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"token_url": "https://example.com/oauth/token"
})
# Get an access token
token = await auth_handler.get_access_token()
# Add authentication to request headers
headers = await auth_handler.add_auth_to_request({})The ToolExecutor class is responsible for executing MCP tools against the corresponding API endpoints.
from openapi2mcp.tool_executor import ToolExecutor
# Create a tool executor
executor = ToolExecutor(tools, auth_handler)
# Execute a tool
result = await executor.execute_tool("toolName", {"param1": "value1"})The MCP server exposes the following endpoints:
GET /mcp- Get information about the MCP serverGET /mcp/tools- Get a list of available toolsPOST /mcp/run- Run a tool and return the resultGET /mcp/sse- Server-Sent Events endpoint for streaming tool execution
GET /mcp HTTP/1.1
Host: localhost:8000Response:
{
"name": "OpenAPI2MCP Server",
"version": "0.1.0",
"supports": {
"tools": true,
"resources": false,
"prompts": false
}
}GET /mcp/tools HTTP/1.1
Host: localhost:8000Response:
{
"tools": [
{
"name": "getUsers",
"description": "Get all users",
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Maximum number of users to return"
}
}
}
},
...
]
}POST /mcp/run HTTP/1.1
Host: localhost:8000
Content-Type: application/json
{
"name": "getUsers",
"parameters": {
"limit": 10
}
}Response:
{
"result": {
"status_code": 200,
"data": {
"users": [
{ "id": 1, "name": "John Doe" },
{ "id": 2, "name": "Jane Smith" }
]
},
"headers": {
"Content-Type": "application/json"
}
}
}You can provide multiple OpenAPI specification files to create a single MCP server with tools from all specifications:
openapi2mcp serve --spec-file api1.yaml --spec-file api2.json --port 8000You can extend the basic server implementation to add custom functionality:
from openapi2mcp.server import MCPServer
class CustomMCPServer(MCPServer):
def __init__(self, spec_files, auth_config=None):
super().__init__(spec_files, auth_config)
# Add custom routes
@self.app.get("/custom")
async def custom_endpoint():
return {"message": "Custom endpoint"}
def custom_method(self):
# Custom functionality
pass
# Create a custom server
server = CustomMCPServer(["openapi.yaml"])
app = server.get_app()If you're experiencing authentication issues:
- Check that your OAuth credentials (client ID, client secret, token URL) are correct
- Ensure that the API provider has authorized your application
- Check if the token has expired (tokens are automatically refreshed, but errors can occur)
If tool execution is failing:
- Check that the API endpoint is accessible
- Verify that the parameters you're providing are valid
- Check the API's documentation for any specific requirements
If parsing of OpenAPI specifications is failing:
- Validate your OpenAPI specification using a tool like Swagger Editor
- Check for unsupported OpenAPI features or extensions
- Try simplifying the specification to isolate the issue
Contributions are welcome! Please feel free to submit a Pull Request or open an issue on GitHub.
-
Clone the repository:
git clone https://github.com/yourusername/openapi2mcp.git cd openapi2mcp -
Install development dependencies:
pip install -e ".[dev]" -
Run tests:
pytest
This project is licensed under the MIT License - see the LICENSE file for details.