OpenCode AI Coding Agent: Setup, Features & Configuration (2026)

EngineeringBy Ivern AI Team14 min read

OpenCode AI Coding Agent: Setup, Features & Configuration (2026)

OpenCode is a free, open-source AI coding agent that runs in your terminal. It supports multiple AI providers (Claude, GPT-4, Gemini), works with BYOK (Bring Your Own Key) pricing, and handles real coding tasks — from debugging to refactoring to writing entire features.

This guide covers installation, model configuration, key features, and practical usage patterns tested as of July 2026.

Related guides: OpenCode Review (50 Tasks Tested) · 7 OpenCode Alternatives · Cursor vs OpenCode · OpenCode vs Aider · Free AI Agent Tools · BYOK AI Platforms Ranked · Browse Gallery

Quick Comparison: OpenCode vs Other AI Coding Agents

Scroll to see full table

FeatureOpenCodeCursorAiderClaude Code
CostFree (BYOK)$20/monthFree (BYOK)$17/month
InterfaceTerminalIDETerminalTerminal
Multi-providerYes (5+)NoYes (3)Claude only
Open sourceYesNoYesNo
Auto-commitsNoNoYesNo

How to Install OpenCode

Prerequisites

  • Node.js 18+ (check with node --version)
  • npm or your preferred package manager (pnpm, yarn, bun)
  • An API key from at least one provider (Anthropic, OpenAI, or Google)

Installation

# Install globally via npm
npm install -g opencode-ai

# Or with pnpm (faster)
pnpm add -g opencode-ai

# Verify installation
opencode --version

As of July 2026, the latest stable version is 0.4.x. Check for updates with:

npm update -g opencode-ai

First Run

# Start OpenCode in your project directory
cd your-project
opencode

OpenCode launches an interactive terminal UI. On first run, it prompts you to configure at least one AI provider.

Configuring AI Providers (BYOK Setup)

OpenCode uses BYOK — you provide your own API keys, and there's no markup on usage. This means you pay provider-direct pricing (typically $2-8/month for moderate usage vs $20/month for Cursor).

Setting API Keys

Create a .env file or set environment variables:

# Anthropic (Claude 3.5 Sonnet, Opus)
export ANTHROPIC_API_KEY="sk-ant-..."

# OpenAI (GPT-4o, GPT-4 Turbo)
export OPENAI_API_KEY="sk-..."

# Google (Gemini 2.5 Pro, Flash)
export GOOGLE_API_KEY="AI..."

# Optional: Groq (fast inference)
export GROQ_API_KEY="gsk_..."

Or create an opencode.json config file in your project root:

{
  "providers": {
    "anthropic": {
      "apiKey": "${ANTHROPIC_API_KEY}",
      "models": ["claude-3.5-sonnet", "claude-3-opus"]
    },
    "openai": {
      "apiKey": "${OPENAI_API_KEY}",
      "models": ["gpt-4o", "gpt-4-turbo"]
    },
    "google": {
      "apiKey": "${GOOGLE_API_KEY}",
      "models": ["gemini-2.5-pro", "gemini-2.5-flash"]
    }
  },
  "defaultModel": "claude-3.5-sonnet"
}

Multi-Provider Routing

OpenCode's standout feature is multi-provider routing — you can switch models mid-session or route different task types to different providers:

  • Claude 3.5 Sonnet: Best for complex refactoring and architecture
  • GPT-4o: Best for quick edits and boilerplate
  • Gemini 2.5 Flash: Best for fast, low-cost tasks ($0.15/M input tokens)

Switch models in the terminal UI with Ctrl+M or configure auto-routing rules in opencode.json.

Advanced Configuration: Model Routing Rules

OpenCode supports automatic model routing based on task type. Configure this in your opencode.json:

{
  "routing": {
    "rules": [
      {
        "pattern": "refactor|architecture|design",
        "model": "claude-3.5-sonnet"
      },
      {
        "pattern": "test|spec|fixture",
        "model": "gpt-4o"
      },
      {
        "pattern": "format|lint|docs|comment",
        "model": "gemini-2.5-flash"
      }
    ],
    "defaultModel": "claude-3.5-sonnet"
  }
}

This routes refactoring tasks to Claude (highest quality), test generation to GPT-4o (good at boilerplate), and documentation/formatting to Gemini Flash (cheapest). Our benchmarks show this routing strategy saves 40-60% compared to using a single premium model for everything.

Project-Level vs Global Configuration

OpenCode supports two configuration scopes:

Global config (~/.config/opencode/config.json): Applied to all projects. Use for API keys and default model preferences.

Project config (.opencode.json in project root): Overrides global settings for a specific project. Use for project-specific model routing, MCP servers, or ignored files.

// .opencode.json — project-level config
{
  "ignore": [
    "node_modules/",
    "*.test.ts",
    "dist/"
  ],
  "contextFiles": [
    "README.md",
    "package.json",
    "tsconfig.json"
  ]
}

The ignore array prevents OpenCode from reading irrelevant files (reducing token costs). The contextFiles array ensures key project files are always included in context.

Key Features (2026)

1. Terminal-Native Interface

OpenCode runs entirely in the terminal with a rich TUI (terminal user interface). Key shortcuts:

Scroll to see full table

ShortcutAction
EnterSend message
Ctrl+MSwitch model
Ctrl+FToggle file context
Ctrl+RRun command preview
TabAccept suggestion
EscCancel generation

2. File Context Awareness

Try AI Presentation Generation — Free

Generate a complete AI-powered deck in under 90 seconds. No credit card needed.

Start Free

Get AI agent tips in your inbox

Multi-agent workflows, product updates, and tips. No spam.

OpenCode reads your project structure and includes relevant files as context automatically. You can also manually attach files:

@src/components/Button.tsx Fix the onClick handler to prevent double-clicks

3. Multi-File Editing

Unlike simpler tools, OpenCode can edit multiple files in a single response. It shows a diff preview before applying changes:

> Refactor the authentication flow to use JWT instead of session cookies

OpenCode proposes changes across:
 - src/lib/auth.ts (modified)
 - src/middleware.ts (modified)  
 - src/app/login/route.ts (modified)
 - src/lib/jwt.ts (new file)

4. Command Execution

OpenCode can run shell commands and interpret their output:

> Run the test suite and fix any failures

[Running: npm test]
✓ 42 passed, 3 failed
→ Fixing src/utils/date.test.ts (timezone handling)
→ Fixing src/api/users.test.ts (mock data mismatch)
→ Fixing src/hooks/useAuth.test.ts (async cleanup)
[Re-running: npm test]
✓ 45 passed, 0 failed

Setting Up MCP Servers with OpenCode

OpenCode supports MCP (Model Context Protocol) servers natively. MCP servers let OpenCode connect to external tools, databases, and APIs without custom code.

Adding MCP Servers

Configure MCP servers in your opencode.json:

{
  "mcp": {
    "servers": {
      "filesystem": {
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
      },
      "github": {
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-github"],
        "env": {
          "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token"
        }
      }
    }
  }
}

Once configured, OpenCode can:

  • Read and write files through the filesystem MCP server
  • Search issues, create PRs, and read repos via the GitHub MCP server
  • Query databases via the PostgreSQL MCP server

For a complete list of useful MCP servers, see our MCP servers guide.

Real-World Workflow: Bug Fix with OpenCode

Here is a practical example of using OpenCode to fix a real bug:

Step 1: Describe the problem

> Users report a 500 error on /api/users when email is null.
  The error occurs in src/api/users.ts around line 47.

Step 2: OpenCode reads and diagnoses

OpenCode: Reading src/api/users.ts...
Found: Line 47 passes `user.email` directly to the database query
without null checking. When email is null, the database constraint
fails and throws a 500 error.

Proposed fix:
1. Add null check before the database query
2. Return a 400 error with a helpful message
3. Add input validation middleware

Step 3: Review and apply the fix

OpenCode: Showing diff for src/api/users.ts

  - const result = await db.query('SELECT * FROM users WHERE email = ?', [user.email])
  + if (!user.email) {
  +   return res.status(400).json({ error: 'Email is required' })
  + }
  + const result = await db.query('SELECT * FROM users WHERE email = ?', [user.email])

Apply changes? [Y/n]

Step 4: Run tests

> Run the test suite to verify the fix

[Running: npm test]
✓ 48 passed, 0 failed (previously 45 passed, 3 failed)

This workflow — diagnose, fix, test — takes about 2-3 minutes with OpenCode and costs approximately $0.08 in API usage (with Claude Sonnet).

OpenCode itself is free. Your only cost is API usage. Here's real-world pricing based on our 50-task benchmark:

Scroll to see full table

ProviderModelCost per TaskMonthly Cost (50 tasks)
AnthropicClaude 3.5 Sonnet$0.08$4
OpenAIGPT-4o$0.12$6
GoogleGemini 2.5 Flash$0.02$1
MixedSonnet + Flash routing$0.05$2.50

Compare this to Cursor at $20/month or Claude Code at $17/month. See our full BYOK AI platforms comparison for detailed cost analysis.

Common Issues and Solutions

"API key not found"

Make sure environment variables are set in your shell profile (~/.bashrc or ~/.zshrc), not just the current session:

echo 'export ANTHROPIC_API_KEY="sk-ant-..."' >> ~/.bashrc
source ~/.bashrc

"Model not available"

Check that you're using the correct model name. OpenCode uses provider-native names:

  • claude-3.5-sonnet (not "Claude Sonnet")
  • gpt-4o (not "GPT-4 Optimized")
  • gemini-2.5-pro (not "Gemini Pro")

Run opencode models to list all available models.

Slow responses

Switch to a faster model for simple tasks. Gemini 2.5 Flash responds in 1-2 seconds vs 5-10 seconds for Claude Opus.

"Token limit exceeded"

Large files can exceed the model's context window. Solutions:

  1. Use @file to attach only specific files instead of entire directories
  2. Configure ignore patterns in opencode.json to skip large files
  3. Use a model with a larger context window (Gemini 2.5 Pro has 1M tokens)
  4. Break complex tasks into smaller, focused requests

"Changes not applied"

If OpenCode proposes changes but they don't appear in your files:

  1. Make sure you pressed Y to confirm the diff
  2. Check that files aren't locked by another process (IDE, git)
  3. Verify you're in the correct project directory (pwd)
  4. Check file permissions (ls -la)

High API costs

If your monthly API bill is higher than expected:

  1. Review your model routing — are you using Claude Opus for simple formatting?
  2. Enable context compression (reduces token usage 30-50%)
  3. Set ignore patterns to exclude node_modules/, dist/, and large data files
  4. Monitor usage on each provider's dashboard
  5. Use our AI agent cost calculator to estimate spend

OpenCode vs Alternatives: When to Use What

  • Use OpenCode if you want a free, multi-provider terminal agent with BYOK pricing
  • Use Cursor if you need IDE integration and visual diff editing
  • Use Aider if you want automatic git commits with every change
  • Use Claude Code if you're committed to the Anthropic ecosystem

Read our full comparisons: Cursor vs OpenCode and OpenCode vs Aider.

FAQ

Is OpenCode free?

Yes. OpenCode is 100% free and open-source. You only pay for the API calls to your chosen AI provider (typically $2-8/month with BYOK). For full pricing details, see our Is OpenCode Free? guide.

Can OpenCode work without an API key?

No. OpenCode requires at least one provider API key to function. However, you can use free-tier APIs like Google's Gemini which offers generous free limits (15 RPM, 1500 requests/day).

Does OpenCode support multiple languages?

Yes. OpenCode works with any programming language — JavaScript, TypeScript, Python, Go, Rust, Java, C++, and more. It reads file extensions and project structure to understand context.

Can OpenCode write entire features?

Yes. In our 50-task benchmark, OpenCode successfully wrote complete features (authentication flows, API endpoints, UI components) from natural language descriptions. See our full OpenCode review for details.

Does OpenCode work on Windows?

Yes, but with limitations. OpenCode runs best on macOS and Linux. On Windows, use WSL (Windows Subsystem for Linux) for full compatibility. Native Windows support is improving but some features (like shell command execution) work better through WSL.

How does OpenCode compare to GitHub Copilot?

OpenCode and Copilot serve different needs. Copilot provides inline code completion inside your IDE. OpenCode is a terminal-based agent that handles complete tasks — reading files, making multi-file edits, running tests, and debugging. They can be used together. See our best free AI coding assistants guide for a full comparison.

Can I use OpenCode with local models?

Yes. OpenCode supports local models via Ollama. Install Ollama, pull a coding model (like ollama pull deepseek-coder), and configure OpenCode to use it. Local models cost $0 but require a GPU with 16GB+ VRAM.

Does OpenCode support MCP servers?

Yes. OpenCode has native MCP (Model Context Protocol) support. You can configure MCP servers in your opencode.json to connect OpenCode to external tools, databases, and APIs. See our MCP servers guide for setup instructions.


Ready to coordinate multiple AI agents? Try Ivern AI free — create squads of AI agents that work together on real tasks. BYOK pricing, 15 free tasks, no credit card required.

More guides: OpenCode Review (50 Tasks) · 7 OpenCode Alternatives · Cursor vs OpenCode · OpenCode vs Aider · Free AI Agent Tools · BYOK AI Platforms · All Guides

✨ AI-Powered Presentations

Create AI-Powered Presentations for Free

Generate complete, polished slide decks in under 90 seconds. Our 3-agent AI pipeline researches, designs, and writes your presentation automatically.

Start Free — 1 AI Presentation Credit Included

No credit card required · Free tier included

Ivern Slides -- Free to Start

Generate complete AI presentations in 60 seconds. 3-agent pipeline, free tier included.

No spam. Unsubscribe anytime.