Skip to content

OpenCode Playbook

A concise guide covering everything you need to know to get started and work effectively with OpenCode.


Table of Contents


How It Works

Reference: OpenCode Documentation

OpenCode is an open-source AI coding agent accessible through multiple interfaces: terminal-based (TUI), desktop app, or IDE extension.

1.1 The Agentic Loop

When you give OpenCode a task, it works through a loop of gathering context, taking action, and verifying results -- repeating until the task is complete. You can interrupt at any point to steer it.

1.2 Models

OpenCode supports multiple LLM providers depending on your connection type. Use /models to switch between available models mid-session.

1.3 Tools

Reference: AI Tools

Tools make OpenCode agentic. Without them, it can only respond with text. With them, it can act.

CategoryWhat OpenCode Can Do
File operationsRead, edit, create files
SearchFind files by pattern (glob), search content (grep)
ExecutionRun shell commands, tests, git operations
WebFetch documentation from URLs
LSPCode intelligence via Language Server Protocol
MCPConnect to external tools and services

1.4 What OpenCode Can Access

When you run opencode in a directory, it gains access to:

  • Your project -- files in the current directory and subdirectories
  • Your terminal -- any command you could run (build tools, git, package managers, etc.)
  • Your git state -- current branch, uncommitted changes, recent history
  • Custom instructions -- AGENTS.md files (also supports CLAUDE.md, GEMINI.md)
  • Extensions -- MCP servers, skills, custom agents

Initial Setup and Knowledge

Reference: Getting Started: Providers

2.0 Getting Started

  1. Install OpenCode:

    bash
    # NPM
    npm install -g opencode
  2. Connect via GitHub Copilot:

    Run opencode and use /connect to authenticate. Select GitHub Copilot and follow the browser authentication flow to log in.

  3. Navigate to your project and initialize:

    bash
    cd your-project
    opencode

    Inside the TUI, run /init to analyze your project and generate an AGENTS.md file.

  4. Test it out with a simple prompt: Explain this repository or What does this project do?

2.1 AGENTS.md

Reference: Rules

AGENTS.md is a markdown file that OpenCode reads at the start of every session. Use it to store instructions, conventions, and context that OpenCode cannot infer from code alone.

What to include:

  • Build/test/lint commands
  • Code style rules that differ from defaults
  • Repository etiquette (branch naming, PR conventions)
  • Architectural decisions specific to your project

What to exclude:

  • Anything OpenCode can figure out by reading code
  • Standard language conventions
  • Long explanations or tutorials

Locations:

LocationScopeShared
~/.config/opencode/AGENTS.mdAll projectsNo (personal)
./AGENTS.md (in git root)Current projectYes (commit to git)
CLAUDE.md or GEMINI.mdCurrent projectYes (also supported)

Run /init to generate a starter AGENTS.md based on your project.

2.2 Common Commands

CommandPurpose
/initGenerate starter AGENTS.md
/modelsList and switch between models
/connectAdd API provider credentials
/newStart fresh session
/sessionsSwitch between sessions
/skillsConfigure skills
/variantsSwitch model variant
/mcpsConfigure MCPs
/editorOpen external editor for composing messages
/themesSelect UI theme

2.3 Key Bindings

Reference: Keybinds

OpenCode uses ctrl+x as the default leader key. Press ctrl+x then the shortcut.

KeyAction
@Add a file/folder to context (fuzzy search)
!Run a shell command directly (no model call)
TabCycle between Plan mode and normal mode
Ctrl+X, NNew session
Ctrl+X, LSession list
Ctrl+X, EOpen external editor
Ctrl+X, TSelect theme
Ctrl+X, BToggle sidebar
Ctrl+X, U / Ctrl+X, RUndo / Redo
Ctrl+PCommand palette
Ctrl+CExit app or clear input
EscInterrupt current operation

2.4 How to Work Effectively

  • Be specific upfront -- reference files with @, mention constraints, point to patterns
  • Give verification criteria -- tests, expected outputs
  • Explore before implementing -- use Plan mode (Tab) for complex problems
  • Delegate, don't dictate -- give context and direction, trust OpenCode with the details
  • Interrupt and steer -- press Esc to interrupt, then provide corrections

2.5 Common Workflow Patterns

Explore → Plan → Confirm → Implement:

Write Tests → Commit → Code → Iterate → Commit:


Best Practices

3.1 The #1 Rule: Give OpenCode a Way to Verify Its Work

Include tests, screenshots, or expected outputs so OpenCode can check itself. This is the single highest-leverage thing you can do.

3.2 Context Management

OpenCode loads context from files, history, and extensions. Keep sessions focused to avoid exceeding context limits.

  • /new between unrelated tasks
  • Use Plan mode for exploration -- it won't pollute your working context
  • Keep AGENTS.md concise
  • Be selective with MCP servers -- they add to your context

3.3 Prompting Tips

StrategyBeforeAfter
Scope the task"add tests for foo.py""write a test for foo.py covering the edge case where the user is logged out, avoid mocks"
Point to sources"why is this API weird?""look through ExecutionFactory's git history and summarize how its API came to be"
Reference patterns"add a calendar widget""look at how DatePicker is implemented, follow the same pattern for a calendar widget"
Describe symptoms"fix the login bug""users report login fails after session timeout, check src/auth/, especially token refresh"

3.4 Avoid Common Failure Patterns

  • Kitchen sink session -- mixing unrelated tasks in one session. Fix: /new between tasks.
  • Correcting over and over -- context polluted with failed approaches. Fix: after 2 failed corrections, /new and write a better prompt.
  • Over-specified AGENTS.md -- OpenCode ignores half of it. Fix: ruthlessly prune.
  • Trust-then-verify gap -- no tests provided. Fix: always provide verification.
  • Too many MCPs -- context overload. Fix: disable unused MCP servers.

Sessions and Memory

4.1 Sessions

Each session is an independent conversation tied to your current directory. Sessions save locally and can be resumed.

ActionCommand
Resume most recentopencode --continue
Pick from recent sessions/sessions
View timelineCtrl+X, G
Rename a sessionCtrl+R
Share a session/share

Session storage:

~/.local/share/opencode/sessions/{session-id}/
├── messages.jsonl     # Full conversation history
├── metadata.json      # Session metadata
└── checkpoints/       # Undo/redo history

4.2 Memory Types

AGENTS.md Files -- You write and maintain these. Loaded in full at session start.

Session History -- OpenCode automatically saves conversation history. Resume any previous session with /sessions.

4.3 Memory Best Practices

  • Be specific: "Use 2-space indentation" not "Format code properly"
  • Use structure: bullet points grouped under descriptive headings
  • Review periodically as your project evolves
  • Commit project AGENTS.md to version control for team consistency
  • Reserve ~/.config/opencode/AGENTS.md for personal preferences only

Rules and Permissions

Reference: Permissions

5.1 Permission System

OpenCode uses a permission configuration to control which actions run automatically, require approval, or are blocked.

Tool TypeExampleDefault Behavior
Read-onlyFile reads, grep, globAllow
Shell commandsBash executionAllow
File modificationEdit/write filesAllow
URL accessFetching external URLsAllow
External directoriesAccess outside working directoryAsk
.env filesRead environment filesDeny

Rules are evaluated with the last matching pattern winning.

5.2 Permission Modes

Each rule resolves to one of three outcomes:

ModeBehavior
allowExecutes without approval
askPrompts user for approval
denyBlocks the action

5.3 Permission Rules

Configure in opencode.json:

json
{
  "permission": {
    "*": "ask",
    "read": "allow",
    "bash": {
      "npm run *": "allow",
      "git push *": "ask",
      "rm -rf *": "deny"
    }
  }
}

A more comprehensive example of common permission rules can be found here

Pattern syntax:

  • * matches zero or more characters
  • ? matches exactly one character
  • ~ or $HOME for home directory expansion

5.4 Approval Process

When prompted (ask mode), you can:

  1. Approve once -- allow this single request
  2. Approve all matching -- allow for the rest of the session
  3. Reject -- block and provide alternative instructions

Skills

Reference: Skills

6.1 What Is a Skill?

A skill is a folder with a SKILL.md file containing instructions that OpenCode loads on-demand when relevant. Skills teach OpenCode to perform tasks in a specific, repeatable way.

6.2 When Is It Used?

  • By OpenCode automatically -- when the task matches the skill's description
  • By you manually -- via the skill tool or direct reference

Example use cases:

  • Create consistent release notes and changelogs
  • Enforce code review standards
  • Generate API documentation
  • Run deployment checklists

6.3 How to Create a Skill

Create a directory with a SKILL.md in .opencode/skills/ or ~/.config/opencode/skills/:

.opencode/skills/git-release/
└── SKILL.md
yaml
---
name: git-release
description: Create consistent releases and changelogs
---
To create a release:
1. Review recent commits since last release
2. Draft release notes grouped by type (features, fixes, breaking changes)
3. Propose version bump (major, minor, patch)
4. Generate `gh release create` command
5. Ask user to review before executing

Run with the skill tool or by describing a task that matches the description.

6.4 Where Skills Live

LocationScope
~/.config/opencode/skills/All projects (personal)
.opencode/skills/Current project (team-shared)
.claude/skills/ or .agents/skills/Also supported (compatibility)

6.5 Skill Permissions

Control skill access in opencode.json:

json
{
  "skill": {
    "*": "allow",
    "dangerous-*": "ask",
    "experimental-*": "deny"
  }
}

Permissions can also be overridden per agent:

json
{
  "agents": {
    "plan": {
      "skill": false
    }
  }
}

6.6 Skill Format

Each SKILL.md must have YAML frontmatter:

  • name (required): 1–64 characters, lowercase alphanumeric with hyphens
  • description (required): 1–1024 characters
  • license, compatibility, metadata (optional)

The skill name must match its directory name and follow the regex pattern: ^[a-z0-9]+(-[a-z0-9]+)*$


MCPs

Reference: MCP Servers

7.1 What Is an MCP?

MCP (Model Context Protocol) is an open standard for connecting OpenCode to external tools, databases, and APIs. MCP servers give OpenCode access to services beyond the terminal.

7.2 Use Cases

  • Query databases (PostgreSQL, etc.)
  • Search documentation across resources (Context7)
  • Monitor errors with Sentry
  • Search code examples from GitHub (Grep by Vercel)
  • Integrate with any MCP-compatible service

7.3 How to Configure

MCP servers are configured in opencode.json.

Local MCP servers run commands on your machine:

json
{
  "mcp": {
    "sentry": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-sentry"],
      "env": {
        "SENTRY_TOKEN": "your-token"
      },
      "enabled": true
    }
  }
}

Remote MCP servers connect via HTTP:

json
{
  "mcp": {
    "context7": {
      "type": "remote",
      "url": "https://context7.example.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_TOKEN"
      }
    }
  }
}

Tool Management:

Control MCP tools globally or per-agent using glob patterns:

json
{
  "mcp": {
    "sentry*": false
  },
  "agents": {
    "debug": {
      "mcp": {
        "sentry*": true
      }
    }
  }
}

7.4 Security Concerns

  • Use third-party MCP servers at your own risk
  • Be cautious with servers that fetch untrusted content (prompt injection risk)
  • MCP servers add to your context -- excessive tools can exceed limits and increase token usage
  • Review server source and permissions before adding

Agents

Reference: Agents

8.1 What Is an Agent?

Agents are specialized AI assistants configured for specific tasks and workflows. They enable focused tools with custom prompts, models, and tool access. Switch between agents using Tab or @ mentions.

8.2 Built-in Agents

Primary Agents (direct interaction):

AgentPurposeTools
BuildDefault agent for full development workAll
PlanAnalysis and planning without code changesRead-only

Subagents (invoked by primary agents or via @ mentions):

AgentPurposeTools
GeneralMulti-step research tasksAll
ExploreQuick codebase explorationRead-only

Hidden System Agents (automatic):

  • Compaction
  • Title
  • Summary

8.3 How to Create Your Own

Option 1: Interactive CLI

bash
opencode agent create

Option 2: JSON configuration

Add to opencode.json:

json
{
  "agents": {
    "code-reviewer": {
      "mode": "primary",
      "description": "Review code for quality and best practices",
      "model": "claude-sonnet-4.5",
      "temperature": 0.3,
      "permission": {
        "read": "allow",
        "edit": "deny",
        "bash": "deny"
      },
      "max_steps": 10
    }
  }
}

Option 3: Markdown files

Create .md files in ~/.config/opencode/agents/ (global) or .opencode/agents/ (project):

markdown
---
name: code-reviewer
description: Review code for quality and best practices
mode: primary
model: claude-sonnet-4.5
temperature: 0.3
---

You are a code reviewer focused on quality and best practices.

Analyze code and provide specific, actionable feedback on:
- Code quality and maintainability
- Security vulnerabilities
- Performance issues
- Best practices violations

8.4 Key Configuration Options

FieldPurpose
descriptionBrief explanation of the agent's purpose (required)
modeprimary, subagent, or all
modelOverride default model
temperatureControl randomness (0.0-1.0)
permissionFine-grained tool access control
promptPath to custom system instructions file
max_stepsLimit agentic iterations
skillEnable/disable/control skill access

8.5 Agent Locations

LocationScope
~/.config/opencode/agents/All projects (personal)
.opencode/agents/Current project (team-shared)

Other Useful Info

9.1 TUI Configuration

Reference: TUI

Customize behavior via tui.json:

json
{
  "theme": "tokyo-night",
  "keybinds": {
    "leader": "ctrl+x"
  },
  "scroll": {
    "speed": 5,
    "acceleration": true
  },
  "diff": {
    "style": "unified"
  },
  "mouse_capture": true
}

Use Ctrl+P (command palette) for runtime customization.

9.2 Editor Setup

The /editor and /export commands use your EDITOR environment variable. Popular options:

bash
# VS Code
export EDITOR="code --wait"

# Cursor
export EDITOR="cursor --wait"

# Vim
export EDITOR="vim"

# Nano
export EDITOR="nano"

9.3 Model Configuration

Configure default model and variants in opencode.json:

json
{
  "provider": "anthropic",
  "model": "claude-opus-4.5",
  "variants": {
    "high-thinking": {
      "provider": "anthropic",
      "model": "claude-opus-4.5",
      "options": {
        "thinking": "high"
      }
    }
  }
}

9.4 Context Management

Strategies to avoid exceeding context limits:

  • Keep AGENTS.md concise (focus on non-obvious project specifics)
  • Disable unused MCP servers
  • Use glob patterns in opencode.json for modular instructions
  • Start /new sessions between unrelated tasks
  • Use subagents for exploration (they run in separate context)

9.5 External References

Load instructions from multiple sources in opencode.json:

json
{
  "instructions": [
    "docs/guidelines.md",
    "packages/*/AGENTS.md",
    "https://example.com/api-conventions.md"
  ]
}

Supports local paths with glob patterns and remote URLs (5-second timeout).

9.6 Troubleshooting

Reference: Troubleshooting

IssueSolution
Model not respondingCheck API key with /connect, verify provider status
Permission prompts too frequentConfigure allowlist in opencode.json
Context limit exceededDisable unused MCPs, keep AGENTS.md concise, start /new session
Undo/redo not workingEnsure you're in a git repository with clean working tree
Skills not loadingCheck file naming (must match directory name), verify YAML frontmatter

Additional Resources

Copyright © MSG Systems Romania AI Labs