Skip to main content
Glama

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 --profile argument to the server.

CLI Arguments

Argument

Description

Example

--profile

Load a specific JSON profile from the profiles/ directory

--profile antigravity


Installation & Setup

1. Install & Build

npm install
npm run build

2. 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

CAUTION

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:

  1. Use Unique Keys: Generate a unique OpenRouter API key specifically for this MCP server. Do not reuse a master key.

  2. Set Hard Key Limits: In your OpenRouter Dashboard (Settings -> Keys), apply a strict USD spending limit to this specific key.

  3. Set Reset Frequencies: Configure the key to reset daily or weekly rather than leaving it uncapped.

  4. 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_... and github_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:

  1. Cost-Aware & Budget-Safe Orchestration: Teaches the agent to route simple queries to cheap models and complex queries to premium models while tracking spending.

  2. Image & Vision Analysis Fallback: Guides text-based or terminal-based clients on how to use our vision_analyze tool to "see" image assets.

  3. Prompt Optimization & Fallback Routing: Keeps major refactoring tasks cost-efficient and outage-resistant.

  4. Multi-Service Log Correlation: Instructs the agent to isolate log ingestion to debug system failures quietly.

  5. Autonomous Loop Safety Policy: A strict financial circuit breaker for autonomous background execution loops.

  6. Workspace Memory & Long-Term Pinning: Solves conversation amnesia by persistently caching architectural and domain constraints.

  7. High-Throughput Batch Operations: Orchestrates multi-file conversions and template updates with cost-effective models.

  8. CI/CD & Build Pipeline Diagnostics: Automates container crash diagnostics and patch validation to resolve build failures.

  9. Monorepo Dependency & Semver Syncing: Performs pre-commit audits to keep package dependencies fully aligned across microservices.

  10. Enterprise Privacy & Sensitive Data Guardrails: Redacts and mocks credentials or proprietary algorithms to prevent sensitive data leaks.

  11. Multi-Model Peer Review & Consensus: Emulates a double-model consensus flow to audit mission-critical code for exploits and concurrency bugs.

  12. Context Window Garbage Collection: Minimizes token pricing and eliminates hallucinations by periodically purging active context bloat.

  13. OpenClaw CLI Loop-Stall & Log Pruning: Formulates terminal hygiene policies to prevent compilation locks and strip noise from test results.

  14. Structured Planning & JSON Chaining: Instructs Hermes-type JSON function call engines to compress reasoning steps and accelerate tool parallel execution.

  15. Diagnostic Self-Healing & Pre-Flight Integration: Mandates early setup diagnostic checks and reactive troubleshooting to handle budget or runtime failures gracefully.

  16. High-Context Codebase Navigation & Model Slicing: Dynamically estimates file token sizes to query and select the most budget-efficient high-context models.

  17. 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.

  18. 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

context_store.json

Vector store for pin_context and reindex_project embeddings

symbol_index.json

Symbol index from index_project

rate_config.json

Persisted budget cap and warning threshold

pricing_cache.json

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 use text-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.

Available Tools

24 tools
chat_completionChat CompletionC

Generate a chat completion using an OpenRouter model

Inputs: prompt (required), model, models, max_tokens, +2 more.

chat_ensembleMulti-Model ConsensusA

Generate a consensus completion by querying multiple distinct models in parallel and synthesizing their responses using a synthesizer model.

Inputs: models (required), prompt (required), max_tokens, temperature, +2 more.

chat_routedIntelligent Routed ChatA

Execute a chat completion with intelligent, automatic cost-aware model routing based on prompt size, required context length, and task attributes.

Inputs: prompt (required), max_tokens, strictness, temperature, +4 more.

chat_with_presetChat with PresetB

Generate a chat completion using a predefined model preset (smart, cheap, creative, fast, coder)

Inputs: preset (required), prompt (required), system_prompt.

clear_contextClear Context MemoryA
Destructive

Delete entries from semantic memory by tag or project

Inputs: tag, project, confirm_wipe_all.

correlate_errorsCorrelate Multi-System ErrorsA

Analyze log snippets from multiple systems to find root causes and correlations

Inputs: logs (required).

dependency_graphDependency Graph AnalysisA
Read-only

Analyze shared dependencies and semver conflicts across multiple projects

Inputs: repos, max_depth, transitive, include_dev, +2 more.

filter_modelsFilter ModelsA
Read-onlyIdempotent

Filter and search available OpenRouter models based on requirements (e.g. cost, context window, vision)

Inputs: limit, query, supports_vision, min_context_length, +1 more.

get_balanceGet Credit BalanceA
Read-only

Check your OpenRouter credit balance

Inputs: no named parameters.

get_budget_statusGet Budget StatusA
Read-onlyIdempotent

Check the current session spending and budget status

Inputs: no named parameters.

get_key_infoGet API Key InfoA
Read-only

Get information about the current API key (limits, usage, etc.)

Inputs: no named parameters.

get_session_usageGet Session UsageA
Read-only

Get the total token usage and estimated cost for the current session

Inputs: no named parameters.

index_projectIndex Project SymbolsB
Destructive

Scan a project directory to index symbols (functions, classes, variables) for cross-project awareness

Inputs: project_name (required), project_path (required).

list_modelsList Available ModelsB
Read-onlyIdempotent

List available models on OpenRouter

Inputs: no named parameters.

optimize_promptOptimize PromptB

Refine and optimize a draft prompt using best practices for LLMs

Inputs: prompt (required), target_model.

pin_contextPin Context MemoryB
Destructive

Store text with optional tags and project association for semantic retrieval

Inputs: text (required), tag, project.

recommend_modelRecommend Model PresetA

Analyze a task and recommend the best model preset (smart, cheap, creative, fast, coder)

Inputs: task (required).

reindex_projectReindex Project EmbeddingsB
Destructive

Perform deep semantic indexing of a project (code chunking + embeddings) for code search

Inputs: project_name (required), max_chunks.

retrieve_contextRetrieve Context MemoryB
Read-only

Search for semantically similar information in memory

Inputs: query (required), tag, top_k, project.

search_symbolsSearch SymbolsA
Read-only

Search for symbols across all indexed projects

Inputs: query (required).

set_budgetSet Budget LimitA
Destructive

Set a session-wide spending limit (in USD) and warning threshold

Inputs: max_dollars, warn_at_percent.

verify_setupVerify Server SetupA
Read-onlyIdempotent

Perform diagnostic checks on OpenRouter credentials, files, and server environment

Inputs: no named parameters.

vision_analyzeAnalyze ImageB

Analyze an image (local file or URL) using a vision-capable model

Inputs: model, prompt, image_url, image_path.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    B3.4/5.0

    Scored across 24 tools

    Disambiguation3/5

    Several tools have overlapping chat generation purposes (chat_completion, chat_with_preset, chat_ensemble, chat_routed) but descriptions distinguish them by mode. Code search tools (search_symbols vs semantic_code_search) and indexing tools (index_project vs reindex_project) are also similar, though their intents are clear enough.

    Naming Consistency4/5

    Most tools follow a verb_noun snake_case pattern (list_models, get_balance, pin_context). Minor deviations like chat_with_preset (preposition) and chat_routed (past participle) are understandable but break the strict pattern.

    Tool Count3/5

    At 24 tools, the server is on the heavy side. It bundles unrelated domains (OpenRouter chat, code indexing, memory, error correlation) into one surface, which feels over-scoped for a single MCP server.

    Completeness4/5

    Core OpenRouter operations (chat, models, budget, usage) are well covered. The supplementary features (indexing, memory) have CRUD-style operations, though delete for indexing and some model detail endpoints are missing. Overall, most workflows can be completed.

    Related MCP Connectors

    Related MCP Servers

    • -
      license
      Not graded
      quality
      Not graded
      maintenance
      A sophisticated MCP server providing advanced memory capabilities with RAG, hallucination detection, and enterprise-grade AI infrastructure for intelligent agent ecosystems.
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that functions as an intelligent gateway for multiple LLM backends including OpenAI, Claude, and Ollama. It supports automatic provider fallback, streaming responses via Server-Sent Events, and real-time monitoring for robust AI integration.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      MCP server that enables agents to dynamically switch between multiple AI models (OpenAI, Anthropic, Google, etc.) with unified protocol-driven configuration and capability discovery.
      Apache 2.0