avatar
Complete Guide to Core Coding Agent Concepts
avatar

yceffort

ยท23 min read
aidevopsbackend

Table of Contents

Introduction

This post is based on leerob's video, translated with additional content and links added from my knowledge. Note that it may differ somewhat from the original.

To properly utilize coding agents, you need to understand several core concepts. Rules, Commands, MCP, Sub-agents, Modes, Hooks, Skills, Plugins - these may sound complex at first, but once you understand the problems each one solves, they become much easier to grasp.

What to Learn First

You don't need to master all concepts at once. Follow this learning path:

Step 1: CLAUDE.md (Rules)

  • The first thing you should set up
  • Writing down project structure, coding conventions, and frequently used commands makes your agent much smarter

Step 2: Hooks

  • Enforce "must-do" tasks like auto-formatting and linting after file saves
  • Prevent the agent from forgetting important steps

Step 3: Commands

  • Create these when repetitive workflows emerge - no need to rush

Step 4: Sub-agents, MCP, Skills

  • Learn these when you need complex operations
  • Trying to use everything from the start only adds complexity

1. Rules - Static Context

Definition

Rules are static context that's always included in every conversation. They automatically load when the agent starts working, providing project context, coding conventions, business requirements, and more.

Background

Early AI coding agents suffered from severe hallucination problems. Models would misunderstand codebase structure, use non-existent APIs, or ignore team coding conventions.

Rules files emerged to solve these problems. Instead of repeatedly entering the same information in every conversation, you write it once and it's automatically referenced in all sessions.

Evolution

Single rules file โ†’ Multiple sub-files โ†’ Eventually merged into unified static context

Initially a single file, but as projects grew complex, they were split into multiple files. However, all files eventually merge into one context that's included in every conversation.

Implementation in Claude Code: CLAUDE.md

In Claude Code, the CLAUDE.md file serves this role.

File Location and Hierarchy:

your-project/
โ”œโ”€โ”€ CLAUDE.md                    # Project root (applies globally)
โ”œโ”€โ”€ .claude/
โ”‚   โ”œโ”€โ”€ CLAUDE.md               # Project configuration
โ”‚   โ””โ”€โ”€ rules/
โ”‚       โ”œโ”€โ”€ code-style.md       # Code style rules
โ”‚       โ”œโ”€โ”€ testing.md          # Testing rules
โ”‚       โ””โ”€โ”€ security.md         # Security rules
โ”œโ”€โ”€ frontend/
โ”‚   โ””โ”€โ”€ CLAUDE.md               # Subdirectory (applies only to this folder)
โ””โ”€โ”€ CLAUDE.local.md             # Personal settings (add to .gitignore)

CLAUDE.md Example:

# Project Overview

Next.js 15-based fintech application using PostgreSQL + Prisma.

## Commands

- `pnpm dev`: Start development server
- `pnpm test`: Run tests
- `pnpm lint`: Run ESLint + Prettier checks

## Code Style

- Use TypeScript strict mode
- Functional components + React hooks only
- Apply Zod schemas to all API responses

## File Boundaries

- Safe to edit: /src/, /tests/
- Never touch: /node_modules/, /.env\*

Core Principles

Include only minimal, high-quality context. Since it's included in every conversation, unnecessary information wastes tokens and degrades performance.

Research shows modern LLMs can consistently follow about 150-200 instructions. Claude Code's system prompt already contains about 50 instructions, so only include truly essential items in CLAUDE.md.

Maintain as a living document. Add rules whenever the agent makes mistakes. During PR reviews, just say "@cursor add this to the rules" and the agent will automatically update them.

Official Documentation


2. Commands / Slash Commands

Definition

Commands are workflows that package frequently used prompts for execution when needed. Enter a command starting with / to execute a predefined prompt.

Background

Using coding agents leads to repetitive request patterns. Asking for "code reviews," "write tests," or "commit and open PR" in detail every time is inefficient.

Commands solve this by executing common workflows with a single command. They can be shared with teams and stored in Git.

Difference from Rules

AspectRulesCommands
ApplicationAlways included in conversationsOnly when explicitly called
PurposeProvide contextExecute workflows
Context ImpactAlways consumes tokensConsumes tokens only when called

Implementation in Claude Code

File Structure:

your-project/
โ”œโ”€โ”€ .claude/
โ”‚   โ””โ”€โ”€ commands/
โ”‚       โ”œโ”€โ”€ review.md           # /project:review
โ”‚       โ”œโ”€โ”€ commit.md           # /project:commit
โ”‚       โ””โ”€โ”€ deploy/
โ”‚           โ””โ”€โ”€ staging.md      # /project:deploy:staging

~/.claude/
โ””โ”€โ”€ commands/
    โ””โ”€โ”€ my-workflow.md          # /user:my-workflow (available in all projects)

Command File Example (.claude/commands/review.md):

---
description: Review code changes
argument-hint: [file-path]
allowed-tools: Read, Grep, Glob, Bash(git diff:*)
---

## Review Target

!`git diff --name-only HEAD~1`

## Changes

!`git diff HEAD~1`

## Review Checklist

1. Code quality and readability
2. Security vulnerabilities
3. Performance impact
4. Test coverage
5. Documentation completeness

Please focus on the $ARGUMENTS file in your review.

Usage:

# In the input field
/project:review src/auth/login.ts

# Or anywhere in conversation by typing /

Advanced Features

Dynamic Argument Handling:

---
argument-hint: [pr-number] [priority] [assignee]
---

Please review PR #$1 with $2 priority and assign to $3.

Hooks within Commands:

---
description: Deploy to staging
hooks:
  PreToolUse:
    - matcher: 'Bash'
      hooks:
        - type: command
          command: './scripts/validate-deploy.sh'
          once: true
---

Please deploy the current branch to staging.

Best Practices

  • Keep it simple. Complex command lists are an anti-pattern.
  • Use only for truly repetitive tasks.
  • Handle workflow orchestration with Skills or Sub-agents, not Commands.

Official Documentation


3. MCP Servers (Model Context Protocol)

Definition

MCP (Model Context Protocol) is an open-source standard that provides AI agents access to external tools and data sources. MCP servers expose tools, prompts, and resources that agents can use.

Background

Early agents only had basic tools like file read/write and shell command execution. But real development workflows require integration with external systems like reading Slack messages, creating Jira issues, managing GitHub PRs, and querying databases.

MCP provides a standardized way to expose third-party tools to agents. It also supports OAuth authentication, making it suitable for security-critical enterprise environments.

Basic vs Third-party Tools

CategoryExamples
Basic Tools (First-party)File read/write, shell commands, code search
MCP Tools (Third-party)Slack, GitHub, Jira, Notion, PostgreSQL, Sentry, etc.

Architecture

Claude Code can act as both MCP client and server. Multiple simultaneous MCP server connections are possible.

MCP Setup in Claude Code

Adding via CLI:

# Connect HTTP server
claude mcp add --transport http notion https://mcp.notion.com/mcp

# With environment variables
claude mcp add github \
  -e GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxx \
  -- docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN ghcr.io/github/github-mcp-server

# List servers
claude mcp list

# Check server status (within Claude Code)
/mcp

Adding via Configuration File (.mcp.json):

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxx"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://..."
      }
    }
  }
}

Scope Options

ScopeDescription
local (default)Current project, personal use only
projectAll project members (stored in .mcp.json)
userPersonal use across all projects

MCP Limitations and Solutions

Problem: As tools multiply, context usage increases dramatically. With 10 MCP servers having 10 tools each, 100 tool definitions get included in context. A 200k context window might effectively become only 70k with too many active MCPs.

Solution: Modern agents apply optimizations learned from Skills patterns. Instead of always loading all tools, they load only the tools actually being used. Both Cursor and Claude Code implement this optimization.

Practical Tips: Register 20-30 MCP servers in configuration but keep active ones under 10, with active tools under 80. Use /mcp command to check current status.

vs Skills: Use MCP only when OAuth is needed. Otherwise, Skills can substitute.

Major MCP Servers

ServerPurpose
@modelcontextprotocol/server-githubGitHub PR, issues, repository management
@modelcontextprotocol/server-slackSlack message read/write
@modelcontextprotocol/server-postgresPostgreSQL queries
@modelcontextprotocol/server-filesystemLocal file system access
Puppeteer MCPBrowser automation, screenshots
Sentry MCPError monitoring

Hundreds of MCP servers are available on GitHub.

Security Considerations

MCP servers access external services on your behalf. Don't install untrusted servers. Servers that fetch content from the internet pose prompt injection risks.

Official Documentation


4. Sub-agents

Definition

Sub-agents are specialized AI assistants that handle specific types of work. Each sub-agent has its own context window, custom system prompt, specific tool access permissions, and independent permission settings.

Background

Complex tasks consume significant context. For example, running tests can produce thousands of lines of output, and searching documentation can accumulate content from dozens of files in context. When all this accumulates in the main conversation, the context window gets depleted quickly.

Sub-agents solve this problem. They handle tasks like test execution or document search in separate contexts and return only the results to the main conversation.

Why Sub-agents Are Useful

Context Separation: Separates exploration and implementation from the main conversation.

Tool Restrictions: Specific sub-agents can use only permitted tools.

# Document reviewer: read-only, no modifications
name: doc-reviewer
tools: Read, Grep
# Edit, Write, Bash, etc. not allowed

Parallel Execution: Multiple sub-agents can work simultaneously.

Implementation in Claude Code

Built-in Sub-agents:

NameDescription
ExploreRead-only codebase exploration
PlanResearch in planning mode
Task (generic)General-purpose sub-agent available without explicit definition

Custom Sub-agent Definition (.claude/agents/security-reviewer.md):

---
name: security-reviewer
description: Security vulnerability analysis expert. Used for security review requests.
tools: Read, Grep, Glob, Bash(npm audit:*, snyk:*)
model: sonnet
---

You are a security review expert. When analyzing code:

1. Check OWASP Top 10 vulnerabilities
2. Verify authentication/authorization logic
3. Check input validation
4. Check for sensitive information exposure
5. Audit dependency security

For all discovered vulnerabilities, provide:

- Severity (Critical/High/Medium/Low)
- Location (filename, line number)
- Description
- Recommended fix

Sub-agent Invocation Methods

Automatic Invocation: Claude automatically selects appropriate sub-agents based on task description.

User: "Check this PR for security vulnerabilities"
Claude: (automatically invokes security-reviewer sub-agent)

Explicit Invocation:

User: "Use the security-reviewer agent to review the auth module"

Parallel Invocation:

User: "Run these in parallel" or "Do some research on this"

Caveats

Context Gatekeeping: Creating a sub-agent hides that domain's context from the main agent. Creating a PythonTests sub-agent means the main agent can't directly see test-related context.

Result Accumulation: If multiple sub-agents each return detailed results, the main context can be depleted quickly.

Official Documentation


5. Modes

Definition

Modes are an extension of Sub-agents that include instructions + system prompt modifications + UI changes to provide agent operation modes optimized for specific tasks.

Difference from Sub-agents

AspectSub-agentMode
System PromptOwn promptCan modify main prompt
UINo changesUI customization possible
ToolsCan restrictRestrict + add new tools
ContextSeparateShared with main
RemindersNoneInclude mode maintenance reminders

What Modes Can Do

  1. System Prompt Modification: Informs about currently available tools and modes
  2. New Tool Access: Add tools for generating and modifying plans
  3. GUI Changes: Provide specialized interfaces
  4. Reminders: Remind about current mode and tasks to focus on

Example: Plan Mode

Claude Code's Plan Mode is for establishing plans before writing code.

  • File modification tools disabled
  • Only plan generation/modification tools enabled
  • "Currently in plan mode. Please finalize plan before writing code" reminder
  • Automatically switches to normal mode when plan is finalized

Limitations

Even with modes, it's still a non-deterministic system. Modes provide more reliable and discoverable functionality, but unexpected behavior can still occur.

Use Hooks when deterministic behavior is required.


6. Hooks

Definition

Hooks are code that executes 100% deterministically at specific points in the agent lifecycle. They allow you to inject deterministic behavior into the agent's non-deterministic nature.

Background

When you ask an agent to "run lint before committing," it sometimes forgets. When you tell it to "format after modifying files," it's inconsistent.

Hooks enforce these "must-do" tasks. The agent cannot forget or ignore them.

Use Cases

Context injection on every execution:

  • Add git status at session start
  • Inject current time information

Pre/post tool execution processing:

  • Before file modification: validation checks
  • After file modification: Prettier formatting, ESLint checks, type checking

Post-session processing:

  • Save conversation logs to database
  • Auto-commit

Hook Types

EventTimingUse Cases
SessionStartSession start/resumeLoad dev context, environment setup
UserPromptSubmitRight after user inputInput validation, context injection, security filtering
PreToolUseBefore tool executionCommand validation, blocking dangerous commands
PostToolUseAfter tool executionFormatting, linting, result logging
PermissionRequestWhen permission requestedAuto approve/deny decisions
StopAgent response completeAuto-commit, completion notifications
SubagentStopSub-agent completionResult processing, trigger next steps
PreCompactBefore compactionTranscript backup
NotificationWhen notification occursCustom notification handling

Implementation in Claude Code

Configuration file locations:

  • User settings: ~/.claude/settings.json
  • Project settings: .claude/settings.json

Configuration example:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
          },
          {
            "type": "command",
            "command": "npx eslint --fix \"$CLAUDE_FILE_PATH\""
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 $CLAUDE_PROJECT_DIR/scripts/validate-command.py"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/scripts/auto-commit.sh"
          }
        ]
      }
    ]
  }
}

Decision Control with Hooks

Hooks can control agent behavior through JSON output:

#!/usr/bin/env python3
import json
import sys

input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})

# Block dangerous commands
if tool_name == "Bash":
    command = tool_input.get("command", "")
    if "rm -rf" in command or ".env" in command:
        output = {
            "decision": "block",
            "reason": "Dangerous command detected"
        }
        print(json.dumps(output))
        sys.exit(2)  # Block

# Auto-approve document files
if tool_name == "Read":
    file_path = tool_input.get("file_path", "")
    if file_path.endswith((".md", ".txt", ".json")):
        output = {
            "decision": "approve",
            "reason": "Document file auto-approved"
        }
        print(json.dumps(output))
        sys.exit(0)

sys.exit(0)  # Proceed normally

Security Considerations

  • Hooks execute arbitrary shell commands automatically on the system
  • Direct modification of configuration files is only applied after review in the /hooks menu
  • Thoroughly implement input validation, path escaping, and sensitive file exclusion

Official Documentation


7. Skills

Definition

Skills are folders that package instructions, scripts, and resources, serving as capability extension units that agents can discover and use when needed. They combine the advantages of Rules and Commands as dynamic context.

Background

Rules (static context) and Commands (workflow execution) each have limitations:

  • Rules: Included in all conversations, wasting tokens
  • Commands: Require explicit invocation, difficult to support complex workflows
  • MCP: Overkill except for OAuth, context bloat issues

What does "overkill except for OAuth" mean?

Setting up an MCP server requires complex tasks like running server processes, writing configuration files, and managing connections. For simply running repetitive prompts or scripts, all this setup is excessive. MCP is truly needed when connecting to external services requiring OAuth authentication (Slack, GitHub, Notion, etc.). Implementing OAuth flows directly is tricky, and MCP standardizes this process. For simple tasks without OAuth, Skills are sufficient.

What is the "context bloat problem"?

When you connect MCP servers, all tool definitions provided by those servers are included in the context. For example:

  • GitHub MCP: 20 tools (create_issue, list_prs, merge_pr...)
  • Slack MCP: 15 tools (send_message, list_channels...)
  • Notion MCP: 25 tools

Just connecting these 3 includes 60 tool definitions in every conversation. Even though you only use 1-2 actually. That's "bloat."

Skills solve all these issues:

  • Load only when needed (not always included like Rules)
  • Agent automatically selects appropriate skills (no explicit invocation like Commands)
  • Open standard usable across multiple agents

Rules vs Commands vs Skills

CharacteristicRulesCommandsSkills
Load timingAlwaysExplicit invocationAutomatically when needed
Context impactAlways consumesConsumes on callConsumes only when used
Discovery methodN/A/ inputAgent automatic decision
Includable elementsTextText + metadataText + scripts + assets
Sharing scopeProjectProject/userEntire ecosystem

Skill Structure

skills/
โ”œโ”€โ”€ code-review/
โ”‚   โ”œโ”€โ”€ SKILL.md              # Skill definition (required)
โ”‚   โ”œโ”€โ”€ SECURITY.md           # Security checklist
โ”‚   โ”œโ”€โ”€ PERFORMANCE.md        # Performance patterns
โ”‚   โ”œโ”€โ”€ STYLE.md              # Style guide
โ”‚   โ””โ”€โ”€ scripts/
โ”‚       โ””โ”€โ”€ run-linters.sh    # Executable scripts
โ”‚
โ”œโ”€โ”€ docx/
โ”‚   โ”œโ”€โ”€ SKILL.md
โ”‚   โ””โ”€โ”€ scripts/
โ”‚       โ”œโ”€โ”€ pack.py
โ”‚       โ””โ”€โ”€ unpack.py
โ”‚
โ””โ”€โ”€ frontend-design/
    โ”œโ”€โ”€ SKILL.md
    โ”œโ”€โ”€ examples/
    โ”‚   โ””โ”€โ”€ landing-page.html
    โ””โ”€โ”€ assets/
        โ””โ”€โ”€ design-tokens.json

SKILL.md Format

---
name: code-review
description: Code review expert. Use for security, performance, style reviews.
metadata:
  category: development
  tags: [review, quality]
---

# Code Review Skill

This skill provides comprehensive guides for code reviews.

## Usage

Automatically activated when code review is requested.

## Checklist

1. Refer to @SECURITY.md for security review
2. Refer to @PERFORMANCE.md for performance review
3. Refer to @STYLE.md for style review

## Scripts

Run linters: `./scripts/run-linters.sh`

Skill Usage Flow

Ecosystem

Skills are an open standard. Developed and open-sourced by Anthropic, adopted by various agent products:

  • Claude Code
  • Cursor
  • GitHub Codex
  • Windsurf
  • VS Code Copilot
  • Other MCP-compatible clients

Official Documentation


8. Plugins

Definition

Plugins are an extension system that packages tools, skills, MCP, and hooks for easy installation. They can be installed from a marketplace and used immediately without complex configuration.

Background

Setting up MCP servers or skills directly requires tedious processes like modifying configuration files, setting environment variables, and installing dependencies. Plugins abstract this complex configuration to automatically set up everything with a single installation.

Plugin Types

TypeDescriptionExamples
Skill + MCP combinationPackage skills and MCP togetherfirecrawl, supabase
LSP pluginsLanguage server integrationtypescript-lsp, pyright-lsp
Hooks + ToolsHook and tool bundleshookify
Search toolsEnhanced search functionalitymgrep

Key Plugins

LSP plugins:

If you frequently use Claude Code in the terminal without an IDE, LSP plugins are useful. They provide real-time type checking, go-to-definition, and auto-completion.

# Useful LSP plugins
typescript-lsp@claude-plugins-official  # TypeScript support
pyright-lsp@claude-plugins-official     # Python type checking

hookify:

Create hooks interactively instead of writing JSON directly.

/hookify "Run prettier after saving files"

mgrep:

More powerful search tool than ripgrep. Supports both local and web search.

mgrep "function handleSubmit"           # Local search
mgrep --web "Next.js 15 app router"     # Web search

Plugin Installation

# Add marketplace
claude plugin marketplace add https://github.com/mixedbread-ai/mgrep

# Within Claude Code
/plugins  # Check plugin list and install

Considerations

Like MCP, plugins affect the context window. Only activate necessary plugins and deactivate unused ones.

Official Documentation


9. Interrelationships Between Concepts

We've explored 8 concepts so far. They don't exist independently but are interconnected.

Relationship Diagram

Defining Hooks Within Commands

You can define command-specific Hooks within Commands files.

---
description: Production deployment
hooks:
  PreToolUse:
    - matcher: 'Bash'
      hooks:
        - type: command
          command: './scripts/check-env.sh'
  PostToolUse:
    - matcher: 'Bash'
      hooks:
        - type: command
          command: './scripts/notify-slack.sh'
---

Please deploy to production environment.

This way, these Hooks only apply when executing the /project:deploy command.

Skills vs MCP: When to Use What?

SituationChoice
OAuth authentication needed (Slack, GitHub, etc.)MCP
Simple script + instruction combinationSkills
External API calls (no authentication)Skills (use curl in scripts)
Share with team/communitySkills (open standard)
Real-time data streamingMCP

Skills are sufficient for most cases. Use MCP only when OAuth is needed or real-time bidirectional communication is required.

Sub-agents vs Modes: When to Use What?

SituationChoice
Want to separate contextSub-agents
Want to maintain main context while limiting tools onlyModes
Execute multiple tasks in parallelSub-agents
UI/reminder customizationModes
Read-only exploration tasksSub-agents (Explore)

10. Real Workflow Examples

Now that we understand the concepts, let's see how they're combined in practice.

Developing a New Feature

Step-by-step explanation:

  1. CLAUDE.md auto-load: Understand project structure, coding conventions
  2. Plan Mode (shift+tab): Establish plan before writing code
  3. Explore Sub-agent: Explore existing code (prevent main context pollution)
  4. Write code: Implement according to plan
  5. Hooks auto-execute: Prettier, ESLint automatically applied on file save
  6. /commit: Auto-generate commit message

Fixing Bugs

Key points:

  • Explore Sub-agent can search through dozens of files while keeping main context clean
  • Returns only cause summary, allowing focus on fixing

Code Review

Component combination:

  • Commands: Shortcut for repetitive review workflows
  • Skills: Provide review checklists and guidelines
  • Sub-agents: Check security, style, tests in parallel

External Service Integration

Selection criteria:

  • If GitHub API needs OAuth authentication โ†’ MCP
  • If gh CLI is already authenticated โ†’ Skills (simpler)

11. Token and Cost Perspective

Coding agents consume tokens. Understanding how each concept impacts token usage allows you to optimize costs.

Token Consumption by Concept

ConceptToken Consumption PointImpact Level
RulesEvery conversation start๐Ÿ”ด High (always included)
CommandsWhen called๐ŸŸก Medium
MCPWhen loading tool definitions๐Ÿ”ด High (all connected tools)
Sub-agentsWhen executed (separate context)๐ŸŸข Low (minimal impact on main)
ModesWhen switching modes๐ŸŸก Medium
HooksWhen executed๐ŸŸข Low (returns result only)
SkillsOnly when needed๐ŸŸข Low

Cost Optimization Tips

1. Diet Your CLAUDE.md

# โŒ Bad: Too verbose

This project started in January 2024,
using Next.js 15.
Our team has 5 members...

# โœ… Good: Core essentials only

Next.js 15 + Prisma + PostgreSQL

- pnpm dev / test / lint
- TypeScript strict

2. Minimize MCP Servers

// โŒ Bad: Connecting unused servers too
{
  "mcpServers": {
    "github": { ... },
    "slack": { ... },
    "notion": { ... },
    "jira": { ... },
    "linear": { ... }
  }
}

// โœ… Good: Only what you actually use
{
  "mcpServers": {
    "github": { ... }
  }
}

3. Separate Context with Sub-agents

Long exploration tasks should be separated into Sub-agents to avoid polluting the main context.

// โŒ Bad: Direct exploration in main
"Find and organize all API endpoints"
โ†’ Contents of dozens of files pile up in main context

// โœ… Good: Use Sub-agents
"Use Explore agent to find API endpoints"
โ†’ Only summary returned to main

4. Use /compact

When conversations get long, use the /compact command to compress context. It preserves important information while saving tokens.

Cost Monitoring

Claude Code shows token usage when sessions end. Check regularly to understand which tasks consume the most tokens.


12. Comparison with Other Agents

Besides Claude Code, there are various coding agents like Cursor, Windsurf, and GitHub Copilot. The same concepts sometimes go by different names.

Terminology Mapping

Claude CodeCursorWindsurfGitHub Copilot
CLAUDE.md.cursorrules.windsurfrules.github/copilot-instructions.md
Commands---
MCPMCPMCP-
Sub-agents-Cascade-
Hooks---
SkillsSkillsSkills-

Claude Code's Unique Features

1. Hooks

A feature unique to Claude Code that other agents don't have. You can inject deterministic code into agent behavior.

2. Granular Sub-agents

Provides built-in Sub-agents like Explore and Plan for specific purposes. Custom Sub-agents are also easy to define.

3. Commands

The most systematic approach to packaging workflows with slash commands.

4. Terminal Native

Runs directly in terminal, not as an IDE plugin. Works in SSH environments and servers.

Key Differences with Cursor

AspectClaude CodeCursor
EnvironmentTerminalIDE (VS Code fork)
ModelsClaude onlyClaude, GPT, others
File editingDirect modificationDiff view within IDE
PricingAPI usage basedMonthly subscription ($20/mo)
StrengthsAutomation, HooksIDE integration, real-time autocomplete

When to Use Claude Code?

  • Heavy terminal work
  • Building CI/CD, automation pipelines
  • When forced execution with Hooks is needed
  • SSH/remote server environments
  • Preference for API usage-based billing

When to Use Cursor?

  • IDE integration is important
  • Leveraging real-time autocomplete
  • Need for various model choices
  • Preference for monthly flat rate

13. Tips and Tricks

A collection of practical tips for real-world use.

Keyboard Shortcuts

ShortcutFunction
Ctrl+UDelete entire input line (faster than repeated backspace)
!Quick bash command prefix
@File search
/Start slash command
Shift+EnterMulti-line input
TabToggle thinking display
Esc EscStop Claude / restore code

Parallel Workflows

/fork - Conversation Branching

Useful for parallel work on non-overlapping tasks. Instead of queuing messages, you can branch conversations to work simultaneously.

/fork  # Branch current conversation

Git Worktrees - Parallel Claude Instances

Running multiple Claude instances in the same repository can cause conflicts. Using Git Worktrees makes each worktree an independent checkout, preventing conflicts.

git worktree add ../feature-branch feature-branch
# Run separate Claude instances in each worktree

Managing Long-Running Commands with tmux

For long-running commands like builds and tests, using tmux maintains sessions. When Claude executes commands in a tmux session, you can monitor logs in real-time.

tmux new -s dev           # Create new session
# Claude executes commands here
tmux attach -t dev        # Reconnect to session

Useful Commands

CommandFunction
/rewindRevert to previous state
/statuslineCustomize status bar with branch, context %, todos, etc.
/checkpointsFile-level undo points
/compactManually compress context
/mcpCheck MCP server status
/pluginsPlugin list and management

Editor Integration

While Claude Code runs in terminal, it's more effective when used alongside an editor.

Recommended Setup:

  • Split screen: Terminal (Claude Code) + Editor
  • Enable auto-save: Claude's file reading always reflects latest state
  • File watcher: Confirm automatic reload of changed files
  • Git integration: Use editor's git features to review Claude changes before committing

14. Common Issues and Solutions

"The agent gives weird answers due to lack of context"

When context is insufficient, agents can hallucinate or give irrelevant answers.

Solutions:

  • Specify project structure and key file locations in CLAUDE.md
  • Explicitly instruct: "First read X file, then work on this"
  • Separate complex tasks into Sub-agents to prevent context pollution

"The agent keeps ignoring my instructions"

Sometimes agents don't follow what's written in CLAUDE.md.

Solutions:

  • Force with Hooks (e.g., always lint after saving files)
  • Write instructions more specifically
  • Use positive statements "do this instead" rather than "never do this"

"Token usage is too high"

Solutions:

  • Diet your CLAUDE.md (only truly necessary items)
  • Separate long tasks into Sub-agents
  • Use /compact command to compress context

15. Real .claude Folder Structure Example

Let's see how to structure this in an actual project.

your-project/
โ”œโ”€โ”€ .claude/
โ”‚   โ”œโ”€โ”€ settings.json           # Hooks configuration
โ”‚   โ”œโ”€โ”€ commands/
โ”‚   โ”‚   โ”œโ”€โ”€ commit.md           # /project:commit
โ”‚   โ”‚   โ”œโ”€โ”€ review.md           # /project:review
โ”‚   โ”‚   โ””โ”€โ”€ deploy/
โ”‚   โ”‚       โ””โ”€โ”€ staging.md      # /project:deploy:staging
โ”‚   โ”œโ”€โ”€ agents/
โ”‚   โ”‚   โ””โ”€โ”€ security-reviewer.md
โ”‚   โ””โ”€โ”€ rules/
โ”‚       โ”œโ”€โ”€ code-style.md
โ”‚       โ””โ”€โ”€ testing.md
โ”œโ”€โ”€ .mcp.json                   # MCP server config (for project sharing)
โ”œโ”€โ”€ CLAUDE.md                   # Main rules file
โ””โ”€โ”€ CLAUDE.local.md             # Personal settings (.gitignore)

settings.json Example:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
          }
        ]
      }
    ]
  }
}

16. Summary

Concept Overview

Coding agents consist of static context, dynamic context, and deterministic execution (Hooks).

๐Ÿ“Œ Static Context (always included)

  • Rules / CLAUDE.md: Basic rules always included in every conversation

โšก Dynamic Context (loaded/called only when needed)

  • Skills: Specialized knowledge/workflows loaded only for specific tasks
  • Commands: Explicitly called command collections
  • MCP Servers: External service integration (Slack, GitHub, DB, etc.)
  • Plugins: Easy bundled provision of tools/skills installation
  • Sub-agents: Sub-agents that delegate specialized tasks
  • Modes: Work-optimized behavior modes (instructions + UI + system prompts)

๐Ÿ”ง Hooks (deterministic execution)

  • Hooks: Automation triggers before/after tool execution, session start/end, etc.

When to Use What?

SituationUse This
Want to inform about project structure, coding rulesRules (CLAUDE.md)
Want to create shortcuts for repetitive workflowsCommands
Want to connect to external services like Slack, GitHub, DBMCP Servers
Want to easily install MCP or skillsPlugins
Want specialized processing in separate contextSub-agents
Always want to run formatting after file modificationHooks
Want to package complex domain knowledge + scriptsSkills

Tips

  1. Keep Rules short: Only core instructions, 50 or fewer
  2. Add to Rules when agent makes mistakes: Manage as living documentation
  3. Keep Commands simple: Use Skills for complex orchestration
  4. MCP only when OAuth is needed: Otherwise use Skills
  5. Ensure consistency with Hooks: Automate linting, formatting, testing
  6. Read Skills first: Check relevant SKILL.md before starting work

References