writing/tutorial/2026/06
TutorialJun 12, 2026·22 min read

OpenCode: Complete Guide to the Open-Source Terminal AI Coding Agent

Master OpenCode, the open-source terminal AI coding agent with 120K+ GitHub stars. Learn installation, provider setup, AGENTS.md initialization, MCP integration, and TypeScript plugin development for data-sovereign coding workflows.

OpenCode has exploded to over 120,000 GitHub stars and 7.5 million monthly active developers, making it the most adopted open-source AI coding agent ever built. Unlike proprietary tools, it runs entirely in your terminal, supports 75+ model providers, works with local models for data privacy, and can be extended with TypeScript plugins.

This guide walks you through everything: installation, provider configuration, project initialization, MCP server integration, and writing your own plugins — giving you a fully customized AI coding workflow.

Prerequisites

Before starting, make sure you have:

  • Node.js 18+ or Bun installed
  • A terminal you're comfortable with
  • An API key for a model provider (Google Gemini, OpenAI, Mistral) or Ollama installed for local models
  • Basic familiarity with JSON configuration files

What You'll Learn

By the end of this guide you will:

  • Install and configure OpenCode for any project
  • Set up cloud and local model providers
  • Initialize projects with intelligent AGENTS.md generation
  • Integrate MCP servers for external tool access
  • Write custom TypeScript plugins to extend OpenCode's capabilities

Step 1: Installing OpenCode

OpenCode offers multiple installation methods:

curl -fsSL https://opencode.ai/install | bash

npm

npm install -g opencode@latest

Bun

bun add -g opencode

After installation, verify it works:

opencode --version

You should see the current version printed in your terminal.

Step 2: Configuring a Model Provider

OpenCode uses an opencode.json configuration file. Create it in your project root or in ~/.config/opencode/opencode.json for global settings.

The $schema field enables autocomplete in most editors.

Google Gemini (free tier available)

Google Gemini has a generous free tier and is the recommended starting point:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "google": {
      "apiKey": "YOUR_GEMINI_API_KEY"
    }
  },
  "model": "google/gemini-2-5-pro"
}

Get a Gemini API key at aistudio.google.com.

OpenAI

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "openai": {
      "apiKey": "YOUR_OPENAI_API_KEY"
    }
  },
  "model": "openai/gpt-4.1"
}

Mistral (EU-hosted, GDPR-friendly)

Mistral is an excellent choice for European and MENA teams requiring data residency:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "mistral": {
      "apiKey": "YOUR_MISTRAL_API_KEY"
    }
  },
  "model": "mistral/mistral-large-latest"
}

Using environment variables

Rather than hardcoding keys, set them as environment variables and reference them:

export GOOGLE_API_KEY="your-key-here"
export OPENAI_API_KEY="your-key-here"

OpenCode automatically detects GOOGLE_API_KEY, OPENAI_API_KEY, and MISTRAL_API_KEY without explicit configuration.

Step 3: Local Models for Complete Data Privacy

For sensitive codebases, financial systems, or environments with strict data residency requirements, run models locally. No API key or internet connection needed.

Ollama setup

Install Ollama from ollama.ai, then pull a coding-optimized model:

ollama pull qwen2.5-coder:32b
# Or the smaller variant for faster responses:
ollama pull qwen2.5-coder:7b

Configure OpenCode to use it:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama (local)",
      "options": {
        "baseURL": "http://127.0.0.1:11434/v1"
      },
      "models": {
        "qwen2.5-coder:32b": {
          "name": "Qwen 2.5 Coder 32B",
          "limit": {
            "context": 128000,
            "output": 32768
          }
        }
      }
    }
  },
  "model": "ollama/qwen2.5-coder:32b"
}

LM Studio setup

LM Studio provides a GUI for managing local models. Once a model is running in LM Studio:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "lmstudio": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "LM Studio (local)",
      "options": {
        "baseURL": "http://127.0.0.1:1234/v1"
      },
      "models": {
        "google/gemma-3n-e4b": {
          "name": "Gemma 3n-e4b (local)"
        }
      }
    }
  }
}

llama.cpp for maximum performance

For bare-metal speed using llama-server:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "llama.cpp": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "llama-server (local)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1"
      },
      "models": {
        "qwen3-coder:a3b": {
          "name": "Qwen3-Coder a3b-30b (local)",
          "limit": {
            "context": 128000,
            "output": 65536
          }
        }
      }
    }
  }
}

Performance tip: For a 32B parameter model, you need at minimum 20GB of unified/VRAM. Quantized Q4 versions run in under 16GB and maintain 90%+ of full-precision quality for code tasks.

Step 4: Initializing Your Project

Navigate to your project directory and launch OpenCode:

cd my-project
opencode

The terminal UI (TUI) opens. Type /init and press Enter. OpenCode analyzes your codebase and generates an AGENTS.md file in the project root.

Example AGENTS.md for a Next.js project

# Project: my-nextjs-app
 
## Tech Stack
- Next.js 15.3 with App Router
- TypeScript strict mode
- Tailwind CSS v4
- Drizzle ORM + PostgreSQL
- Vitest + React Testing Library
 
## Project Structure
- `app/` — Next.js routes and layouts
- `components/` — Reusable UI components
- `lib/` — Shared utilities and server functions
- `server/` — Database schema and queries
 
## Conventions
- Components named in PascalCase
- Server Actions in `app/actions/*.ts`
- API routes in `app/api/[route]/route.ts`
- Database queries in `server/queries/*.ts`
- Environment variables via `.env.local`, accessed through `lib/env.ts`
 
## Commands
- `npm run dev` — Start development server
- `npm run build` — Production build
- `npm test` — Run test suite
- `npm run db:push` — Apply schema changes

Commit AGENTS.md to git. This file is shared context that helps every team member's OpenCode session understand the project without re-analyzing it each time.

Customize the generated file: add architecture decisions, banned patterns, or important domain concepts your team uses.

Step 5: Core Commands and Navigation

Once OpenCode is running, these commands are available:

CommandDescription
/initAnalyze project and create AGENTS.md
/clearClear conversation context
/add path/to/fileAdd a specific file to the context window
/modelSwitch model provider mid-session
/helpList all available commands

Keyboard shortcuts

ShortcutAction
Ctrl+CCancel current operation
Ctrl+LClear terminal screen
TabAutocomplete commands
↑ / ↓Navigate command history
Ctrl+KKill current line

Effective prompting patterns

Ask for plans before changes:

"Before making any changes, explain what you plan to do to add pagination to the products listing page."

Scope changes explicitly:

"Refactor only lib/auth.ts to use the new session format. Do not touch other files."

Use context references:

"Using the Drizzle schema in server/db/schema.ts, write a query that returns all active users with their last login date."

Step 6: LSP Integration — Type-Aware AI

Enable Language Server Protocol support for richer, type-aware code assistance:

{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "lsp": "allow"
  }
}

With LSP active, OpenCode connects to your project's language server and gains access to:

  • Type information — sees the same types your editor sees
  • Go-to-definition — understands symbol references across files
  • Diagnostics — aware of TypeScript errors before suggesting changes
  • Hover documentation — accesses JSDoc comments and type signatures

For TypeScript projects, ensure the TypeScript language server is available:

npm install -g typescript typescript-language-server

LSP support is available for TypeScript, Python, Go, Rust, Java, and most languages with a standard LSP server.

Step 7: Connecting MCP Servers

The Model Context Protocol (MCP) lets you connect OpenCode to external tools and data sources. Configure MCP servers in opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "filesystem": {
      "type": "local",
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/me/projects/allowed-dir"
      ]
    },
    "database": {
      "type": "local",
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost/mydb"
      ]
    },
    "github": {
      "type": "local",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "your-token"
      }
    }
  }
}

With MCP connected, you can prompt OpenCode to:

  • Query your database schema and write type-safe queries against it
  • Read and create GitHub issues
  • Access files outside the current project directory

Step 8: Writing TypeScript Plugins

Plugins are the most powerful OpenCode feature, letting you add custom tools and intercept execution hooks.

Install the plugin SDK

npm install @opencode-ai/plugin

Custom tool: run project tests for a module

// .opencode/plugins/test-runner.ts
import { type Plugin, tool } from "@opencode-ai/plugin"
 
export const TestRunnerPlugin: Plugin = async (ctx) => {
  return {
    tool: {
      run_module_tests: tool({
        description: "Run the test suite for a specific module and return pass/fail summary",
        args: {
          module: tool.schema.string(),
        },
        async execute(args, context) {
          const { directory } = context
          return `Executing: vitest run ${args.module} in ${directory}`
        },
      }),
    },
  }
}

Lifecycle hook: sanitize bash commands

// .opencode/plugins/safety-guard.ts
import { escape } from "shescape"
 
export const SafetyGuardPlugin = async (ctx) => {
  return {
    "tool.execute.before": async (input, output) => {
      if (input.tool === "bash") {
        output.args.command = escape(output.args.command)
      }
    },
  }
}

Environment injection hook

// .opencode/plugins/env-injector.ts
import type { Plugin } from "@opencode-ai/plugin"
 
export const EnvInjectorPlugin: Plugin = async ({ project }) => {
  return {
    "shell.env": async (input, output) => {
      output.env.PROJECT_ROOT = project.root
      output.env.NODE_ENV = "development"
    },
  }
}

Registering plugins in opencode.json

{
  "$schema": "https://opencode.ai/config.json",
  "plugin": [
    "./.opencode/plugins/test-runner.ts",
    "./.opencode/plugins/safety-guard.ts",
    "./.opencode/plugins/env-injector.ts"
  ]
}

For published npm plugins, add them by package name:

{
  "plugin": [
    "opencode-helicone-session",
    "opencode-wakatime",
    "@my-org/internal-standards"
  ]
}

Step 9: Team Configuration Best Practices

Shared project-level config

Commit opencode.json to git without API keys (use environment variables instead):

{
  "$schema": "https://opencode.ai/config.json",
  "model": "google/gemini-2-5-pro",
  "permission": {
    "lsp": "allow",
    "bash": "ask"
  },
  "plugin": [
    "./.opencode/plugins/project-standards.ts"
  ],
  "mcp": {
    "database": {
      "type": "local",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "${DATABASE_URL}"]
    }
  }
}

Personal override config

Each developer keeps ~/.config/opencode/opencode.json for their API keys and personal preferences, which merges with the project config without affecting the shared file.

AGENTS.md maintenance

Treat AGENTS.md like production documentation. Update it when:

  • You adopt a new library or pattern
  • You add important domain concepts
  • You establish new architectural decisions
  • You discover patterns that should be avoided

A well-maintained AGENTS.md dramatically improves AI suggestion quality across your entire team.

Troubleshooting

Provider not responding: Verify your API key is set in the environment. Run echo $GOOGLE_API_KEY to confirm. OpenCode reads GOOGLE_API_KEY, OPENAI_API_KEY, and MISTRAL_API_KEY automatically.

Slow local model responses: Use a quantized (Q4 or Q8) model. For a 16GB RAM machine, qwen2.5-coder:7b-q8 gives the best speed-quality balance for coding tasks.

AGENTS.md not being loaded: It must be in the project root — the same directory where you run opencode. If your terminal is in a subdirectory, OpenCode may not find it.

LSP errors on startup: Ensure the language server binary is in your PATH. For TypeScript: verify typescript-language-server --version works in your terminal.

Plugin not loading: TypeScript plugins require a working tsconfig.json in the project root. Check that @opencode-ai/plugin is installed locally in node_modules.

Next Steps

Now that OpenCode is configured for your workflow:

  • Explore the plugin registry at opencode.ai/plugins for community-built integrations
  • Try agentic mode for multi-file refactors: describe the change at a high level and let OpenCode plan and execute
  • Integrate with CI for automated code review using opencode --no-tui in pipelines
  • Combine with Git worktrees to run parallel OpenCode sessions on different features simultaneously — see our Git Worktrees tutorial

Conclusion

OpenCode delivers the flexibility that proprietary coding agents can't: full provider choice, local model support for sensitive codebases, and an extensible plugin system that adapts to your team's exact workflow. With its LSP integration and MCP protocol support, it plugs into the same ecosystem your existing tools use — no new APIs to learn, no vendor lock-in.

The 7.5 million developers already using OpenCode daily are proof that open-source AI tooling has reached production quality. Configure it once, commit your AGENTS.md, and your entire team inherits a consistent, powerful AI coding assistant from day one.