OpenRouter MCP Server
The OpenRouter MCP Server provides a unified interface to interact with OpenRouter.ai's AI models through the Model Context Protocol (MCP), offering:
Model Interaction: Send messages to AI models via chat completion with customizable parameters like temperature
Model Discovery: Search and filter models by provider, capabilities (tools, vision, functions, JSON mode), context length, and pricing
Model Information: Retrieve detailed specifications for any model ID and validate IDs for recognition
Performance Optimizations: Utilizes model caching, rate limit management, and exponential backoff for retries
Structured Responses: All results follow a standardized
ToolResultformat with clear error handlingSimple Configuration: Easy setup through environment variables and MCP configuration files
Provides a type-safe interface for accessing and interacting with OpenRouter.ai's diverse model ecosystem
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@OpenRouter MCP Server summarize this article in 3 bullet points using claude-3-opus"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
OpenRouter MCP Server
A Model Context Protocol (MCP) server providing seamless integration with OpenRouter.ai's diverse model ecosystem. Access various AI models through a unified, type-safe interface with built-in caching, rate limiting, and error handling.
Features
Model Access
Direct access to all OpenRouter.ai models
Automatic model validation and capability checking
Default model configuration support
Performance Optimization
Smart model information caching (1-hour expiry)
Automatic rate limit management
Exponential backoff for failed requests
Unified Response Format
Consistent
ToolResultstructure for all responsesClear error identification with
isErrorflagStructured error messages with context
Related MCP server: OpenRouter MCP Multimodal Server
Installation
pnpm install @mcpservers/openrouteraiConfiguration
Prerequisites
Get your OpenRouter API key from OpenRouter Keys
Choose a default model (optional)
Environment Variables
OPENROUTER_API_KEY: Required. Your OpenRouter API key.OPENROUTER_DEFAULT_MODEL: Optional. The default model to use if not specified in the request (e.g.,openrouter/auto).OPENROUTER_MAX_TOKENS: Optional. Default maximum number of tokens to generate ifmax_tokensis not provided in the request.OPENROUTER_PROVIDER_QUANTIZATIONS: Optional. Comma-separated list of default quantization levels to filter by (e.g.,fp16,int8) ifprovider.quantizationsis not provided in the request. (Phase 1)OPENROUTER_PROVIDER_IGNORE: Optional. Comma-separated list of default provider names to ignore (e.g.,mistralai,openai) ifprovider.ignoreis not provided in the request. (Phase 1)OPENROUTER_PROVIDER_SORT: Optional. Default sort order for providers ("price", "throughput", or "latency"). Overridden byprovider.sortargument. (Phase 2)OPENROUTER_PROVIDER_ORDER: Optional. Default prioritized list of provider IDs (JSON array string, e.g.,'["openai/gpt-4o", "anthropic/claude-3-opus"]'). Overridden byprovider.orderargument. (Phase 2)OPENROUTER_PROVIDER_REQUIRE_PARAMETERS: Optional. Default boolean (trueorfalse) to only use providers supporting all specified request parameters. Overridden byprovider.require_parametersargument. (Phase 2)OPENROUTER_PROVIDER_DATA_COLLECTION: Optional. Default data collection policy ("allow" or "deny"). Overridden byprovider.data_collectionargument. (Phase 2)OPENROUTER_PROVIDER_ALLOW_FALLBACKS: Optional. Default boolean (trueorfalse) to control fallback behavior if preferred providers fail. Overridden byprovider.allow_fallbacksargument. (Phase 2)
# Example .env file content
OPENROUTER_API_KEY=your-api-key-here
OPENROUTER_DEFAULT_MODEL=openrouter/auto
OPENROUTER_MAX_TOKENS=1024
OPENROUTER_PROVIDER_QUANTIZATIONS=fp16,int8
OPENROUTER_PROVIDER_IGNORE=openai,anthropic
OPENROUTER_PROVIDER_SORT=price
OPENROUTER_PROVIDER_ORDER='["openai/gpt-4o", "anthropic/claude-3-opus"]'
OPENROUTER_PROVIDER_REQUIRE_PARAMETERS=true
OPENROUTER_PROVIDER_DATA_COLLECTION=deny
OPENROUTER_PROVIDER_ALLOW_FALLBACKS=falseOPENROUTER_PROVIDER_QUANTIZATIONS=fp16,int8 OPENROUTER_PROVIDER_IGNORE=openai,anthropic
### Setup
Add to your MCP settings configuration file (`cline_mcp_settings.json` or `claude_desktop_config.json`):
```json
{
"mcpServers": {
"openrouterai": {
"command": "npx",
"args": ["@mcpservers/openrouterai"],
"env": {
"OPENROUTER_API_KEY": "your-api-key-here",
"OPENROUTER_DEFAULT_MODEL": "optional-default-model",
"OPENROUTER_MAX_TOKENS": "1024",
"OPENROUTER_PROVIDER_QUANTIZATIONS": "fp16,int8",
"OPENROUTER_PROVIDER_IGNORE": "openai,anthropic"
}
}
}
}
## Response Format
All tools return responses in a standardized structure:
```typescript
interface ToolResult {
isError: boolean;
content: Array<{
type: "text";
text: string; // JSON string or error message
}>;
}Success Example:
{
"isError": false,
"content": [{
"type": "text",
"text": "{\"id\": \"gen-123\", ...}"
}]
}Error Example:
{
"isError": true,
"content": [{
"type": "text",
"text": "Error: Model validation failed - 'invalid-model' not found"
}]
}Available Tools
chat_completion
Sends a request to the OpenRouter Chat Completions API.
Input Schema:
model(string, optional): The model to use (e.g.,openai/gpt-4o,google/gemini-pro). OverridesOPENROUTER_DEFAULT_MODEL. Defaults toopenrouter/autoif neither is set.Model Suffixes: You can append
:nitroto a model ID (e.g.,openai/gpt-4o:nitro) to potentially route to faster, experimental versions if available. Append:floor(e.g.,mistralai/mistral-7b-instruct:floor) to use the cheapest available variant of a model, often useful for testing or low-cost tasks. Note: Availability of:nitroand:floorvariants depends on OpenRouter.
messages(array, required): An array of message objects conforming to the OpenAI chat completion format.temperature(number, optional): Sampling temperature. Defaults to 1.max_tokens(number, optional): Maximum number of tokens to generate in the completion. OverridesOPENROUTER_MAX_TOKENS.provider(object, optional): Provider routing configuration. Overrides correspondingOPENROUTER_PROVIDER_*environment variables.quantizations(array of strings, optional): List of quantization levels to filter by (e.g.,["fp16", "int8"]). Only models matching one of these levels will be considered. OverridesOPENROUTER_PROVIDER_QUANTIZATIONS. (Phase 1)ignore(array of strings, optional): List of provider names to exclude (e.g.,["openai", "anthropic"]). Models from these providers will not be used. OverridesOPENROUTER_PROVIDER_IGNORE. (Phase 1)sort("price" | "throughput" | "latency", optional): Sort providers by the specified criteria. OverridesOPENROUTER_PROVIDER_SORT. (Phase 2)order(array of strings, optional): A prioritized list of provider IDs (e.g.,["openai/gpt-4o", "anthropic/claude-3-opus"]). OverridesOPENROUTER_PROVIDER_ORDER. (Phase 2)require_parameters(boolean, optional): If true, only use providers that support all specified request parameters (like tools, functions, temperature). OverridesOPENROUTER_PROVIDER_REQUIRE_PARAMETERS. (Phase 2)data_collection("allow" | "deny", optional): Specify whether providers are allowed to collect data from the request. OverridesOPENROUTER_PROVIDER_DATA_COLLECTION. (Phase 2)allow_fallbacks(boolean, optional): If true (default), allows falling back to other providers if the preferred ones fail or are unavailable. If false, fails the request if preferred providers cannot be used. OverridesOPENROUTER_PROVIDER_ALLOW_FALLBACKS. (Phase 2)
Example Usage:
{
"tool": "chat_completion",
"arguments": {
"model": "anthropic/claude-3-haiku",
"messages": [
{ "role": "user", "content": "Explain the concept of quantization in AI models." }
],
"max_tokens": 500,
"provider": {
"quantizations": ["fp16"],
"ignore": ["openai"],
"sort": "price",
"order": ["anthropic/claude-3-haiku", "google/gemini-pro"],
"require_parameters": true,
"allow_fallbacks": false
}
}
}This example requests a completion from anthropic/claude-3-haiku, limits the response to 500 tokens. It specifies provider routing options: prefer fp16 quantized models, ignore openai providers, sort remaining providers by price, prioritize anthropic/claude-3-haiku then google/gemini-pro, require the chosen provider to support all request parameters (like max_tokens), and disable fallbacks (fail if the prioritized providers cannot fulfill the request).
search_models
Search and filter available models:
interface ModelSearchRequest {
query?: string;
provider?: string;
minContextLength?: number;
capabilities?: {
functions?: boolean;
vision?: boolean;
};
}
// Response: ToolResult with model list or errorget_model_info
Get detailed information about a specific model:
{
model: string; // Model identifier
}validate_model
Check if a model ID is valid:
interface ModelValidationRequest {
model: string;
}
// Response:
// Success: { isError: false, valid: true }
// Error: { isError: true, error: "Model not found" }Error Handling
The server provides structured errors with contextual information:
// Error response structure
{
isError: true,
content: [{
type: "text",
text: "Error: [Category] - Detailed message"
}]
}Common Error Categories:
Validation Error: Invalid input parametersAPI Error: OpenRouter API communication issuesRate Limit: Request throttling detectionInternal Error: Server-side processing failures
Handling Responses:
async function handleResponse(result: ToolResult) {
if (result.isError) {
const errorMessage = result.content[0].text;
if (errorMessage.startsWith('Error: Rate Limit')) {
// Handle rate limiting
}
// Other error handling
} else {
const data = JSON.parse(result.content[0].text);
// Process successful response
}
}Development
See CONTRIBUTING.md for detailed information about:
Development setup
Project structure
Feature implementation
Error handling guidelines
Tool usage examples
# Install dependencies
pnpm install
# Build project
pnpm run build
# Run tests
pnpm testChangelog
See CHANGELOG.md for recent updates including:
Unified response format implementation
Enhanced error handling system
Type-safe interface improvements
License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Available Tools
4 toolschat_completionA
Sends conversational context (messages) to OpenRouter.ai for completion using a specified model. Use this for dialogue, text generation, or instruction-following tasks. Supports advanced provider routing and parameter overrides. Returns the generated text response.
Inputs: messages (required), model, provider, max_tokens, +1 more.
get_model_infoA
Retrieves the complete metadata for a single OpenRouter.ai model specified by its unique ID. Use this when you know the model ID and need its full details (pricing, context limits, capabilities, etc.). Returns a model information object.
Inputs: model (required).
search_modelsA
Queries the OpenRouter.ai model registry, filtering by various criteria like capabilities, pricing, or provider. Use this to discover models suitable for specific needs. Returns a list of matching model metadata objects.
Inputs: limit, query, provider, capabilities, +4 more.
validate_modelA
Verifies if a given model ID exists within the OpenRouter.ai registry. Use this for a quick check of model ID validity before making other API calls. Returns a boolean value (true if valid, false otherwise).
Inputs: model (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
All four tools serve clearly distinct purposes: chat_completion generates text, get_model_info retrieves details for a specific model, search_models filters models by criteria, and validate_model checks model existence. No overlap or ambiguity.
All tool names follow a consistent verb_noun pattern (chat_completion, get_model_info, search_models, validate_model) using snake_case. This makes the API predictable and easy to use.
With 4 tools, the set is well-scoped for OpenRouter's purpose: one core action (chat), two for model discovery (get and search), and one for validation. No bloat or deficiency.
The tool set covers the essential workflows: chatting, retrieving model metadata, searching for models, and verifying model existence. No critical missing functionality for typical use.
Maintenance
Related MCP Connectors
OpenRouter for tools and data. Compare catalog providers and call them from one hosted MCP endpoint.
AI model routing on your own vendor keys: pick the best model per prompt, or route and run it.
The OpenRouter MCP server plugs OpenRouter into the AI tools you already use. Once connected, your assistant can pull live OpenRouter data (models, prices, your credits, rankings, and docs) and send quick test messages, all without leaving your editor.
Related MCP Servers
- AlicenseBqualityBmaintenanceProvides chat and image analysis capabilities through OpenRouter.ai's diverse model ecosystem, enabling both text conversations and powerful multimodal image processing with various AI models.11579 npm102Apache 2.0
- FlicenseBqualityDmaintenanceProvides access to OpenRouter.ai's diverse model ecosystem for text chat and image analysis capabilities, with support for multimodal conversations and automatic image optimization.712 npm-
- AlicenseNot gradedqualityDmaintenanceProvides seamless access to 200+ AI models through OpenRouter's unified API, featuring multi-model collaboration, vision support, intelligent benchmarking, and collective intelligence capabilities for enhanced decision-making.1,013 npm10MIT
- AlicenseAqualityBmaintenanceProvides access to 400+ AI models from OpenRouter, enabling users to chat with models like GPT-4, Claude, Gemini, and Llama, compare responses across multiple models, and retrieve model information with pricing details.487 npm14MIT