โ ESSAY
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.
You don't need to master all concepts at once. Follow this learning path:
Step 1: CLAUDE.md (Rules)
Step 2: Hooks
Step 3: Commands
Step 4: Sub-agents, MCP, Skills
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.
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.
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.
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\*
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.
Commands are workflows that package frequently used prompts for execution when needed. Enter a command starting with / to execute a predefined prompt.
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.
| Aspect | Rules | Commands |
|---|---|---|
| Application | Always included in conversations | Only when explicitly called |
| Purpose | Provide context | Execute workflows |
| Context Impact | Always consumes tokens | Consumes tokens only when called |
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 /
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.
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.
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.
| Category | Examples |
|---|---|
| Basic Tools (First-party) | File read/write, shell commands, code search |
| MCP Tools (Third-party) | Slack, GitHub, Jira, Notion, PostgreSQL, Sentry, etc. |
Claude Code can act as both MCP client and server. Multiple simultaneous MCP server connections are possible.
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 | Description |
|---|---|
local (default) | Current project, personal use only |
project | All project members (stored in .mcp.json) |
user | Personal use across all projects |
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.
| Server | Purpose |
|---|---|
| @modelcontextprotocol/server-github | GitHub PR, issues, repository management |
| @modelcontextprotocol/server-slack | Slack message read/write |
| @modelcontextprotocol/server-postgres | PostgreSQL queries |
| @modelcontextprotocol/server-filesystem | Local file system access |
| Puppeteer MCP | Browser automation, screenshots |
| Sentry MCP | Error monitoring |
Hundreds of MCP servers are available on GitHub.
MCP servers access external services on your behalf. Don't install untrusted servers. Servers that fetch content from the internet pose prompt injection risks.
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.
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.
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.
Built-in Sub-agents:
| Name | Description |
|---|---|
| Explore | Read-only codebase exploration |
| Plan | Research 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
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"
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.
Modes are an extension of Sub-agents that include instructions + system prompt modifications + UI changes to provide agent operation modes optimized for specific tasks.
| Aspect | Sub-agent | Mode |
|---|---|---|
| System Prompt | Own prompt | Can modify main prompt |
| UI | No changes | UI customization possible |
| Tools | Can restrict | Restrict + add new tools |
| Context | Separate | Shared with main |
| Reminders | None | Include mode maintenance reminders |
Claude Code's Plan Mode is for establishing plans before writing code.
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.
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.
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.
Context injection on every execution:
Pre/post tool execution processing:
Post-session processing:
| Event | Timing | Use Cases |
|---|---|---|
SessionStart | Session start/resume | Load dev context, environment setup |
UserPromptSubmit | Right after user input | Input validation, context injection, security filtering |
PreToolUse | Before tool execution | Command validation, blocking dangerous commands |
PostToolUse | After tool execution | Formatting, linting, result logging |
PermissionRequest | When permission requested | Auto approve/deny decisions |
Stop | Agent response complete | Auto-commit, completion notifications |
SubagentStop | Sub-agent completion | Result processing, trigger next steps |
PreCompact | Before compaction | Transcript backup |
Notification | When notification occurs | Custom notification handling |
Configuration file locations:
~/.claude/settings.json.claude/settings.jsonConfiguration 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"
}
]
}
]
}
}
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
/hooks menuSkills 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.
Rules (static context) and Commands (workflow execution) each have limitations:
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:
| Characteristic | Rules | Commands | Skills |
|---|---|---|---|
| Load timing | Always | Explicit invocation | Automatically when needed |
| Context impact | Always consumes | Consumes on call | Consumes only when used |
| Discovery method | N/A | / input | Agent automatic decision |
| Includable elements | Text | Text + metadata | Text + scripts + assets |
| Sharing scope | Project | Project/user | Entire ecosystem |
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
---
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`
Skills are an open standard. Developed and open-sourced by Anthropic, adopted by various agent products:
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.
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.
| Type | Description | Examples |
|---|---|---|
| Skill + MCP combination | Package skills and MCP together | firecrawl, supabase |
| LSP plugins | Language server integration | typescript-lsp, pyright-lsp |
| Hooks + Tools | Hook and tool bundles | hookify |
| Search tools | Enhanced search functionality | mgrep |
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
# Add marketplace
claude plugin marketplace add https://github.com/mixedbread-ai/mgrep
# Within Claude Code
/plugins # Check plugin list and install
Like MCP, plugins affect the context window. Only activate necessary plugins and deactivate unused ones.
We've explored 8 concepts so far. They don't exist independently but are interconnected.
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.
| Situation | Choice |
|---|---|
| OAuth authentication needed (Slack, GitHub, etc.) | MCP |
| Simple script + instruction combination | Skills |
| External API calls (no authentication) | Skills (use curl in scripts) |
| Share with team/community | Skills (open standard) |
| Real-time data streaming | MCP |
Skills are sufficient for most cases. Use MCP only when OAuth is needed or real-time bidirectional communication is required.
| Situation | Choice |
|---|---|
| Want to separate context | Sub-agents |
| Want to maintain main context while limiting tools only | Modes |
| Execute multiple tasks in parallel | Sub-agents |
| UI/reminder customization | Modes |
| Read-only exploration tasks | Sub-agents (Explore) |
Now that we understand the concepts, let's see how they're combined in practice.
Step-by-step explanation:
shift+tab): Establish plan before writing codeKey points:
Component combination:
Selection criteria:
gh CLI is already authenticated โ Skills (simpler)Coding agents consume tokens. Understanding how each concept impacts token usage allows you to optimize costs.
| Concept | Token Consumption Point | Impact Level |
|---|---|---|
| Rules | Every conversation start | ๐ด High (always included) |
| Commands | When called | ๐ก Medium |
| MCP | When loading tool definitions | ๐ด High (all connected tools) |
| Sub-agents | When executed (separate context) | ๐ข Low (minimal impact on main) |
| Modes | When switching modes | ๐ก Medium |
| Hooks | When executed | ๐ข Low (returns result only) |
| Skills | Only when needed | ๐ข Low |
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.
Claude Code shows token usage when sessions end. Check regularly to understand which tasks consume the most tokens.
Besides Claude Code, there are various coding agents like Cursor, Windsurf, and GitHub Copilot. The same concepts sometimes go by different names.
| Claude Code | Cursor | Windsurf | GitHub Copilot |
|---|---|---|---|
| CLAUDE.md | .cursorrules | .windsurfrules | .github/copilot-instructions.md |
| Commands | - | - | - |
| MCP | MCP | MCP | - |
| Sub-agents | - | Cascade | - |
| Hooks | - | - | - |
| Skills | Skills | Skills | - |
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.
| Aspect | Claude Code | Cursor |
|---|---|---|
| Environment | Terminal | IDE (VS Code fork) |
| Models | Claude only | Claude, GPT, others |
| File editing | Direct modification | Diff view within IDE |
| Pricing | API usage based | Monthly subscription ($20/mo) |
| Strengths | Automation, Hooks | IDE integration, real-time autocomplete |
A collection of practical tips for real-world use.
| Shortcut | Function |
|---|---|
Ctrl+U | Delete entire input line (faster than repeated backspace) |
! | Quick bash command prefix |
@ | File search |
/ | Start slash command |
Shift+Enter | Multi-line input |
Tab | Toggle thinking display |
Esc Esc | Stop Claude / restore code |
/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
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
| Command | Function |
|---|---|
/rewind | Revert to previous state |
/statusline | Customize status bar with branch, context %, todos, etc. |
/checkpoints | File-level undo points |
/compact | Manually compress context |
/mcp | Check MCP server status |
/plugins | Plugin list and management |
While Claude Code runs in terminal, it's more effective when used alongside an editor.
Recommended Setup:
When context is insufficient, agents can hallucinate or give irrelevant answers.
Solutions:
Sometimes agents don't follow what's written in CLAUDE.md.
Solutions:
Solutions:
/compact command to compress contextLet'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\""
}
]
}
]
}
}
Coding agents consist of static context, dynamic context, and deterministic execution (Hooks).
๐ Static Context (always included)
โก Dynamic Context (loaded/called only when needed)
๐ง Hooks (deterministic execution)
| Situation | Use This |
|---|---|
| Want to inform about project structure, coding rules | Rules (CLAUDE.md) |
| Want to create shortcuts for repetitive workflows | Commands |
| Want to connect to external services like Slack, GitHub, DB | MCP Servers |
| Want to easily install MCP or skills | Plugins |
| Want specialized processing in separate context | Sub-agents |
| Always want to run formatting after file modification | Hooks |
| Want to package complex domain knowledge + scripts | Skills |