claude-openrouter-delegate-mcp
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., "@claude-openrouter-delegate-mcpdelegate this to openrouter: summarize the code in src/lib"
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.
claude-openrouter-delegate-mcp
Delegate tasks from an Anthropic-backed Claude Code session to OpenRouter-backed Claude Code sessions — without the two ever sharing environment variables.
Pointing Claude Code at OpenRouter means exporting ANTHROPIC_* variables into
your shell. Those variables are process-wide, so one shell is either "Anthropic"
or "OpenRouter", never both — and an exported ANTHROPIC_AUTH_TOKEN holding your
OpenRouter key is one stray subprocess away from leaking.
This MCP server spawns each delegated session as a child process with an explicitly constructed environment. Your Opus session keeps its own credentials; the delegate gets OpenRouter's. They run side by side in the same terminal.
┌────────────────────────────┐
│ Claude Code (Opus) │ your session, Anthropic credentials
│ │
│ └─ mcp: openrouter ──────┼──▶ spawn: claude -p (fresh env)
└────────────────────────────┘ ANTHROPIC_BASE_URL=https://openrouter.ai/api
ANTHROPIC_AUTH_TOKEN=sk-or-v1-…
→ deepseek/deepseek-v4-flash-0731This is a sibling of claude-ollama-delegate-mcp, which does the same thing for a local Ollama server. The difference that shapes everything here: OpenRouter costs real money and offers 400+ models, so this package adds an API-key path, a model catalog with prices, and per-job cost reporting.
Quick start
# 1. an OpenRouter API key: https://openrouter.ai/keys
export OPENROUTER_API_KEY=sk-or-v1-...
# 2. register the server
claude mcp add openrouter --scope user -- npx -y claude-openrouter-delegate-mcp
# 3. restart your Claude Code sessionThen ask for delegation in plain language:
delegate this to openrouter: summarise every exported symbol in src/
By default the server only delegates when you explicitly ask. To let the orchestrator decide for itself, see Delegation modes.
Related MCP server: Ollama MCP Server
Contents
How it works
OpenRouter exposes an Anthropic-compatible POST /v1/messages endpoint
alongside its OpenAI-shaped one, so Claude Code talks to it unmodified when
pointed at the right base URL. Each delegated task runs as claude -p in its own
process with:
ANTHROPIC_BASE_URL=https://openrouter.ai/api
ANTHROPIC_AUTH_TOKEN=<your OpenRouter key>
ANTHROPIC_DEFAULT_OPUS_MODEL=<model>
ANTHROPIC_DEFAULT_SONNET_MODEL=<model>
ANTHROPIC_DEFAULT_HAIKU_MODEL=<small model>
ANTHROPIC_SMALL_FAST_MODEL=<small model>
CLAUDE_CODE_SUBAGENT_MODEL=<model>
ANTHROPIC_CUSTOM_HEADERS=HTTP-Referer: …⏎X-Title: …
CLAUDE_CODE_MAX_OUTPUT_TOKENS=<clamped per model>The base URL stops at /api because Claude Code appends /v1/messages itself.
ANTHROPIC_AUTH_TOKEN is used rather than ANTHROPIC_API_KEY because it is sent
as Authorization: Bearer <key>, which is the scheme OpenRouter expects.
The child environment is built from a small per-platform allowlist. Anything
matching ANTHROPIC_*, CLAUDE_*, AWS_*, GOOGLE_*, AZURE_*, OPENAI_*,
BEDROCK_*, VERTEX_* or OPENROUTER_* is dropped before the OpenRouter
values are applied. That last prefix is deliberate: the delegate needs the key
only as ANTHROPIC_AUTH_TOKEN, so it never receives a second copy under a name
that other tooling it runs might pick up.
Delegates also start with --strict-mcp-config and no MCP config, which keeps
their startup fast and stops them from recursively calling this server.
Two details that are not optional
Output-token clamping. Claude Code asks for max_tokens: 32000 on every
request. Plenty of OpenRouter models cap lower — amazon/nova-micro-v1 allows
5120 — and reject the request outright. The server reads
top_provider.max_completion_tokens from the catalog and pins
CLAUDE_CODE_MAX_OUTPUT_TOKENS to what the chosen model actually accepts.
Tool-calling is mandatory. Claude Code sends a ~110 KB body with a full tool
schema on every request. A model that cannot call tools fails on turn one, after
you have paid for it. The server refuses such models up front using the
catalog's supported_parameters.
Prerequisites
Requirement | Notes |
Node.js 20+ |
|
An OpenRouter account | openrouter.ai/keys. Credits must be topped up. |
Claude Code CLI | claude.com/code. |
node --version
claude --version
curl -s -H "Authorization: Bearer $OPENROUTER_API_KEY" \
https://openrouter.ai/api/v1/credits # {"data":{"total_credits":…}}Installation
From npm (recommended)
claude mcp add openrouter --scope user \
--env OPENROUTER_API_KEY=sk-or-v1-... \
-- npx -y claude-openrouter-delegate-mcpOr install it globally, which also puts the settings CLI on your PATH:
npm install -g claude-openrouter-delegate-mcp
openrouter-mcp-config --api-key sk-or-v1-...
claude mcp add openrouter --scope user -- claude-openrouter-delegate-mcpFrom source
git clone https://github.com/histonedev/claude-openrouter-delegate-mcp.git
cd claude-openrouter-delegate-mcp
npm install # builds automatically via the prepare script
claude mcp add openrouter --scope user -- node "$(pwd)/dist/index.js"Run the settings CLI as node dist/cli.js …, or npm link to get
openrouter-mcp-config on your PATH.
Confirm
claude mcp list # openrouter: ... - ✔ ConnectedThen restart your Claude Code session — the tool list is read at startup.
The API key
Resolved from the first of these that is set:
OPENROUTER_API_KEY(highest — the name the rest of the ecosystem uses)OPENROUTER_MCP_API_KEYapiKeyFilein a config file — a path to a file containing the keyapiKeyin a config file
openrouter-mcp-config --api-key sk-or-v1-... # writes ~/.openrouter-mcp/config.json, mode 0600
openrouter-mcp-config --api-key-file ~/.secrets/or # or keep it somewhere else entirelyThe key is never exposed through an MCP tool. openrouter_models reports it as
sk-or-v1-a...7f2e, the CLI prints the same masked form, and the config file is
written 0600. A key passed with --api-key --scope project is redirected to
the user config, because project configs get committed.
If you would rather have no key on disk at all, pin it on the MCP registration
with --env OPENROUTER_API_KEY=… and skip the config file.
Configuration
Settings resolve from four layers, later winning over earlier:
built-in defaults
user config —
~/.openrouter-mcp/config.json(override with$OPENROUTER_MCP_CONFIG)project config —
./openrouter-mcp.config.jsonin the server's working directoryenvironment variables
{
"delegationMode": "ondemand",
"defaultModel": "deepseek/deepseek-v4-flash-0731",
"smallModel": "google/gemini-3.7-flash",
"allowedModels": ["deepseek/deepseek-v4-flash-0731", "qwen/qwen3.7-flash"],
"defaultPermissionMode": "auto",
"maxOutputTokens": 16000,
"requireToolSupport": true
}Setting | Env var | Default | Meaning |
|
|
| How eagerly delegation is used |
|
| — | Your OpenRouter key |
|
|
| Model when a call omits one |
|
| same as | Model for the delegate's background/utility slot |
|
|
| Models delegation may use |
|
|
| Permission mode for delegates |
|
|
| Ceiling, clamped again per model |
|
|
| Reject models that cannot call tools |
|
|
| Endpoint (point at a proxy if you have one) |
|
| this repo |
|
|
|
| Path to the Claude Code CLI |
|
|
| Prompts, transcripts, results |
|
|
| Hard kill for one turn |
|
|
| Output above this is truncated; full text on disk |
Changing settings
Settings are changed from a terminal, never by the model:
openrouter-mcp-config # show current settings + active layers
openrouter-mcp-config --mode auto # off | ondemand | auto
openrouter-mcp-config --default-model qwen/qwen3.7-flash
openrouter-mcp-config --small-model google/gemini-3.7-flash
openrouter-mcp-config --allow deepseek/deepseek-v4-flash-0731,qwen/qwen3.7-flash
openrouter-mcp-config --permission-mode acceptEdits
openrouter-mcp-config --scope project # write ./openrouter-mcp.config.jsonThen restart your Claude Code session so the server re-reads its config.
There is deliberately no MCP tool for this. See Security model.
Delegation modes
This controls how eagerly the orchestrator reaches for delegation, by rewriting the tool descriptions the model actually reads. Changing it requires a session restart, by design.
Mode | Effect |
| The |
| Delegate only when you explicitly ask — "delegate this", "use openrouter", "ask deepseek". |
| The orchestrator decides for itself, using criteria baked into the description. |
Both modes carry an explicit cost warning, because unlike a local model every delegated turn is billed and every request carries tens of thousands of input tokens.
Choosing a model
OpenRouter serves 400+ models. openrouter_models filters to tool-capable ones
and truncates by default, since dumping the whole catalog into the orchestrator's
context is expensive in itself.
openrouter_models({ filter: "gemini", limit: 10 })
openrouter_models({ free_only: true })The default is deepseek/deepseek-v4-flash-0731: tool-capable, 1.3M context, and
cheap. Set allowedModels to pin delegation to a shortlist you trust — the
allowed set is embedded in the delegate_start description, so the orchestrator
knows the menu without an extra call, and any other model is rejected by name
rather than silently substituted.
Model quality varies, and that is your problem to manage
These are not Claude models, and Claude Code leans on the model harder than a chat UI does. Observed while building this package, on real runs:
A model may call its tools correctly and then return no final text. The work happened; the closing message did not. The server detects this and hands back the recorded activity trail instead of an empty result.
A model may emit its own native tool-call markup as plain text — DeepSeek producing
<|DSML|tool_calls>inside a reasoning block — instead of a structured tool call. Nothing executes and the tokens are still billed. Longer and more convoluted prompts make this more likely.The
tool calls: 0annotation on a finished job is there for the classic failure: a confident answer about your repository that no tool call backs.
Prefer short, single-purpose prompts for weaker models, cap work with
max_turns, and check delegate_status when a claim matters.
Costs
Every finished job reports a cost, and the label tells you how much to trust it:
cost: $0.00045 (billed by OpenRouter, 1 generation(s))
cost: >=$0.00045 (billed so far -- 1 of 2 generations recorded)
cost: $0.00924 (rough list-price estimate; actual routing may differ several-fold)OpenRouter returns its generation id as the Anthropic message id, so the server
collects them and asks /v1/generation what each request actually cost. That is
the authoritative number. Billing records land a moment after the generation
finishes, so a job may briefly report a partial sum — shown as >=, never as a
final figure, because the one direction a cost display must not be wrong in is
downward.
The estimate is the fallback when a record cannot be fetched. Treat it as an order of magnitude only: in testing, identical token counts on the same model were billed ten times apart depending on provider routing and cache hits, and list-price arithmetic came out 20× high on one run.
Two things worth knowing about token counts:
Claude Code reports almost the entire prompt as
cache_creation_input_tokens, notinput_tokens. Thetokens: in …line sums all input classes. A job that looks like "12 input tokens" is really ~42,000.OpenRouter routes to providers that often do not honour the cache (
native_tokens_cached: 0), so a resumed conversation is not as cheap as the cache-read figures suggest.
Cutting the bill. smallModel is the biggest lever: Claude Code's haiku slot
serves background utility calls, and pointing it at something cheap while the
main model stays capable costs almost nothing in quality. After that: max_turns
caps an agentic loop, and allowed_tools stops a delegate exploring more of the
repo than the task needs.
Tool reference
Tool | Purpose |
| List models with prices and context windows, report settings and credit balance (read-only) |
| Start a task; returns a |
| Send another message to the same session |
| Poll state plus a tail of the delegate's tool calls |
| Collect final output |
| Terminate a running delegate and everything it started |
| List jobs, grouped by conversation, with total spend |
delegate_start
Parameter | Type | Notes |
| string | The task. Mutually exclusive with |
| string | Path to a file holding the prompt. Preferred when long. |
| string | OpenRouter id, e.g. |
| string | Override the background/utility model for this call. |
| string | Working directory for the delegate. |
| enum |
|
| string[] | e.g. |
| string[] | e.g. |
| string | Extra instructions for the delegate |
| number | Cap the delegate's agentic turns — also a cost cap |
| string[] | Additional accessible directories |
| number | Block up to N seconds (0–600). Default 0 = return immediately. |
delegate_followup takes job_id or session_id, plus the same
prompt/prompt_file pair and optional permission_mode, max_turns,
wait_seconds.
Operating it
Asynchronous by default
delegate_start returns a job_id in milliseconds; the delegate keeps running
in the background. This keeps a long task from stalling your session or tripping
an MCP client timeout — most clients give up on a single request after 60
seconds, which is less than many delegated tasks take.
delegate_start({ prompt: "Audit src/ for unused exports" })
→ job_id A, session_id S, turn 1, state: running
delegate_status({ job_id: "A" })
→ recent activity:
[tool] Grep: export
[tool] Read: /repo/src/index.ts
delegate_result({ job_id: "A" })
→ the final textPass wait_seconds on any of those to block instead — useful for short tasks,
but keep it under your client's request timeout.
Two-way conversations
Every job carries a session_id. Passing its job_id to delegate_followup
resumes the session with full history; the session_id stays stable across turns
while each turn gets a fresh job_id.
delegate_start({ prompt: "Summarise the auth flow in this repo" })
→ job A, session S, turn 1
delegate_followup({ job_id: "A", prompt: "Now list every place it can fail" })
→ job B, session S, turn 2 (delegate still remembers turn 1)Resuming replays the conversation as input tokens, so a long thread costs more per turn than a fresh one — but still far less than rebuilding the same context.
Long prompts
Every prompt parameter has a prompt_file counterpart. Internally the prompt is
always written to disk and fed to the CLI over stdin — never as an argv entry
and never through a shell. Backticks, $(...), quotes, newlines and glob
characters pass through verbatim, and there is no argv length limit.
Permissions
// read-only review
delegate_start({ prompt: "...", disallowed_tools: ["Write", "Edit", "NotebookEdit"] })
// tightly scoped
delegate_start({ prompt: "...", allowed_tools: ["Read", "Grep", "Glob"] })Cancelling
delegate_cancel({ job_id: "A" })Kills the delegate and everything it started, and stops it spending any more credits. The server also kills running delegates when it shuts down.
Job artifacts
Each job writes to ~/.openrouter-mcp/jobs/<job_id>/:
File | Contents |
| Exactly what was sent |
| Full |
| Metadata: state, model, tokens, cost, generation ids, timings, exit code |
| Final output text |
stream.jsonl is where to look when a delegate's summary is unconvincing: it
holds the actual tool results, not the model's account of them. Nothing is pruned
automatically — delete the directory whenever you like.
Troubleshooting
No OpenRouter API key configured
Set OPENROUTER_API_KEY, or openrouter-mcp-config --api-key sk-or-v1-..., then
restart the session.
OpenRouter rejected the API key (HTTP 401)
Check it at openrouter.ai/keys. Note that the key
is read at server start, so a fresh key needs a session restart.
Model "x" does not support tool calling
Working as intended — Claude Code sends a tool schema on every request. Pick
another model, or set requireToolSupport: false to try anyway.
Model "x" is not in the allowed list
Working as intended. openrouter-mcp-config --allow <models>, then restart.
The delegate returns no text, or its tool calls do nothing
A model-quality problem, not a wiring one — see
Model quality varies.
Try a shorter prompt or a stronger model, and read stream.jsonl to see what
actually happened.
Request timed out from your MCP client
wait_seconds exceeded the client's per-request timeout (often 60s). Drop it and
poll with delegate_status instead — that is what the async design is for.
HTTP 400 about max_tokens
The model's output cap is below what was requested. The server clamps to the
catalog's value automatically; if the catalog is wrong, lower maxOutputTokens.
Tools do not appear in Claude Code
The tool list is read at session start. Restart, or check claude mcp list.
Delegate fails instantly with a launch error
The CLI was not found. Set OPENROUTER_MCP_CLAUDE_BIN to the absolute path of
claude.
Platform support
Platform | Status |
Windows | Tested end to end |
macOS | Supported; same POSIX code path as Linux |
Linux | Supported |
Platform differences are isolated in src/platform.ts:
Binary resolution. On POSIX, spawn searches PATH. On Windows a native
install gives claude.exe while an npm install gives claude.cmd, which
CreateProcess cannot execute directly — so the server walks PATH × PATHEXT
preferring .exe, and falls back to routing a .cmd shim through cmd.exe.
Argument escaping. That fallback applies two layers: MSVCRT argv quoting, then
a caret escape of cmd's own metacharacters (& | < > ^ " ( ) % !). Skipping the
second layer is the classic .cmd command-injection hole. Prompts never touch
this path — they travel over stdin. One limitation: a multi-line
append_system_prompt cannot cross a cmd.exe command line, so the server raises
a clear error pointing at OPENROUTER_MCP_CLAUDE_BIN instead of silently
mangling it.
Environment allowlist. Windows preserves a much larger set than POSIX.
SystemRoot and windir are not optional — strip them and Winsock fails to
initialise, so the child cannot open a socket at all.
Cancellation. POSIX children are spawned detached as process-group leaders
and cancelled with process.kill(-pid); Windows uses taskkill /T /F.
Security model
Credential isolation is the point. The child environment is constructed from
scratch rather than inherited, and provider variables are stripped before the
OpenRouter values are applied. test/env-unit.mjs asserts that the key reaches
the child in exactly one variable and that no parent secret survives;
test/e2e.mjs poisons the parent with a fake ANTHROPIC_API_KEY and a real
ANTHROPIC_BASE_URL=https://api.anthropic.com and confirms the delegate sees
neither.
The key is never readable through a tool. Every diagnostic path masks it, and
test/readonly.mjs asserts that no tool output and no CLI output contains the
key. This matters more here than in the Ollama sibling, where the token is the
literal string ollama.
Delegation policy is not model-writable. There is no MCP tool to change
delegationMode, allowedModels, or the API key. A model that finds ondemand
inconvenient cannot flip itself to auto and start spending. Settings load once
at startup, are never mutated at runtime, and the tool descriptions state that
the policy is not the model's to change.
This is a guardrail, not a security boundary. An agent with shell access can
still edit the config file. What removing the tool buys you is that such a change
is a visible file edit that only takes effect on the next restart, rather than a
single silent tool call mid-task. To make it airtight, pin the values via --env
on the MCP registration, which overrides the config files:
claude mcp add openrouter --scope user \
--env OPENROUTER_API_KEY=sk-or-v1-... \
--env OPENROUTER_MCP_DELEGATION_MODE=ondemand \
--env OPENROUTER_MCP_ALLOWED_MODELS=deepseek/deepseek-v4-flash-0731 \
-- node /path/to/claude-openrouter-delegate-mcp/dist/index.jsSpending is real. A runaway auto-mode orchestrator spends your credits, not
your patience. Keep an OpenRouter key limit on the key you give this server —
that is a ceiling the model cannot argue with.
Delegates inherit your filesystem. They run as your user in the cwd you
give them, with defaultPermissionMode. Treat a delegated session as you would
any Claude Code session — use disallowed_tools or a read-only permission mode
when handing work to a model you trust less.
Development
npm install # installs and builds
npm run build # tsc
npm run dev # tsc --watchTests
node test/env-unit.mjs # env isolation, key handling, model slot wiring
node test/pricing-unit.mjs # cost arithmetic, catalog filtering, URL normalisation
node test/quoting.mjs # Windows argv/cmd escaping, incl. an injection probe
node test/killtree-unit.mjs # process-tree termination (cross-platform)
OPENROUTER_API_KEY=... node test/e2e.mjs # full MCP round trip (costs ~$0.01)
OPENROUTER_API_KEY=... node test/async.mjs # async polling, prompt_file, cancel
CFG_PATH=/tmp/c.json CFG_CWD=/tmp node test/readonly.mjs # config is read-only to the modelnpm test runs the four that need no network. They pass on Windows and POSIX
alike — the process-tree test builds its tree out of node processes rather than
shell built-ins, so it is not POSIX-only.
Publishing a release
npm login # interactive, once per machine
npm version patch # or minor / major -- tags and bumps
npm publish # prepare script builds first
git push --follow-tagsRun npm publish from a real terminal, not a script or a non-interactive
shell. With WebAuthn/security-key 2FA the CLI completes the challenge by opening
a browser; without a TTY it cannot, and falls back to demanding a TOTP code that
a security key cannot produce (npm error code EOTP). For CI, use a granular
access token with Bypass 2FA instead.
The package ships only dist/, README.md and LICENSE. publishConfig.access
is public, and prepare runs tsc before packing, so a stale dist/ can never
be published.
Layout
File | Responsibility |
| MCP server, tool registration and handlers |
| Layered config loading, API-key resolution, masking |
| Startup-resolved settings singleton |
| Mode-dependent tool descriptions, cost warnings |
| Child-environment construction and the provider-variable blocklist |
| Windows/POSIX spawn, argument escaping, process-tree kill |
| Job lifecycle, |
| Catalog, pricing, tool-support enforcement, billing lookups |
|
|
License
MIT — see LICENSE.
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 Servers
- -license-quality-maintenanceGives Claude access to multiple AI models (Gemini, OpenAI, OpenRouter, Ollama) for enhanced development capabilities including extended reasoning, collaborative development, code review, and advanced debugging.
- Alicense-qualityDmaintenanceEnables Claude to delegate coding tasks to local Ollama models, reducing API token usage by up to 98.75% while leveraging local compute resources. Supports code generation, review, refactoring, and file analysis with Claude providing oversight and quality assurance.29422AGPL 3.0
- AlicenseAqualityDmaintenanceEnables Claude Code to delegate tasks to OpenAI's Codex CLI (GPT-5.4) with structured execution traces, parallel execution, session persistence, and adversarial code review.15MIT
- AlicenseAqualityCmaintenanceCost-aware, multimodal OpenCode task router and sub-agent MCP server for Claude Code, providing tools for delegation, status, review, revision, abort, models, and usage.7MIT
Related MCP Connectors
Real-time chat hub for AI agents — Claude Code, Cursor, Cline, Codex over MCP or REST.
Persistent context for Claude. Your AI always knows your projects and next actions across sessions.
Paid remote MCP for Claude Code skill update gate MCP, structured receipts, audit logs, and reviewer
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/histonedev/claude-openrouter-delegate-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server