# Opencode > Agents are specialized AI assistants with custom prompts, models, and tool access. Two types: --- # OpenCode Agents ## Overview Agents are specialized AI assistants with custom prompts, models, and tool access. Two types: 1. **Primary agents**: Main assistants you interact with (cycle with Tab) 2. **Subagents**: Specialized assistants invoked by primary agents or @ mentions ## Built-in Agents ### Build (Primary) Default agent with all tools enabled for full development work. ### Plan (Primary) Analysis agent with restricted permissions. By default: - File edits: Ask before making changes - Bash commands: Ask before running Use for planning without modifying code. ### General (Subagent) General-purpose agent for: - Researching complex questions - Searching for code - Multi-step tasks ### Explore (Subagent) Fast codebase exploration agent for: - Finding files by patterns - Searching code for keywords - Answering codebase questions ## Usage ### Primary Agents - Switch with **Tab** key - Or use configured `switch_agent` keybind ### Subagents - Automatically invoked by primary agents - Manually invoke with @ mention: ``` @general help me search for this function ``` ### Session Navigation Navigate between parent and child sessions: - **Leader+Right**: Cycle forward (parent → child1 → child2 → parent) - **Leader+Left**: Cycle backward ## Configuration ### JSON Config ```json { "agent": { "code-reviewer": { "description": "Reviews code for best practices and issues", "mode": "subagent", "model": "anthropic/claude-sonnet-4-5", "prompt": "You are a code reviewer. Focus on security, performance, maintainability.", "temperature": 0.1, "tools": { "write": false, "edit": false }, "permission": { "bash": "ask" } } } } ``` ### Markdown Files Create in `~/.config/opencode/agent/` or `.opencode/agent/`: **review.md:** ```markdown --- description: Reviews code for quality and best practices mode: subagent model: anthropic/claude-sonnet-4-5 temperature: 0.1 tools: write: false edit: false bash: false --- You are in code review mode. Focus on: - Code quality and best practices - Potential bugs and edge cases - Performance implications - Security considerations Provide constructive feedback without making direct changes. ``` ## Agent Options ### Required - **description**: What the agent does and when to use it ### Optional - **mode**: "primary", "subagent", or "all" (default: "all") - **model**: Override default model (e.g., "anthropic/claude-haiku-4-5") - **prompt**: Custom system prompt or `{file:./prompts/review.txt}` - **temperature**: 0.0-1.0 (lower = focused, higher = creative) - 0.0-0.2: Very focused (analysis, planning) - 0.3-0.5: Balanced (general development) - 0.6-1.0: Creative (brainstorming) - **maxSteps**: Max iterations before forced stop - **tools**: Tool availability overrides - **permission**: Permission overrides ### Tools Override ```json { "agent": { "readonly": { "tools": { "write": false, "edit": false, "bash": false, "mymcp_*": false // Wildcard patterns supported } } } } ``` ### Permissions ```json { "agent": { "build": { "permission": { "edit": "ask", "bash": { "git status": "allow", "git *": "ask", "*": "ask" } } } } } ``` In markdown: ```markdown --- permission: edit: deny bash: "git diff": allow "git log*": allow "*": ask webfetch: deny --- ``` ### Provider-Specific Options Pass through to provider (e.g., OpenAI reasoning): ```json { "agent": { "deep-thinker": { "model": "openai/gpt-5", "reasoningEffort": "high", "textVerbosity": "low" } } } ``` ## Default Agent Set which agent starts by default: ```json { "default_agent": "plan" // Must be primary agent } ``` Applies to: TUI, CLI (`opencode run`), desktop app, GitHub Action. ## Creating Agents ### Interactive Creation ```bash opencode agent create ``` Prompts for: 1. Save location (global/project) 2. Description 3. Tool access 4. Creates markdown file ### List Agents ```bash opencode agent list ``` ## Example Agents ### Documentation Writer **~/.config/opencode/agent/docs-writer.md:** ```markdown --- description: Writes and maintains project documentation mode: subagent tools: bash: false --- You are a technical writer. Create clear, comprehensive documentation. Focus on: - Clear explanations - Proper structure - Code examples - User-friendly language ``` ### Security Auditor **~/.config/opencode/agent/security-auditor.md:** ```markdown --- description: Performs security audits and identifies vulnerabilities mode: subagent tools: write: false edit: false --- You are a security expert. Focus on identifying potential security issues. Look for: - Input validation vulnerabilities - Authentication and authorization flaws - Data exposure risks - Dependency vulnerabilities - Configuration security issues ``` ### Debug Agent ```json { "agent": { "debug": { "description": "Focused debugging with investigation tools", "mode": "subagent", "tools": { "write": false, "edit": false, "bash": true, "read": true, "grep": true } } } } ``` ## Common Use Cases - **Build**: Full development with all tools - **Plan**: Analysis and planning without changes - **Review**: Code review with read-only + docs - **Debug**: Investigation with bash and read tools - **Docs**: Documentation with file ops, no system commands ## Model Selection OpenCode supports provider/model format (e.g., `anthropic/claude-sonnet-4-5`, `openai/gpt-4`, `deepseek-ai/DeepSeek-V3`). **Recommendations:** - **General development:** Claude Sonnet 4.5, GPT-4, DeepSeek V3 - **Fast tasks:** Claude Haiku, GPT-4 Mini - **Complex reasoning:** Claude Opus 4.5, DeepSeek R1 - **Local/cost-conscious:** Ollama, LM Studio with smaller models ## Session Navigation Primary and subagent invocations create a session tree: ``` Primary Agent (parent) ├── Subagent 1 (child) ├── Subagent 2 (child) └── Subagent 3 (child) ``` Navigate with: - **Leader+Right**: Next session (parent → child1 → child2 → parent) - **Leader+Left**: Previous session (reverse order) ## Notes - Agent names from markdown files match filename (e.g., `review.md` → `review`) - Global config agents override built-in if same name - Subagents inherit primary agent's model unless overridden - Temperature defaults: 0.1 for analysis, 0.55 for Qwen models - Provider-specific options pass through to underlying API (e.g., `reasoningEffort`, `textVerbosity`) --- # OpenCode CLI Reference ## Default Command ```bash # Start TUI in current directory opencode # Start TUI in specific directory opencode /path/to/project ``` ## TUI Command ```bash opencode [project] ``` ### Flags - `--continue`, `-c`: Continue last session - `--session`, `-s`: Session ID to continue - `--prompt`, `-p`: Prompt to use - `--model`, `-m`: Model in format provider/model - `--agent`: Agent to use - `--port`: Port to listen on - `--hostname`: Hostname to listen on ### Examples ```bash # Continue last session opencode -c # Use specific model opencode -m anthropic/claude-sonnet-4-5 # Start with prompt opencode -p "Explain the codebase" ``` ## Agent Commands ### Create Agent ```bash opencode agent create ``` Interactive wizard to create new agent. ### List Agents ```bash opencode agent list ``` ## Auth Commands ### Login to Provider ```bash opencode auth login ``` Configure API keys for providers. Stored in `~/.local/share/opencode/auth.json`. ### List Authenticated Providers ```bash opencode auth list # or opencode auth ls ``` ### Logout from Provider ```bash opencode auth logout ``` ## GitHub Commands ### Install GitHub Agent ```bash opencode github install ``` Sets up GitHub Actions workflow for repository automation. ### Run GitHub Agent ```bash opencode github run ``` Flags: - `--event`: GitHub mock event - `--token`: GitHub personal access token ## MCP Commands ### Add MCP Server ```bash opencode mcp add ``` Interactive wizard for local or remote MCP servers. ### List MCP Servers ```bash opencode mcp list # or opencode mcp ls ``` ### Authenticate with OAuth MCP ```bash # Interactive selection opencode mcp auth # Specific server opencode mcp auth # List OAuth-capable servers opencode mcp auth list # or opencode mcp auth ls ``` ### Logout from MCP ```bash opencode mcp logout ``` ### Debug MCP OAuth ```bash opencode mcp debug ``` ## Models Commands ### List Available Models ```bash # All models opencode models # Models from specific provider opencode models anthropic # Refresh cache from models.dev opencode models --refresh # Verbose output (includes costs) opencode models --verbose ``` ## Run Command Non-interactive execution: ```bash opencode run [message..] ``` ### Flags - `--command`: Command to run - `--continue`, `-c`: Continue last session - `--session`, `-s`: Session ID to continue - `--share`: Share the session - `--model`, `-m`: Model (provider/model format) - `--agent`: Agent to use - `--file`, `-f`: File(s) to attach - `--format`: Output format (default or json) - `--title`: Session title - `--attach`: Attach to running server (e.g., http://localhost:4096) - `--port`: Local server port ### Examples ```bash # Quick question opencode run "Explain async/await in JavaScript" # With file attachment opencode run -f config.json "Analyze this config" # Attach to running server opencode run --attach http://localhost:4096 "Explain closures" # JSON output opencode run --format json "List all functions" ``` ## Serve Command Start headless HTTP server: ```bash opencode serve ``` Flags: - `--port`, `-p`: Port to listen on - `--hostname`: Hostname to listen on Use with `opencode run --attach` to avoid MCP cold boot times. ## Session Commands ### List Sessions ```bash opencode session list ``` Flags: - `--max-count`, `-n`: Limit to N recent sessions - `--format`: Output format (table or json) ## Stats Command Show usage statistics: ```bash opencode stats ``` Flags: - `--days`: Last N days (default: all time) - `--tools`: Number of tools to show (default: all) - `--project`: Filter by project (default: all) ## Export Command Export session as JSON: ```bash # Interactive selection opencode export # Specific session opencode export ``` ## Import Command Import session from JSON or share URL: ```bash # From file opencode import session.json # From share URL opencode import https://opncd.ai/s/abc123 ``` ## Web Command Start web interface: ```bash opencode web ``` Flags: - `--port`, `-p`: Port to listen on - `--hostname`: Hostname to listen on ## ACP Command Start Agent Client Protocol server: ```bash opencode acp ``` Flags: - `--cwd`: Working directory - `--port`: Port to listen on - `--hostname`: Hostname to listen on ## Uninstall Command Remove OpenCode and related files: ```bash opencode uninstall ``` Flags: - `--keep-config`, `-c`: Keep config files - `--keep-data`, `-d`: Keep sessions and snapshots - `--dry-run`: Show what would be removed - `--force`, `-f`: Skip confirmation ## Upgrade Command Update to latest or specific version: ```bash # Latest version opencode upgrade # Specific version opencode upgrade v0.1.48 ``` Flags: - `--method`, `-m`: Installation method (curl, npm, pnpm, bun, brew) ## Global Flags Available for all commands: - `--help`, `-h`: Display help - `--version`, `-v`: Print version - `--print-logs`: Print logs to stderr - `--log-level`: Set log level (DEBUG, INFO, WARN, ERROR) ## Environment Variables ### General - `OPENCODE_AUTO_SHARE`: Auto-share sessions (boolean) - `OPENCODE_GIT_BASH_PATH`: Git Bash path on Windows - `OPENCODE_CONFIG`: Config file path - `OPENCODE_CONFIG_DIR`: Config directory path - `OPENCODE_CONFIG_CONTENT`: Inline JSON config - `OPENCODE_DISABLE_AUTOUPDATE`: Disable auto-updates - `OPENCODE_DISABLE_PRUNE`: Disable old data pruning - `OPENCODE_DISABLE_TERMINAL_TITLE`: Disable terminal title updates - `OPENCODE_PERMISSION`: Inline permissions JSON - `OPENCODE_DISABLE_DEFAULT_PLUGINS`: Disable default plugins - `OPENCODE_DISABLE_LSP_DOWNLOAD`: Disable LSP auto-downloads - `OPENCODE_ENABLE_EXPERIMENTAL_MODELS`: Enable experimental models - `OPENCODE_DISABLE_AUTOCOMPACT`: Disable auto-compaction - `OPENCODE_CLIENT`: Client identifier (default: "cli") - `OPENCODE_ENABLE_EXA`: Enable Exa web search ### Experimental - `OPENCODE_EXPERIMENTAL`: Enable all experimental features - `OPENCODE_EXPERIMENTAL_ICON_DISCOVERY`: Icon discovery - `OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT`: Disable copy on select - `OPENCODE_EXPERIMENTAL_BASH_MAX_OUTPUT_LENGTH`: Max bash output length - `OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS`: Bash timeout (ms) - `OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX`: Max output tokens - `OPENCODE_EXPERIMENTAL_FILEWATCHER`: Enable file watcher - `OPENCODE_EXPERIMENTAL_OXFMT`: Enable oxfmt formatter - `OPENCODE_EXPERIMENTAL_LSP_TOOL`: Enable LSP tool ## Examples ```bash # Complete workflow opencode auth login # Configure provider cd /path/to/project # Navigate to project opencode # Start TUI # In TUI: /init # Initialize project # Quick tasks opencode run "Add error handling to auth.ts" opencode run -f package.json "Update dependencies" # Server mode opencode serve & # Start server opencode run --attach http://localhost:4096 "Review code" # Session management opencode session list # List sessions opencode export abc123 # Export session opencode import session.json # Import session # Statistics opencode stats --days 7 # Last 7 days opencode stats --project myapp # Specific project ``` --- # OpenCode Configuration ## Config Locations Configuration files are merged in this order (later overrides earlier): 1. Global: `~/.config/opencode/opencode.json` 2. Project: `./opencode.json` (or nearest Git directory) 3. Custom: Set via `OPENCODE_CONFIG` environment variable 4. Custom directory: Set via `OPENCODE_CONFIG_DIR` ## Format Supports JSON and JSONC (JSON with Comments): ```jsonc { "$schema": "https://opencode.ai/config.json", // Your configuration "theme": "opencode", "model": "anthropic/claude-sonnet-4-5" } ``` ## Core Settings ### Models ```json { "provider": {}, "model": "anthropic/claude-sonnet-4-5", "small_model": "anthropic/claude-haiku-4-5" } ``` - `model`: Main model for tasks - `small_model`: Cheaper model for lightweight tasks (title generation, etc) ### TUI Settings ```json { "tui": { "scroll_speed": 3, "scroll_acceleration": { "enabled": true } } } ``` - `scroll_acceleration.enabled`: macOS-style scroll acceleration (overrides scroll_speed) - `scroll_speed`: Multiplier for scroll speed (default: 1, min: 1) ### Theme ```json { "theme": "opencode" } ``` ### Autoupdate ```json { "autoupdate": true // or false, or "notify" } ``` ## Tools Configuration ### Global Tools ```json { "tools": { "write": true, "bash": true, "edit": false } } ``` ### Wildcard Patterns ```json { "tools": { "mymcp_*": false // Disable all tools from mymcp server } } ``` ## Agents ### Define Agents ```jsonc { "agent": { "code-reviewer": { "description": "Reviews code for best practices", "mode": "subagent", "model": "anthropic/claude-sonnet-4-5", "prompt": "You are a code reviewer...", "tools": { "write": false, "edit": false }, "temperature": 0.1 } } } ``` ### Agent Options - `description` (required): What the agent does - `mode`: "primary", "subagent", or "all" - `model`: Override default model - `prompt`: Custom system prompt or `{file:./path.txt}` - `tools`: Tool availability overrides - `temperature`: 0.0-1.0 (lower = more focused) - `maxSteps`: Max iterations before stopping - `permission`: Permission overrides ### Default Agent ```json { "default_agent": "plan" // Must be a primary agent } ``` ## Commands ### JSON Configuration ```json { "command": { "test": { "template": "Run the full test suite with coverage", "description": "Run tests with coverage", "agent": "build", "model": "anthropic/claude-haiku-4-5" } } } ``` ### Command Options - `template` (required): Prompt template - `description`: Description shown in TUI - `agent`: Which agent executes the command - `subtask`: Force subagent invocation (boolean) - `model`: Override default model ### Template Variables - `$ARGUMENTS`: All arguments as single string - `$1`, `$2`, `$3...`: Individual arguments - `!`command``: Shell command output - `@filename`: File contents ## Permissions ```json { "permission": { "edit": "ask", // "allow", "ask", "deny" "bash": { "git push": "ask", "git *": "ask", "*": "allow" }, "webfetch": "deny" } } ``` Per-agent permissions: ```json { "agent": { "build": { "permission": { "bash": { "git push": "ask" } } } } } ``` ## Formatters ```json { "formatter": { "prettier": { "disabled": true }, "custom-prettier": { "command": ["npx", "prettier", "--write", "$FILE"], "environment": { "NODE_ENV": "development" }, "extensions": [".js", ".ts", ".jsx", ".tsx"] } } } ``` ## MCP Servers ### Local MCP ```json { "mcp": { "my-mcp": { "type": "local", "command": ["npx", "-y", "package-name"], "enabled": true, "environment": { "API_KEY": "{env:MY_API_KEY}" }, "timeout": 5000 } } } ``` ### Remote MCP ```json { "mcp": { "my-remote": { "type": "remote", "url": "https://mcp.example.com", "enabled": true, "headers": { "Authorization": "Bearer {env:API_KEY}" }, "oauth": { "clientId": "{env:CLIENT_ID}", "clientSecret": "{env:CLIENT_SECRET}", "scope": "tools:read" } } } } ``` ## Sharing ```json { "share": "manual" // "auto", "manual", or "disabled" } ``` ## Instructions ```json { "instructions": [ "CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md" ] } ``` ## Provider Management ### Disable Providers ```json { "disabled_providers": ["openai", "gemini"] } ``` ### Enable Only Specific Providers ```json { "enabled_providers": ["anthropic", "openai"] } ``` Note: `disabled_providers` takes priority over `enabled_providers`. ## Variable Substitution ### Environment Variables ```json { "model": "{env:OPENCODE_MODEL}", "provider": { "anthropic": { "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } } } ``` ### File Contents ```json { "instructions": ["./custom-instructions.md"], "provider": { "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } } } } ``` ## Keybinds ```json { "keybinds": { "leader": "ctrl+x", "switch_agent": "tab", "new_session": "ctrl+x n", "undo": "ctrl+x u" } } ``` ## Environment Variables Common environment variables: - `OPENCODE_CONFIG`: Path to config file - `OPENCODE_CONFIG_DIR`: Path to config directory - `OPENCODE_CONFIG_CONTENT`: Inline JSON config - `OPENCODE_DISABLE_AUTOUPDATE`: Disable auto-updates - `OPENCODE_PERMISSION`: Inline permissions JSON - `OPENCODE_CLIENT`: Client identifier (default: "cli") ## Schema Validation Config uses schema from https://opencode.ai/config.json for editor autocomplete and validation. --- # OpenCode Documentation OpenCode is an open-source AI coding agent providing terminal-based interface, desktop app, and IDE extension capabilities for developers. Built with TypeScript, MIT licensed, and supporting 75+ LLM providers. ## Installation ### Installation Methods ```bash # Install script (recommended) curl -fsSL https://opencode.ai/install | bash # npm npm install -g opencode-ai # Homebrew (macOS/Linux) brew install opencode # Chocolatey (Windows) choco install opencode # Docker docker run -it --rm ghcr.io/sst/opencode # Arch Linux (paru) paru -S opencode # Or use any Node package manager pnpm add -g opencode-ai bun add -g opencode-ai yarn global add opencode-ai ``` ## Quick Start ```bash # Navigate to your project cd /path/to/project # Start OpenCode opencode # Configure a provider /connect # Initialize project analysis /init ``` ## Core Concepts ### Primary Agents - **Build** (default): Full development capabilities with all tools enabled - **Plan**: Analysis-only mode - generates implementation strategies without modifying code Switch between primary agents with Tab key. ### Subagents Invoke specialized agents via `@mention`: - **General**: Research and multi-step task execution - **Explore**: Fast codebase exploration ### Built-in Tools - `bash` - Execute shell commands - `edit` - Modify files via exact string replacements - `write` - Create new files - `read` - Read file contents (supports line ranges) - `grep` - Search file contents with regex - `glob` - Find files by pattern - `list` - List directory contents - `patch` - Apply patch files - `skill` - Load reusable skills - `webfetch` - Fetch web content ### Configuration Locations (Merged, Later Overrides) 1. Global: `~/.config/opencode/opencode.json` 2. Project: `./opencode.json` 3. Environment: `OPENCODE_CONFIG` variable ### Basic Configuration Example ```json { "$schema": "https://opencode.ai/config.json", "model": "anthropic/claude-sonnet-4-5", "theme": "opencode", "autoupdate": true } ``` ## Key Features ### File References Use `@` syntax to reference files in prompts: ``` How is auth handled in @src/auth.ts? ``` ### Built-in Commands - `/connect` - Add or configure providers - `/models` - Select which model to use - `/init` - Create AGENTS.md project analysis - `/undo` - Revert last changes (including files) - `/redo` - Restore changes - `/share` - Share conversation with others - `/help` - Display help information ### Image Support Drag and drop images or use `![image](path)` for design references in prompts. ## Common Workflows ### Add a Feature (Plan-First Approach) ``` # Switch to Plan mode # Describe feature When a user deletes a note, flag as deleted in the database. Create a screen showing deleted notes with undelete/permanent delete options. # Review plan Sounds good! Make the changes. # Switch back to Build mode ``` ### Make Targeted Changes ``` Add authentication to /settings route. Use the same pattern as @packages/functions/src/notes.ts ``` ### Undo/Redo Operations ``` # Undo last change (reverts all modifications) /undo # Restore changes /redo ``` ## Permissions & Safety ### Control Tool Access ```json { "permission": { "edit": "ask", "bash": { "git push": "ask", "*": "allow" } } } ``` Permission levels: - `"allow"` - Allow without asking - `"ask"` - Prompt for confirmation - `"deny"` - Block completely ## Providers OpenCode supports 75+ LLM providers including: **Major Providers:** - Anthropic Claude - OpenAI - Google Gemini - DeepSeek - Together AI - OpenRouter - Z.AI - OpenCode Zen (curated, tested models) **Cloud Platforms:** - Amazon Bedrock - Google Vertex AI - Azure OpenAI **Local Models:** - Ollama - LM Studio Configure providers with `/connect` command or environment variables. ## Advanced Features ### Custom Agents Define specialized agents in JSON or Markdown: **JSON:** ```json { "agent": { "code-reviewer": { "description": "Reviews code for issues", "mode": "subagent", "model": "anthropic/claude-sonnet-4-5", "temperature": 0.1, "tools": { "write": false, "edit": false } } } } ``` **Markdown** (`.opencode/agent/review.md`): ```markdown --- description: Code review agent mode: subagent tools: write: false edit: false --- Review code for quality and best practices. ``` ### Custom Commands Create reusable commands: **JSON:** ```json { "command": { "test": { "template": "Run full test suite with coverage", "description": "Run tests", "agent": "build" } } } ``` **Markdown** (`.opencode/command/test.md`): ```markdown --- description: Run tests with coverage agent: build --- Run the full test suite and show failures. ``` ### Skills Create reusable instructions in `.opencode/skill//SKILL.md`: ```markdown --- name: git-release description: Create consistent releases --- ## What I do - Draft release notes from merged PRs - Propose version bump ``` ### MCP Servers Integrate external tools via Model Context Protocol: **Local Server:** ```json { "mcp": { "my-mcp": { "type": "local", "command": ["npx", "-y", "package-name"], "environment": { "API_KEY": "{env:MY_API_KEY}" } } } } ``` **Remote Server:** ```json { "mcp": { "my-remote": { "type": "remote", "url": "https://mcp.example.com" } } } ``` ## Best Practices 1. **Use Plan mode** for reviewing changes before implementation 2. **Reference files** with `@` for proper context 3. **Enable only needed MCPs** to conserve context tokens 4. **Configure permissions** for risky operations 5. **Create custom agents** for specific task types 6. **Use skills** for reusable workflows 7. **Set up formatters** for code consistency 8. **Commit AGENTS.md** to version control for team sharing ## Links - **Website:** https://opencode.ai - **Documentation:** https://opencode.ai/docs - **GitHub:** https://github.com/sst/opencode - **Discord:** https://opencode.ai/discord - **Models:** https://models.dev --- # OpenCode MCP Servers ## Overview MCP (Model Context Protocol) adds external tools to OpenCode. Supports local and remote servers. **Caveat**: MCP servers add to context. Be selective - some servers (like GitHub MCP) can exceed context limits. ## Configuration Define in `opencode.json` under `mcp`: ```jsonc { "mcp": { "server-name": { "type": "local", // or "remote" "enabled": true, // ... type-specific options } } } ``` ## Local MCP Servers ### Basic Configuration ```json { "mcp": { "my-local-mcp": { "type": "local", "command": ["npx", "-y", "package-name"], "enabled": true, "environment": { "API_KEY": "{env:MY_API_KEY}" }, "timeout": 5000 } } } ``` ### Options | Option | Type | Required | Description | |--------|------|----------|-------------| | `type` | string | Y | Must be "local" | | `command` | array | Y | Command and args to run server | | `enabled` | boolean | N | Enable/disable on startup | | `environment` | object | N | Environment variables | | `timeout` | number | N | Timeout in ms (default: 5000) | ### Example: MCP Everything ```json { "mcp": { "mcp_everything": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-everything"] } } } ``` Usage: ``` use the mcp_everything tool to add 3 and 4 ``` ## Remote MCP Servers ### Basic Configuration ```json { "mcp": { "my-remote-mcp": { "type": "remote", "url": "https://mcp.example.com", "enabled": true, "headers": { "Authorization": "Bearer {env:API_KEY}" } } } } ``` ### Options | Option | Type | Required | Description | |--------|------|----------|-------------| | `type` | string | Y | Must be "remote" | | `url` | string | Y | MCP server URL | | `enabled` | boolean | N | Enable/disable on startup | | `headers` | object | N | HTTP headers | | `oauth` | object/false | N | OAuth config or false to disable | | `timeout` | number | N | Timeout in ms (default: 5000) | ## OAuth Authentication ### Automatic OAuth Most servers auto-detect OAuth. No config needed: ```json { "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp" } } } ``` OpenCode will: 1. Detect 401 response 2. Use Dynamic Client Registration (RFC 7591) if supported 3. Store tokens securely ### Pre-registered Credentials If you have client credentials: ```json { "mcp": { "my-oauth-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": { "clientId": "{env:MCP_CLIENT_ID}", "clientSecret": "{env:MCP_CLIENT_SECRET}", "scope": "tools:read tools:execute" } } } } ``` ### OAuth Options | Option | Type | Description | |--------|------|-------------| | `oauth` | object/false | OAuth config or false to disable | | `clientId` | string | OAuth client ID | | `clientSecret` | string | OAuth client secret | | `scope` | string | OAuth scopes | ### Manual Authentication ```bash # Authenticate with server opencode mcp auth my-oauth-server # List servers and auth status opencode mcp list # Remove credentials opencode mcp logout my-oauth-server ``` Tokens stored in `~/.local/share/opencode/mcp-auth.json`. ### Disable OAuth For API key-based servers: ```json { "mcp": { "my-api-key-server": { "type": "remote", "url": "https://mcp.example.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer {env:MY_API_KEY}" } } } } ``` ### Debugging OAuth ```bash # View auth status opencode mcp auth list # Debug specific server opencode mcp debug my-oauth-server ``` ## Managing MCP Tools ### Global Enable/Disable ```json { "mcp": { "my-mcp-foo": { "type": "local", "command": ["bun", "x", "foo"] } }, "tools": { "my-mcp-foo": false // Disable globally } } ``` ### Wildcard Patterns ```json { "tools": { "my-mcp*": false // Disable all matching } } ``` Glob patterns: - `*`: Zero or more characters - `?`: Exactly one character - Literal match: All other characters ### Per-Agent Disable globally, enable for specific agents: ```json { "mcp": { "my-mcp": { "type": "local", "command": ["bun", "x", "my-mcp-command"], "enabled": true } }, "tools": { "my-mcp*": false }, "agent": { "my-agent": { "tools": { "my-mcp*": true } } } } ``` ## Example Servers ### Sentry ```json { "mcp": { "sentry": { "type": "remote", "url": "https://mcp.sentry.dev/mcp", "oauth": {} } } } ``` Authenticate: ```bash opencode mcp auth sentry ``` Usage: ``` Show me latest unresolved issues. use sentry ``` ### Context7 Free docs search: ```json { "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp" } } } ``` With API key for higher limits: ```json { "mcp": { "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } } } } ``` Usage: ``` Configure Cloudflare Worker to cache JSON for 5 minutes. use context7 ``` Or add to AGENTS.md: ```markdown When you need to search docs, use `context7` tools. ``` ### Grep by Vercel Search GitHub code: ```json { "mcp": { "gh_grep": { "type": "remote", "url": "https://mcp.grep.app" } } } ``` Usage: ``` How to set custom domain in SST Astro? use gh_grep ``` Or add to AGENTS.md: ```markdown If unsure how to do something, use `gh_grep` to search GitHub examples. ``` ## CLI Commands ```bash # Add MCP server opencode mcp add # List servers opencode mcp list # Authenticate opencode mcp auth [name] # List OAuth servers opencode mcp auth list # Logout opencode mcp logout # Debug OAuth opencode mcp debug ``` ## Best Practices 1. **Be selective**: MCP servers add context - only enable what you need 2. **Use per-agent**: Enable specific servers for specific agents 3. **Test connection**: Use `opencode mcp debug` to troubleshoot 4. **Document usage**: Add to AGENTS.md when server should be used 5. **Monitor context**: Watch for context limit issues with large servers ## Variable Substitution Use environment variables in config: ```json { "mcp": { "my-server": { "environment": { "API_KEY": "{env:MY_API_KEY}" }, "headers": { "Authorization": "Bearer {env:AUTH_TOKEN}" } } } } ``` --- # OpenCode Providers ## Overview OpenCode supports 75+ LLM providers via AI SDK and Models.dev. Supports both cloud and local models. ## Setup 1. Add credentials: `/connect` command or environment variables 2. Configure provider in `opencode.json` 3. Select model: `/models` command Credentials stored in `~/.local/share/opencode/auth.json`. ## Provider Configuration ### Base URL Customize endpoint for any provider: ```json { "provider": { "anthropic": { "options": { "baseURL": "https://api.anthropic.com/v1" } } } } ``` ## OpenCode Zen Recommended for beginners. Tested and verified models by OpenCode team. ```bash # Authenticate /connect # Select opencode # Visit https://opencode.ai/auth # Copy API key ``` Optional - completely standard provider. ## Major Providers ### Anthropic Claude Claude Pro/Max recommended: ```bash /connect # Select Anthropic > Claude Pro/Max # Authenticate in browser ``` Or with API key: - Create API Key: Get code from browser - Manually enter API Key: Paste existing key ### OpenAI ```bash # Get key from https://platform.openai.com/api-keys /connect # Select OpenAI # Enter API key ``` ### Amazon Bedrock Requirements: 1. Request model access in Bedrock console 2. Set authentication: - `AWS_ACCESS_KEY_ID`: IAM access key - `AWS_PROFILE`: SSO profile (after `aws sso login`) - `AWS_BEARER_TOKEN_BEDROCK`: Long-term API key ```bash AWS_ACCESS_KEY_ID=XXX opencode ``` Or in bash profile: ```bash export AWS_ACCESS_KEY_ID=XXX ``` ### Google Vertex AI Requirements: 1. Enable Vertex AI API 2. Set environment: - `GOOGLE_CLOUD_PROJECT`: Project ID (required) - `VERTEX_LOCATION`: Region (default: global) - Authentication: - `GOOGLE_APPLICATION_CREDENTIALS`: Service account JSON path - Or: `gcloud auth application-default login` ```bash GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json \ GOOGLE_CLOUD_PROJECT=project-id \ opencode ``` Tip: Use `global` region for better availability. ### GitHub Copilot Requires Pro+ for some models. Enable in GitHub Copilot settings. ```bash /connect # Select GitHub Copilot # Visit github.com/login/device # Enter code ``` ### DeepSeek ```bash # Get key from https://platform.deepseek.com/ /connect # Select DeepSeek # Enter API key ``` ### Azure OpenAI Requirements: 1. Create Azure OpenAI resource (get resource name and API key) 2. Deploy model (deployment name must match model name) ```bash /connect # Select Azure # Enter API key ``` Set resource name: ```bash export AZURE_RESOURCE_NAME=XXX opencode ``` Endpoint: `https://RESOURCE_NAME.openai.azure.com/` Note: If you see "cannot assist" errors, change content filter from DefaultV2 to Default. ### Other Providers #### Groq ```bash # Get key from https://console.groq.com/ /connect ``` #### Cerebras ```bash # Get key from https://inference.cerebras.ai/ /connect ``` #### Together AI ```bash # Get key from https://api.together.ai /connect ``` #### Fireworks AI ```bash # Get key from https://app.fireworks.ai/ /connect ``` #### OpenRouter ```bash # Get key from https://openrouter.ai/settings/keys /connect ``` Customize provider routing: ```json { "provider": { "openrouter": { "models": { "moonshotai/kimi-k2": { "options": { "provider": { "order": ["baseten"], "allow_fallbacks": false } } } } } } } ``` ## Local Models ### Ollama ```json { "provider": { "ollama": { "npm": "@ai-sdk/openai-compatible", "name": "Ollama (local)", "options": { "baseURL": "http://localhost:11434/v1" }, "models": { "llama2": { "name": "Llama 2" } } } } } ``` Tip: Increase `num_ctx` (16k-32k) if tool calls aren't working. ### Ollama Cloud ```bash # Get key from https://ollama.com/ > Settings > Keys /connect # Pull model info locally first ollama pull gpt-oss:20b-cloud /models ``` ### LM Studio ```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 ```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 } } } } } } ``` ## Custom Providers Add any OpenAI-compatible provider: ```bash /connect # Scroll to "Other" # Enter provider ID (e.g., "myprovider") # Enter API key ``` Configure in opencode.json: ```json { "provider": { "myprovider": { "npm": "@ai-sdk/openai-compatible", "name": "My Provider", "options": { "baseURL": "https://api.myprovider.com/v1", "apiKey": "{env:MY_API_KEY}", "headers": { "Authorization": "Bearer custom-token" } }, "models": { "my-model": { "name": "My Model", "limit": { "context": 200000, "output": 65536 } } } } } } ``` Options: - **npm**: AI SDK package (use `@ai-sdk/openai-compatible` for OpenAI-compatible APIs) - **name**: Display name - **baseURL**: API endpoint - **apiKey**: API key (use `{env:VAR}` for environment variables) - **headers**: Custom headers - **models**: Available models - **limit.context**: Max input tokens - **limit.output**: Max output tokens ## Gateway Providers ### Cloudflare AI Gateway Access multiple providers through unified endpoint with unified billing: ```bash /connect # Select Cloudflare AI Gateway # Enter API token ``` Set account and gateway: ```bash export CLOUDFLARE_ACCOUNT_ID=your-account-id export CLOUDFLARE_GATEWAY_ID=your-gateway-id ``` Add models: ```json { "provider": { "cloudflare-ai-gateway": { "models": { "openai/gpt-4o": {}, "anthropic/claude-sonnet-4": {} } } } } ``` ### Helicone Observability platform with logging and analytics: ```bash # Get key from https://helicone.ai /connect # Select Helicone ``` Models auto-route to appropriate provider. For custom configs: ```json { "provider": { "helicone": { "npm": "@ai-sdk/openai-compatible", "name": "Helicone", "options": { "baseURL": "https://ai-gateway.helicone.ai", "headers": { "Helicone-Cache-Enabled": "true", "Helicone-User-Id": "opencode" } }, "models": { "gpt-4o": { "name": "GPT-4o" } } } } } ``` Common headers: - `Helicone-Cache-Enabled`: Enable caching - `Helicone-User-Id`: Track by user - `Helicone-Property-*`: Custom properties - `Helicone-Session-Id`: Group requests - `Helicone-Prompt-Id`: Prompt versioning See [Helicone docs](https://docs.helicone.ai/helicone-headers/header-directory). ### ZenMux ```bash # Get key from https://zenmux.ai/settings/keys /connect ``` Add models: ```json { "provider": { "zenmux": { "models": { "somecoolnewmodel": {} } } } } ``` ## Provider Management ### Disable Providers ```json { "disabled_providers": ["openai", "gemini"] } ``` ### Enable Only Specific ```json { "enabled_providers": ["anthropic", "openai"] } ``` Note: `disabled_providers` takes priority. ## Troubleshooting 1. **Check auth**: `opencode auth list` 2. **Verify config**: - Provider ID matches `/connect` ID - Correct npm package - Valid baseURL 3. **Environment variables**: Check required vars are set 4. **Refresh models**: `opencode models --refresh` ## Model Format Use `provider/model-id` format: - `anthropic/claude-sonnet-4-5` - `openai/gpt-4o` - `opencode/gpt-5.1-codex` (OpenCode Zen) List models: `opencode models [provider]` --- # OpenCode Tools ## Overview Tools let the LLM perform actions in your codebase. All tools enabled by default without permission requirements. Configure via: - Global: `tools` option - Per-agent: Agent-specific overrides - Permissions: `permission` option ## Built-in Tools ### bash Execute shell commands. ```json { "tools": { "bash": true } } ``` Runs terminal commands like `npm install`, `git status`, etc. ### edit Modify files via exact string replacements. ```json { "tools": { "edit": true } } ``` Primary way LLM modifies code. Performs precise edits by replacing exact text. ### write Create new files or overwrite existing. ```json { "tools": { "write": true } } ``` Allows file creation. Overwrites if file exists. ### read Read file contents. ```json { "tools": { "read": true } } ``` Returns file contents. Supports line ranges for large files. ### grep Search file contents with regex. ```json { "tools": { "grep": true } } ``` Fast codebase search. Full regex syntax, file pattern filtering. ### glob Find files by pattern. ```json { "tools": { "glob": true } } ``` Search using glob patterns (`**/*.js`, `src/**/*.ts`). Results sorted by modification time. ### list List directory contents. ```json { "tools": { "list": true } } ``` Lists files/directories. Accepts glob patterns for filtering. ### lsp (experimental) Code intelligence via LSP servers. Requires `OPENCODE_EXPERIMENTAL_LSP_TOOL=true` or `OPENCODE_EXPERIMENTAL=true`. ```json { "tools": { "lsp": true } } ``` Operations: - `goToDefinition` - `findReferences` - `hover` - `documentSymbol` - `workspaceSymbol` - `goToImplementation` - `prepareCallHierarchy` - `incomingCalls` - `outgoingCalls` Configure LSP servers: [LSP Servers docs](/docs/lsp). ### patch Apply patch files. ```json { "tools": { "patch": true } } ``` Applies diffs and patches to codebase. ### skill Load skill definitions. ```json { "tools": { "skill": true } } ``` Loads `SKILL.md` files. Control with `permission.skill`. See [Skills docs](/docs/skills). ### todowrite Manage todo lists. ```json { "tools": { "todowrite": true } } ``` Creates/updates task lists for complex operations. Disabled for subagents by default. ### todoread Read todo lists. ```json { "tools": { "todoread": true } } ``` Reads current todo state. Disabled for subagents by default. ### webfetch Fetch web content. ```json { "tools": { "webfetch": true } } ``` Allows reading web pages. Useful for docs and research. ## Global Configuration ### Disable Tools ```json { "tools": { "write": false, "bash": false } } ``` ### Wildcard Patterns ```json { "tools": { "mymcp_*": false // Disable all MCP tools matching pattern } } ``` ## Per-Agent Configuration Override global settings for specific agents: ```json { "tools": { "write": true, "bash": true }, "agent": { "plan": { "tools": { "write": false, "bash": false } } } } ``` In markdown: ```markdown --- description: Read-only analysis mode: subagent tools: write: false edit: false bash: false --- Analyze code without modifications. ``` ## MCP Tools MCP servers provide additional tools. Manage like built-in tools: ```json { "mcp": { "my-mcp": { "type": "local", "command": ["npx", "my-mcp-server"] } }, "tools": { "my-mcp*": false // Disable all tools from this MCP } } ``` See [MCP Servers docs](/docs/mcp-servers). ## Custom Tools Define your own tools in config. See [Custom Tools docs](/docs/custom-tools). ## Internals ### Ignore Patterns Tools like `grep`, `glob`, `list` use [ripgrep](https://github.com/BurntSushi/ripgrep). Respects `.gitignore` by default. To include ignored files, create `.ignore` file: ``` !node_modules/ !dist/ !build/ ``` This allows searching within normally ignored directories. ## Tool Permissions Control execution permissions separately from availability: ```json { "permission": { "edit": "ask", // Ask before editing "bash": "allow", // Allow without asking "webfetch": "deny" // Deny completely } } ``` Permission levels: - `"allow"`: Execute without asking - `"ask"`: Prompt for approval - `"deny"`: Disable tool ### Per-Command Bash Permissions ```json { "permission": { "bash": { "git push": "ask", "git *": "ask", "*": "allow" } } } ``` ### Per-Agent Permissions ```json { "agent": { "plan": { "permission": { "edit": "deny", "bash": "deny" } } } } ``` See [Permissions docs](/docs/permissions). ## Common Patterns ### Read-Only Agent ```json { "agent": { "readonly": { "tools": { "write": false, "edit": false, "bash": false } } } } ``` ### Analysis Agent ```json { "agent": { "analyze": { "tools": { "write": false, "edit": false, "bash": true, // Allow for running checks "read": true, "grep": true, "glob": true } } } } ``` ### Documentation Agent ```json { "agent": { "docs": { "tools": { "bash": false, "write": true, "edit": true, "webfetch": true // For research } } } } ``` ## Best Practices 1. **Be selective**: Disable unused tools to reduce context 2. **Use permissions**: Control risky operations (bash, edit) 3. **Per-agent config**: Different tools for different agents 4. **MCP wildcards**: Disable entire MCP servers when not needed 5. **Test carefully**: Verify tool access matches intent