Skip to main content
Glama

opencode-v2-mcp

English version

npm (npmjs.org) GitHub Packages License: MIT

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. Три причины и фиксы:

  1. Отсутствовал флаг --auto. Без него opencode не может неинтерактивно подтверждать edit/shell-разрешения — добавлен в runOpenCode() безусловно.

  2. spawn("opencode", ...) без абсолютного пути. GUI-приложения (включая Claude Code Desktop) не всегда наследуют пользовательский PATH, где установлен opencode — используется абсолютный путь к бинарнику. Проверьте и при необходимости поправьте путь в server.mjs (spawn("/home/USER/.opencode/bin/opencode", ...)) под вашу установку — which opencode подскажет актуальный путь.

  3. 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).

Лицензия

MIT

Available Tools

1 tool
opencode_executeA

Execute one bounded coding task through OpenCode v2 and return a compact JSON report with diff/test context.

ParametersJSON Schema
NameRequiredDescriptionDefault
cwdYesAbsolute working directory/repository root.
taskYesBounded coding task with goal, constraints, files, acceptance criteria, and verification command.
agentNoOpenCode v2 agent name, e.g. claude-worker or build.claude-worker
modelNoOptional OpenCode provider/model, e.g. openai/gpt-5.5.
sessionIdNoContinue a specific OpenCode session instead of starting a new one.
timeoutMsNoInternal OpenCode timeout; must be below Claude MCP per-server timeout.
standaloneNoUse OpenCode private standalone server for this run. Default false uses normal v2 service behavior.
continueSessionNoContinue last OpenCode session; ignored when sessionId is set.

TDQS

A3.5/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines2/5

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. 1 tool updatev0.2.0
    • First observedopencode_execute

TDQS

B3.2/5.0

Scored across 1 tool

Disambiguation5/5

Only one tool exists, so there is no possibility of confusion or overlap. The tool's purpose is singular and clearly defined.

Naming Consistency3/5

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.

Tool Count1/5

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.

Completeness1/5

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

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers