Skip to main content
Glama
opencode-mcp-bridge

opencode-mcp-bridge

by Dheerax

opencode-mcp-bridge

opencode-mcp-bridge Architecture Infographic

A Model Context Protocol (MCP) server that lets any AI tool (Claude Code, Antigravity, VS Code, Cursor, Windsurf, JetBrains, Claude Desktop, etc.) delegate tasks to the OpenCode CLI as a subagent — driven entirely through OpenCode's own opencode serve HTTP/SSE API, with async push events, task contracts, context tracking, checkpoints, and multi-session orchestration.

Agent instructions live in AGENTS.md — or just call the opencode_guide tool once this server is registered; it returns the same guide live from the running server's actual state.

Architecture

The bridge talks to a single, long-lived opencode serve process over plain HTTP:

  • One shared process, unlimited sessions. server-manager.ts spawns and singleton-manages opencode serve (state tracked in ~/.opencode-bridge/server.json); every opencode_start call just creates a lightweight session on that one server instead of launching a new CLI process per task. No node-pty native binding, no per-task re-authentication.

  • One event stream, every session. A single SSE connection to /api/event carries events for all sessions, tagged by durable.aggregateID; http-bridge.ts fans them out to the right local session (session.next.step.started/ended/failed, session.next.tool.called, session.next.text.delta, …) and derives status (running / idle / waiting_input / error) from them — no ANSI scraping, no idle-timer heuristics.

  • Self-healing. OpenCode's HTTP API does not surface session-runner failures (e.g. a model resolution error) as API-visible errors or events — a failed session just sits at running forever, indistinguishable from working. The bridge tails OpenCode's own internal log (~/.local/share/opencode/log/opencode.log) to detect these failures immediately, and runs a stall watchdog (zero tokens generated N seconds after a prompt) as a second line of defense. Because a single such failure has been observed to wedge that server process's entire turn queue, detecting one triggers an automatic restart of opencode serve so subsequent sessions aren't collateral damage.

Related MCP server: mcp-opencode

Features

  • ⚡ Async Events: Writes state transitions (running, idle, waiting_input, error, stale, contract_violated) to ~/.opencode-mcp-events.jsonl.

  • 🔀 Multi-Session Orchestration: Run up to 3 concurrent OpenCode sessions with dependency ordering (opencode_batch).

  • 🗂️ Context Bucket: Tracks every file creation/modification reported by the session's event stream.

  • 🛡️ Task Contracts: Enforce duration limits, path scope restrictions, file count caps, and forbidden commands.

  • 📸 Checkpoints & Recovery: Auto-save state snapshots every 60s and retry failed sessions from any checkpoint.

  • 🎯 Pre-Flight Classifier: Score incoming tasks to decide whether to delegate and recommend the best model.

  • 🩺 Failure visibility: opencode_health exposes last_error — the real underlying exception from OpenCode's runner, not just a generic hang.

  • 🖥️ Server introspection: opencode_server_health / opencode_server_restart expose and control the underlying opencode serve process itself, separate from any individual session.

  • 📖 Self-documenting: opencode_guide returns a complete, live behavioral guide (model selection, workflow, gotchas) generated from the running server's actual state — works identically in any MCP host.

Prerequisites

  • Node.js v18+

  • OpenCode CLI installed and authenticated (opencode auth login) — run opencode --version to confirm it's on PATH.

Quick Start

  1. Clone and build:

    git clone https://github.com/Dheerax/opencode_mcp.git
    cd opencode_mcp
    npm install
    npm run build
  2. Register as an MCP server:

    • Claude Code:

      claude mcp add -s user opencode-mcp-bridge -- node /absolute/path/to/opencode_mcp/dist/index.js
    • Antigravity / VS Code / Cursor / Windsurf: Add to your MCP server configuration:

      {
        "mcpServers": {
          "opencode-mcp-bridge": {
            "command": "node",
            "args": ["/absolute/path/to/opencode_mcp/dist/index.js"]
          }
        }
      }
  3. Run Setup: Invoke the opencode_setup tool once from your host agent to generate workspace integration instructions, then call opencode_guide to get the full usage guide.

All tools

See AGENTS.md for the complete tool reference table and workflow guide — or call the opencode_guide MCP tool directly, which returns the same content live.

Troubleshooting

If a session's status stays error immediately and opencode_health's last_error mentions ModelUnavailableError for a provider you expect to work (e.g. a google/* model), the provider's cached OAuth token has likely expired. Re-authenticate it directly:

opencode auth logout <provider>
opencode auth login <provider>

This is an OpenCode/provider-auth issue, not something the bridge can fix by itself — it can only detect it, report it via last_error, and recover the server process so it doesn't stay wedged for other sessions.

License

MIT

Available Tools

28 tools
opencode_activeB

Returns the ID and status of the currently active session.

Inputs: no named parameters.

opencode_batchB

Starts up to 3 parallel OpenCode sessions with dependency support.

Inputs: tasks (required).

opencode_batch_statusC

Returns status for a batch of session IDs.

Inputs: session_ids (required).

opencode_checkpointB

Saves a checkpoint snapshot of session state WITHOUT interrupting it.

Inputs: session_id.

opencode_classifyB

Classifies a task to decide whether to delegate to OpenCode, recommended model, and strategy.

Inputs: task (required).

opencode_commandC

Sends a command or text to OpenCode and submits it with Enter.

Inputs: command (required), session_id.

opencode_configC

Gets or updates configuration options (effort_level, default_model, default_agent).

Inputs: effort_level, default_agent, default_model.

opencode_contextA

Returns the operation log and file changes tracked for this session.

Inputs: last_n, session_id.

opencode_diffC

Returns change metadata for a specific file tracked during the session.

Inputs: filepath (required), session_id.

opencode_guideA

Returns the complete behavioral guide for using opencode-mcp-bridge correctly — when to delegate, model selection, the async event-driven workflow, batch/dependency orchestration, guardrails, and how to diagnose a failed session. Call this first before delegating a task through OpenCode.

Inputs: no named parameters.

opencode_healthB

Returns a full health report for a session: status, uptime, last activity, output line count, recovery attempts, contract violations, file change count, and operation log count.

Inputs: session_id.

opencode_interruptC

Sends Ctrl+C to interrupt the task, returns the final output buffer and reason.

Inputs: reason (required), session_id.

opencode_killC

Terminates a session and frees all its resources.

Inputs: session_id.

opencode_listB

Lists all tracked OpenCode sessions with their IDs, tasks, statuses, and active status.

Inputs: no named parameters.

opencode_list_checkpointsA

Lists all saved checkpoints sorted by recency.

Inputs: no named parameters.

opencode_logsC

Returns recent bridge log entries.

Inputs: last_n, session_id.

opencode_modeC

Gets or sets the delegation toggle ('on' | 'off').

Inputs: mode.

opencode_readB

Returns the last 200 lines of buffered output and current session status.

Inputs: session_id.

opencode_retryB

Loads a saved checkpoint and spawns a new session continuing from that state.

Inputs: checkpoint_id (required), continuation_hint.

opencode_sendB

Sends raw text or keystrokes to the PTY. Supports , , , , , , , , .

Inputs: input (required), session_id.

opencode_server_healthA

Reports the state of the underlying opencode serve process itself (pid, port, alive, HTTP-healthy, whether an automatic recovery is in progress) — distinct from opencode_health, which reports a single session's state.

Inputs: no named parameters.

opencode_server_restartA

Forcibly restarts the underlying opencode serve process. Disruptive: every in-flight session on that process is interrupted. Normally unnecessary — the bridge restarts automatically when it detects a wedged or failed session — use this only to force a clean process explicitly (e.g. right after fixing provider auth).

Inputs: no named parameters.

opencode_set_modelA

Dynamically switches the AI model on an active or idle session for subsequent prompts.

Inputs: model (required), session_id.

opencode_setupA

One-time setup: writes OpenCode subagent guidelines to local workspace and user home profile directory.

Inputs: no named parameters.

opencode_startA

Spawns a new OpenCode CLI session and starts the initial task. Returns session_id and events_log_path. After starting, use a persistent background notification watcher on <events_log_path> to receive events (running, idle, waiting_input, done, stale, contract_violated). Call opencode_read when notified, then opencode_kill when done.

Inputs: task (required), fork, agent, model, +8 more.

opencode_statusA

Returns the current status of a session: running, idle, waiting_input, stale, done, error, contract_violated, or starting.

Inputs: session_id.

opencode_switchC

Switches the active session to the specified session ID.

Inputs: session_id (required).

opencode_usageC

Queries OpenCode model and statistics information.

Inputs: no named parameters.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.3/5.0

    Scored across 28 tools

    Disambiguation5/5

    Each tool clearly targets a distinct aspect of session or server management: health vs status vs context vs diff serve different query depths, send vs command vs interrupt handle different input methods, and checkpoint/retry/list_checkpoints form a clear lifecycle. The only near-overlap (health vs server_health) is explicitly disambiguated in the description.

    Naming Consistency4/5

    All tools share the opencode_ prefix and use snake_case, providing a consistent style. However, the pattern mixes bare nouns (health, status, context) with verb-first forms (set_model, list_checkpoints, server_restart), so it is not a strict verb_noun pattern throughout.

    Tool Count3/5

    28 tools is on the heavy side, straddling the 'too many' threshold. The breadth is justified by the complex session-lifecycle and server-management domain, but the count exceeds the typical well-scoped range and may introduce selection overhead for agents.

    Completeness5/5

    The surface covers the full session lifecycle (start, read, interrupt, kill), checkpointing (save, list, retry), batch operations, configuration, and server health. No obvious dead ends or missing operations for the stated purpose of bridging to OpenCode.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers