opencode-v2-mcp
This server lets any MCP client (Claude Code, Codex CLI, Cursor-agent, etc.) delegate one bounded coding task at a time to a local OpenCode v2 instance and receive a compact execution report.
Run a single coding task via
opencode_execute, specifying the working directory and a detailed task description.Optionally choose the OpenCode agent (
agent, defaultclaude-worker) and model (model, e.g.openai/gpt-5.5).Continue an existing OpenCode session with
sessionId, or resume the last session withcontinueSession.Set an internal timeout (
timeoutMs, up to 1 hour) and optionally use OpenCode's private standalone server mode (standalone).Get back the model's final text,
git diff --stat,git status --short, exit code, session ID, and error tail for verification.Integrates with Claude Code via
claude mcp add, Codex CLI viacodex mcp add, and Cursor-agent viamcp.json.Supports proxy environment variables for cloud model access, and is designed to work around known OpenCode v2 CLI/ecosystem issues.
Click on "Deploy 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., "@opencode-v2-mcpFix the failing unit tests in the auth service"
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.
opencode-v2-mcp
MCP-сервер, который позволяет Claude Code, Codex CLI, Cursor-agent (или
любому другому MCP-клиенту) делегировать выполнение ограниченных задач по
написанию кода локальному OpenCode v2.x. Один
инструмент — opencode_execute — запускает opencode run --format json,
парсит NDJSON-вывод и возвращает компактный отчёт: текст ответа,
git diff --stat, git status --short, код возврата и sessionID.
Сервер реализован через стандартный @modelcontextprotocol/sdk
(stdio-транспорт) — он не завязан на конкретного клиента и работает
одинаково с любым MCP-совместимым хостом без каких-либо доработок кода.
Подключение к Claude Code, Codex CLI и Cursor-agent подтверждено вживую
(разделы ниже).
Написан по мотивам референсной реализации из community-инструкции
«Claude Code Desktop → OpenCode v2 как субагент-исполнитель кода» и
доработан тремя фиксами, без которых обёртка не работает с реальной
установкой opencode v2.0.12 (подробности — раздел «Известные баги
экосистемы» ниже).
Полная история разработки, диагностики и сравнения с другими community
MCP-обёртками (все они не работают против opencode v2.x по разным
причинам) — в second-brain/opencode-subagent-mcp.md (личная заметка,
не публикуется).
Требования
OpenCode v2.x, установленный и доступный в
PATH(opencode --versionдолжен показывать2.x).Node.js 18+.
Настроенный провайдер/модель в OpenCode (
opencode auth login,opencode auth list).Проект, где будет выполняться
opencode_execute, должен содержатьopencode.jsonс JSON-блокомagent(см. ниже — markdown-агенты.opencode/agent/*.mdв этой версии зависают).
Related MCP server: opencode-mcp-bridge
Установка
Вариант 1 — из npm (npmjs.org, рекомендуется)
Пакет опубликован как opencode2-mcp
— полностью публичный, ставится без авторизации:
npm install -g opencode2-mcpВариант 2 — из исходников
git clone git@github.com:yuriisamohvalov-creator/opencode-mcp.git ~/tools/opencode-mcp
cd ~/tools/opencode-mcp
npm installВариант 3 — из GitHub Packages
Тот же пакет также зеркалирован в GitHub Packages под именем
@yuriisamohvalov-creator/opencode-v2-mcp.
Важно: в отличие от npmjs.org, GitHub Packages требует аутентификации
даже для публичных пакетов — понадобится .npmrc со scoped-registry и
GitHub-токеном с правом read:packages:
# ~/.npmrc или в проекте
echo "@yuriisamohvalov-creator:registry=https://npm.pkg.github.com" >> ~/.npmrc
npm login --registry=https://npm.pkg.github.com --scope=@yuriisamohvalov-creator
npm install -g @yuriisamohvalov-creator/opencode-v2-mcpПодключение к Claude Code
NODE_BIN="$(which node)"
claude mcp add --scope user opencode-v2 -- "$NODE_BIN" "$HOME/tools/opencode-mcp/server.mjs"Если для выхода в интернет (облачные провайдеры моделей) нужен прокси —
передайте его переменными окружения при регистрации, они наследуются
дочерним процессом opencode:
claude mcp add --scope user opencode-v2 \
-e HTTPS_PROXY=http://127.0.0.1:10808 -e HTTP_PROXY=http://127.0.0.1:10808 \
-- "$NODE_BIN" "$HOME/tools/opencode-mcp/server.mjs"Проверка:
claude mcp get opencode-v2
# Status: ✔ ConnectedПосле подключения новой сессии Claude Code (или рестарта текущей)
инструмент opencode_execute доступен как mcp__opencode-v2__opencode_execute.
Подключение к Codex CLI
NODE_BIN="$(which node)"
codex mcp add opencode-v2 \
--env HTTPS_PROXY=http://127.0.0.1:10808 --env HTTP_PROXY=http://127.0.0.1:10808 \
-- "$NODE_BIN" "$HOME/tools/opencode-mcp/server.mjs"
codex mcp list # должен показать opencode-v2 в статусе enabledВажно: по умолчанию Codex блокирует вызовы MCP-инструментов approval-
политикой, даже если approval выставлен в never — это особенность
самого Codex, не обёртки. Запускайте с флагом --approve-for-me
(безопасный режим через workspace-write sandbox, не с
--dangerously-bypass-approvals-and-sandbox):
codex exec --approve-for-me "Use the opencode-v2 MCP tool opencode_execute with cwd=/path/to/project, agent=claude-worker, task='...'"Если запускаете codex exec вне git-репозитория — понадобится ещё
--skip-git-repo-check.
Подключение к Cursor-agent
Cursor не предоставляет CLI-команду для добавления MCP-сервера — правьте
конфиг-файл напрямую: ~/.cursor/mcp.json (глобально) или
.cursor/mcp.json в конкретном проекте. Формат идентичен Claude
Code/Codex:
{
"mcpServers": {
"opencode-v2": {
"command": "/absolute/path/to/node",
"args": ["/absolute/path/to/opencode-mcp/server.mjs"],
"env": {
"HTTPS_PROXY": "http://127.0.0.1:10808",
"HTTP_PROXY": "http://127.0.0.1:10808"
}
}
}
}После правки файла сервер нужно явно одобрить:
cursor-agent mcp list # должен показать opencode-v2
cursor-agent mcp enable opencode-v2Использование в неинтерактивном режиме:
cursor-agent -p --output-format json --force \
"Use the opencode-v2 MCP tool opencode_execute with cwd=/path/to/project, agent=claude-worker, task='...'"Первый вызов после добавления сервера обычно заметно медленнее
последующих (холодный старт сессии cursor, наблюдалось ~20с против
обычных 6–10с у прямого CLI-вызова opencode).
Конфигурация проекта — только JSON-агент
В корне проекта, где будет работать opencode_execute, создайте
opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"agent": {
"claude-worker": {
"description": "Implements a bounded coding task delegated by Claude Code",
"mode": "primary",
"prompt": "You are an implementation worker. Work only inside the current project. Make the smallest coherent change. Run relevant tests. Never commit, push, or delete broad paths. End with a concise summary."
}
}
}Не используйте markdown-файлы агентов (.opencode/agent/<name>.md) —
в установленной opencode v2.0.12 они приводят к зависанию opencode run
без единой строки вывода, воспроизведено многократно с разным содержимым
frontmatter. JSON-агент через opencode.json работает надёжно.
Использование инструмента
{
"task": "Add a slugify() helper in src/lib/slug.ts with tests. Acceptance: kebab-case, trims whitespace. Verify with `npm test -- slug`.",
"cwd": "/absolute/path/to/project",
"agent": "claude-worker",
"model": "openai/gpt-5.5", // опционально, provider/model
"timeoutMs": 900000 // опционально, по умолчанию 15 минут
}Ответ:
{
"ok": true,
"exitCode": 0,
"sessionID": "ses_...",
"text": "...финальный ответ модели...",
"diffStat": "...git diff --stat...",
"statusShort": "...git status --short..."
}Известные баги экосистемы, исправленные в этой обёртке
Референсная реализация, взятая за основу, не работала «из коробки» против
opencode v2.0.12. Три причины и фиксы:
Отсутствовал флаг
--auto. Без негоopencodeне может неинтерактивно подтверждать edit/shell-разрешения — добавлен вrunOpenCode()безусловно.spawn("opencode", ...)без абсолютного пути. GUI-приложения (включая Claude Code Desktop) не всегда наследуют пользовательскийPATH, где установленopencode— используется абсолютный путь к бинарнику. Проверьте и при необходимости поправьте путь вserver.mjs(spawn("/home/USER/.opencode/bin/opencode", ...)) под вашу установку —which opencodeподскажет актуальный путь.opencode v2резолвит текущий проект через переменную окружения$PWD, а не через реальныйcwdпроцесса.child_process.spawn()в Node корректно меняет OS-уровневыйcwdдочернего процесса, но НЕ обновляетPWDв егоenv— без явногоenv: { ...process.env, PWD: input.cwd }opencodeне находит определённого вopencode.jsonагента и падает с"Agent not found". Это не специфично для данной обёртки — баг актуален для любой Node/Bun-обёртки вокругopencode run, использующейspawn()сcwd.
Ограничения
Одна задача — один запуск
opencode run, без параллелизма в рамках одного вызова инструмента.Инструмент не проверяет
permission-конфигурацию OpenCode сам — если агент запрещает нужную команду,opencode runзавершится без изменений и с пустымtext; смотритеstderrTail/exitCodeв ответе.Не подменяет ревью: вызывающая сторона должна самостоятельно проверять
diffStat/statusShortи результаты тестов, а не доверять только полюok.
Смежные пакеты
Тот же синхронный паттерн (один блокирующий MCP-тул, без отдельного check/kill) применён и к двум другим шагам цепочки делегирования:
codex-cli-sync-mcp— аналогичная обёртка над Codex CLI (codex exec).cursor-agent-sync-mcp— аналогичная обёртка над Cursor-agent CLI (cursor-agent -p).
Лицензия
Available Tools
1 toolopencode_executeA
Execute one bounded coding task through OpenCode v2 and return a compact JSON report with diff/test context.
| Name | Required | Description | Default |
|---|---|---|---|
| cwd | Yes | Absolute working directory/repository root. | |
| task | Yes | Bounded coding task with goal, constraints, files, acceptance criteria, and verification command. | |
| agent | No | OpenCode v2 agent name, e.g. claude-worker or build. | claude-worker |
| model | No | Optional OpenCode provider/model, e.g. openai/gpt-5.5. | |
| sessionId | No | Continue a specific OpenCode session instead of starting a new one. | |
| timeoutMs | No | Internal OpenCode timeout; must be below Claude MCP per-server timeout. | |
| standalone | No | Use OpenCode private standalone server for this run. Default false uses normal v2 service behavior. | |
| continueSession | No | Continue last OpenCode session; ignored when sessionId is set. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, so the description carries the full burden. It does disclose the output behavior (returns diff/test context, implying filesystem changes), but omits consequential traits of an autonomous-agent tool: it can modify files in cwd, run shell commands and tests, and may run up to an hour by default. These risk-relevant behaviors are left to inference.
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?
A single front-loaded sentence that leads with the verb and resource and ends with the output contract. Zero filler, no repetition of schema contents, and every word earns its place.
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 schema thoroughly documents all 8 parameters and the description names the return format, which partly offsets the missing output schema. However, for a tool that launches an autonomous coding agent, the description lacks the behavioral context an agent needs: safety profile, failure semantics, repo-mutation expectations, and what the report actually contains.
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 of 3 applies; the description adds no parameter-level meaning beyond the schema. The schema itself documents all parameters well (e.g., timeoutMs must stay below the MCP per-server timeout, continueSession is ignored when sessionId is set), so no compensation is needed.
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 opens with a specific verb ('Execute') bound to a concrete resource ('one bounded coding task through OpenCode v2') and names the return contract ('compact JSON report with diff/test context'). With no sibling tools to confuse it with, an agent can immediately tell what this tool does.
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?
No siblings or alternatives are named, and the description never states when to prefer this tool, what kinds of tasks suit it, or when to avoid it. The only usage signal is the word 'bounded,' with the task parameter's schema hinting at scope, but this does not amount to explicit when/when-not guidance.
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.
1 tool update
v0.2.0- First observed
opencode_execute
TDQS
Scored across 1 tool
Only one tool exists, so there is no possibility of confusion or overlap. The tool's purpose is singular and clearly defined.
The single tool name 'opencode_execute' is clear and follows a verb_noun pattern, but with only one tool, there is no pattern to evaluate. It is consistent within itself, though limited.
With only a single tool, the server's surface is extremely thin. For a coding task execution server, one might expect at least a few operations (e.g., list tasks, cancel, etc.). This seems minimal and likely insufficient for robust use.
The single tool appears to cover only one narrow action (execute a coding task). There are no supporting tools for querying status, listing tasks, or managing results, leading to significant gaps in typical workflow coverage.
Maintenance
Related MCP Connectors
A paid remote MCP for OpenAI Codex agent coordination MCP, built to return verdicts, receipts, usage
A paid remote MCP for OpenAI Codex context compressor, built to return verdicts, receipts, usage log
No-data MCP handoff for local Claude Code to Codex harness moves. $49 lifetime.
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.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceEnables ISLI agents and MCP clients to dispatch natural-language coding and terminal tasks to a locally-installed Claude Code CLI, supporting both one-shot execution and persistent sessions with workspace and security controls.-
- AlicenseNot gradedqualityBmaintenanceExposes opencode's coding agent and shell as MCP tools, enabling MCP-only AI clients to execute shell commands, manage files, and run agent sessions with async job handling.6 npm1MIT
- AlicenseAqualityCmaintenanceEnables Codex to delegate coding tasks to an OpenCode CLI locally, returning structured results such as exit codes, session summaries, tool calls, and git diffs.2MIT
- FlicenseCqualityCmaintenanceEnables Claude Desktop to act as a planning agent while delegating coding tasks to OpenCode CLI, returning execution status, file diffs, and output, with support for continuing sessions and opening workspaces in IDEs.151-