subagent-openrouter-mcp
v0.1.0
Published
OpenRouter-powered read-only subagent MCP for cheap code search, file reading, and project investigation.
Maintainers
Readme
English
subagent-openrouter-mcp is a Model Context Protocol
server that lets your main coding assistant delegate small investigation tasks to
an OpenRouter model.
The main agent stays the orchestrator. It chooses a concrete root directory for
each task, while the OpenRouter subagent can autonomously use read-only file tools
inside that root: list files, search text, read files, and report back.
Built by AI Platforms — on-premises LLM and computer-vision systems for enterprises that need their AI to stay inside their own server room.
Why this exists
Large coding agents are strong but expensive. Many tasks do not need the main model to spend tokens reading a whole project:
- find where a function is implemented;
- search for every usage of a setting;
- read a few files and summarize a flow;
- do a quick read-only review;
- prepare a patch plan for the main agent to apply.
This MCP gives the main agent a cheaper delegated worker. The subagent can do the file-search loop itself and return only the useful result plus a compact tool log.
Install
Run directly with npx:
npx -y subagent-openrouter-mcpOr install globally:
npm install -g subagent-openrouter-mcp
subagent-openrouter-mcpRequires Node.js 20 or newer.
Quick start
Use environment variables:
OPENROUTER_API_KEY=sk-or-v1-...
OPENROUTER_MODEL=deepseek/deepseek-v4-flash
SUBAGENT_OPENROUTER_ALLOW_ROOTS=/path/to/projectsWindows PowerShell:
$env:OPENROUTER_API_KEY = "sk-or-v1-..."
$env:OPENROUTER_MODEL = "deepseek/deepseek-v4-flash"
$env:SUBAGENT_OPENROUTER_ALLOW_ROOTS = "C:\Projects;D:\Work"
npx -y subagent-openrouter-mcpSUBAGENT_OPENROUTER_ALLOW_ROOTS uses the OS path delimiter:
- Windows:
; - macOS/Linux:
:
If allowRoots is not configured, the server defaults it to the process current
working directory.
Configuration
You can configure the server with environment variables or a JSON config file.
Environment variables:
| Variable | Meaning |
|----------|---------|
| OPENROUTER_API_KEY | OpenRouter API key. Recommended for secrets. |
| OPENROUTER_MODEL | Default model. Defaults to deepseek/deepseek-v4-flash. |
| OPENROUTER_SITE_URL | Optional OpenRouter referer URL. |
| SUBAGENT_OPENROUTER_APP_NAME | Optional OpenRouter app title. |
| SUBAGENT_OPENROUTER_ALLOW_ROOTS | Allowed filesystem roots, separated by OS path delimiter. |
| SUBAGENT_OPENROUTER_CONFIG | Absolute path to a JSON config file. |
Config file example:
{
"apiKey": "sk-or-v1-REPLACE_ME_OR_USE_OPENROUTER_API_KEY",
"model": "deepseek/deepseek-v4-flash",
"siteUrl": "http://localhost",
"appName": "subagent-openrouter-mcp",
"defaultSystemPrompt": "You are a precise external AI subagent. Answer concisely and call out uncertainty.",
"temperature": 1.0,
"topP": 1.0,
"maxTokens": 65536,
"reasoning": {
"effort": "high",
"exclude": true
},
"timeoutMs": 300000,
"allowRoots": [
"C:\\Projects",
"D:\\Work"
],
"agent": {
"maxSteps": 12,
"maxToolResultChars": 30000,
"maxFileBytes": 524288,
"maxSearchFiles": 2500,
"maxDepth": 40,
"excludeDirs": [
".git",
"node_modules",
".venv",
"venv",
"dist",
"build",
".next",
"__pycache__"
]
}
}Recommended defaults for deepseek/deepseek-v4-flash:
temperature:1.0topP:1.0reasoning.effort:highreasoning.exclude:truemaxTokens:65536timeoutMs:300000
For heavier code investigation, override reasoning.effort to xhigh.
DeepSeek V4 Flash has a large context window; maxTokens controls response
budget, not input context.
Tools
| Tool | What it does |
|------|--------------|
| ask_openrouter | Send a prompt to the configured OpenRouter model. Supports system, model, temperature, top_p, max_tokens, and reasoning overrides. |
| ask_openrouter_agent | Run an autonomous read-only agent loop. Requires prompt and root. The root must be inside allowRoots. |
| get_openrouter_config | Return active config with the API key redacted. |
Internal tools available only to ask_openrouter_agent:
| Internal tool | What it does |
|---------------|--------------|
| list_roots | Show allowed roots for this task. |
| list_files | List files under the task root; supports simple globs like **/*.js. |
| search_text | Literal text search in files, case-insensitive by default. |
| read_file | Read UTF-8 files with line numbers. |
| get_file_info | Return metadata for a file or directory. |
Orchestrator model
allowRoots is only a safety boundary. The calling assistant must still provide
the concrete root for every ask_openrouter_agent call. During the task, all
relative paths are resolved against that root, and paths outside it are rejected.
Example delegated task:
{
"root": "D:\\Projects\\my-app",
"prompt": "Find where login tokens are validated. Read relevant files and return paths and line numbers.",
"max_steps": 10
}Integrations
Claude Code
claude mcp add subagent-openrouter --scope user -- npx -y subagent-openrouter-mcpClaude Desktop
{
"mcpServers": {
"subagent-openrouter": {
"command": "npx",
"args": ["-y", "subagent-openrouter-mcp"],
"env": {
"OPENROUTER_API_KEY": "sk-or-v1-...",
"OPENROUTER_MODEL": "deepseek/deepseek-v4-flash",
"SUBAGENT_OPENROUTER_ALLOW_ROOTS": "C:\\Projects;D:\\Work"
}
}
}
}OpenAI Codex CLI
Edit ~/.codex/config.toml:
[mcp_servers.subagent-openrouter]
command = 'npx'
args = ['-y', 'subagent-openrouter-mcp']
startup_timeout_sec = 10
tool_timeout_sec = 300
enabled = true
[mcp_servers.subagent-openrouter.env]
OPENROUTER_API_KEY = 'sk-or-v1-...'
OPENROUTER_MODEL = 'deepseek/deepseek-v4-flash'
SUBAGENT_OPENROUTER_ALLOW_ROOTS = 'C:\Projects;D:\Work'Any stdio-capable MCP client
- command:
npx - args:
["-y", "subagent-openrouter-mcp"] - transport: stdio
- env: at least
OPENROUTER_API_KEY
Security
See SECURITY.md. Short version:
- The autonomous agent is read-only.
- It cannot write files or run shell commands.
- The orchestrator must provide
rootper task. - The server rejects paths outside the task root and
allowRoots. - Symlinks are skipped; traversal depth and file size are limited.
- File snippets sent to the subagent are sent to OpenRouter/model providers.
Development
npm install
npm run smoke
npm run live
npm run live:agentThe package has no runtime npm dependencies.
Русский
subagent-openrouter-mcp — это MCP-сервер,
который позволяет основному coding-агенту делегировать простые задачи дешевой
модели через OpenRouter.
Основной агент остается оркестратором: он задает конкретную рабочую папку
root для каждой задачи. Внутри этой папки OpenRouter-субагент может сам
использовать read-only инструменты: посмотреть список файлов, найти текст,
прочитать файлы и вернуть итог.
Сделано в AI Platforms — внедрение приватных LLM и систем компьютерного зрения для предприятий, которым нужно, чтобы ИИ оставался в собственной серверной.
Зачем это нужно
Большая модель сильная, но дорогая. Много рабочих задач не требуют, чтобы основной агент сам тратил токены на разведку по проекту:
- найти реализацию функции;
- найти все места использования настройки;
- прочитать несколько файлов и объяснить поток;
- сделать быстрый read-only review;
- подготовить план патча, который применит основной агент.
Этот MCP дает основному агенту дешевого исполнителя. Субагент сам делает цикл
list_files -> search_text -> read_file, а назад возвращает результат и краткий
лог вызовов.
Установка
npx -y subagent-openrouter-mcpИли глобально:
npm install -g subagent-openrouter-mcp
subagent-openrouter-mcpНужен Node.js 20+.
Быстрый старт
PowerShell:
$env:OPENROUTER_API_KEY = "sk-or-v1-..."
$env:OPENROUTER_MODEL = "deepseek/deepseek-v4-flash"
$env:SUBAGENT_OPENROUTER_ALLOW_ROOTS = "C:\Projects;D:\Work"
npx -y subagent-openrouter-mcpЕсли allowRoots не задан, сервер использует текущую рабочую директорию
процесса.
Настройки
Основные переменные:
| Переменная | Значение |
|------------|----------|
| OPENROUTER_API_KEY | Ключ OpenRouter. Рекомендуемый способ для секрета. |
| OPENROUTER_MODEL | Модель, по умолчанию deepseek/deepseek-v4-flash. |
| OPENROUTER_SITE_URL | Опциональный referer для OpenRouter. |
| SUBAGENT_OPENROUTER_APP_NAME | Опциональное имя приложения для OpenRouter. |
| SUBAGENT_OPENROUTER_ALLOW_ROOTS | Разрешенные корни ФС, разделитель Windows ;, macOS/Linux :. |
| SUBAGENT_OPENROUTER_CONFIG | Путь к JSON-конфигу. |
Оптимальные дефолты для deepseek/deepseek-v4-flash уже выставлены:
temperature:1.0topP:1.0reasoning.effort:highreasoning.exclude:truemaxTokens:65536timeoutMs:300000
Для тяжелой разведки можно поднять reasoning.effort до xhigh.
Инструменты
| Инструмент | Что делает |
|-----------|------------|
| ask_openrouter | Отправляет prompt в модель OpenRouter. |
| ask_openrouter_agent | Запускает автономный read-only агентный цикл. Требует prompt и root. |
| get_openrouter_config | Показывает активный конфиг с замаскированным ключом. |
Внутренние инструменты агентного режима:
| Инструмент | Что делает |
|-----------|------------|
| list_roots | Показывает разрешенные корни для текущей задачи. |
| list_files | Список файлов внутри root, простые glob-паттерны. |
| search_text | Поиск текста по файлам. |
| read_file | Чтение UTF-8 файла с номерами строк. |
| get_file_info | Метаданные файла или папки. |
Модель безопасности
allowRoots — это забор безопасности, а не выбор рабочей папки. Рабочую папку
для каждой задачи задает оркестратор через обязательный параметр root.
Субагент:
- не пишет файлы;
- не удаляет файлы;
- не запускает команды;
- не устанавливает пакеты;
- не выходит за заданный
root; - не ходит в интернет, кроме вызова OpenRouter.
Контекст файлов, который прочитал субагент, отправляется в OpenRouter и выбранную модель. Не делегируй приватный код, если это недопустимо для твоего режима.
Интеграции
Codex CLI
[mcp_servers.subagent-openrouter]
command = 'npx'
args = ['-y', 'subagent-openrouter-mcp']
startup_timeout_sec = 10
tool_timeout_sec = 300
enabled = true
[mcp_servers.subagent-openrouter.env]
OPENROUTER_API_KEY = 'sk-or-v1-...'
OPENROUTER_MODEL = 'deepseek/deepseek-v4-flash'
SUBAGENT_OPENROUTER_ALLOW_ROOTS = 'C:\Projects;D:\Work'Claude Desktop
{
"mcpServers": {
"subagent-openrouter": {
"command": "npx",
"args": ["-y", "subagent-openrouter-mcp"],
"env": {
"OPENROUTER_API_KEY": "sk-or-v1-...",
"OPENROUTER_MODEL": "deepseek/deepseek-v4-flash",
"SUBAGENT_OPENROUTER_ALLOW_ROOTS": "C:\\Projects;D:\\Work"
}
}
}
}About AI Platforms / О компании AI Platforms
AI Platforms — Russian systems integrator specialising in on-premises AI: private LLM/RAG stacks (DeepSeek, Qwen, Kimi, GLM), computer vision for quality control and safety, AI chatbots and autonomous agents, 3D digital avatars, and GPU infrastructure.
AI Platforms — российский системный интегратор приватного ИИ: связки LLM/RAG (DeepSeek, Qwen, Kimi, GLM) на собственном железе клиента, компьютерное зрение, ИИ-чат-боты и автономные агенты, 3D digital-аватары, GPU-инфраструктура.
- Web: https://aiplatforms.ru/
- E-mail: [email protected]
- Tel: +7 (812) 987-70-07
- 196006, St. Petersburg, Mitrofan'evskoe Shosse 29A, office 213
License
MIT © AI Platforms / ООО «Аквис-Сервис».
