Skip to main content
Glama
OpenCode Remote Bridge

OpenCode Remote Bridge

by sandro9800
README.md
# OpenCode Remote Bridge

An authenticated [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) bridge for controlling a local [OpenCode](https://opencode.ai/) instance remotely. It exposes OpenCode session, filesystem, terminal, and Git operations over Streamable HTTP and can publish the endpoint through a temporary Cloudflare Quick Tunnel.

> **Security warning:** This project intentionally provides powerful access to the machine running OpenCode. Filesystem tools can read, create, overwrite, and delete files; the terminal tool can execute commands through OpenCode. Only connect trusted MCP clients, protect your token, and review your OpenCode permissions. Do not expose the local bridge port directly to the internet.

## Features

- Bearer-token authentication with timing-safe comparison
- MCP Streamable HTTP transport
- OpenCode session and prompt management
- File read, write, list, search, and delete tools
- Terminal commands through an OpenCode session
- Git status and diff tools
- One-command manager for OpenCode, the bridge, and Cloudflare Tunnel
- Separate OpenCode client profile; your normal OpenCode config is not overwritten

## Requirements

- Debian/Ubuntu Linux (Debian in Termux/PRoot is supported)
- Node.js 20+ and npm
- OpenCode CLI available as `opencode`
- Cloudflare Tunnel client available as `cloudflared`
- Python 3, OpenSSL, curl, and Git
- Network access

Ports **4096** (OpenCode API) and **8787** (MCP bridge) must be available on localhost.

## Install system requirements (Debian/Ubuntu)

Run as root, or prefix commands with `sudo` on a normal Debian/Ubuntu installation.

Install basic utilities:

```bash
apt-get update
apt-get install -y ca-certificates curl git openssl python3
```

Install Node.js 22 and npm (Node.js 20+ is required):

```bash
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt-get install -y nodejs
node --version
npm --version
```

Install OpenCode CLI using its official installer:

```bash
curl -fsSL https://opencode.ai/v2/install | bash
export PATH="$HOME/.opencode/bin:$PATH"
opencode --version
```

Add the PATH export to your shell profile (for Bash, `~/.bashrc`) if the installer did not do so.

Install Cloudflare Tunnel client:

```bash
install -d -m 0755 /usr/share/keyrings
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' > /etc/apt/sources.list.d/cloudflared.list
apt-get update
apt-get install -y cloudflared
cloudflared --version
```

Official references: [OpenCode CLI](https://opencode.ai/docs/) · [Cloudflare Tunnel on Debian/Ubuntu](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/create-local-tunnel/).

## Install this project

```bash
git clone https://github.com/sandro9800/opencode-remote-bridge.git
cd opencode-remote-bridge
chmod +x mcp scripts/install.sh
./scripts/install.sh
```

The installer installs npm dependencies and creates a unique local `.bridge-token` with restricted permissions. The token is ignored by Git. Never commit or share it.

## Start

```bash
./mcp start
./mcp client
```

The launcher starts the OpenCode API at `http://127.0.0.1:4096`, the MCP bridge at `http://127.0.0.1:8787/mcp`, and a Cloudflare Quick Tunnel. It detects the temporary `*.trycloudflare.com` URL and updates a dedicated OpenCode client profile with the URL and local token. In the client, inspect the MCP connection or list its tools.

## Connect other AI assistants

You can connect an external AI assistant to this bridge using **MCP Streamable HTTP**. The assistant can then use the bridge's tools to create OpenCode sessions, send prompts, inspect results, work with files, and run permitted terminal commands through OpenCode.

### 1. Get the connection details

Start the bridge on the device running OpenCode:

```bash
./mcp start
./mcp status
```

Use the current Cloudflare Quick Tunnel URL shown by the launcher, followed by `/mcp`:

```text
https://YOUR-TUNNEL.trycloudflare.com/mcp
```

Read the private bearer token locally from the project directory:

```bash
cat .bridge-token
```

Do not paste the token into chats, publish it, or commit it. Keep the bridge and tunnel running while the external assistant is connected. Quick Tunnel URLs are temporary and can change after a restart.

### 2. Configure your MCP client

The client must support **remote MCP over Streamable HTTP** and custom HTTP headers. Configure the server URL above and add this header:

```text
Authorization: Bearer YOUR_BRIDGE_TOKEN
```

Replace the URL and token placeholders with your current values. Keep credentials in the client's secret store or environment variables when supported; avoid committing tokens to client configuration files.

#### Cursor

Add an MCP server in Cursor's MCP settings. For clients that use a project `.cursor/mcp.json` or equivalent JSON configuration, the server entry has this shape:

```json
{
  "mcpServers": {
    "opencode-remote-bridge": {
      "url": "https://YOUR-TUNNEL.trycloudflare.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_BRIDGE_TOKEN"
      }
    }
  }
}
```

If your Cursor version supports environment-variable interpolation or secret inputs, use that instead of writing the token directly in the file.

#### VS Code

In `.vscode/mcp.json`, configure a remote HTTP MCP server. VS Code supports input variables so the token can be entered as a secret:

```json
{
  "inputs": [
    {
      "type": "promptString",
      "id": "bridge-token",
      "description": "OpenCode Remote Bridge token",
      "password": true
    }
  ],
  "servers": {
    "opencode-remote-bridge": {
      "type": "http",
      "url": "https://YOUR-TUNNEL.trycloudflare.com/mcp",
      "headers": {
        "Authorization": "Bearer ${input:bridge-token}"
      }
    }
  }
}
```

#### Claude Code

Claude Code can add a remote HTTP MCP server from the terminal:

```bash
claude mcp add --transport http opencode-remote-bridge https://YOUR-TUNNEL.trycloudflare.com/mcp --header "Authorization: Bearer YOUR_BRIDGE_TOKEN"
claude mcp list
```

Use the current tunnel URL and token. Be aware that command-line arguments may be stored in shell history; prefer a safer credential-handling method if available in your environment.

#### Claude Desktop and other MCP clients

If your client does not support remote HTTP MCP servers directly but supports local stdio servers, you may be able to use an HTTP-to-stdio proxy such as `mcp-remote`:

```json
{
  "mcpServers": {
    "opencode-remote-bridge": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://YOUR-TUNNEL.trycloudflare.com/mcp",
        "--header",
        "Authorization: Bearer YOUR_BRIDGE_TOKEN"
      ]
    }
  }
}
```

This requires Node.js/npm and a client that supports stdio MCP servers. Merge the entry into the client's existing MCP configuration; do not replace unrelated servers. Protect the token in this file.

### 3. What to ask the connected assistant

After the client connects, enable the MCP server and check that its bridge tools are available. Example requests:

- "Create an OpenCode session and ask it to inspect this project's architecture."
- "Send this implementation task to OpenCode, then wait for the result and summarize it."
- "Ask OpenCode to review the current Git diff and identify risky changes."
- "Run the project's tests through OpenCode and report any failures."

The external assistant is the controller; OpenCode performs the work in its own environment through the bridge. The available operations are limited to the tools exposed by this bridge.

### 4. Skills, agents, and project instructions

MCP connects the assistant to OpenCode's tools; it does **not** automatically copy skills or agents between AI products.

- **External assistant skills:** remain installed in the external assistant's own environment.
- **OpenCode skills and agents:** must be installed/configured in the OpenCode environment on the device running this bridge.
- **Project instructions:** files such as `AGENTS.md` remain in the project and can be read by OpenCode according to its configuration.

For example, ask the external assistant to use its own code-review skill to prepare a review, then have it send OpenCode a prompt to inspect the repository while following the project's `AGENTS.md` and configured OpenCode skills/agents.

### 5. Security and troubleshooting

- Keep the bridge bound to localhost; expose it through the managed tunnel rather than opening the local bridge port directly to the internet.
- Anyone with the bearer token can invoke all tools exposed by the bridge. Treat it like a password and connect only trusted assistants.
- The bridge is not a hardened sandbox or a per-tool authorization system. File and terminal tools can make consequential changes.
- If authentication fails, verify the token and current tunnel URL. If the tunnel was restarted, copy the new URL.
- If the server is unreachable, check `./mcp status` and `./mcp logs` on the host running OpenCode.

## Autonomous Goal Runner

The bridge includes a persistent autonomous goal loop. Submit one high-level goal and it coordinates three OpenCode sessions:

1. **Orchestrator** breaks the goal into concrete tasks and decides what remains.
2. **Worker** performs the task using the configured OpenCode tools, skills and agents.
3. **Reviewer** independently inspects the project and checks whether the original goal is actually complete.

The loop continues asynchronously until the reviewer verifies completion, the goal is cancelled, an error occurs, or the iteration limit is reached. Goal state is persisted in `.goal-runner/goals.json` with restrictive file permissions.

### MCP goal tools

- `list_goal_models`: discover the providers and models currently available in OpenCode.
- `start_goal`: start a goal with optional working directory, iteration limit and per-role model choices.
- `get_goal_status`: inspect progress, sessions, selected models, review and errors.
- `list_goals`: list recent goals.
- `control_goal`: pause, resume or cancel a goal.

Use `auto` for any role's model to select from the connected OpenCode model catalog, or use the exact `providerID/modelID` returned by `list_goal_models`. Example request to an MCP client:

```text
Start a goal: make this project production-ready. Use auto model selection, work in the current project, and run tests. Keep working until an independent review verifies every acceptance criterion.
```

### Providers, including NVIDIA

The Goal Runner uses OpenCode's live provider/model catalog rather than maintaining a fixed provider list. Configure providers in OpenCode first; any provider and model exposed by the OpenCode API can be selected for the orchestrator, worker or reviewer. This includes cloud providers, local model servers and custom providers supported by your OpenCode version.

**NVIDIA NIM / build.nvidia.com:** configure NVIDIA credentials and the NVIDIA provider in OpenCode using its current provider setup instructions. Once connected, NVIDIA models appear in `list_goal_models` and can be selected like any other provider. The Goal Runner does not hardcode an NVIDIA model name or require a separate NVIDIA key field.

Provider setup: [OpenCode providers documentation](https://opencode.ai/docs/providers/) · [NVIDIA API Catalog](https://build.nvidia.com/).

### Model selection

- **Auto:** choose a model from the available catalog using role-aware capability hints.
- **Manual:** select a provider/model independently for orchestrator, worker and reviewer.
- **Fallback:** configure multiple providers in OpenCode and change the role's selected model if a provider is unavailable. Automatic cross-provider retries are not yet enabled.

### Limits and safety

- Default maximum: 20 iterations; configurable from 1 to 100.
- Each goal runs in the background and can be paused, resumed or cancelled.
- The worker inherits the permissions of the OpenCode instance. Review its permissions before starting autonomous work.
- The reviewer is a separate model/session, but it is not a formal proof system; inspect important changes and test results yourself.
- Goal state survives bridge restarts, but an in-flight goal is not automatically resumed after a process restart. Use `list_goals` and resume it.
- Avoid running multiple goals against the same working directory simultaneously.

## Commands

| Command | Action |
|---|---|
| `./mcp start` | Start all services |
| `./mcp stop` | Stop managed services |
| `./mcp restart` | Restart all services |
| `./mcp status` | Show service state and tunnel URL |
| `./mcp logs` | Show recent logs |
| `./mcp client` | Open isolated OpenCode client |

Logs/PIDs: `~/.local/state/opencode-remote-bridge/`. Client profile: `~/.config/opencode-remote-bridge/`.

## Termux + Debian (PRoot)

In Termux:

```bash
pkg update && pkg upgrade
pkg install proot-distro git
proot-distro install debian
proot-distro login debian --shared-tmp
```

Inside Debian, follow **Install system requirements** and **Install this project** above. Run `./mcp start` and `./mcp client` from the Debian shell. Keep Termux alive: Android battery management or force-stopping Termux can terminate background processes. Consider excluding Termux from battery optimization.

## Configuration

The bundled `./mcp` manager currently uses the default local ports (4096 and 8787). Keep these defaults when using the manager. The server also accepts these environment variables when run directly with `npm start`:

| Variable | Default | Meaning |
|---|---|---|
| `BRIDGE_HOST` | `127.0.0.1` | MCP bind interface |
| `BRIDGE_PORT` | `8787` | MCP port |
| `OPENCODE_URL` | `http://127.0.0.1:4096` | Local OpenCode API |
| `BRIDGE_TOKEN_FILE` | `.bridge-token` | Private token file |

Keep the bridge bound to localhost when using a tunnel. `.env.example` lists the variables; export them in the shell before running the server directly.

## MCP tools (17)

**OpenCode sessions:** `opencode_health`, `list_sessions`, `get_session_messages`, `create_session`, `send_prompt`, `get_session_status`, `send_prompt_async`, `abort_session`, `delete_session` (requires `confirm: "DELETE"`).

**Filesystem:** `read_file`, `write_file`, `list_files`, `search_files`, `delete_file` (requires `confirm: "DELETE"`).

**Terminal:** `run_command` (runs through an OpenCode session and its configured permissions).

**Git:** `git_status`, `git_diff`.

## Project layout

```text
src/
  config.js
  server.js
  lib/                 # OpenCode API, output, path helpers
  middleware/          # Bearer authentication
  tools/               # OpenCode, filesystem, terminal, Git tools
scripts/
  install.sh
mcp                    # service manager
.github/workflows/
  ci.yml
```

## Development

```bash
npm install
npm run check
npm start
```

GitHub Actions runs JavaScript and shell syntax checks on pushes and pull requests.

## Security

- Every installation must use its own unpredictable bearer token.
- Never publish `.bridge-token`, client configuration, or credentials.
- OpenCode and the bridge bind to localhost; Cloudflare Tunnel is the public ingress.
- Quick Tunnel URLs are temporary and change on restart; the launcher refreshes the client profile.
- Anyone with the bearer token can invoke all exposed MCP tools. Treat it like a password.
- Filesystem and terminal tools are powerful. This is not a hardened sandbox or per-tool authorization system.

## Troubleshooting

- **Port in use:** stop the conflicting service before starting.
- **Tunnel URL missing:** inspect `./mcp logs`.
- **401 Unauthorized:** restart to refresh the isolated client profile, then reconnect.
- **OpenCode unavailable:** check the OpenCode CLI and logs.
- **Termux stops services:** keep Termux alive and review Android battery optimization.

## License

MIT. See [LICENSE](LICENSE).