claude-openrouter-delegate-mcp
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: openrouter-mcp
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 возвращает свой идентификатор генерации как идентификатор сообщения Anthropic, поэтому сервер собирает их и запрашивает /v1/generation, чтобы узнать, сколько на самом деле стоила каждая генерация. Это авторитетное число. Записи о списаниях появляются через мгновение после завершения генерации, поэтому задача может кратко показывать частичную сумму — она отображается как >=, но никогда как итоговая цифра, потому что единственное направление, в котором отображение стоимости не должно ошибаться, — это вниз.
Оценка — это запасной вариант, когда запись не удаётся получить. Относитесь к ней только как к порядку величины: при тестировании одинаковые количества токенов на одной и той же модели выставлялись в счёт в десять раз по-разному в зависимости от маршрутизации провайдера и попаданий в кэш, а арифметика по прейскуранту в одном прогоне оказалась завышенной в 20 раз.
Две вещи, которые стоит знать о подсчёте токенов:
Claude Code сообщает почти весь промпт как
cache_creation_input_tokens, а неinput_tokens. Строкаtokens: in …суммирует все классы входных токенов. Задача, которая выглядит как «12 входных токенов», на самом деле — ~42 000.OpenRouter маршрутизирует к провайдерам, которые часто не соблюдают кэш (
native_tokens_cached: 0), поэтому возобновлённый разговор не так дёшев, как предполагают цифры чтения из кэша.
Сокращаем счёт. smallModel — самый мощный рычаг: слот haiku в Claude Code обслуживает фоновые служебные вызовы, и направить его на что-то дешёвое, пока основная модель остаётся способной, почти ничего не стоит по качеству. После этого: max_turns ограничивает агентный цикл, а allowed_tools не даёт делегату исследовать больше репозитория, чем нужно для задачи.
Справочник по инструментам
Инструмент | Назначение |
| Список моделей с ценами и контекстными окнами, настройки отчёта и баланс кредитов (только чтение) |
| Запустить задачу; возвращает |
| Отправить ещё одно сообщение в ту же сессию |
| Опрос состояния плюс хвост вызовов инструментов делегата |
| Собрать итоговый вывод |
| Завершить работающего делегата и всё, что он запустил |
| Список задач, сгруппированных по разговору, с общими расходами |
delegate_start
Параметр | Тип | Примечания |
| string | Задача. Взаимоисключающе с |
| string | Путь к файлу с промптом. Предпочтителен для длинных промптов. |
| string | Идентификатор OpenRouter, напр. |
| string | Переопределить фоновую/служебную модель для этого вызова. |
| string | Рабочий каталог для делегата. |
| enum |
|
| string[] | напр. |
| string[] | напр. |
| string | Дополнительные инструкции для делегата |
| number | Ограничить число агентных ходов делегата — это также ограничение расходов |
| string[] | Дополнительные доступные каталоги |
| number | Блокировать до N секунд (0–600). По умолчанию 0 = вернуться немедленно. |
delegate_followup принимает job_id или session_id, а также ту же пару
prompt/prompt_file и необязательные permission_mode, max_turns,
wait_seconds.
Эксплуатация
Асинхронность по умолчанию
delegate_start возвращает job_id за миллисекунды; делегат продолжает работать
в фоне. Это не даёт длинной задаче заблокировать вашу сессию или сорвать таймаут
MCP-клиента — большинство клиентов отказываются от одного запроса через 60
секунд, а это меньше, чем занимают многие делегированные задачи.
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 textПередайте wait_seconds в любой из этих вызовов, чтобы вместо этого блокировать выполнение — полезно для коротких задач, но держите значение ниже таймаута запроса вашего клиента.
Двусторонние разговоры
Каждая задача несёт session_id. Передача её job_id в delegate_followup
возобновляет сессию с полной историей; session_id остаётся стабильным между
ходами, тогда как каждый ход получает свежий 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)Возобновление воспроизводит разговор как входные токены, поэтому длинная ветка обсуждения стоит дороже за ход, чем новая — но всё равно гораздо дешевле, чем пересобирать тот же контекст заново.
Длинные промпты
У каждого параметра промпта есть аналог prompt_file. Внутренне промпт всегда
записывается на диск и подаётся в CLI через stdin — никогда как элемент argv
и никогда через оболочку. Обратные кавычки, $(...), кавычки, переводы строк и
символы глобов проходят без изменений, и нет ограничения на длину argv.
Разрешения
// read-only review
delegate_start({ prompt: "...", disallowed_tools: ["Write", "Edit", "NotebookEdit"] })
// tightly scoped
delegate_start({ prompt: "...", allowed_tools: ["Read", "Grep", "Glob"] })Отмена
delegate_cancel({ job_id: "A" })Убивает делегата и всё, что он запустил, и останавливает дальнейшее списание кредитов. Сервер также убивает работающих делегатов при завершении работы.
Артефакты задач
Каждая задача пишет в ~/.openrouter-mcp/jobs/<job_id>/:
Файл | Содержимое |
| Ровно то, что было отправлено |
| Полная стенограмма |
| Метаданные: состояние, модель, токены, стоимость, идентификаторы генераций, тайминги, код выхода |
| Итоговый текст вывода |
stream.jsonl — это то, куда стоит смотреть, когда сводка делегата неубедительна: там хранятся фактические результаты инструментов, а не пересказ модели. Ничего не удаляется автоматически — удалите каталог, когда захотите.
Устранение неполадок
No OpenRouter API key configured
Задайте OPENROUTER_API_KEY или выполните openrouter-mcp-config --api-key sk-or-v1-..., затем
перезапустите сессию.
OpenRouter rejected the API key (HTTP 401)
Проверьте ключ на openrouter.ai/keys. Обратите внимание, что ключ
считывается при запуске сервера, поэтому для нового ключа нужен перезапуск сессии.
Model "x" does not support tool calling
Работает как задумано — Claude Code отправляет схему инструментов в каждом запросе. Выберите
другую модель или задайте requireToolSupport: false, чтобы попробовать в любом случае.
Model "x" is not in the allowed list
Работает как задумано. Выполните openrouter-mcp-config --allow <models>, затем перезапустите.
Делегат не возвращает текст, или его вызовы инструментов ничего не делают
Это проблема качества модели, а не подключения — см.
Качество моделей различается.
Попробуйте более короткий промпт или более сильную модель и прочитайте stream.jsonl, чтобы увидеть,
что произошло на самом деле.
Request timed out от вашего MCP-клиента
wait_seconds превысил таймаут запроса клиента (часто 60 с). Уберите его и опрашивайте
через delegate_status — именно для этого и задумана асинхронная архитектура.
HTTP 400 про max_tokens
Потолок вывода модели ниже запрошенного. Сервер автоматически ограничивает значение
по каталогу; если каталог неверен, уменьшите maxOutputTokens.
Инструменты не появляются в Claude Code
Список инструментов считывается при запуске сессии. Перезапустите или проверьте claude mcp list.
Делегат мгновенно падает с ошибкой запуска
CLI не найден. Задайте OPENROUTER_MCP_CLAUDE_BIN как абсолютный путь к
claude.
Поддержка платформ
Платформа | Статус |
Windows | Протестировано от начала до конца |
macOS | Поддерживается; тот же POSIX-путь кода, что и Linux |
Linux | Поддерживается |
Различия платформ изолированы в src/platform.ts:
Разрешение бинарника. На POSIX spawn ищет в PATH. На Windows нативная
установка даёт claude.exe, а установка через npm даёт claude.cmd, который
CreateProcess не может выполнить напрямую — поэтому сервер проходит по PATH × PATHEXT,
предпочитая .exe, и в крайнем случае маршрутизирует обёртку .cmd через cmd.exe.
Экранирование аргументов. Этот запасной вариант применяет два слоя: квотирование argv по MSVCRT, затем
экранирование служебных символов cmd кареткой (& | < > ^ " ( ) % !). Пропуск второго
слоя — это классическая дыра для внедрения команд в .cmd. Промпты никогда не касаются
этого пути — они идут через stdin. Одно ограничение: многострочный
append_system_prompt не может пересечь командную строку cmd.exe, поэтому сервер
выдаёт понятную ошибку, указывающую на OPENROUTER_MCP_CLAUDE_BIN, вместо того чтобы молча
исказить его.
Разрешительный список окружения. Windows сохраняет гораздо больший набор, чем POSIX.
SystemRoot и windir не являются необязательными — удалите их, и Winsock не сможет
инициализироваться, так что дочерний процесс вообще не сможет открыть сокет.
Отмена. Дочерние процессы POSIX порождаются detached как лидеры групп процессов
и отменяются через process.kill(-pid); Windows использует taskkill /T /F.
Модель безопасности
Изоляция учётных данных — это суть. Окружение дочернего процесса строится с нуля,
а не наследуется, и переменные провайдера удаляются до применения значений OpenRouter.
test/env-unit.mjs проверяет, что ключ достигает дочернего процесса ровно в одной
переменной и что ни один родительский секрет не выживает;
test/e2e.mjs отравляет родителя поддельным ANTHROPIC_API_KEY и настоящим
ANTHROPIC_BASE_URL=https://api.anthropic.com и подтверждает, что делегат не видит
ни того, ни другого.
Ключ никогда не читается через инструмент. Каждый диагностический путь маскирует его, и
test/readonly.mjs проверяет, что ни вывод инструментов, ни вывод CLI не содержат ключ.
Здесь это важнее, чем в родственном проекте для Ollama, где токен — это буквальная
строка ollama.
Политика делегирования не доступна для записи модели. Нет MCP-инструмента для изменения
delegationMode, allowedModels или ключа API. Модель, которой неудобен режим ondemand,
не может переключить себя на auto и начать тратить. Настройки загружаются один раз
при запуске, никогда не изменяются во время выполнения, и в описаниях инструментов указано,
что политика не входит в полномочия модели.
Это ограждение, а не граница безопасности. Агент с доступом к оболочке может
по-прежнему редактировать файл конфигурации. Что даёт удаление инструмента — так это то, что такое
изменение становится видимым редактированием файла, которое вступает в силу только при следующем
перезапуске, а не одним тихим вызовом инструмента посреди задачи. Чтобы сделать это
герметичным, закрепите значения через --env при регистрации MCP, что переопределяет файлы
конфигурации:
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.jsРасходы реальны. Вышедший из-под контроля оркестратор в режиме auto тратит ваши кредиты, а не
ваше терпение. Установите лимит ключа OpenRouter на ключе, который вы даёте этому серверу —
это потолок, с которым модель не может спорить.
Делегаты наследуют вашу файловую систему. Они работают от вашего имени пользователя в cwd,
который вы им даёте, с defaultPermissionMode. Относитесь к делегированной сессии так же, как
к любой сессии Claude Code — используйте disallowed_tools или режим разрешений «только чтение»,
когда поручаете работу модели, которой доверяете меньше.
Разработка
npm install # installs and builds
npm run build # tsc
npm run dev # tsc --watchТесты
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 запускает четыре теста, которым не нужна сеть. Они проходят как в Windows, так и в POSIX — тест дерева процессов строит своё дерево из процессов node, а не из встроенных команд оболочки, поэтому он не привязан только к POSIX.
Публикация релиза
npm login # interactive, once per machine
npm version patch # or minor / major -- tags and bumps
npm publish # prepare script builds first
git push --follow-tagsЗапускайте npm publish из настоящего терминала, а не из скрипта или неинтерактивной оболочки. При 2FA через WebAuthn/security-ключ CLI проходит проверку, открывая браузер; без TTY он не может этого сделать и вместо этого требует TOTP-код, который security-ключ не может сгенерировать (npm error code EOTP). Для CI вместо этого используйте гранулярный токен доступа с правом Bypass 2FA.
Пакет поставляется только с dist/, README.md и LICENSE. publishConfig.access имеет значение public, а prepare запускает tsc перед упаковкой, поэтому устаревший dist/ никогда не будет опубликован.
Структура
Файл | Назначение |
| MCP-сервер, регистрация инструментов и обработчики |
| Многоуровневая загрузка конфигурации, определение API-ключа, маскирование |
| Синглтон настроек, определяемых при запуске |
| Описания инструментов в зависимости от режима, предупреждения о стоимости |
| Формирование окружения дочерних процессов и блок-список переменных провайдера |
| Запуск в Windows/POSIX, экранирование аргументов, завершение дерева процессов |
| Жизненный цикл задач, разбор |
| Каталог, ценообразование, контроль поддержки инструментов, биллинговые запросы |
| CLI настроек |
Лицензия
MIT — см. LICENSE.
Available Tools
7 toolsdelegate_cancelCancel a delegated taskA
Terminate a running delegated session and everything it started. Also stops it spending any more of the user's OpenRouter credits.
| Name | Required | Description | Default |
|---|---|---|---|
| job_id | Yes | The job_id to cancel. |
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 discloses that the tool terminates 'everything it started' and stops spending credits, which are important behavioral consequences. However, it doesn't mention whether the cancellation is reversible or what happens to already-completed results.
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 two sentences, front-loaded with the primary action, and includes a key secondary effect (credit spending). 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?
Given the tool's simplicity (one parameter, no output schema, no annotations), the description is fairly complete. It covers the main action and a critical side effect. It could mention that the job must be running, but that's implied by 'running delegated session'.
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?
The schema description coverage is 100% for the single parameter 'job_id', which is self-explanatory. The description adds no extra meaning beyond the schema, but since the schema already fully documents the parameter, a baseline of 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 the tool's purpose: 'Terminate a running delegated session and everything it started.' It uses a specific verb ('Terminate') and resource ('running delegated session'), and distinguishes it from siblings like delegate_start and delegate_status by focusing on cancellation.
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 implies when to use it (when a delegated session is running and needs to be stopped), but does not explicitly mention alternatives or when not to use it. It also doesn't clarify that it's for running sessions only, which could be inferred but not stated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
delegate_followupContinue a delegated conversationA
Send another message to an existing delegated session, resuming its full conversation history. Identify it by job_id (any turn) or session_id. Returns a new job_id for this turn while keeping the same session_id, so you can go back and forth with the delegate.
Note that resuming replays the whole conversation as input tokens, so a long thread costs more per turn than a fresh one -- but still far less than re-establishing the same context from scratch.
Only continue conversations the user asked you to start.
| Name | Required | Description | Default |
|---|---|---|---|
| job_id | No | A job_id from any earlier turn of the conversation. | |
| prompt | No | The next message. Use prompt_file for long prompts. | |
| max_turns | No | Cap the delegate's agentic turns for this turn. | |
| session_id | No | The Claude Code session id, as an alternative to job_id. | |
| prompt_file | No | Path to a file holding the next message. | |
| wait_seconds | No | Block up to this many seconds before returning. | |
| permission_mode | No | Override the permission mode for this turn. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Without annotations, the description carries the burden. It discloses that resuming replays the whole conversation as input tokens and notes cost implications, and clearly states that a new job_id is returned while session_id stays constant. This is transparent behavioral info beyond the basic function.
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 concise: a few sentences, front-loaded with the main purpose and identification methods. Every sentence adds value (usage guidance, cost note, return behavior). No fluff.
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 tool has 7 params, no required, no output schema, no annotations. The description covers the key behaviors (return values, cost, when to use). It doesn't describe error cases or all parameter nuances, but it handles the most important aspects. Slightly better than average for a delegation tool.
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%, so baseline is 3. The description adds value by explaining how job_id vs session_id identify the session (any turn or session_id), and advises using prompt_file for long prompts讷. It also implies that wait_seconds and permission_mode are per-turn overrides, though not explicit. Slightly above baseline.
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's purpose: 'Send another message to an existing delegated session, resuming its full conversation history.' It uses a specific verb (send) and resource (delegated session), and differentiates from siblings like delegate_start by focusing on continuation rather than initiation.
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 explicitly states when to use it: 'Send another message to an existing delegated session' and 'Only continue conversations the user asked you to start,' which sets a clear usage boundary. It also explains the alternative of starting fresh (and cost trade-offs), and mentions using prompt_file for long prompts, giving practical guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
delegate_listList delegated tasksA
Show delegated jobs from this server's lifetime, newest first, grouped by conversation, with the estimated total spend.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Maximum jobs to list. Default 20. | |
| state | No | Filter by state. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of behavioral disclosure. It transparently mentions key behaviors: shows jobs from the server's lifetime (all historical jobs), orders newest first, groups by conversation, and includes estimated total spend. This goes beyond a generic 'list' by specifying output structure and a calculated metric, providing useful expectations for the agent.
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?
Single, information-dense sentence that covers purpose, ordering, grouping, and an output summary metric. No wasted words; it front-loads the primary function and key behavioral details.
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 tool is a simple list operation with two optional parameters well-described in the schema. The description adds value by specifying sort order, grouping, and the spend estimate, which are not in the schema. It lacks information about pagination or default limits, but the schema covers the limit parameter. Overall, sufficient for the tool's simplicity.
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?
The schema has 100% coverage with descriptions for both `limit` and `state`. The description itself does not add meaning beyond what the schema provides; the mention of filtering by state is implied by the parameter but not elaborated. Since coverage is complete, the baseline is 3.
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's purpose: to show delegated jobs from the server's lifetime, with specific ordering (newest first), grouping (by conversation), and a summary metric (estimated total spend). It uses an action verb ('show') and a resource ('delegated jobs'), and the scope is well-defined, distinguishing it from action-oriented siblings like delegate_start or delegate_cancel.
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 conveys that this is a list operation for delegated jobs, which differentiates it from the action-oriented siblings (start, followup, status, result, cancel). However, it does not explicitly state when to use this tool instead of others, such as delegate_status for checking a single job's status, or mention any preconditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
delegate_resultGet a delegated task's outputA
Return the final text produced by a delegated session, with its token usage, estimated cost and session_id for follow-ups. Blocks until the job finishes if you pass wait_seconds.
| Name | Required | Description | Default |
|---|---|---|---|
| job_id | Yes | The job_id to collect. | |
| wait_seconds | No | Block up to this many seconds for the job to finish. |
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 explicitly discloses the blocking behavior with wait_seconds and details what is returned (text, token usage, cost, session_id). However, it does not state whether the operation is read-only or what happens if the job is not finished when wait_seconds is not passed, leaving minor behavioral gaps.
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 two short, dense sentences. The first states the core functionality and return fields, and the second provides the critical blocking behavior. No waste, information is front-loaded, and it is easy to scan.
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 simple two-parameter tool without an output schema, the description covers the essentials: what it returns, the optional blocking behavior, and follow-up information. It does not address failure scenarios or the result when the job is incomplete without wait_seconds, but these are minor gaps given the tool's simplicity.
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 the schema already fully documents job_id and wait_seconds. The description does not add any extra meaning to the parameters beyond what the schema provides, so the 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 specifies that the tool returns the final text of a delegated session along with token usage, cost, and session ID. It distinguishes itself from siblings like delegate_status (status checks) and delegate_followup (continuations) by focusing on retrieving the completed output, making its purpose unambiguous.
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 implies when to use it (when you need the final output) and mentions blocking with wait_seconds, but does not explicitly contrast it with alternatives like delegate_status or delegate_followup, nor does it state when not to use it. This is clear context without exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
delegate_startDelegate a task to an OpenRouter modelA
Start a headless Claude Code session backed by an OpenRouter model and return immediately with a job_id. It runs in its own process with its own environment, so your Anthropic credentials and model settings are untouched. Poll with delegate_status, collect with delegate_result, and continue the conversation with delegate_followup. Pass prompt_file for long prompts.
Default: deepseek/deepseek-v4-flash-0731.
WHEN TO USE -- ON EXPLICIT REQUEST ONLY. Delegation mode is "ondemand". Call this only when the user actually asks for it: "delegate this", "use openrouter", "ask gemini", "run this on a cheaper model", or when they name an OpenRouter model. If the user has not asked for delegation, do the work yourself and do not offer this tool unprompted.
COSTS REAL MONEY. Each delegated turn is billed to the user's OpenRouter credits, and every request carries Claude Code's full system prompt and tool schema (tens of thousands of input tokens), so even a short task is not free. Do not delegate speculatively, do not retry a failed delegation repeatedly without changing something, and prefer one well-specified task over several exploratory ones. Reported costs are estimates from list prices; the authoritative figure is on openrouter.ai/activity.
This policy is set by the user and is not yours to change. If it is getting in the way, say so and let the user run openrouter-mcp-config; do not edit config files to widen it.
| Name | Required | Description | Default |
|---|---|---|---|
| cwd | No | Working directory for the delegated session. Defaults to the server's cwd. | |
| model | No | OpenRouter model id, e.g. "google/gemini-2.5-flash". Must be in the allowed list. | |
| prompt | No | The task for the delegated session. Use prompt_file for long prompts. | |
| add_dirs | No | Additional directories the delegate may access. | |
| max_turns | No | Cap the delegate's agentic turns. Each turn is billed, so this is also a cost cap. | |
| prompt_file | No | Path to a file holding the prompt. Preferred for long or special-character-heavy prompts. | |
| small_model | No | Model for the delegate's background/small-model slot. Defaults to the configured one. | |
| wait_seconds | No | Block up to this many seconds for completion. Default 0. | |
| allowed_tools | No | Tool allowlist, e.g. ['Read','Grep','Bash(git *)']. | |
| permission_mode | No | Permission mode for the delegate. Defaults to the configured default. | |
| disallowed_tools | No | Tool denylist, e.g. ['Write','Edit']. | |
| append_system_prompt | No | Extra instructions appended to the delegate's system prompt. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Although no annotations are provided, the description discloses that it runs in its own process, doesn't touch Anthropic credentials, and prominently warns 'COSTS REAL MONEY' with billing details and token usage. It also notes the async nature (return immediately).
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?
Well-structured with clear sections (purpose, behavior, when-to-use, cost, policy). Though somewhat verbose, each sentence adds value—warnings about cost and usage are important.
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?
Covers async behavior, cost implications, policy, and references sibling tools (delegate_status, delegate_result). Given the complexity of delegation (cost, permissions, background process), this description is complete enough for an agent to act.
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 covers all 12 parameters with descriptions (100% coverage). The description adds minimal extra beyond schema, e.g., 'Pass `prompt_file` for long prompts' which is already implied. Baseline of 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?
Clearly states 'Start a headless Claude Code session backed by an OpenRouter model and return immediately with a job_id.' It distinguishes from sibling tools by outlining the delegation flow (status, result, followup).
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 specifies when to use: 'ON EXPLICIT REQUEST ONLY' with concrete examples. Also states 'If the user has not asked for delegation, do the work yourself and do not offer this tool unprompted.' Provides clear alternatives and cost warnings.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
delegate_statusCheck a delegated taskA
Report whether a delegated job is still running, plus a tail of what the session has been doing -- its actual tool calls and partial text. Optionally block until it finishes. Use the tool-call trace to check that a delegate really did the work it claims.
| Name | Required | Description | Default |
|---|---|---|---|
| job_id | Yes | The job_id returned by delegate_start or delegate_followup. | |
| wait_seconds | No | Block up to this many seconds waiting for completion. | |
| progress_limit | No | How many recent activity lines to show. Default 15. |
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 discloses the reporting behavior (status, tail, blocking) and a verification use case. However, it doesn't state whether checking status has side effects (e.g., marks job as read), how errors are handled, or the return format. It adds useful context but is not exhaustive.
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 two sentences, front-loaded with the primary purpose, and contains no redundant or vague wording. It efficiently communicates the tool's function and a key use case.
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 status tool with 3 parameters and no output schema, the description covers the essential aspects: status reporting, activity tail, optional blocking, and verification usage. It doesn't detail the return structure, but the description's 'report whether... plus a tail' gives a sufficient mental model. The lack of an explicit non-destructive note is a minor gap.
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 the baseline is 3. The description's references to blocking and tail map to wait_seconds and progress_limit, but the schema already describes these parameters clearly. No additional meaning is added beyond 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 the tool reports whether a delegated job is still running, provides a tail of tool calls and partial text, and optionally blocks. This distinguishes it from siblings like delegate_result (fetching final result) and delegate_start/delegate_followup/delegate_cancel/delegate_list. Specific verb+resource with unique features.
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 gives a concrete use case: 'Use the tool-call trace to check that a delegate really did the work it claims.' This implies when to use this tool (status/trace verification) and communicates its value over siblings. It doesn't explicitly exclude alternatives or state when not to use, but provides clear context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
openrouter_modelsList OpenRouter modelsA
List OpenRouter models available for delegation with their prices and context windows, plus the current delegation policy, credit balance, and the environment a delegated session receives. OpenRouter serves several hundred models, so results are filtered to tool-capable ones and truncated -- pass filter to search by name and limit to see more. Use this to pick a model, to check the balance before delegating, or to report the configuration when the user asks about it.
These settings are user-controlled. There is no tool to change them: if the user wants a different delegation mode, model policy, or API key, tell them to run openrouter-mcp-config in a terminal and restart the session. Do not edit the config files yourself.
Default: deepseek/deepseek-v4-flash-0731.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Maximum models to list. Default 30. | |
| filter | No | Case-insensitive substring match on model id or name, e.g. "gemini" or "qwen". | |
| free_only | No | Only models that cost nothing. | |
| tools_only | No | Only models that support tool calling. Default true; Claude Code needs it. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden and does so well. It discloses that results are 'filtered to tool-capable ones and truncated,' that filtering is by default active (tools_only), the default model value, and that these settings are user-controlled with no tool to change them, including a 'do not edit config files' safety instruction.
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?
Three compact paragraphs, each earning its place: purpose/result orientation, usage guidance with alternatives, and the default model. Front-loaded with the core listing purpose, with no fluff or repetition of schema content.
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?
Despite having no output schema, the description explicitly states what the response contains (prices, context windows, delegation policy, credit balance, environment). It also covers filtering/truncation behavior, parameter hints, defaults, and the limitation that settings cannot be changed via this tool. This is complete for a listing tool.
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%, so the baseline is 3. The description adds value beyond the schema by explaining parameter intent: 'pass `filter` to search by name and `limit` to see more,' and clarifies the default filtering behavior relevant to tools_only. free_only is not mentioned in the description, but the schema already documents it fully.
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?
Description opens with a specific verb+resource: 'List OpenRouter models available for delegation with their prices and context windows, plus the current delegation policy, credit balance, and the environment a delegated session receives.' It goes beyond a simple name by defining scope (delegation) and the exact data returned. It also clearly distinguishes itself from the sibling delegate_* tools as a read-only listing tool.
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?
Explicit usage guidance is provided: 'Use this to pick a `model`, to check the balance before delegating, or to report the configuration when the user asks about it.' It also gives when-not-to-use and an alternative action: if the user wants config changes, 'tell them to run `openrouter-mcp-config` in a terminal and restart the session. Do not edit the config files yourself.'
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
7 tool updates
v1.0.0- First observed
delegate_cancel - First observed
delegate_followup - First observed
delegate_list - First observed
delegate_result - First observed
delegate_start - First observed
delegate_status - First observed
openrouter_models
TDQS
Scored across 7 tools
Each tool maps to a distinct stage or aspect of the delegation lifecycle: models/config discovery, start, follow-up, status, final result, cancel, and list. The only superficially similar pair (delegate_status vs delegate_result) is clearly separated by monitoring vs collecting final output.
Six of seven tools share the clean delegate_ prefix with a readable action, making the lifecycle easy to scan. Minor deviation: delegate_status, delegate_result, and delegate_followup use nouns rather than verbs, and openrouter_models breaks the prefix pattern.
Seven tools is well-scoped for a delegation server: one discovery/config tool plus six lifecycle operations. Each tool covers a necessary step without redundancy or bloat.
The delegation workflow is fully covered: inspect models/config, start, monitor, collect, resume, cancel, and list jobs. Deliberately missing config-editing tools are documented as user-controlled via a separate CLI, so there are no dead ends for the stated purpose.
Maintenance
Related MCP Connectors
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.
Work on your own computers from Claude or ChatGPT: run commands, edit and search files.
AI routing, memory, guardrails, and governance. Routes across Claude, GPT, Gemini.
Agent personas for Claude. 16 tools, 13 personas, 3 workflows. Zero extra API cost. Free.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables Claude Code to delegate tasks to free OpenRouter models as callable tools while keeping the Anthropic endpoint for the orchestrator, with optional sandboxed file and shell access.MIT
- AlicenseNot gradedqualityBmaintenanceEnables Claude to invoke third-party models from OpenRouter as tools mid-conversation, including sticky multi-model chat history and model discovery.6 npmMIT
- AlicenseNot gradedqualityCmaintenanceEnables Claude Code and Claude Desktop to delegate coding tasks to any model available in OpenCode while Claude remains the orchestrator, planning work, reviewing diffs, and running tests. Supports synchronous and async delegation, model selection, session continuation, and permission-aware execution.5MIT
- AlicenseAqualityBmaintenanceEnables Claude Code to offload bulk tasks to cheap OpenRouter worker models via tiered model selection, parallel batch execution, daily budget caps, and cost logging.3MIT