Skip to main content
Glama
OpenCode V2 MCP Bridge
by ddarkwing

OpenCode V2 MCP Bridge

MCP-сервер, который позволяет Cursor (и любому другому MCP-клиенту) запускать агентов OpenCode V2 с выбранной моделью: oc_task({ agent, model, prompt }).

Написан потому, что популярные community-мосты (opencode-mcp, mcp-server-opencode, opencode-mcp-bridge и т.п.) используют старый API OpenCode (/session, /agent) и на OpenCode V2 возвращают HTML веб-приложения вместо JSON.

Работает через общий фоновый сервис OpenCode, поэтому сессии видны и в TUI, и в Cursor. Пароль сервиса читается локально и никуда не отправляется.

Требования

  • OpenCode V2 (opencode --version, проверено на 2.1.1)

  • Node.js 22+

  • Cursor с поддержкой MCP (или любой MCP-клиент)

  • Linux/macOS (Windows — см. раздел «Windows»)

Related MCP server: opencode-mcp

Установка

tar -xzf opencode-v2-mcp-bridge-1.0.0.tar.gz
cd opencode-v2-mcp-bridge
./install.sh

Скрипт:

  1. копирует мост в ~/.config/opencode/mcp-bridge;

  2. добавляет сервер opencode в ~/.cursor/mcp.json (существующие серверы сохраняются);

  3. кладёт примеры агентов в ~/.config/opencode/agents (если таких файлов ещё нет).

Затем перезапустите Cursor.

Опции:

./install.sh --dir ~/tools/opencode-mcp-bridge   # другой каталог установки
./install.sh --no-agents                        # не устанавливать агентов

Ручная установка:

mkdir -p ~/.config/opencode/mcp-bridge
cp -R dist run.sh README.md LICENSE ~/.config/opencode/mcp-bridge/
chmod +x ~/.config/opencode/mcp-bridge/run.sh

~/.cursor/mcp.json:

{
  "mcpServers": {
    "opencode": {
      "command": "/home/<you>/.config/opencode/mcp-bridge/run.sh",
      "args": []
    }
  }
}

Инструменты

Инструмент

Назначение

oc_agents

Список агентов проекта: id, режим, модель

oc_models

Список моделей provider/model, фильтр по провайдеру

oc_task

Новая сессия для agent (+ model), промпт, ожидание результата

oc_reply

Продолжить существующую сессию

oc_status

Статус, агент, модель, стоимость, последний ответ

oc_cancel

Прервать выполнение

oc_sessions

Последние сессии проекта

oc_task по умолчанию ждёт 50 секунд — это меньше типичного таймаута MCP-клиента. Для длинных задач:

oc_task({ ..., background: true })  ->  sessionID
oc_status({ sessionID, waitSeconds: 120 })

Модели

По умолчанию используется модель, заданная у агента. Если у агента модели нет, он наследует модель родительской сессии (так же ведут себя его субагенты).

Переменные окружения (задаются в ~/.cursor/mcp.json → env):

Переменная

Значение

OPENCODE_FORCE_MODEL

Всегда использовать эту модель, игнорируя аргумент и конфиг агента

OPENCODE_FALLBACK_MODEL

Один автоматический повтор при outcome: "failed"

OPENCODE_BASE_URL

URL сервиса (по умолчанию определяется через opencode service status)

OPENCODE_SERVER_USERNAME

Basic-auth пользователь, по умолчанию opencode

OPENCODE_SERVER_PASSWORD

Пароль (по умолчанию читается из service.json)

OPENCODE_DEFAULT_DIRECTORY

Каталог проекта по умолчанию

Ретрай не срабатывает для background: true, таймаутов, отмены и отказов в permissions — чтобы не дублировать работу.

Пример: бесплатная модель + платный fallback

"env": {
  "OPENCODE_FORCE_MODEL": "opencode/deepseek-v4.1-flash-free",
  "OPENCODE_FALLBACK_MODEL": "deepseek/deepseek-flash"
}

deepseek/deepseek-flash — официальный id DeepSeek-V4.1-Flash у провайдера deepseek. Чтобы он появился, добавьте провайдера в ~/.config/opencode/opencode.json (ключ — из DEEPSEEK_API_KEY или файла):

"providers": {
  "deepseek": {
    "name": "DeepSeek",
    "package": "aisdk:@ai-sdk/openai-compatible",
    "settings": {
      "baseURL": "https://api.deepseek.com",
      "apiKey": "{file:~/.config/opencode/deepseek.key}"
    },
    "models": {
      "deepseek-flash": {
        "name": "DeepSeek V4.1 Flash",
        "limit": { "context": 1048576, "output": 393216 }
      }
    }
  }
}

После правки: opencode reload.

В ответе oc_task при срабатывании fallback появляется блок:

"fallback": {
  "from": "opencode/deepseek-v4.1-flash-free#default",
  "to": "deepseek/deepseek-flash",
  "reason": "Free usage limit reached...",
  "originalSessionID": "ses_..."
}

Агенты

Глобальные: ~/.config/opencode/agents/<name>.md. Проектные: .opencode/agents/<name>.md.

Чтобы агента можно было запускать из Cursor, он должен быть mode: all или mode: primary. Агенты mode: subagent запускаются только другим агентом OpenCode.

---
description: Дешёвый read-only ревьюер
mode: all
permissions:
  - action: edit
    resource: "*"
    effect: deny
  - action: shell
    resource: "*"
    effect: deny
---
Ты — лаконичный ревьюер. Не используй инструменты.

Модель в агенте можно не указывать — тогда он наследует модель сессии, и OPENCODE_FORCE_MODEL / OPENCODE_FALLBACK_MODEL действуют на всю цепочку включая субагентов.

Диагностика

Проверить, что сервис жив:

opencode service status

Проверить мост вручную (MCP Inspector):

npx -y @modelcontextprotocol/inspector ~/.config/opencode/mcp-bridge/run.sh

Логи Cursor:

tail -40 "$(ls -dt ~/.cursor/logs/*/ 2>/dev/null | head -1)mcp-server-user-opencode.log"
# или
tail -40 "$(ls -dt ~/.config/Cursor/logs/*/ 2>/dev/null | head -1)mcp-server-user-opencode.log"

Типичные ошибки:

Симптом

Причина / решение

OpenCode service is not running

opencode service start

Connection closed сразу после запуска

нет node/opencode в PATH — run.sh уже добавляет типовые пути; проверьте NODE_BIN/OPENCODE_BIN

fetch failed

неверный OPENCODE_BASE_URL или сервис перезапустился (пароль/порт изменились) — перезапустите MCP-сервер

provider.quota / Free usage limit reached

сработает fallback, если задан OPENCODE_FALLBACK_MODEL

Инструменты не появились

перезапустите Cursor или MCP-сервер в настройках

Windows

run.sh рассчитан на bash. Варианты:

  • WSL + Cursor в WSL;

  • запускать напрямую: node dist/index.mjs с переменными OPENCODE_BASE_URL, OPENCODE_SERVER_PASSWORD, OPENCODE_DEFAULT_DIRECTORY;

  • либо добавить в mcp.json:

{
  "mcpServers": {
    "opencode": {
      "command": "node",
      "args": ["C:/path/to/opencode-v2-mcp-bridge/dist/index.mjs"],
      "env": { "OPENCODE_BASE_URL": "http://127.0.0.1:4096", "OPENCODE_SERVER_PASSWORD": "..." }
    }
  }
}

Безопасность

Мост не хранит секретов: URL и пароль читаются из локального сервиса OpenCode (opencode service status, ~/.config/opencode/service.json). Наружу ничего не отправляется, кроме запросов к вашему локальному OpenCode.

Лицензия

MIT.

Available Tools

7 tools
oc_agentsList OpenCode agentsA

List agents available in an OpenCode project, including each agent's mode and assigned model. Use the returned id as the agent argument of oc_task.

Inputs: directory.

oc_cancelCancel an OpenCode sessionB

Interrupt the active execution of a session.

Inputs: sessionID (required).

oc_modelsList OpenCode modelsA

List models available to OpenCode, optionally filtered by provider. Returns ids usable as model (provider/model).

Inputs: provider, directory.

oc_replyReply in an OpenCode sessionB

Send a follow-up prompt to an existing OpenCode session and wait for the answer.

Inputs: prompt (required), sessionID (required), timeoutSeconds.

oc_sessionsList OpenCode sessionsC

List recent OpenCode sessions for a directory.

Inputs: limit, directory.

oc_statusGet OpenCode session statusB

Return status, agent, model, cost and the latest assistant message for a session.

Inputs: sessionID (required), waitSeconds.

oc_taskRun an OpenCode agent taskA

Create a fresh OpenCode session for the given agent (and optional model override), send a prompt, and by default wait for completion. Returns the agent's final text plus session id, cost and token usage. If OPENCODE_FORCE_MODEL is set on the bridge, that model is always used.

Inputs: prompt (required), agent, model, title, +3 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 7 tools

    Disambiguation5/5

    Each tool maps to a distinct OpenCode operation: discovery (oc_agents, oc_models), session creation/reuse (oc_task, oc_reply), inspection (oc_status, oc_sessions), and interruption (oc_cancel). The descriptions clearly differentiate oc_task as creating a fresh session from oc_reply as continuing an existing one.

    Naming Consistency5/5

    All tools use the same `oc_` prefix and short, readable suffixes. The pattern is predictable even though some names are nouns (oc_agents, oc_models, oc_sessions) and some imply actions (oc_task, oc_reply, oc_cancel, oc_status).

    Tool Count5/5

    Seven tools is well scoped for an MCP bridge around OpenCode sessions. Each tool earns its place by covering a distinct part of the discovery, execution, inspection, and control workflow.

    Completeness4/5

    The surface covers agent/model discovery, task creation, follow-up replies, status inspection, cancellation, and session listing, which is a full practical lifecycle. Minor gaps exist around explicit session cleanup/deletion or richer session history retrieval, but core workflows are covered.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables MCP clients such as Claude, Cursor, and VS Code to delegate coding tasks to an OpenCode server, including asking questions, running background jobs, monitoring progress, responding to input/permissions, and reviewing changes across projects.
      22,709 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Connects MCP clients such as Claude, Cursor, and VS Code to OpenCode's headless API so users can delegate coding tasks, ask questions, run work in the background, and resolve permission or input requests across projects. It also supports monitoring job progress, reviewing resulting changes, and inspecting conversation history.
      22,709 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables MCP clients such as Claude, Cursor, and VS Code to delegate coding tasks to OpenCode, including asking questions, implementing features, monitoring background work, handling prompts and permissions, and reviewing changes across projects.
      22,709 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Connects MCP clients such as Claude, Cursor, and VS Code to OpenCode's headless API so users can ask questions, implement features, monitor background jobs, respond to prompts and permissions, and review changes across multiple projects. It supports synchronous runs, fire-and-forget jobs with polling, and project-scoped workflows.
      22,709 npm
      MIT