Skip to content
Published on

Claude Code Complete Guide: Subagents, Hooks, Agent SDK — Everything About Agentic Coding

Authors

Introduction: The Era of Agentic Coding

2025 marks the year the AI coding paradigm fundamentally shifted. Beyond simple code autocomplete, we have entered the era of Agentic Coding — where AI autonomously explores codebases, formulates plans, edits files, and runs tests.

Anthropic's Claude Code stands at the forefront of this paradigm. Operating through a terminal-native interface, it understands your entire project context and integrates naturally into developer workflows. It is not just a chatbot — it is a true coding agent.

This guide covers everything from Claude Code's core features to subagents, the hooks system, Agent SDK, and MCP server integration — the complete picture of agentic coding.

Target audience: Developers, team leads, and DevOps engineers interested in AI coding tools. Assumes basic terminal and Git knowledge.


1. What Is Claude Code

1.1 Core Concepts

Claude Code is Anthropic's terminal-based agentic coding tool. Rather than an IDE plugin, it runs directly in your terminal with three core capabilities:

CapabilityDescriptionExample
Read codebaseUnderstands full project structure and filesDependency analysis, architecture mapping
Edit filesPerforms code modifications, creation, deletionBug fixes, refactoring, new features
Run commandsExecutes shell commands directlyRunning tests, builds, Git operations

The key differentiator is depth of context. Claude Code understands not just individual files, but the entire project — directory structure, dependency relationships, coding conventions, and Git history.

1.2 Terminal-First Philosophy

Claude Code's choice of the terminal is deliberate:

  • Maximum flexibility: Combines with any editor or workflow
  • Automation friendly: Integrates into scripts and CI/CD pipelines
  • Low overhead: No additional IDE installation, works over SSH
  • Transparency: All commands and file changes are visible in the terminal
# Basic Claude Code execution
claude

# Run with a specific prompt
claude "Analyze the architecture of this project"

# Pipeline mode
cat error.log | claude "Analyze this error and fix it"

1.3 How It Works

Claude Code's workflow follows these steps:

  1. Context gathering: Scans project structure, CLAUDE.md files, Git state
  2. Plan formulation: Analyzes user request and creates a work plan
  3. Tool usage: Reads/writes files, executes commands, searches
  4. Verification: Confirms changes, runs tests
  5. Feedback loop: Makes additional modifications based on results

Throughout this process, users can review and approve each step. Balancing autonomy with control is Claude Code's design philosophy.


2. Claude Code vs Cursor vs GitHub Copilot

A comparison of the three major players in the agentic coding tool market.

2.1 Feature Comparison

FeatureClaude CodeCursorGitHub Copilot
InterfaceTerminal (CLI)IDE (VS Code fork)IDE plugin
Codebase understandingEntire projectEntire projectFile/tab level
File editingDirect editingDirect editingSuggestion-based
Command executionYesLimitedNo
Agent modeNativeComposer AgentAgent mode (preview)
SubagentsParallel subagentsNot supportedNot supported
Hooks systemBuilt-in hooksNot supportedNot supported
Custom agentsAgent SDKNot supportedExtensions
MCP supportNativeSupportedLimited
Automation/CIExcellentLimitedGitHub Actions
Multi-repoWorktree supportLimitedNot supported
PricingAPI usage-based20/20/40 per month10/10/19 per month

2.2 When to Choose Which Tool

Claude Code is ideal when:

  • You need complex refactoring across a large codebase
  • You want to integrate AI into CI/CD pipelines
  • You frequently make changes spanning multiple files
  • You want to build custom agents to automate team workflows

Cursor is ideal when:

  • You prefer a visual IDE environment
  • Real-time suggestions while coding are important
  • You are familiar with the VS Code ecosystem

GitHub Copilot is ideal when:

  • You want to start lightweight in your existing IDE
  • Inline autocomplete is your primary use case
  • You need tight integration with the GitHub ecosystem

3. Installation and Setup

3.1 Installation

Installing Claude Code is straightforward via npm:

# Requires Node.js 18 or higher
npm install -g @anthropic-ai/claude-code

# Or run with npx in a specific directory
npx @anthropic-ai/claude-code

After installation, proceed with authentication:

# Authentication process starts on first run
claude

# Authenticate with Anthropic account or API key
# Browser opens to complete authentication

3.2 VS Code Extension

While Claude Code is a terminal tool, it also provides a VS Code extension:

# Install the VS Code extension
code --install-extension anthropic.claude-code

Benefits of the VS Code extension:

  • Use Claude Code panel within the editor
  • View file changes in diff view
  • Ask questions about specific code via inline comments

3.3 Basic Configuration

# View configuration
claude config list

# Set model (default: claude-sonnet-4-20250514)
claude config set model claude-sonnet-4-20250514

# Permission settings
claude config set permissions.allow-edit true
claude config set permissions.allow-exec true

# Auto-approve patterns
claude config set permissions.auto-approve-commands "npm test,npm run lint"

3.4 Terminal Environment Tips

# Run Claude Code in tmux session (useful for long tasks)
tmux new-session -s claude
claude

# Save work logs
claude --output-dir ./claude-logs

# Non-interactive mode (for scripts)
claude -p "Update the README.md" --yes

4. Mastering CLAUDE.md

4.1 What Is CLAUDE.md

CLAUDE.md is a markdown file that conveys project context, conventions, and instructions to Claude Code. It is automatically read when Claude Code starts a project — the core mechanism for helping AI understand your project's "rules."

4.2 CLAUDE.md Hierarchy

CLAUDE.md can exist in multiple locations with hierarchical application:

LocationScopePurpose
~/.claude/CLAUDE.mdGlobalCommon rules for all projects
Project root CLAUDE.mdEntire projectArchitecture, tech stack, rules
Subdirectory CLAUDE.mdThat directoryModule-specific rules
.claude/CLAUDE.mdPersonalPersonal settings (not in Git)

4.3 Writing Effective CLAUDE.md

# Project Overview

This project is a blog platform built on Next.js 14.
Uses TypeScript with Tailwind CSS for styling.

# Tech Stack

- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS
- Database: PostgreSQL + Prisma ORM
- Testing: Jest + React Testing Library

# Coding Conventions

- Components: Functional components with arrow functions
- Naming: camelCase (variables/functions), PascalCase (components/types)
- Import order: External libraries > Internal modules > Relative paths
- Error handling: Use Result type pattern instead of try-catch

# Testing Rules

- Unit tests required for all new functions
- Test command: npm test
- Lint command: npm run lint
- Ensure npm run build passes before PR

# Prohibited Patterns

- No use of any type
- No console.log (use logger)
- No hardcoded strings (use constants file)

# Directory Structure

src/
app/ - Next.js App Router pages
components/ - Reusable components
lib/ - Utilities, helper functions
types/ - TypeScript type definitions
hooks/ - Custom React hooks

4.4 Advanced CLAUDE.md Patterns

Conditional instructions:

# File-Specific Rules

- When modifying files under /src/api/: Always update API docs as well
- When modifying files under /src/components/: Update Storybook stories
- When changing database schema: Auto-generate migration files

Workflow instructions:

# Work Order

1. First explore and understand relevant code
2. Explain implementation plan
3. Implement changes
4. Run and verify tests
5. Update related documentation

4.5 CLAUDE.md Management Commands

# Add to CLAUDE.md during a conversation
claude /add-memory "API responses always use snake_case"

# Check currently applied memory
claude /memory

# Auto-generate CLAUDE.md during project initialization
claude /init

5. Core Workflows

5.1 The Explore - Plan - Implement - Verify Cycle

Claude Code's fundamental work cycle has four stages:

Stage 1: Explore

> Analyze the authentication system architecture of this project

What Claude Code does:
- Scans project directory structure
- Searches auth-related files (grep, glob)
- Analyzes dependencies (package.json, import tracing)
- Checks configuration files

Stage 2: Plan

> I want to add refresh token rotation to the JWT token renewal logic

What Claude Code does:
- Analyzes current token renewal logic
- Lists files that need changes
- Explains implementation plan
- Analyzes expected impact scope

Stage 3: Implement

Once the user approves the plan, Claude Code directly modifies the code. It shows diffs before each file change and requests approval.

Stage 4: Verify

> Test and verify the changes

What Claude Code does:
- Runs npm test
- Lint check
- Type check
- Build verification

5.2 Real Scenario: Bug Fix

# Pipe error log to Claude Code
cat error.log | claude "Analyze this error and fix it"

# Claude Code's workflow:
# 1. Analyze error message
# 2. Search related source code
# 3. Identify root cause
# 4. Write fix
# 5. Run tests to confirm fix

5.3 Real Scenario: Adding a New Feature

> Add an activity history timeline to the user profile page.
> Show the last 30 days of activity in chronological order,
> with infinite scroll to load older activities.

Claude Code's work:
1. Analyze existing profile page code
2. Check/create activity data API endpoint
3. Implement timeline component
4. Implement infinite scroll logic
5. Apply styling
6. Write and run tests

5.4 Git Workflow Integration

# Create a commit from current changes
claude commit

# Create a PR
claude "Create a PR from the changes on the current branch"

# Code review
claude "Review the changes in PR #42"

# Resolve merge conflicts
claude "Resolve the current merge conflicts"

6. Subagents Deep Dive

6.1 What Are Subagents

Subagents are one of Claude Code's most powerful features. The main agent splits complex tasks into multiple independent subtasks and executes them in parallel.

Main Agent (Orchestrator)
├── Subagent 1: Implement API endpoints
├── Subagent 2: Write frontend components
├── Subagent 3: Database migration
└── Subagent 4: Write test code

6.2 How Subagents Work

Subagents have the following characteristics:

CharacteristicDescription
Independent contextEach subagent has its own context window
Parallel executionMultiple subagents work simultaneously
Result integrationMain agent synthesizes subagent results
Failure isolationOne subagent's failure does not affect others
Read-only optionAnalysis/exploration subagents can run read-only

6.3 Subagent Usage Patterns

Pattern 1: Large-Scale Refactoring

> Convert all class components to functional components across the project

Main agent's work:
1. Search all files using class components
2. Divide files into groups
3. Assign each group to a subagent
4. Subagents perform conversion in parallel
5. Integrate results and run tests

Pattern 2: Multi-File Analysis

> Analyze security vulnerabilities in this project

Subagent 1: Analyze authentication/authorization code
Subagent 2: Check SQL injection possibilities
Subagent 3: Check XSS vulnerabilities
Subagent 4: Dependency security audit

Pattern 3: Code Generation + Testing

> Create a user management CRUD API

Subagent 1: Generate API routes and controllers
Subagent 2: Generate data models and migrations
Subagent 3: Write integration tests
Subagent 4: Generate API documentation

6.4 Background Agents

Claude Code can continue working in the background:

# Start background agent
claude --background "Increase test coverage to above 80%"

# Check background agent status
claude --list-backgrounds

# Review results
claude --resume <session-id>

Use cases for background agents:

  • Long-running refactoring tasks
  • Large-scale code migration
  • Test coverage improvement
  • Documentation tasks

6.5 Parallel Work with Worktrees

Combining with Git worktrees enables even more powerful parallel work:

# Create worktree and perform independent work
claude "Create a worktree and refactor the auth module on the feature-auth branch"

# Continue other work on main branch
claude "Continue with the bug fix"

Benefits of worktrees:

  • Isolated work environment: Experiment without affecting main code
  • Parallel development: Develop multiple features simultaneously
  • Safe experimentation: Just delete the worktree if it fails

7. Hooks System

7.1 What Are Hooks

Hooks are custom actions that automatically execute in response to specific events in Claude Code. They are the core mechanism for automating development workflows.

7.2 Types of Hooks

Hook EventTrigger PointUse Case
PreToolUseBefore tool executionBlock dangerous commands, back up files
PostToolUseAfter tool executionAuto-formatting, lint execution
NotificationWhen notification occursSlack alerts, email sending
StopWhen agent terminatesFinal verification, report generation

7.3 Configuring Hooks

Hooks are configured in the .claude/settings.json file:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "command": "cp \"$CLAUDE_FILE_PATH\" \"$CLAUDE_FILE_PATH.bak\" 2>/dev/null || true"
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\""
      },
      {
        "matcher": "Write",
        "command": "npx eslint --fix \"$CLAUDE_FILE_PATH\""
      }
    ],
    "Notification": [
      {
        "matcher": "",
        "command": "terminal-notifier -message \"$CLAUDE_NOTIFICATION\" -title \"Claude Code\""
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "command": "npm test 2>&1 | tail -20"
      }
    ]
  }
}

7.4 Practical Hook Recipes

Recipe 1: Auto-Test Execution

Automatically run related tests whenever a file is modified:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "command": "if [[ \"$CLAUDE_FILE_PATH\" == *.ts ]]; then npx jest --findRelatedTests \"$CLAUDE_FILE_PATH\" --passWithNoTests; fi"
      }
    ]
  }
}

Recipe 2: Auto-Formatting Pipeline

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" && npx eslint --fix \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
      }
    ]
  }
}

Recipe 3: Security Guardrails

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "if echo \"$CLAUDE_COMMAND\" | grep -qE 'rm -rf|DROP TABLE|DELETE FROM'; then echo 'BLOCKED: Dangerous command detected' && exit 1; fi"
      }
    ]
  }
}

Recipe 4: Change Logging

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "echo \"$(date): $CLAUDE_FILE_PATH modified\" >> .claude/change.log"
      }
    ]
  }
}

7.5 Debugging Hooks

# View hook execution logs
claude --verbose

# Disable a specific hook
claude config set hooks.PostToolUse.enabled false

# Skip hooks (temporarily)
claude --no-hooks

8. Agent SDK

8.1 Agent SDK Overview

The Agent SDK enables programmatic access to Claude Code's core capabilities, allowing you to build custom AI agents.

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

const agent = new AgentSDK({
  model: 'claude-sonnet-4-20250514',
  permissions: {
    fileRead: true,
    fileWrite: true,
    commandExec: ['npm test', 'npm run lint'],
  },
})

8.2 Core Concepts

ConceptDescription
SessionConversation context with the agent
ToolsCapabilities available to the agent
PermissionsLimits on the agent's scope of work
EventsEvents that occur during agent work

8.3 Building Custom Agents

Example 1: Code Review Agent

import { AgentSDK } from '@anthropic-ai/claude-code-sdk'

async function createCodeReviewAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `You are a senior code reviewer.
    Review code from these perspectives:
    1. Security vulnerabilities
    2. Performance issues
    3. Coding convention compliance
    4. Test coverage`,
    permissions: {
      fileRead: true,
      fileWrite: false,
      commandExec: ['git diff'],
    },
  })

  const session = await agent.createSession()
  const result = await session.send('Review the changes in the current PR')

  console.log(result.response)
  console.log('Issues found:', result.issues)
}

Example 2: Auto-Documentation Agent

async function createDocAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `Automatically generate JSDoc/TSDoc documentation for functions and modules.
    Update existing docs or create new ones where missing.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npm run build'],
    },
  })

  const session = await agent.createSession()
  await session.send('Add documentation to all exported functions in the src/lib/ directory')
}

Example 3: Database Migration Agent

async function createMigrationAgent() {
  const agent = new AgentSDK({
    model: 'claude-sonnet-4-20250514',
    systemPrompt: `A specialized agent for managing Prisma migrations.
    Analyzes schema changes and generates safe migrations.`,
    permissions: {
      fileRead: true,
      fileWrite: true,
      commandExec: ['npx prisma migrate dev', 'npx prisma generate', 'npx prisma db push'],
    },
  })

  const session = await agent.createSession()
  await session.send('Create a migration to add a profileImage field to the User model')
}

8.4 Event Handling

const session = await agent.createSession()

session.on('toolUse', (event) => {
  console.log(`Tool used: ${event.tool} - ${event.description}`)
})

session.on('fileChange', (event) => {
  console.log(`File changed: ${event.path} - ${event.type}`)
})

session.on('commandExec', (event) => {
  console.log(`Command executed: ${event.command}`)
  console.log(`Result: ${event.output}`)
})

session.on('error', (event) => {
  console.error(`Error occurred: ${event.message}`)
})

8.5 Permission Model

Security is a core design principle of the Agent SDK:

const agent = new AgentSDK({
  permissions: {
    // File access control
    fileRead: true,
    fileWrite: true,
    fileGlob: ['src/**/*.ts', 'tests/**/*.ts'], // Allowed patterns
    fileExclude: ['*.env', 'secrets/**'], // Blocked patterns

    // Command execution control
    commandExec: ['npm test', 'npm run lint', 'npx prisma migrate dev'],

    // Network access control
    networkAccess: false,

    // MCP server access
    mcpServers: ['filesystem', 'database'],
  },
})

9. MCP Server Integration

9.1 What Is MCP (Model Context Protocol)

MCP is a standard protocol that enables AI models to access external tools and data sources. Claude Code natively supports MCP, enabling integration with various external systems:

Claude Code <--MCP--> Database Server
Claude Code <--MCP--> GitHub API
Claude Code <--MCP--> Slack API
Claude Code <--MCP--> File System
Claude Code <--MCP--> Custom API

9.2 MCP Server Configuration

Register MCP servers at the project level in .claude/settings.json:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_xxxxxxxxxxxx"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
      }
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_TOKEN": "xoxb-xxxxxxxxxxxx"
      }
    }
  }
}
MCP ServerPurposeCapabilities
filesystemFile systemFile read/write, directory traversal
githubGitHub integrationPRs, issues, code search, reviews
postgresPostgreSQLQuery execution, schema inspection
sqliteSQLiteLocal database operations
slackSlack integrationMessage sending, channel queries
puppeteerWeb browserWeb scraping, E2E testing
memoryPersistent memoryData persistence across sessions
brave-searchWeb searchReal-time web search
sentryError trackingError log queries, analysis
linearProject managementIssue tracking, sprint management

9.4 Building Custom MCP Servers

Create custom MCP servers to connect your own APIs or internal systems:

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

const server = new McpServer({
  name: 'my-internal-api',
  version: '1.0.0',
})

// Define tools
server.tool(
  'getDeployStatus',
  'Get deployment status',
  {
    environment: { type: 'string', enum: ['staging', 'production'] },
  },
  async (params) => {
    const status = await fetchDeployStatus(params.environment)
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(status, null, 2),
        },
      ],
    }
  }
)

server.tool(
  'triggerDeploy',
  'Trigger a deployment',
  {
    environment: { type: 'string' },
    version: { type: 'string' },
  },
  async (params) => {
    const result = await triggerDeploy(params.environment, params.version)
    return {
      content: [
        {
          type: 'text',
          text: `Deployment triggered: ${result.id}`,
        },
      ],
    }
  }
)

// Start server
const transport = new StdioServerTransport()
await server.connect(transport)

9.5 MCP Server Usage Scenarios

Scenario 1: Database-Integrated Development

> Check the users table schema and create a new API endpoint

Claude Code's work:
1. Query schema via MCP postgres server
2. Analyze existing API patterns
3. Generate new endpoint code
4. Generate migration file
5. Write tests

Scenario 2: GitHub-Integrated Workflow

> Check recently opened issues with the bug label,
> and fix the highest priority one

Claude Code's work:
1. Query issue list via MCP github server
2. Analyze priorities
3. Explore and fix related code
4. Create PR

10. Advanced Patterns

10.1 Multi-Repository Work

Perform tasks spanning multiple repositories:

# In a monorepo environment
claude "Analyze the impact of changes to the packages/shared library on
packages/web and packages/api, and perform all necessary updates"

10.2 Git Worktree Usage

# Develop multiple features simultaneously
claude "Create worktrees and perform these tasks in parallel:
1. feature/auth - Refactor authentication module
2. feature/dashboard - Optimize dashboard performance
3. fix/memory-leak - Fix memory leak"

10.3 Scheduled Tasks

Schedule repetitive tasks with Claude Code:

# Generate daily code quality report
claude schedule --cron "0 9 * * *" "Generate a code quality report and share it on Slack"

# Check dependency updates every Monday
claude schedule --cron "0 10 * * 1" "Check npm outdated and apply safe updates"

10.4 Headless Mode and CI/CD Integration

# GitHub Actions example
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Claude Code Review
        run: |
          npx @anthropic-ai/claude-code -p \
            "Review the changes in this PR and leave comments" \
            --yes --output-format json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

10.5 Context Window Optimization

Strategies for efficiently using context in large projects:

  1. Pre-provide project context via CLAUDE.md: Supply essential information upfront instead of repeated exploration
  2. Distribute context via subagents: Split large tasks into smaller independent tasks
  3. Compress conversations with /compact: Retain only essentials in long conversations
  4. File filtering: Exclude unnecessary files with .claudeignore
# .claudeignore example
node_modules/
dist/
.next/
coverage/
*.lock
*.log

11. Real-World Case Studies and Productivity Data

11.1 Anthropic Internal Usage Data

Usage data shared by Anthropic's internal development team:

MetricValue
Code writing time reduction~40-60%
Code review time reduction~30-50%
Average bug fix time50% decrease vs. baseline
Test coverage improvementAverage 15-20% increase
Daily commit countAverage 2-3x increase

11.2 Case Study 1: Large-Scale Migration

Situation: Migrating 200 React class components to functional components

  • Estimated manual work: 2-3 weeks (1 person)
  • With Claude Code: 2 days (subagent parallel processing)
  • Conversion success rate: 95% (remaining 5% required manual review)

11.3 Case Study 2: API Integration Development

Situation: External payment API integration (Stripe)

  • Work performed by Claude Code:
    • API documentation analysis (using MCP brave-search)
    • Interface type definitions
    • Service layer implementation
    • Webhook handler implementation
    • Error handling
    • 80% of unit/integration tests written
  • Time taken: 4 hours (vs. 2-3 days manually)

11.4 Case Study 3: Legacy Code Modernization

Situation: Modernizing a jQuery + PHP app to Next.js + TypeScript

  • Defined migration rules in CLAUDE.md
  • Parallel component-by-component conversion via subagents
  • Automatic type checking and testing via hooks
  • Reduced a 6-week project to 2 weeks

11.5 Tips for Maximizing Productivity

  1. Write detailed CLAUDE.md: The highest ROI investment
  2. Start with small tasks: Build trust with bug fixes and test additions before tackling larger work
  3. Use hooks actively: Automate repetitive verification tasks
  4. Leverage subagents: Split large tasks for parallel processing
  5. Always verify results: Review AI output rather than blindly trusting it

12. Tips and Tricks

12.1 Keyboard Shortcuts

ShortcutFunction
Ctrl+CCancel current task
Ctrl+DEnd session
EscCancel current input
TabAutocomplete
Up/DownBrowse previous commands

12.2 Slash Commands

/help          # Help
/clear         # Clear conversation
/compact       # Compress conversation
/memory        # Check memory (CLAUDE.md)
/add-memory    # Add rule to memory
/model         # Change model
/cost          # Check current session cost
/diff          # View current changes
/undo          # Undo last change
/review        # Request code review
/init          # Initialize project
/bug           # Bug report
/config        # Change settings

12.3 Using the Memory System

Claude Code's memory system maintains learned content across sessions:

# Add memory during conversation
/add-memory "API responses in this project always use camelCase"
/add-memory "Test files are located in __tests__ directories"
/add-memory "Always run npx prisma generate after Prisma migrations"

12.4 Writing Effective Prompts

Bad prompt:

Make a login feature

Good prompt:

Add Google OAuth login using NextAuth.js.
- Configure in /app/api/auth/[...nextauth]/route.ts
- Use Google Provider
- Include user ID in session
- Create login/logout button component
- Integrate into existing Navbar component

12.5 Debugging Strategies

# Verbose logging mode
claude --verbose

# Tool usage logging
claude --debug-tools

# Export session history
claude --export-session ./session-log.json

# Switch to a specific model for comparison
claude --model claude-opus-4-20250514

12.6 Cost Optimization

# Check current session cost
/cost

# Economy mode (use Haiku)
claude --model claude-haiku

# Set automatic cost alerts
claude config set cost.alert-threshold 5.00

13. Quiz

Test your understanding of Claude Code.

Q1. What are Claude Code's three core capabilities?

A1. Claude Code's three core capabilities are:

  1. Read codebase: Understands full project structure and files
  2. Edit files: Performs code modifications, creation, and deletion
  3. Run commands: Executes shell commands directly

The combination of these three capabilities makes Claude Code a true coding agent rather than a simple chatbot.

Q2. What are the four key characteristics of subagents?

A2. The four key characteristics of subagents:

  1. Independent context: Each subagent has its own context window
  2. Parallel execution: Multiple subagents work simultaneously
  3. Result integration: The main agent synthesizes results
  4. Failure isolation: One failure does not affect other tasks
Q3. In the CLAUDE.md hierarchy, which has the highest priority?

A3. The subdirectory CLAUDE.md has the highest priority. The hierarchy is:

  1. Global CLAUDE.md (lowest)
  2. Project root CLAUDE.md
  3. Subdirectory CLAUDE.md (highest — within that directory)

More specific settings override general ones.

Q4. What is MCP (Model Context Protocol), and what external systems can it integrate with?

A4. MCP is a standard protocol that enables AI models to access external tools and data sources. Examples of integrable systems:

  • Databases: PostgreSQL, SQLite, MySQL
  • Version control: GitHub, GitLab
  • Communication: Slack, Discord
  • Project management: Linear, Jira
  • Web browser: Puppeteer
  • Search: Brave Search
  • Error tracking: Sentry
  • Custom APIs: Build your own MCP server
Q5. When does the PostToolUse hook fire, and what are typical use cases?

A5. The PostToolUse hook fires immediately after Claude Code uses a tool (file editing, command execution, etc.).

Typical use cases:

  • Auto-formatting: Automatically run Prettier/ESLint after file modification
  • Auto-testing: Automatically run related tests after file changes
  • Change logging: Automatically record file change history
  • Type checking: Automatically run type checks after TypeScript file modifications

This enables automatic code quality maintenance.


References

Official Documentation

  1. Anthropic Claude Code Official Docs
  2. Claude Code GitHub Repository
  3. Model Context Protocol (MCP) Official Site
  4. MCP Server Directory
  5. Anthropic API Documentation

Blog Posts and Technical Articles

  1. Anthropic Blog - Introducing Claude Code
  2. Claude Code Best Practices
  3. CLAUDE.md Writing Guide
  4. Claude Code Hooks Documentation
  5. Agent SDK Guide
  1. Awesome Claude Code - Community Resources
  2. Claude Code Discord Community
  3. MCP Server Development Guide
  4. Agentic Coding Trends Analysis
  5. Claude Code vs Traditional AI Coding Tools
  6. Anthropic Cookbook - Claude Code Examples
  7. Claude Code Slash Commands Reference