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 "Install 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 Serversummarize 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.
| Name | Required | Description | Default |
|---|---|---|---|
| model | No | (Optional) The specific OpenRouter model ID (e.g., "google/gemini-pro") to use for this completion request. If omitted, the server's configured default model will be used. | |
| messages | Yes | (Required) An ordered array of message objects representing the conversation history. Each object must include `role` ("system", "user", or "assistant") and `content` (the text of the message). Minimum 1 message, maximum 100. | |
| provider | No | (Optional) An object allowing fine-grained control over how OpenRouter selects the underlying AI provider for this request, overriding any server-level defaults. | |
| max_tokens | No | (Optional) Sets an upper limit on the number of tokens generated in the response. Overrides the server default if specified. Influences provider routing based on model context limits. | |
| temperature | No | (Optional) Controls the randomness of the generated output. Ranges from 0.0 (deterministic) to 2.0 (highly random). Affects creativity versus coherence. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It mentions 'advanced provider routing and parameter overrides' and that it returns a 'generated text response', but does not disclose important behaviors such as authentication requirements, rate limits, what happens on failure, or whether the request is destructive. The description is adequate but not comprehensive for an unannotated tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is three sentences long, front-loaded with the primary action, and contains no filler. Every sentence adds meaningful information: action, use cases, and key features.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description mentions returning 'the generated text response' but does not specify the exact output structure (e.g., whether it's a raw string or an object with choices). With no output schema, more detail would be helpful. It covers the main purpose and parameters adequately but lacks detail on error handling or response format.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so baseline is 3. The description adds context like 'advanced provider routing and parameter overrides' which connects to the provider parameter, but does not elaborate on the semantics of individual parameters beyond what the schema already provides. The description adds marginal value over the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states that it sends conversational messages to OpenRouter.ai for completion using a specified model, explicitly listing use cases like dialogue, text generation, and instruction-following. This effectively distinguishes it from sibling tools (get_model_info, search_models, validate_model) which are about model metadata, not generating completions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description tells when to use the tool ('for dialogue, text generation, or instruction-following tasks') but does not explicitly state when not to use it or provide alternatives. Given the sibling tools are unrelated, the guidance is clear enough but lacks explicit exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| model | Yes | (Required) The unique identifier string of the OpenRouter.ai model whose details are being requested. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, but the description adequately discloses the read-only nature and the type of information returned (pricing, limits, capabilities). However, it does not discuss rate limits or authentication requirements, which are acceptable for a simple retrieval tool without annotations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two concise sentences: first states the action and resource, second provides usage guidance and output description. No wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a single-parameter read tool with no output schema, the description covers what the tool does, when to use it, and what it returns. It is complete enough for an agent to invoke correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, and the description's mention of 'unique ID' mirrors the schema description. No additional semantics are added beyond what the schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool retrieves complete metadata for a single model by ID, distinguishing it from siblings like search_models (which likely doesn't require exact ID) and chat_completion (generates completions).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly advises using the tool when the model ID is known and full details are needed, but does not mention when not to use or name alternatives directly.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | (Optional) Limits the number of matching models returned in the response. Must be between 1 and 50. Defaults to 10. | |
| query | No | (Optional) A text query string to search within model names, descriptions, and provider details. | |
| provider | No | (Optional) Restricts the search to models offered by a specific provider ID (e.g., "openai", "anthropic"). | |
| capabilities | No | (Optional) An object specifying required model capabilities. | |
| maxPromptPrice | No | (Optional) Filters for models whose price for processing 1,000 prompt tokens is less than or equal to this value. | |
| maxContextLength | No | (Optional) Filters for models that support at most the specified context window size (in tokens). | |
| minContextLength | No | (Optional) Filters for models that support at least the specified context window size (in tokens). | |
| maxCompletionPrice | No | (Optional) Filters for models whose price for generating 1,000 completion tokens is less than or equal to this value. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the burden. It describes a query operation returning metadata, which implies non-destructive behavior, but it doesn't specify authentication, rate limits, or potential side effects. Adequate but minimal behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences, front-loaded with the main action and filtering intent. Every sentence adds value with no redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, the description at least states the return type (list of metadata objects). All 8 parameters have schema descriptions, and the description covers the core use case. Lacks mention of pagination or ordering, but the limit parameter mitigates this slightly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with detailed parameter descriptions. The description adds high-level purpose ('filtering by various criteria') but does not introduce meaning beyond what the schema already provides, so baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it queries the model registry with filtering, and differentiates from siblings like chat_completion (generation) and get_model_info (single model details). The phrase 'Use this to discover models' directly indicates purpose.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly says 'Use this to discover models suitable for specific needs.' While it doesn't list when not to use or alternatives, the sibling context provides differentiation, making usage guidance clear if not exhaustive.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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).
| Name | Required | Description | Default |
|---|---|---|---|
| model | Yes | (Required) The unique identifier string of the OpenRouter.ai model to check for validity. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries full burden. It discloses that the tool returns a boolean ('true if valid, false otherwise') and the action is a read-only existence check. No contradictions or hidden behaviors.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two concise sentences with no extraneous information. The key information (verb, resource, when to use, return value) is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (one parameter, boolean return), the description is nearly complete. It lacks details on error states or network requirements, but these are minor for a simple existence check.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% for the single parameter 'model'. The description adds little beyond the schema—it restates the purpose but doesn't provide additional format or usage details. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description specifies the verb 'Verifies' and resource 'model ID exists within OpenRouter registry', clearly distinguishing from sibling tools like get_model_info (which likely returns details) and search_models (which is for searching).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides explicit usage context: 'Use this for a quick check of model ID validity before making other API calls.' This tells when to use it, though it doesn't explicitly state alternatives or when not to use.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
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
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
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
- AlicenseBqualityAmaintenanceProvides 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.1167885Apache 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
- 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.1459MIT
- AlicenseAqualityCmaintenanceProvides 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.45613MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/heltonteixeira/openrouterai'
If you have feedback or need assistance with the MCP directory API, please join our Discord server