Skip to content

OpenCode

OpenCode is an MIT-licensed, open-source AI coding agent for the terminal built by SST (YC-backed). With 147k+ GitHub stars and releases shipping multiple times per week, it’s one of the fastest-moving projects in the agentic coding space. Its key differentiators over Claude Code and Mistral Vibe are built-in LSP integration (real-time type errors fed to the agent), a client/server architecture (attach multiple sessions to one server), and a rich headless JSON event stream for automation pipelines.

OpenCode is a terminal-based AI coding agent that can:

  • Read, write, and edit files with exact-string replacement
  • Execute shell commands in a stateful bash session
  • Search files by name (glob) and content (grep/regex)
  • Fetch and parse web pages
  • Receive real-time LSP diagnostics (type errors, missing imports) as it edits
  • Connect to MCP servers for extended capabilities
  • Run headless with structured JSON output for CI/CD pipelines
  • Operate as a persistent server that multiple clients can attach to
ToolDescriptionClaude Code Equivalent
readRead file contents (supports line ranges)Read
writeCreate or overwrite filesWrite
editExact-string replacementEdit
apply_patchApply unified diff patches
bashExecute shell commandsBash
globFind files by patternGlob
grepRegex content searchGrep
webfetchFetch and parse web pagesWebFetch
lspCode intelligence (definitions, references, hover)
skillLoad SKILL.md instruction filesSkill
questionPrompt user for clarificationAskUserQuestion
FeatureClaude CodeMistral VibeOpenCode
LicenseProprietaryApache 2.0MIT
Model supportClaude onlyAny OpenAI-compatAny (ai-sdk providers)
Self-hostedNoYesYes
LSP integrationNoNoYes (20+ languages)
Client/serverNoNoYes (opencode serve)
Headless modeNovibe -popencode run + JSON events
MCP supportYesYes (stdio+HTTP)Yes (stdio+SSE+OAuth)
Custom instructionsCLAUDE.mdAGENTS.mdAGENTS.md + CLAUDE.md fallback
GitHub starsN/A~5k~147k
Cost$20-200/mo subscriptionFree (self-host)Free (self-host) or provider tokens

Verdict: OpenCode’s LSP integration and client/server architecture make it the best open-source shell for agentic coding. Claude Code has higher benchmark scores. Vibe has simpler setup for self-hosted Devstral. Use OpenCode when you want LSP diagnostics, session persistence, or the richest automation API.

Terminal window
curl -fsSL https://opencode.ai/install | bash
Terminal window
# npm (package name is opencode-ai, NOT opencode)
npm i -g opencode-ai
# Homebrew (use the tap for latest)
brew install anomalyco/tap/opencode
# Bun
bun add -g opencode-ai
Terminal window
# Windows (Scoop)
scoop install opencode
# Arch Linux
sudo pacman -S opencode
# Nix
nix run nixpkgs#opencode
Terminal window
brew install --cask opencode-desktop

Also available for Windows (NSIS installer) and Linux (deb/rpm) at the OpenCode website.

Common Install Mistakes

  • The npm package is opencode-ai, not opencode — wrong name installs a different package
  • On Homebrew, brew install anomalyco/tap/opencode is more current than brew install opencode
  • On WSL: the curl script may install into WSL instead of native Windows. Use Git Bash (MinGW64) if targeting native Windows.

OpenCode uses opencode.json (or opencode.jsonc) for configuration:

  • Project-level: ./opencode.json in the repo root (highest priority)
  • Global: ~/.config/opencode/opencode.json
  • Auth: ~/.config/opencode/auth.json (API keys, separate from config)

Add the $schema key for IDE autocompletion of all config options:

{
"$schema": "https://opencode.ai/config.json",
"model": "anthropic/claude-sonnet-4-5",
"small_model": "anthropic/claude-haiku-4-5"
}
{
"$schema": "https://opencode.ai/config.json",
"model": "vllm/devstral-123b",
"small_model": "vllm/devstral-123b",
"provider": {
"vllm": {
"npm": "@ai-sdk/openai-compatible",
"name": "Local vLLM",
"options": {
"baseURL": "http://192.168.1.19:8000/v1"
},
"models": {
"devstral-123b": {
"name": "Devstral 123B (Self-Hosted)"
}
}
}
}
}

The model ID (e.g., devstral-123b) must exactly match what vLLM exposes at /v1/models.

API keys live in ~/.config/opencode/auth.json, not in the main config:

{
"anthropic": {
"api_key": "sk-ant-..."
},
"vllm": {
"api_key": "your-vllm-key"
}
}
{
"permission": {
"*": "ask",
"bash": {
"*": "ask",
"git *": "allow",
"npm *": "allow",
"rm *": "deny"
},
"edit": "allow",
"read": "allow",
"grep": "allow",
"glob": "allow"
}
}

Values: "allow" (auto-approve), "ask" (prompt user), "deny" (block). Wildcard patterns supported for bash commands.

OpenCode searches for instruction files in this order:

  1. AGENTS.md in current directory (traverses upward to repo root)
  2. ~/.config/opencode/AGENTS.md (global)
  3. CLAUDE.md in current directory (legacy fallback)
  4. ~/.claude/CLAUDE.md (Claude Code global fallback)

To include additional instruction files:

{
"instructions": [
"CONTRIBUTING.md",
"docs/style-guide.md",
".cursor/rules/*.md"
]
}

Glob patterns and remote URLs are supported.

The /init slash command runs a guided setup to generate AGENTS.md from your project.

{
"mcp": {
"filesystem": {
"type": "local",
"command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"],
"enabled": true,
"timeout": 5000
},
"git": {
"type": "local",
"command": ["uvx", "mcp-server-git"],
"enabled": true
}
}
}
{
"mcp": {
"my-api": {
"type": "remote",
"url": "https://mcp.example.com",
"enabled": true,
"headers": {
"Authorization": "Bearer {env:MY_TOKEN}"
}
}
}
}
{
"mcp": {
"notion": {
"type": "remote",
"url": "https://mcp.notion.com",
"oauth": {
"clientId": "{env:NOTION_CLIENT_ID}",
"clientSecret": "{env:NOTION_SECRET}",
"scope": "tools:read tools:execute"
}
}
}
}

Management commands: opencode mcp list, opencode mcp debug <name>, opencode mcp auth <name>.

Environment variable substitution: {env:VAR_NAME} works in all config values.

OpenCode’s standout feature. The agent receives real-time diagnostics from language servers as it edits — catching type errors, missing imports, and syntax issues in-loop without needing a separate compile step.

LanguageServerRequired
TypeScript/JavaScripttypescripttypescript in project deps
Gogoplsgopls binary
Rustrust-analyzerrust-analyzer binary
Pythonpyright / pylsprespective binary
Rubysolargraphsolargraph gem
C/C++clangdclangd binary
JavajdtlsEclipse JDT LS
Vue@vue/language-servernpm package
Sveltesvelte-language-servernpm package
Astro@astrojs/language-servernpm package

OpenCode auto-downloads missing LSP servers unless OPENCODE_DISABLE_LSP_DOWNLOAD=true.

{
"lsp": {
"my-language": {
"command": ["my-lsp-server", "--stdio"],
"extensions": [".mylang"],
"disabled": false
}
}
}

To disable all LSP: "lsp": false.

All tools are enabled by default. Disable specific tools in config:

{
"tools": {
"webfetch": false,
"websearch": false
}
}

Web search requires OPENCODE_ENABLE_EXA=true in environment. Uses Exa AI for search results.

The opencode run command executes a task non-interactively — critical for CI/CD and orchestration scripts.

Terminal window
# Simple one-shot task
opencode run "Fix all TypeScript errors in src/"
# With model override
opencode run "Refactor the auth module" --model anthropic/claude-sonnet-4-5
# Auto-approve all tool calls (for automated pipelines)
opencode run "Run tests and fix failures" --dangerously-skip-permissions
# Attach file context
opencode run "Review this file" --file src/auth.ts
Terminal window
opencode run "Fix the bug" --format json --dangerously-skip-permissions

Outputs newline-delimited JSON (JSONL) with event types:

EventKey Fields
step_startsessionID, part.snapshot
tool_usepart.tool, part.state.input, part.state.output
textpart.text
step_finishpart.cost, part.tokens, part.reason
errorerror.data.message

Start a persistent server and attach multiple headless jobs:

Terminal window
# Start server (once per project)
opencode serve --port 4096 &
# Attach headless jobs (multiple can run concurrently)
opencode run --attach http://localhost:4096 "Fix auth module" --format json
opencode run --attach http://localhost:4096 "Write tests" --format json

This avoids MCP server cold-start overhead on every invocation — significantly faster than stateless CLI calls.

Terminal window
# Continue last session
opencode run "Continue the refactoring" --continue
# Resume specific session
opencode run "Fix the remaining issues" --session ses_XXXXXXXXXXXXXXXXXXXX
# Fork a session (don't overwrite original)
opencode run "Try a different approach" --fork --session ses_XXXX

Session data stored at ~/.local/share/opencode/.

{
"$schema": "https://opencode.ai/config.json",
"model": "vllm/devstral-123b",
"provider": {
"vllm": {
"npm": "@ai-sdk/openai-compatible",
"name": "Obelisk vLLM",
"options": {
"baseURL": "http://your-server:8000/v1"
},
"models": {
"devstral-123b": {
"name": "Devstral 123B"
}
}
}
}
}

Verify the model is accessible: curl http://your-server:8000/v1/models.

Claude Code + OpenCode Orchestration (Best of Both Worlds)

Section titled “Claude Code + OpenCode Orchestration (Best of Both Worlds)”

Like the Vibe Orchestration pattern, OpenCode can serve as a grunt-work executor dispatched by Claude Code. OpenCode’s advantages over Vibe for orchestration: LSP diagnostics catch type errors in-loop, session continuity via --continue/--attach, and JSONL events with token/cost tracking per step.

When to use OpenCode vs Vibe as the dispatch target:

TaskUse OpenCodeUse Vibe
TypeScript / Go / Rust / Python editsBest (LSP)Good
Long multi-step sessionsBest (compaction + sessions)Risky (no compaction)
CI/CD with cost trackingBest (JSONL has tokens/cost)Limited (internal only)
Quick one-shot tasksGoodBest (faster cold start)
Scripted dispatch to arbitrary dirsNo --workdir flagBest (--workdir)
Markdown / configs / docsGoodBest (lighter, LSP irrelevant)
┌──────────────────────────────────────────────────────────────────┐
│ Claude Code (Brain) │
│ Plans → Dispatches → Reviews → Synthesizes → Commits │
│ │
│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │
│ │ opencode run │ │ opencode run │ │ opencode run │ │
│ │ --attach :4096 │ │ --attach :4096 │ │ --attach :4096 │ │
│ │ TypeScript src │ │ Go backend │ │ Tests │ │
│ │ (LSP catches │ │ (LSP catches │ │ (parallel) │ │
│ │ type errors) │ │ type errors) │ │ │ │
│ └────────────────┘ └────────────────┘ └────────────────┘ │
│ ↓ ↓ ↓ │
│ opencode run (synthesizer) → Claude Code (judgment only) │
└──────────────────────────────────────────────────────────────────┘

Start one server per project — all headless jobs attach to it, avoiding MCP cold-start overhead:

Terminal window
# Start server (once per project, runs in background)
cd /path/to/project && opencode serve --port 4096 &
# Dispatch parallel agents — all attach to the same server
opencode run --attach http://localhost:4096 \
--model vllm/devstral-123b \
--dangerously-skip-permissions \
"Create src/lib/auth.ts with login, logout, session functions" &
opencode run --attach http://localhost:4096 \
--model vllm/devstral-123b \
--dangerously-skip-permissions \
"Write tests for src/lib/utils.ts at src/tests/utils.test.ts" &
opencode run --attach http://localhost:4096 \
--model vllm/devstral-123b \
--dangerously-skip-permissions \
"Document all exports in src/lib/ to docs/api.md" &
wait # All three complete in parallel

OpenCode’s --format json outputs structured events that pipelines can parse:

Terminal window
opencode run "Fix all TypeScript errors" \
--model vllm/devstral-123b \
--format json \
--dangerously-skip-permissions \
| jq 'select(.type == "step_finish") | {cost: .part.cost, tokens: .part.tokens}'

Each step_finish event includes cost and tokens (input/output/total) — useful for tracking spend in automated pipelines.

OpenCode’s --continue flag resumes the last session, preserving context:

Terminal window
# Step 1: Research
opencode run "Read src/api/ and list all endpoints" \
--model vllm/devstral-123b --dangerously-skip-permissions
# Step 2: Build on the research (same context)
opencode run "Add a new POST /api/reset-password endpoint following those patterns" \
--model vllm/devstral-123b --dangerously-skip-permissions --continue

This is something Vibe cannot do — each vibe -p invocation starts fresh with no memory.

ApproachClaude TokensSelf-Hosted TokensTime
Claude Code solo~500K ($2-10)01 session
Claude + OpenCode dispatch~50K ($0.20-1)Unlimited (free)Faster (parallel)
Claude + Vibe dispatch~50K ($0.20-1)Unlimited (free)Faster (parallel)
OpenCode solo (self-hosted)0UnlimitedSlower (weaker planning)

Define specialized agents in opencode.json:

{
"agent": {
"reviewer": {
"description": "Code review without making changes",
"mode": "primary",
"model": "anthropic/claude-opus-4-5",
"permission": {
"edit": "deny",
"write": "deny",
"bash": "deny"
}
},
"fast": {
"description": "Quick tasks with auto-approval",
"model": "anthropic/claude-haiku-4-5",
"permission": { "*": "allow" }
}
},
"default_agent": "reviewer"
}

Use with: opencode run "Review the PR" --agent reviewer.

  • LSP is the killer feature — use it on TypeScript, Go, Rust, and Python repos for significantly fewer hallucinated edits
  • opencode serve once per project, then attach headless jobs — avoids cold starts
  • /init generates AGENTS.md from your project — good starting point for custom rules
  • $schema in opencode.json enables full IDE autocompletion for config
  • Session fork (--fork --session) lets you try different approaches without losing the original session
  • OpenCode reads CLAUDE.md automatically — zero-effort migration from Claude Code
IssueWorkaroundStatus
npm package is opencode-ai not opencodeUse correct namePermanent
Context compaction at hardcoded 75% thresholdCan cause issues on long sessions; no config override yetOpen (#11314)
--format json may fail with --command flagUse positional arg insteadOpen (#2923)
WSL path breakage with Windows Desktop appClone repos into WSL filesystem, not /mnt/c/By design
Linux clipboard requires xclip/wl-clipboardInstall: sudo apt install xclipBy design
Excessive token consumption on large reposFixed in recent versions; monitor usageResolved
Corrupt plugin cache causes startup hangDelete plugin key from config, or remove ~/.cache/opencodeWorkaround
  • Claude Code - Anthropic’s proprietary agentic coding CLI (highest benchmark scores)
  • Mistral Vibe - Open-source CLI with self-hosted Devstral backend
  • OpenHands - Web-based autonomous coding agent with sandbox isolation
  • Gemini Code - Google’s Gemini CLI for multi-model orchestration
  • AI Agent Pricing - Cost comparison across all CLI agents