OpenRouter MCP Server
Integrates with Google Cloud's Gemini models via OpenRouter for multimodal and chat-based AI interactions.
Enables use of OpenAI's models (e.g., GPT) through OpenRouter's unified API for text generation and completions.
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 Serverchat with claude-sonnet: write a haiku about space"
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
An unofficial, production-ready Model Context Protocol (MCP) server that acts as an intelligent, agentic gateway to OpenRouter's 200+ AI models. Built for advanced multi-repo development workflows.
Now fully modularized and config-driven for maximum flexibility.
๐๏ธ Architecture
The server follows a Domain-Specific Modular Architecture:
Server Core: Lightweight orchestrator in
src/index.ts.Domain Orchestrator: Namespace capability loader in
src/domains/index.ts(Gateway, Intelligence, Diagnostics).Domain Tool Modules: Specialized toolsets in
src/tools/(Chat, Models, Context, Code, etc.).Native MCP Primitives: Standard MCP Resources (
src/resources/) and Prompts (src/prompts/).Shared Helpers: Centralized infrastructure in
src/helpers/(Rate limiting, Pricing, Embeddings, Firewall).
Related MCP server: Multi-LLM Gateway MCP
โ๏ธ Configuration & Profiles
Tool Toggling
You can enable or disable any tool without changing code via tools.config.json in the root directory.
Profiles
Profiles allow you to quickly switch between different toolsets for different workflows.
Antigravity Profile: Optimized for use with the Antigravity agent, disabling redundant internal tools.
Usage: Pass the
--profileargument to the server.
CLI Arguments
Argument | Description | Example |
| Load a specific JSON profile from the |
|
Installation & Setup
1. Install & Build
npm install
npm run build2. Configure API Key
Create .env in the project root:
OPENROUTER_API_KEY=sk-or-...The server also checks ~/.config/openrouter-mcp/.env as a user-level override. Set OPENROUTER_MCP_ENV_PATH to point to an alternative location if needed.
In Docker, inject the variable directly via -e OPENROUTER_API_KEY=... or compose environment: โ no .env file required inside the container.
3. Register with your MCP Client
In your mcp_config.json:
{
"mcpServers": {
"openrouter": {
"command": "node",
"args": ["/absolute/path/to/openrouter-mcp/build/index.js", "--profile", "antigravity"]
}
}
}Security & Cost Control
NOTICE TO USERS: Defense-in-Depth Budgeting
The Universal MCP for OpenRouter provides powerful application-level budget controls (via the set_budget tool) and automatic circuit breakers. However, you should treat these tools as just one line of defense specifically tailored for application development and dynamic agentic workflows.
You must ALWAYS implement infrastructure-level limits directly through OpenRouter.
If your IDE crashes, an agent enters an infinite loop that bypasses the MCP, or your API key is somehow exposed, the MCP's circuit breakers cannot protect you. To ensure true financial safety, follow these OpenRouter best practices:
Use Unique Keys: Generate a unique OpenRouter API key specifically for this MCP server. Do not reuse a master key.
Set Hard Key Limits: In your OpenRouter Dashboard (Settings -> Keys), apply a strict USD spending limit to this specific key.
Set Reset Frequencies: Configure the key to reset daily or weekly rather than leaving it uncapped.
Base Account Limits: Ensure your base OpenRouter account has a global maximum spending limit configured.
Use OpenRouter's native limits to protect your wallet, and use the Universal MCP's budget tools to manage your agent's behavior.
๐ก๏ธ Secret Redaction & Prompt Injection Firewall
The server includes a built-in, local Security Firewall in src/helpers/rate-guard.ts (sanitizeInputPrompt) that automatically intercepts prompts and embeddings payloads to:
Redact API Keys & Credentials:
OpenRouter API keys (
sk-or-v1-...)OpenAI API keys (
sk-proj-...)Anthropic API keys (
sk-ant-api...)GitHub Personal Access Tokens (
ghp_...andgithub_pat_...)AWS Access Key IDs (
AKIA...)Google Cloud / OAuth Tokens (
ya29....)Multi-line SSH & PEM private key blocks (
-----BEGIN ... KEY-----)
Sanitize Prompt Injection Delimiters: Strips or replaces context poisoning markers (
<|im_start|>system,[SYSTEM_INSTRUCTION_OVERRIDE]) to prevent external prompt injection exploits.
This prevents accidental exposure of credentials to external network suppliers and protects against context poisoning. If you explicitly need to transmit raw credentials for testing or key rotation workflows, set DISABLE_REDACTION=true.
Usage Guide
Basic & Smart Chat Completions
# Direct Model completions (custom or auto)
chat_completion(prompt: "Explain how JWT refresh tokens work", model: "anthropic/claude-sonnet-4.6")
# Thin preset completion (smart, cheap, fast, coder, creative)
chat_with_preset(preset: "fast", prompt: "Summarize this in 3 bullets: ...")
# Intelligent dynamic routing (evaluates budget constraints and circuit breakers)
chat_routed(prompt: "Write a high-performance HTTP gateway", strictness: "quality")
# Parallel Multi-Model Consensus Peer Review (polls up to 5 models concurrently)
chat_ensemble(
models: ["deepseek/deepseek-chat", "anthropic/claude-sonnet-4.6", "google/gemini-3.1-pro-preview"],
prompt: "Auditing constant-time cryptographic checks for timing attacks"
)Budget Safety (set this first)
set_budget(max_dollars: 5.00, warn_at_percent: 75)
get_budget_status()The budget cap is enforced before each API call fires. Configuration survives server restarts (rate_config.json). Circuit breakers open automatically after failures, parsing HTTP Retry-After response headers (on 429 rate limits) or applying adaptive exponential backoff (5s โ 10s โ 20s โ 40s โ 60s max) so healthy models recover as soon as rate limits clear.
Semantic Code Search (incremental background watch indexing)
# Step 1 โ index the project (spins up background watchers with automatic build/cache directory pruning)
index_project(project_path: "/path/to/repo", project_name: "my-api")
# Step 2 โ embed code chunks (uses MD5 checks to execute cost-free incremental reindexing)
reindex_project(project_name: "my-api")
# Step 3 โ semantic search
semantic_code_search(query: "where do we handle auth token expiry")Semantic Memory
# Pin an architectural decision
pin_context(
text: "We use JWT with 15-min access tokens and 7-day refresh tokens.",
tag: "decision",
project: "auth-service"
)
# Retrieve relevant context later
retrieve_context(query: "how does authentication work", top_k: 3)Deep Transitive Auditing & Diagnostics
# Parse lockfiles in sub-milliseconds and trace co-existing semver conflicts
dependency_graph(transitive: true, check_conflicts: true)
# Trace targeted deep dependency paths leading to a specific package
dependency_graph(transitive: true, focus_package: "lodash", max_depth: 5)
# Multi-service log correlation and cascading fault root-cause analysis
correlate_errors(logs: [
{ system_name: "API Gateway", content: "ERROR: Connection timeout after 30s" },
{ system_name: "Database Server", content: "WARN: Connection pool exhausted (100/100)" }
])๐ Native MCP Resources (openrouter://...)
Passive read-only state endpoints exposed directly as standard MCP Resources:
openrouter://modelsโ Cached model catalog, context limits, and token pricing rates.openrouter://budget/statusโ Real-time spend metrics, budget caps, and circuit breaker status.openrouter://account/balanceโ Credit balance and API key details.openrouter://memory/allโ Pinned semantic context notes and workspace memory.
๐ Native MCP Prompts (list_prompts / get_prompt)
Structured system prompt templates discoverable via the MCP prompts capability:
cost-aware-orchestrationโ Teaches agents budget-safe model selection and credit checks.multi-model-consensusโ Configures parallel peer review workflows.autonomous-budget-safetyโ Financial circuit breaker policy for autonomous loops.distributed-diagnosticsโ Multi-service log correlation and trace isolation.workspace-memory-pinningโ Workspace memory and architectural decision pinning.
๐ Agent System Prompt Addendums
To help your agentic coding assistants (like Claude Code, OpenClaw, or Hermes) make the best use of this MCP server, we have provided structured system prompt templates in the templates/system-prompt-addendums/ directory:
Cost-Aware & Budget-Safe Orchestration: Teaches the agent to route simple queries to cheap models and complex queries to premium models while tracking spending.
Image & Vision Analysis Fallback: Guides text-based or terminal-based clients on how to use our
vision_analyzetool to "see" image assets.Prompt Optimization & Fallback Routing: Keeps major refactoring tasks cost-efficient and outage-resistant.
Multi-Service Log Correlation: Instructs the agent to isolate log ingestion to debug system failures quietly.
Autonomous Loop Safety Policy: A strict financial circuit breaker for autonomous background execution loops.
Workspace Memory & Long-Term Pinning: Solves conversation amnesia by persistently caching architectural and domain constraints.
High-Throughput Batch Operations: Orchestrates multi-file conversions and template updates with cost-effective models.
CI/CD & Build Pipeline Diagnostics: Automates container crash diagnostics and patch validation to resolve build failures.
Monorepo Dependency & Semver Syncing: Performs pre-commit audits to keep package dependencies fully aligned across microservices.
Enterprise Privacy & Sensitive Data Guardrails: Redacts and mocks credentials or proprietary algorithms to prevent sensitive data leaks.
Multi-Model Peer Review & Consensus: Emulates a double-model consensus flow to audit mission-critical code for exploits and concurrency bugs.
Context Window Garbage Collection: Minimizes token pricing and eliminates hallucinations by periodically purging active context bloat.
OpenClaw CLI Loop-Stall & Log Pruning: Formulates terminal hygiene policies to prevent compilation locks and strip noise from test results.
Structured Planning & JSON Chaining: Instructs Hermes-type JSON function call engines to compress reasoning steps and accelerate tool parallel execution.
Diagnostic Self-Healing & Pre-Flight Integration: Mandates early setup diagnostic checks and reactive troubleshooting to handle budget or runtime failures gracefully.
High-Context Codebase Navigation & Model Slicing: Dynamically estimates file token sizes to query and select the most budget-efficient high-context models.
Real-Time Semantic Context & Background Indexing: Instructs the agent to rely on automatic background filesystem watching and line-shift resilient incremental re-indexing, avoiding manual indexing commands.
Zero-Cost Local Proxy & Resilient Fallback Routing: Teaches the agent to leverage local model endpoints for free routine generations while ensuring transparent remote LLM failover.
Copy and paste these templates directly into your bot's system instructions or configuration environment to get started.
Persistent Files
File | Purpose |
| Vector store for |
| Symbol index from |
| Persisted budget cap and warning threshold |
| Serialized pricing and model catalog cache for zero-network startups |
Notes
Reasoning models:
<think>blocks are automatically extracted and displayed separately.Embedding models: Pinned text uses
text-embedding-3-small. Code chunks usetext-embedding-3-large.Custom Presets can be modified in
src/config.ts.stdout is redirected to stderr to protect the MCP stdio protocol stream.
Maintained by Antigravity ยท Last updated May 21, 2026
โ๏ธ Trademark Disclaimer
"Universal MCP for OpenRouter" is an independent, community-developed project. It is not affiliated with, endorsed by, or officially connected to OpenRouter, Inc. "OpenRouter" is a trademark of OpenRouter, Inc.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
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/villagertim/universal-mcp-for-openrouter'
If you have feedback or need assistance with the MCP directory API, please join our Discord server