Skip to main content
Glama
Dheerax

opencode-mcp-bridge

by Dheerax
README.md
# opencode-mcp-bridge

![opencode-mcp-bridge Architecture Infographic](assets/infographic.png)

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](https://github.com/sst/opencode) 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`](./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.

## 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](https://nodejs.org) v18+
- [OpenCode CLI](https://github.com/sst/opencode) installed and authenticated (`opencode auth login`) — run `opencode --version` to confirm it's on PATH.

## Quick Start

1. **Clone and build:**
   ```bash
   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:**
     ```bash
     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:
     ```json
     {
       "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`](./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:

```bash
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](./LICENSE)

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

ActivitySlowing
ResponsivenessNo issues