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
- Initial Setup and Knowledge
- Best Practices
- Sessions and Memory
- Rules and Permissions
- Skills
- MCPs
- Agents
- Other Useful Info
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.
| Category | What OpenCode Can Do |
|---|---|
| File operations | Read, edit, create files |
| Search | Find files by pattern (glob), search content (grep) |
| Execution | Run shell commands, tests, git operations |
| Web | Fetch documentation from URLs |
| LSP | Code intelligence via Language Server Protocol |
| MCP | Connect 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.mdfiles (also supportsCLAUDE.md,GEMINI.md) - Extensions -- MCP servers, skills, custom agents
Initial Setup and Knowledge
Reference: Getting Started: Providers
2.0 Getting Started
Install OpenCode:
bash# NPM npm install -g opencodeConnect via GitHub Copilot:
Run
opencodeand use/connectto authenticate. Select GitHub Copilot and follow the browser authentication flow to log in.Navigate to your project and initialize:
bashcd your-project opencodeInside the TUI, run
/initto analyze your project and generate anAGENTS.mdfile.Test it out with a simple prompt:
Explain this repositoryorWhat 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:
| Location | Scope | Shared |
|---|---|---|
~/.config/opencode/AGENTS.md | All projects | No (personal) |
./AGENTS.md (in git root) | Current project | Yes (commit to git) |
CLAUDE.md or GEMINI.md | Current project | Yes (also supported) |
Run /init to generate a starter AGENTS.md based on your project.
2.2 Common Commands
| Command | Purpose |
|---|---|
/init | Generate starter AGENTS.md |
/models | List and switch between models |
/connect | Add API provider credentials |
/new | Start fresh session |
/sessions | Switch between sessions |
/skills | Configure skills |
/variants | Switch model variant |
/mcps | Configure MCPs |
/editor | Open external editor for composing messages |
/themes | Select UI theme |
2.3 Key Bindings
Reference: Keybinds
OpenCode uses ctrl+x as the default leader key. Press ctrl+x then the shortcut.
| Key | Action |
|---|---|
@ | Add a file/folder to context (fuzzy search) |
! | Run a shell command directly (no model call) |
Tab | Cycle between Plan mode and normal mode |
Ctrl+X, N | New session |
Ctrl+X, L | Session list |
Ctrl+X, E | Open external editor |
Ctrl+X, T | Select theme |
Ctrl+X, B | Toggle sidebar |
Ctrl+X, U / Ctrl+X, R | Undo / Redo |
Ctrl+P | Command palette |
Ctrl+C | Exit app or clear input |
Esc | Interrupt 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.
/newbetween 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
| Strategy | Before | After |
|---|---|---|
| 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:
/newbetween tasks. - Correcting over and over -- context polluted with failed approaches. Fix: after 2 failed corrections,
/newand 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.
| Action | Command |
|---|---|
| Resume most recent | opencode --continue |
| Pick from recent sessions | /sessions |
| View timeline | Ctrl+X, G |
| Rename a session | Ctrl+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 history4.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.mdto version control for team consistency - Reserve
~/.config/opencode/AGENTS.mdfor 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 Type | Example | Default Behavior |
|---|---|---|
| Read-only | File reads, grep, glob | Allow |
| Shell commands | Bash execution | Allow |
| File modification | Edit/write files | Allow |
| URL access | Fetching external URLs | Allow |
| External directories | Access outside working directory | Ask |
| .env files | Read environment files | Deny |
Rules are evaluated with the last matching pattern winning.
5.2 Permission Modes
Each rule resolves to one of three outcomes:
| Mode | Behavior |
|---|---|
| allow | Executes without approval |
| ask | Prompts user for approval |
| deny | Blocks the action |
5.3 Permission Rules
Configure in opencode.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$HOMEfor home directory expansion
5.4 Approval Process
When prompted (ask mode), you can:
- Approve once -- allow this single request
- Approve all matching -- allow for the rest of the session
- 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
skilltool 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---
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 executingRun with the skill tool or by describing a task that matches the description.
6.4 Where Skills Live
| Location | Scope |
|---|---|
~/.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:
{
"skill": {
"*": "allow",
"dangerous-*": "ask",
"experimental-*": "deny"
}
}Permissions can also be overridden per agent:
{
"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:
{
"mcp": {
"sentry": {
"type": "local",
"command": ["npx", "-y", "@modelcontextprotocol/server-sentry"],
"env": {
"SENTRY_TOKEN": "your-token"
},
"enabled": true
}
}
}Remote MCP servers connect via HTTP:
{
"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:
{
"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):
| Agent | Purpose | Tools |
|---|---|---|
| Build | Default agent for full development work | All |
| Plan | Analysis and planning without code changes | Read-only |
Subagents (invoked by primary agents or via @ mentions):
| Agent | Purpose | Tools |
|---|---|---|
| General | Multi-step research tasks | All |
| Explore | Quick codebase exploration | Read-only |
Hidden System Agents (automatic):
- Compaction
- Title
- Summary
8.3 How to Create Your Own
Option 1: Interactive CLI
opencode agent createOption 2: JSON configuration
Add to opencode.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):
---
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 violations8.4 Key Configuration Options
| Field | Purpose |
|---|---|
description | Brief explanation of the agent's purpose (required) |
mode | primary, subagent, or all |
model | Override default model |
temperature | Control randomness (0.0-1.0) |
permission | Fine-grained tool access control |
prompt | Path to custom system instructions file |
max_steps | Limit agentic iterations |
skill | Enable/disable/control skill access |
8.5 Agent Locations
| Location | Scope |
|---|---|
~/.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:
{
"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:
# 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:
{
"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.jsonfor modular instructions - Start
/newsessions between unrelated tasks - Use subagents for exploration (they run in separate context)
9.5 External References
Load instructions from multiple sources in opencode.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
| Issue | Solution |
|---|---|
| Model not responding | Check API key with /connect, verify provider status |
| Permission prompts too frequent | Configure allowlist in opencode.json |
| Context limit exceeded | Disable unused MCPs, keep AGENTS.md concise, start /new session |
| Undo/redo not working | Ensure you're in a git repository with clean working tree |
| Skills not loading | Check file naming (must match directory name), verify YAML frontmatter |