# Context Strategies for AI Coding Agents Understanding how to provide context to AI coding agents like Claude and OpenCode involves several complementary approaches. Many developers confuse these different strategies or wonder if some are being phased out in favor of others. This article clarifies the terminology, explains how each approach works, and shows how they work together. ## Understanding RAG vs Context Patterns **RAG (Retrieval-Augmented Generation)** technically refers to: - Vector embeddings of your codebase - Semantic search to retrieve relevant chunks - Dynamically injecting those chunks into the LLM context However, what most AI coding tools (including OpenCode and Claude) actually use are **context patterns** or **context injection strategies**, which include: 1. **Static Project Context** → Rules files (AGENTS.md, CLAUDE.md) 2. **Agent Specialization** → Different AI configurations for different tasks 3. **Dynamic Data Access** → MCP servers, file reads, web fetches 4. **Tool Restrictions** → Permissions systems for different modes These are better described as **"context strategies"** rather than RAG styles, though they serve similar purposes of giving the AI relevant information. ## Context Strategy #1: Static Project Context (Rules) ### What It's Called **"Rules"** or **"Custom Instructions"** ### What It Is A markdown file (commonly `AGENTS.md` or `CLAUDE.md`) that provides persistent context about your project, coding standards, structure, and conventions. This file is automatically loaded into every conversation session. ### Where It Lives - **Project-specific:** In your project root (e.g., `/my-project/AGENTS.md`) - **Global:** In `~/.config/opencode/AGENTS.md` (applies to all projects) - **Additional instructions:** Referenced via `opencode.json`'s `instructions` field ### Is It Being Phased Out? **No!** This is still the primary way to give project-level context. It works alongside (not in competition with) other approaches. ### Example AGENTS.md ```markdown # SST v3 Monorepo Project This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure - `packages/` - Contains all workspace packages (functions, core, web, etc.) - `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts) - `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards - Use TypeScript with strict mode enabled - Shared code goes in `packages/core/` with proper exports configuration - Functions go in `packages/functions/` - Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions - Import shared modules using workspace names: `@my-app/core/example` ``` ### Referencing External Files You can reference external documentation in two ways: #### Using opencode.json (Recommended) ```json { "$schema": "https://opencode.ai/config.json", "instructions": [ "CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md" ] } ``` #### Manual Instructions in AGENTS.md ```markdown # TypeScript Project Rules ## External File Loading CRITICAL: When you encounter a file reference (e.g., @rules/general.md), use your Read tool to load it on a need-to-know basis. ## Development Guidelines For TypeScript code style: @docs/typescript-guidelines.md For React patterns: @docs/react-patterns.md For API standards: @docs/api-standards.md ``` ### When to Use - Project structure and organization - Coding standards and conventions - Naming patterns - Architecture decisions - Monorepo workspace configuration - Import/export patterns ## Context Strategy #2: Agent Specialization ### What It's Called **"Agents"** (Primary Agents and Subagents) ### What It Is Configured AI assistants with specific purposes, permissions, prompts, and tool access. Think of AGENTS.md as the "employee handbook" (everyone reads it) and Agents as "job roles" (different people with different permissions). ### Types of Agents #### Primary Agents Main assistants you switch between using the **Tab** key: - **`build`** - Full access for development work (default) - **`plan`** - Read-only mode for analysis and planning (no file edits, no bash commands) - Custom primary agents you create #### Subagents Specialized helpers invoked by primary agents automatically or via `@mention`: - **`general`** - Built-in research and complex search agent - Custom subagents like `code-reviewer`, `docs-writer`, `security-auditor` ### Configuration Agents can be configured in two ways: #### JSON Configuration ```json { "$schema": "https://opencode.ai/config.json", "agent": { "code-reviewer": { "description": "Reviews code for best practices and potential issues", "mode": "subagent", "model": "anthropic/claude-sonnet-4-20250514", "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.", "tools": { "write": false, "edit": false } }, "plan": { "mode": "primary", "model": "anthropic/claude-haiku-4-20250514", "tools": { "write": false, "edit": false, "bash": false } } } } ``` #### Markdown Configuration Place files in `~/.config/opencode/agent/` or `.opencode/agent/`: **~/.config/opencode/agent/docs-writer.md:** ```markdown --- description: Writes and maintains project documentation mode: subagent model: anthropic/claude-sonnet-4-20250514 temperature: 0.3 tools: bash: false --- You are a technical writer. Create clear, comprehensive documentation. Focus on: - Clear explanations - Proper structure - Code examples - User-friendly language ``` ### Agent Options - **`description`** - What the agent does and when to use it (required) - **`mode`** - `primary`, `subagent`, or `all` (default: `all`) - **`model`** - Override the default model for this agent - **`temperature`** - Control randomness (0.0-1.0) - 0.0-0.2: Focused and deterministic (analysis, planning) - 0.3-0.5: Balanced (general development) - 0.6-1.0: Creative (brainstorming, exploration) - **`prompt`** - Custom system prompt file: `"{file:./prompts/custom.txt}"` - **`tools`** - Enable/disable specific tools - **`permissions`** - Set `ask`, `allow`, or `deny` for tools - **`disable`** - Set to `true` to disable the agent ### Permissions System You can configure fine-grained permissions: ```json { "$schema": "https://opencode.ai/config.json", "agent": { "build": { "permission": { "edit": "ask", "bash": { "git push": "ask", "git status": "allow", "*": "ask" }, "webfetch": "deny" } } } } ``` Permission levels: - **`ask`** - Prompt for approval before running - **`allow`** - Allow without approval - **`deny`** - Disable completely ### Creating Agents Use the interactive command: ```bash opencode agent create ``` This will: 1. Ask where to save (global or project-specific) 2. Request a description 3. Generate appropriate system prompt and identifier 4. Let you select tool access 5. Create the markdown configuration file ### Usage Examples **Switch between primary agents:** ``` <Tab> # Switches from build → plan or plan → build ``` **Invoke a subagent:** ``` @code-reviewer analyze the authentication logic in src/auth.ts ``` **Navigate between sessions:** ``` Ctrl+Right # Cycle forward through parent → child sessions Ctrl+Left # Cycle backward ``` ### Common Agent Use Cases | Agent Type | Purpose | Tools | Example | |------------|---------|-------|---------| | **build** | Full development | All enabled | Default coding work | | **plan** | Analysis/planning | Read-only | Review before implementing | | **code-reviewer** | Code review | Read + docs tools | Quality checks | | **debug** | Investigation | Bash + read tools | Troubleshooting | | **docs-writer** | Documentation | File ops, no bash | Writing guides | | **security-auditor** | Security review | Read-only | Vulnerability checks | ### Example: Security Auditor Subagent **~/.config/opencode/agent/security-auditor.md:** ```markdown --- description: Performs security audits and identifies vulnerabilities mode: subagent temperature: 0.1 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 Provide specific recommendations with code examples. ``` **Usage:** ``` @security-auditor review the API endpoints in packages/functions/src/api/ ``` ### When to Use - Different workflows need different tool access - Analysis work vs implementation work - Specialized reviews (security, performance, accessibility) - Different models for different tasks (fast for planning, capable for implementation) ## Context Strategy #3: Dynamic Data Access ### What It Is Real-time access to external data sources and tools during conversations, including: - **MCP Servers** - Model Context Protocol servers (e.g., Obsidian vault, databases) - **File Operations** - Read specific files on-demand - **Web Fetches** - Retrieve documentation or APIs - **Custom Tools** - Project-specific integrations ### MCP Servers Example Your Obsidian vault integration is an example of this. The agent can: ```bash # Read files from Obsidian vault obsidian_get_file_contents("Computer Tech/Docker/nginx.md") # Search vault content obsidian_simple_search("reverb techniques") # Update specific sections obsidian_patch_content( filepath="Audio Science/Delays.md", target_type="heading", target="## Advanced Techniques", operation="append", content="New technique content..." ) ``` ### When to Use - Access external knowledge bases (Obsidian, Notion, wikis) - Query databases or APIs - Retrieve up-to-date documentation - Project-specific data sources ## How These Strategies Work Together These are **complementary systems**, not competing approaches. Here's how they interact: ### Example Workflow: Adding a Feature 1. **AGENTS.md provides foundation:** - Project structure - Coding standards - Architecture patterns 2. **Switch to plan agent:** - Press `Tab` to switch to read-only mode - Request: "Plan how to add OAuth authentication" - Agent reads relevant files, analyzes structure - Proposes implementation plan 3. **Review and refine:** - Agent references MCP server for similar patterns: `@general find OAuth examples` - Discusses approach without making changes 4. **Switch to build agent:** - Press `Tab` to return to build mode - Request: "Implement the plan" - Agent creates files following AGENTS.md conventions 5. **Code review:** - `@security-auditor review the new OAuth implementation` - Subagent analyzes security implications - Returns to main session with recommendations ### Mental Model ``` ┌─────────────────────────────────────────────────────┐ │ AGENTS.md - "The Employee Handbook" │ │ (Everyone reads this - project knowledge) │ └─────────────────────────────────────────────────────┘ ↓ provides context to ┌─────────────────────────────────────────────────────┐ │ Agents - "Job Roles" │ │ ├─ Primary: build (full access) │ │ ├─ Primary: plan (read-only) │ │ └─ Subagents: specialized helpers │ └─────────────────────────────────────────────────────┘ ↓ can access ┌─────────────────────────────────────────────────────┐ │ Dynamic Data - "External Resources" │ │ ├─ MCP Servers (Obsidian, databases) │ │ ├─ File reads (on-demand) │ │ └─ Web fetches (docs, APIs) │ └─────────────────────────────────────────────────────┘ ``` ## OpenCode Implementation Summary OpenCode supports all these context strategies: ✅ **AGENTS.md files** (project and global) ✅ **Custom instructions** via `opencode.json` ✅ **Primary agents** (build, plan) - switch with Tab ✅ **Subagents** (create custom ones, invoke with @mention) ✅ **MCP servers** (Obsidian, databases, custom integrations) ✅ **Agent configuration** (JSON or Markdown) ✅ **Permissions system** (ask/allow/deny per tool) ✅ **Custom prompts** per agent ✅ **Different models** per agent ✅ **Temperature control** per agent ✅ **Tool restrictions** per agent ## Practical Example: Obsidian Vault Setup For an educational Obsidian vault, you might combine: ### 1. AGENTS.md (Project Structure) ```markdown # midimaze Obsidian Vault Educational knowledge base for Recording Arts & Technology. ## Critical Rule: File Placement ALWAYS ask user to confirm directory before creating files. Public content → Topic folders (Audio Science/, Computer Tech/, etc.) Personal content → _Nakul/ folder ## Frontmatter Standards Every article MUST include: - created: Pacific Time ISO 8601 - updated: Initially same as created - slug: Random 11-char alphanumeric ``` ### 2. Custom Agent (Educational Writer) **~/.config/opencode/agent/obsidian-writer.md:** ```markdown --- description: Specialized for writing educational Obsidian articles mode: subagent model: anthropic/claude-sonnet-4-20250514 temperature: 0.4 tools: bash: false --- You are an educational content writer for the midimaze Obsidian vault. Focus on: - Clear, example-driven explanations - Proper frontmatter with Pacific timezone - Asking user for directory placement - Using sentence case headings - Intermediate technical knowledge level ``` ### 3. MCP Server (Dynamic Access) ```javascript // Agent can access vault via MCP tools MCP_DOCKER_obsidian_simple_search("delay effects") MCP_DOCKER_obsidian_get_file_contents("Audio Science/Audio Effects/Delays/...") ``` ### Usage ```bash # Regular session with build agent opencode # Use custom writer subagent @obsidian-writer create an article about compression techniques # AGENTS.md ensures proper structure # obsidian-writer ensures educational tone # MCP server provides access to existing articles ``` ## Best Practices ### For AGENTS.md - Keep it focused on project structure and standards - Commit it to version control - Update when architecture changes - Use global AGENTS.md for personal preferences ### For Agents - Create specialized agents for distinct workflows - Use descriptive names and clear descriptions - Set appropriate permissions for each agent's purpose - Use lower temperature for analysis, higher for creativity ### For Dynamic Access - Use MCP servers for external data sources - Keep credentials secure - Document available tools in AGENTS.md - Prefer specific tools over general bash commands ## Common Misconceptions ### ❌ "AGENTS.md is being replaced by agents" **Reality:** They serve different purposes. AGENTS.md is project knowledge; agents are workflow configurations. ### ❌ "You should use only one approach" **Reality:** Use all three together for best results. ### ❌ "RAG is what AI coding tools use" **Reality:** Most use context injection patterns, not true vector-based RAG. ### ❌ "More agents = better performance" **Reality:** A few well-configured agents are better than many overlapping ones. ## Conclusion Understanding these three context strategies—static project context (AGENTS.md), agent specialization (primary/subagents), and dynamic data access (MCP servers)—allows you to effectively guide AI coding agents. They're complementary tools that work together: AGENTS.md provides the foundation, agents provide specialized workflows, and dynamic access provides real-time information. The key is recognizing that these aren't competing approaches or "RAG styles," but rather different layers of context that combine to give AI agents the information they need to help you effectively. ## Further Reading - [OpenCode Agents Documentation](https://opencode.ai/docs/agents) - [OpenCode Rules Documentation](https://opencode.ai/docs/rules) - [OpenCode MCP Servers](https://opencode.ai/docs/mcp-servers) - [Model Context Protocol](https://modelcontextprotocol.io/)