Skip to content
Published on

Claude Code Complete Guide: How to Revolutionize Development Productivity with Anthropic's AI Coding Agent

Authors
  • Name
    Twitter

1. Introduction to Claude Code

What is Agentic Coding?

Agentic Coding is a paradigm that goes beyond AI simply auto-completing code — it understands the codebase, independently navigates and edits files, executes commands, and autonomously performs development tasks. While traditional code auto-completion tools were limited to predicting "the next line," agentic coding tools understand the developer's intent and autonomously handle the entire workflow.

Claude Code is the terminal-based AI coding agent officially provided by Anthropic. It operates as a CLI (Command Line Interface), not an IDE plugin, managing the entire process of reading, modifying, and executing code through natural language commands in the terminal.

Key Features

The key features that differentiate Claude Code from existing AI coding tools are as follows.

  • Terminal Native: Runs directly from the terminal without being tied to any IDE. Can be used anywhere including SSH remote servers, Docker containers, and CI/CD pipelines.
  • Codebase Understanding: Automatically analyzes project structure, identifies inter-file dependencies, and performs context-aware tasks.
  • Tool-Based Architecture: Combines various built-in tools such as Read, Write, Edit, Bash, Glob, and Grep to perform complex tasks.
  • Git Native Integration: Handles the entire Git workflow through natural language — commits, branch creation, PR writing, and code review.
  • Extended Thinking: Enables a chain of thought where the model reasons through complex problems before writing code, activated by default.
  • Multi-Agent: Uses the Task tool and Subagents to handle up to 10 parallel tasks simultaneously.

What Tasks Is It Best For?

Claude Code is particularly powerful in the following scenarios.

1. Large-scale refactoring    -> "Convert all class components to function components"
2. Codebase exploration       -> "Analyze where the authentication logic is implemented"
3. Bug debugging              -> "Analyze this error log and find the cause and fix it"
4. Test code generation       -> "Write unit tests for this module"
5. Git workflow               -> "Commit the changes and create a PR"
6. Documentation              -> "Write JSDoc for this API"
7. CI/CD automation           -> "Automate code review in GitHub Actions"

2. Installation and Initial Setup

System Requirements

To use Claude Code, the following environment is required.

  • OS: macOS, Linux (Windows via WSL)
  • Node.js: v18 or higher (for npm installation)
  • Account: Claude Pro, Max, Teams, Enterprise, or Console (API) account (free plan not supported)

Installation Methods

The native binary installation is the currently recommended official method. It requires no separate Node.js dependency and supports automatic updates.

# macOS / Linux native installation
curl -fsSL https://claude.ai/install.sh | bash

Method 2: Installation via npm

If a Node.js environment is already set up, installation via npm is also possible.

# npm global installation
npm install -g @anthropic-ai/claude-code

# Verify installation
claude --version

Method 3: VS Code Extension

Installation is also possible directly from the VS Code marketplace.

1. In VS Code, press Cmd+Shift+X (Mac) / Ctrl+Shift+X (Windows/Linux)
2. Search for "Claude Code"
3. Click Install

Authentication Setup

Claude Code supports two authentication methods.

OAuth Authentication (Pro/Max/Teams/Enterprise)

# Browser OAuth authentication on first run
claude

# Manual login
claude auth login

When you first run the claude command, a browser opens and the OAuth flow begins where you log in with your Anthropic account. After authentication, a token is stored locally and subsequent logins are automatic.

API Key Authentication (Console)

# Set API key as environment variable
export ANTHROPIC_API_KEY="sk-ant-api03-..."

# Or save in .env file
echo 'ANTHROPIC_API_KEY=sk-ant-api03-...' >> ~/.zshrc
source ~/.zshrc

API keys can be generated at Anthropic Console. Be careful never to commit API keys to public repositories.

Model Selection

Claude Code supports multiple Claude models. The default model is Claude Sonnet, and it can be changed as needed.

# Check and change model
claude --model claude-sonnet-4-6
claude --model claude-opus-4-6
claude --model claude-haiku-3-5

# Change model during conversation
/model

Installation Verification

To verify that the installation was completed successfully, run the following commands.

# Version check
claude --version

# Simple test
claude "Say hello"

# Environment diagnostics
claude doctor

3. Basic Usage

Claude Code supports three execution modes. Choose the appropriate mode depending on the situation.

3.1 Interactive Mode

The most basic usage. Running claude in the terminal starts an interactive REPL environment.

# Start interactive mode
claude

# Start in project directory (recommended)
cd ~/my-project && claude

In interactive mode, you give instructions in natural language.

> Analyze the structure of this project

> Add JWT verification logic to the src/auth/login.ts file

> Update all dependencies in package.json to their latest versions

Claude automatically selects and executes the appropriate tools for each task. It requests user approval before modifying files or executing commands.

3.2 One-shot Mode

Passing an initial prompt as an argument starts the conversation with that prompt immediately executed.

# Start with an initial prompt
claude "Find all deprecated API usage in TypeScript files under the src directory"

# Ask questions while referencing a specific file
claude "Analyze the performance issues in this file" --file src/utils/parser.ts

3.3 Pipe / Headless Mode

Using the --print (-p) flag runs in non-interactive mode. This is suitable for CI/CD pipelines or script automation.

# Non-interactive execution
claude -p "Organize the dependency list in package.json"

# Pipe input via stdin
cat error.log | claude -p "Analyze this error log and suggest solutions"

# Analyze PR diff
git diff main...HEAD | claude -p "Review these changes for security vulnerabilities"

# Specify output format
claude -p "Analyze the project structure" --output-format json

# Use in CI/CD pipeline
claude -p "Perform a code review" \
  --dangerously-skip-permissions \
  --output-format stream-json

Key characteristics of pipe mode are as follows.

FeatureDescription
--print / -pActivate non-interactive mode
--output-formatSupports text, json, stream-json
--dangerously-skip-permissionsSkip all permission checks (CI/CD only)
--session-idMaintain multi-turn session
--resumeContinue from previous session
--append-system-promptAppend to default system prompt

Multi-Turn Session Example

# Continuous conversation with session ID
claude -p "Analyze the project structure" --session-id my-review

# Follow-up question in the same session
claude -p "What improvements can be made to the structure we just analyzed?" \
  --session-id my-review --resume

4. Core Slash Commands

In Claude Code's interactive mode, you can use slash commands starting with /. These commands provide various functions including session management, model switching, and cost checking.

Essential Commands Summary

CommandDescriptionWhen to Use
/helpShow all available commandsWhen first starting out
/initGenerate CLAUDE.md fileWhen starting a new project
/modelChange AI model (Sonnet/Opus/Haiku)Based on task complexity
/compactCompress conversation historyContext saving in long sessions
/costCheck current session token usageCost monitoring
/clearReset conversation historyWhen starting a new topic
/doctorDiagnose installation statusWhen issues occur
/reviewPerform code reviewPre-PR review
/commitCreate Git commitWhen saving changes
/hooksConfigure custom hooksWhen setting up automation workflows
/loginRe-authenticateWhen token expires
/logoutLogoutWhen switching accounts
/configCheck and modify settingsWhen customizing settings
/permissionsManage permission settingsWhen adjusting security

Key Commands in Detail

/init -- Project Initialization

/init

/init automatically generates a CLAUDE.md file at the project root. This file includes project structure, build commands, coding conventions, and more. This is the first command you should run in a new project.

/compact -- Conversation Compression

# Default compression
/compact

# Compress with custom instructions
/compact Keep only authentication-related context

/compact summarizes conversation history to free up context window space. It removes unnecessary duplication while preserving essential information. This is an essential command for long coding sessions. Claude Code automatically performs auto-compaction when the context limit is reached, but manual execution allows for more precise control.

/model -- Change Model

/model

Running this displays a list of available models, and you can select the one appropriate for the current task. General recommendations are as follows.

  • Haiku: Simple questions, quick code generation, cost saving
  • Sonnet: Everyday coding tasks (default, most balanced choice)
  • Opus: Complex architecture design, large-scale refactoring, tasks requiring deep reasoning

/cost -- Check Cost

/cost

Displays the number of input/output tokens used in the current session and estimated cost. Useful for session management, and comparing costs before and after /compact lets you verify savings.

/doctor -- Environment Diagnostics

/doctor

Automatically checks installation status, API connection, permission settings, MCP configuration, and more. If issues are detected, it suggests solutions. According to Anthropic's official documentation, it automatically diagnoses 85% of common issues.

Custom Slash Commands

Creating Markdown files in the .claude/commands/ directory allows you to create custom slash commands.

<!-- .claude/commands/review-security.md -->

Perform a security review focusing on the following items:

1. SQL Injection vulnerabilities
2. XSS vulnerabilities
3. Authentication/authorization bypass possibilities
4. Sensitive information exposure
5. CSRF vulnerabilities

Analyze only the changed files and indicate severity (High/Medium/Low) for each item.

A file created this way can be invoked as /review-security.


5. Tools System

The core strength of Claude Code lies in its tool-based architecture that combines various built-in tools to perform tasks. Claude automatically selects and executes appropriate tools based on the user's request.

Complete Built-in Tools List

Read-Only Tools (Zero-risk)

These tools do not modify the file system or external state, so they require no separate permission approval.

ToolDescriptionUsage Examples
ReadRead file contents (including images, PDFs)Source code analysis, config file review
GlobFile name pattern matching**/*.ts, src/**/*.test.js pattern search
GrepFile content search (ripgrep-based)Regex code pattern search
WebSearchWeb searchLatest docs, API reference lookup
WebFetchFetch URL contentRead public URL content

Write Tools

Tools that modify files or execute commands. By default, they request user approval before execution.

ToolDescriptionUsage Examples
EditPrecisely modify file content (string replacement)Modify specific functions, rename variables
MultiEditSimultaneously modify multiple locations in one fileAdd multiple import statements
WriteCreate file or completely overwriteCreate new files, write config files
BashExecute shell commandsnpm install, git commit, docker build
NotebookEditEdit Jupyter notebook cellsModify data analysis notebooks

Agent Tools

Tools for splitting complex tasks and parallel processing.

ToolDescriptionUsage Examples
TaskCreate and execute sub-agentsParallel code review, multi-file analysis

How Each Tool Works

Read -- File Reading

The Read tool reads files using absolute paths.
- Text files: Display content with line numbers
- Images (PNG, JPG): Multimodal analysis
- PDF: Specific page range can be specified (pages: "1-5")
- Jupyter notebooks: Display all cells and outputs
- Large files: Partial reading with offset and limit

Edit -- Precise Modification

The Edit tool works by finding a unique string in a file and precisely replacing it. Since it does not overwrite the entire file, it is safe.

Workflow:
1. Check file content with Read
2. Specify old_string (existing content) and new_string (new content)
3. Verify that old_string is unique within the file
4. If not unique, retry with more surrounding context

Bash -- Command Execution

The Bash tool executes shell commands. Security is applied in a sandbox environment, with a maximum timeout of 10 minutes (600 seconds).

# Examples of tasks executable with the Bash tool
npm install express
git status
docker compose up -d
python manage.py migrate
kubectl get pods

Glob searches by file name patterns, and Grep searches file content with regular expressions. Both tools are ripgrep-based and provide fast performance even on large codebases.

Glob examples:
- **/*.ts         -> All TypeScript files
- src/**/test.*   -> All test files under src
- *.{js,jsx,ts,tsx} -> All JavaScript/TypeScript files

Grep examples:
- "TODO|FIXME"              -> All TODO/FIXME comments
- "function\s+\w+"          -> Function declaration search
- "import.*from\s+'react'"  -> React import search

Task -- Sub-Agents

The Task tool creates sub-agents with independent context windows. It is used for splitting complex tasks or parallel processing. Details are covered in Section 9: Multi-Agent Architecture.


6. Permission Modes

Claude Code provides 4 permission modes for security. Each mode defines the level of autonomy granted to Claude.

4 Permission Modes

1. Normal Mode (Default)

The most common mode -- read operations are auto-approved and write/execute operations request user confirmation.

Auto-approved: Read, Glob, Grep, WebSearch, WebFetch
Confirmation needed: Edit, Write, Bash, NotebookEdit

Suitable for approximately 85% of usage scenarios.

2. Plan Mode

Only allows read-only access; blocks file modifications and command execution. Used during code analysis or architecture design phases.

Auto-approved: Read, Glob, Grep, WebSearch, WebFetch
Blocked:       Edit, Write, Bash (all write operations)

3. Auto-accept Mode

Auto-approves file reads and writes, but still requests confirmation for shell commands. Suitable for tasks requiring repetitive file modifications like large-scale refactoring.

# Run in auto-accept mode
claude --auto-accept-edits

4. Bypass Mode (Dangerous)

Skips all permission checks. Should only be used in isolated CI/CD environments. Never use in local development environments.

# CI/CD only -- never use locally
claude --dangerously-skip-permissions

Fine-Grained Permission Control with settings.json

You can define fine-grained permission rules per tool in ~/.claude/settings.json (global) or .claude/settings.json (project).

{
  "permissions": {
    "allow": [
      "Read",
      "Edit",
      "MultiEdit",
      "Write",
      "Glob",
      "Grep",
      "Bash(npm run lint)",
      "Bash(npm run test *)",
      "Bash(git status)",
      "Bash(git diff *)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(curl *)",
      "Bash(wget *)",
      "WebFetch(domain:internal.company.com)"
    ]
  }
}

The rule evaluation order is as follows.

  1. deny rules are checked first -- if matched, unconditionally blocked
  2. allow rules are checked -- if matched, auto-approved
  3. If matched by neither, user confirmation is requested (ask)

Project-Level Permission Inheritance

Project .claude/settings.json deny rules are merged with global rules, but allow rules cannot exceed global permissions. This prevents malicious project configurations from bypassing system security.

Sandboxing

Separate from permissions, OS-level sandboxing is applied. This physically restricts Bash tool's file system and network access.

  • macOS: Seatbelt-based sandbox
  • Linux: bubblewrap (bwrap)-based isolation
# Disable sandbox (only in trusted environments)
claude --dangerously-disable-sandbox

7. CLAUDE.md Usage

What is CLAUDE.md?

CLAUDE.md is a project memory file that conveys project context, coding conventions, build commands, and more to Claude Code. It is automatically loaded at the start of every session and directly impacts the quality of Claude's responses.

Memory System Structure

Claude Code provides two memory systems.

1. CLAUDE.md (Manual Memory)

A project context file directly written by developers. It supports a hierarchical structure.

~/.claude/CLAUDE.md                 -> Global (applied to all projects)
~/project/CLAUDE.md                 -> Project root
~/project/src/CLAUDE.md             -> Subdirectory
~/project/src/components/CLAUDE.md  -> More specific directory

All levels of CLAUDE.md are loaded simultaneously, and more specific levels take precedence in case of conflicts.

2. Auto Memory (Automatic Memory)

Memory that is automatically saved when you tell Claude to "remember this." Build commands, debugging insights, architecture notes, and workflow habits are automatically accumulated.

> Remember that this project always uses vitest for testing

Saved to memory.

CLAUDE.md Writing Best Practices

Effective CLAUDE.md Example

# Project Overview

Next.js 14 App Router-based tech blog. MDX-based content management.

# Tech Stack

- Framework: Next.js 14 (App Router)
- Language: TypeScript 5.3
- Styling: Tailwind CSS v3
- DB: Prisma + PostgreSQL
- Test: Vitest + React Testing Library

# Build and Run Commands

- `npm run dev` -- Development server
- `npm run build` -- Production build
- `npm run test` -- Run tests
- `npm run lint` -- Run ESLint

# Coding Conventions

- Use function components only (no class components)
- Prefer named exports (default exports only for pages)
- Always wrap error handling in try-catch
- Variable names in camelCase, type names in PascalCase
- Import order: react -> external libraries -> internal modules -> styles

# Architecture

- app/ -- Next.js App Router pages
- components/ -- Reusable components
- lib/ -- Utilities and helpers
- prisma/ -- DB schema and migrations

# Important Notes

- Always apply authentication middleware on API Routes
- Use Prisma's select to fetch only needed fields in DB queries
- Store environment variables only in .env.local (never commit)

Writing Principles

The principles recommended by Anthropic's official guide for writing CLAUDE.md are as follows.

  1. Keep it concise: 150 lines or fewer is recommended. Frontier LLMs can consistently follow approximately 150-200 instructions.
  2. Include only high-signal information: Exclude content that Claude can read from the code and reason about itself.
  3. Avoid code snippets: Code becomes outdated quickly. Use file:line references instead.
  4. Let linters do linting: Leave code style rules to tools like ESLint and Prettier. Enforcing style through LLMs is inefficient.
  5. Progressive disclosure: Do not put everything in the root CLAUDE.md; distribute across relevant directories.

8. MCP (Model Context Protocol) Server Integration

What is MCP?

Model Context Protocol (MCP) is an open-source standard protocol for AI models to interact with external tools, databases, and APIs. Claude Code can connect to various MCP servers as an MCP client to extend its capabilities.

How to Add MCP Servers

Adding via CLI Command

# Add HTTP remote server
claude mcp add circleback --transport http https://app.circleback.ai/api/mcp

# Add stdio local server
claude mcp add my-tool --type stdio --command node /path/to/tool.js

# Add with environment variables
claude mcp add github-mcp \
  --type stdio \
  --command npx \
  --args "-y @modelcontextprotocol/server-github" \
  --env GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxx

# Check server list
claude mcp list

# Remove server
claude mcp remove my-tool

Direct Configuration in settings.json

When complex configuration is needed, directly editing the settings file is more convenient.

{
  "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://user:pass@localhost:5432/mydb"
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/docs"]
    }
  }
}
MCP ServerFunctionUse Cases
server-githubGitHub API integrationIssues, PRs, repo management
server-postgresPostgreSQL accessDB schema analysis, query execution
server-filesystemFile system accessReading files outside project
server-puppeteerBrowser controlWeb scraping, E2E testing
server-slackSlack integrationMessage search, channel management
server-notionNotion integrationDocument search, note management
server-linearLinear integrationIssue tracking, project management

Using Claude Code as an MCP Server

Interestingly, Claude Code itself can be exposed as an MCP server. This allows other MCP clients like Claude Desktop, Cursor, and Windsurf to remotely invoke Claude Code's file editing and command execution capabilities.

# Run Claude Code as MCP server
claude mcp serve

MCP Tool Search enables lazy loading of MCP servers. It reduces context usage by up to 95%, allowing you to register many MCP servers without worrying about context limits.

# Diagnose issues with MCP debug mode
claude --mcp-debug

9. Multi-Agent Architecture

Task Tool: The Core of Parallel Processing

Claude Code's multi-agent system is based on the Task tool. The Task tool creates sub-agents with independent context windows to perform work in parallel.

Task Tool Characteristics

  • Independent Context: Each Task has a separate context window from the main conversation
  • Parallel Execution: Up to 10 simultaneous Tasks, queued when exceeded
  • Context Pollution Prevention: Only Task results are returned to the main conversation, so unnecessary intermediate steps do not pollute the main context
  • Additional Context: Effectively extends the context window in large codebases

Usage Example

> Write test code for the following 3 modules in parallel:
  1. src/auth/login.ts
  2. src/api/users.ts
  3. src/utils/validator.ts

Upon receiving this request, Claude simultaneously creates 3 Tasks that independently write test code.

Subagents: Specialized Agents

Subagents are persistent, specialized agents built on top of the Task tool. Defined via Markdown files, they have specialized system prompts, tool access permissions, and independent permission settings optimized for specific domains.

Subagent Definition

## <!-- .claude/agents/security-reviewer.md -->

name: Security Reviewer
description: An agent specialized in reviewing security vulnerabilities
tools:

- Read
- Grep
- Glob
- WebSearch

---

You are a security expert. When reviewing code, analyze from the following perspectives:

1. OWASP Top 10 vulnerabilities
2. Authentication/authorization flaws
3. Data leakage risks
4. Insecure dependencies

Include severity (Critical/High/Medium/Low) and fix suggestions for each finding.

Execution Flow

User request
    |
Main Claude (Orchestrator)
    |
+-------------+-------------+-------------+
| Task 1      | Task 2      | Task 3      |
| Security    | Performance | Test        |
| Reviewer    | Analyzer    | Generator   |
+-------------+-------------+-------------+
    |                |             |
Result collection and synthesis
    |
Final response

Parallel vs Sequential Patterns

Parallel Pattern

Used when processing independent tasks simultaneously.

Suitable scenarios:
- Test code generation for multiple files
- Code review of multiple modules
- Documentation of multiple API endpoints
- Multilingual translation

Sequential Pattern

Used when there are dependencies between tasks. The output of a previous Subagent becomes input for the next.

Suitable scenarios:
- Analysis -> Design -> Implementation -> Testing pipeline
- DB schema change -> Migration -> API modification -> Testing

Background Agents

Claude Code also supports asynchronous agent execution. You can send sub-agents to the background and continue with other tasks.

# Create a worktree for isolated environment work
claude --worktree feature-auth

10. IDE Integration

VS Code Integration

The VS Code extension is Claude Code's most polished IDE integration. It displays edits and diffs with native UI, allowing you to leverage all of Claude Code's features without using the terminal.

Key Features

  • Native Chat Panel: Integrated graphical interface within the IDE
  • Checkpoint-Based Undo: Ability to revert Claude's changes in groups
  • @Mention File References: Reference specific line ranges like @src/auth/login.ts:25-50
  • Parallel Conversations: Run multiple Claude conversations simultaneously in separate tabs
  • Diff Viewer: Review code changes proposed by Claude using the IDE's native diff view
  • Conversation History: Search and resume conversations from previous sessions

Installation and Setup

1. Install "Claude Code" from VS Code marketplace
2. Claude Code CLI must already be installed in the terminal
3. After installation, a Claude icon appears in the sidebar
4. Click to open the chat panel

Keyboard Shortcuts

Cmd+Shift+P (Mac) / Ctrl+Shift+P (Windows)
  -> Type "Claude Code" to see available commands

Key shortcuts:
- Open/close Claude Code panel
- Send selection to Claude
- Start Claude with current file context

JetBrains Integration

The Claude Code plugin is also available for JetBrains IDEs (IntelliJ, WebStorm, PyCharm, etc.).

Installation

1. Search for "Claude Code [Beta]" in JetBrains Marketplace
2. Click Install
3. Restart IDE

Features

  • Runs the CLI within the IDE's integrated terminal
  • Displays code changes in the IDE's native diff viewer
  • Shares ~/.claude/settings.json settings with VS Code

Comparison with Cursor: What's Different?

Claude Code and Cursor are both AI coding tools but take different approaches.

ItemClaude CodeCursor
FormCLI + IDE ExtensionIndependent IDE (VS Code fork)
EnvironmentsTerminal, SSH, Docker, CI/CD anywhereWithin Cursor IDE only
ModelsClaude only (Sonnet/Opus/Haiku)Multi-model (Claude, GPT-4o, o3, etc.)
PricingConsumption-based (per token) or Pro/Max subscriptionMonthly flat rate ($20/40)
StrengthsTerminal integration, automation, CI/CD, MCPCodebase indexing, inline editing
AgentsTask tool, Subagent, 10 parallelComposer Agent Mode
CustomizationCLAUDE.md, hooks, MCP, custom commands.cursorrules, custom models

Claude Code is advantageous for: Terminal-centric workflows, CI/CD automation, remote server work, large-scale refactoring, MCP ecosystem usage

Cursor is advantageous for: GUI-centric development, inline code completion, flexible multi-model switching, Tab-completion speed


11. Custom Hooks

What Are Hooks?

Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They operate deterministically without relying on the LLM.

Event Types

Claude Code can execute hooks at the following events.

EventTimingUse Cases
PreToolUseBefore tool executionBlock dangerous operations, input validation
PostToolUseAfter tool executionCode formatting, linting, test execution
NotificationWhen Claude sends a notificationSlack notifications, sound playback
StopOn response completionLog recording, cleanup tasks

Hook Configuration Methods

Method 1: /hooks Command (Interactive)

/hooks
-> Select event (e.g., PostToolUse)
-> Matcher pattern (e.g., Edit|Write)
-> Command (e.g., npx prettier --write $FILE)

Method 2: Direct settings.json Editing

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx prettier --write $(echo $TOOL_INPUT | jq -r '.file_path')"
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "echo $TOOL_INPUT | jq -r '.command' | grep -q 'rm -rf /' && exit 1 || exit 0"
      }
    ]
  }
}

Hook Communication Protocol

Hooks communicate with Claude Code through stdin, stdout, stderr, and exit code.

stdin:     Event-specific JSON data (file paths, tool input, etc.)
stdout:    Messages to pass to Claude
stderr:    Logging (not passed to Claude)
exit code: 0 = success/continue, 1 = block/abort, 2 = error

Practical Hook Examples

Automatic Code Formatting (PostToolUse)

Automatically runs Prettier whenever Claude modifies a file.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "FILE=$(echo $TOOL_INPUT | jq -r '.file_path') && npx prettier --write \"$FILE\" 2>/dev/null || true"
      }
    ]
  }
}

Blocking Dangerous Commands (PreToolUse)

Pre-blocks dangerous commands like rm -rf /, DROP TABLE.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "CMD=$(echo $TOOL_INPUT | jq -r '.command') && echo \"$CMD\" | grep -qE '(rm -rf /|DROP TABLE|format c:)' && echo 'BLOCKED: Dangerous command detected' && exit 1 || exit 0"
      }
    ]
  }
}

Automatic Lint Checking (PostToolUse)

Automatically runs ESLint after file modifications.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "FILE=$(echo $TOOL_INPUT | jq -r '.file_path') && [[ \"$FILE\" =~ \\.(ts|tsx|js|jsx)$ ]] && npx eslint --fix \"$FILE\" 2>/dev/null || true"
      }
    ]
  }
}

12. Git Integration

Commit Workflow

Claude Code's Git integration goes beyond simply executing git commands -- it analyzes changes and automatically generates meaningful commit messages.

Basic Commit

> Commit the current changes

Claude goes through the following process.

  1. Check changed files with git status
  2. Analyze change content with git diff
  3. Identify existing commit message style with git log
  4. Analyze change content and write commit message
  5. Selectively git add only related files
  6. Create commit and verify result

Selective Staging

> Commit only the changes in the auth/ directory
> Commit excluding test files
> Separate security-related changes into a separate commit

Commit Best Practices

Claude Code follows these principles.

  • Automatically excludes sensitive files (.env, credentials, etc.)
  • Explicitly stages individual files instead of git add -A
  • Respects pre-commit hooks (no --no-verify usage)
  • References existing commit message style for consistency
  • Defaults to creating new commits instead of --amend

PR Creation

> Create a PR with the current changes

Claude uses gh pr create to perform the following.

  1. Analyze all commits on the branch (not just the latest, but ALL commits)
  2. Write PR title (within 70 characters)
  3. Write PR body including summary, change list, and test checklist
  4. Push to remote branch
  5. Create PR and return URL

PR Body Format

## Summary

- Added JWT refresh token logic to the authentication module
- Implemented automatic renewal when token expires

## Test plan

- [ ] Refresh token issuance test
- [ ] Expired token renewal test
- [ ] Invalid refresh token rejection test

Code Review

> Review the current changes
> Perform a security-focused review of this PR

Claude analyzes the diff and reviews the following.

  • Potential bugs and logical errors
  • Security vulnerabilities
  • Performance issues
  • Coding convention compliance
  • Test coverage

A confidence score (0-100) is assigned to each finding, with 80 or above indicating a high probability of being an actual issue.

GitHub Actions Integration

Claude Code can perform automated code reviews in GitHub Actions through claude-code-action.

# .github/workflows/claude-review.yml
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]
  issue_comment:
    types: [created]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          # Auto-respond when @claude is mentioned in PR comments
          trigger_phrase: '@claude'

Simplified Installation

# Auto-install GitHub App from within Claude Code
/install-github-app

This command guides you through GitHub App setup, secret registration, and workflow file creation.


13. Advanced Usage Patterns

13.1 Large-Scale Refactoring

Large-scale refactoring is one of the use cases where Claude Code truly shines.

Strategy: Incremental Approach

Step 1: Analysis
> Find all files using class components in this project

Step 2: Planning
> Create a plan to convert these components to function components.
  Include conversion order, dependencies, and risk factors.

Step 3: Execution (Auto-accept mode recommended)
> Start the conversion beginning with src/components/Header.tsx

Step 4: Verification
> Run the tests for converted files and report the results

Parallel Refactoring with Subagents

Refactoring independent modules in parallel can significantly reduce work time.

> Refactor the following 3 modules in parallel:
  1. src/auth/ -- class -> function component
  2. src/api/ -- callback -> async/await
  3. src/utils/ -- CommonJS -> ES Module
  Also update the tests for each.

13.2 Automatic Test Code Generation

Basic Test Generation

> Write unit tests for all functions in src/utils/validator.ts.
  Include edge cases and error cases.

Specifying Test Strategy

> Write integration tests for src/api/users.ts.
  - Use Vitest + Supertest
  - Test DB is SQLite in-memory
  - Initialize DB before and after each test
  - Test both authenticated/unauthenticated cases
  - Also verify error response format

Coverage Improvement

> Analyze the npm run test -- --coverage results and
  supplement tests for files with less than 80% coverage.

13.3 Debugging Workflow

Error Log Analysis

# Pipe error log directly
npm run build 2>&1 | claude -p "Analyze this build error and fix it"

# Stack trace analysis
cat crash.log | claude -p "Find the root cause of this crash"

Interactive Debugging

> TypeError: Cannot read properties of undefined (reading 'map')
  This error occurs in src/components/UserList.tsx.
  Find the cause and fix it.

Claude performs the following process.

  1. Read the file and analyze the code
  2. Trace related data flow (parent components, API calls, etc.)
  3. Identify conditions where undefined occurs
  4. Suggest and apply fix code
  5. Search for other potential bugs with the same pattern

Performance Profiling

> This API endpoint has a response time of over 3 seconds.
  Analyze the code and suggest performance improvements.
  Focus on N+1 queries, unnecessary loops, and caching opportunities.

13.4 Documentation Automation

JSDoc / TSDoc Generation

> Write JSDoc for all public functions in the src/lib/ directory.
  Include parameter types, return values, and examples.

API Documentation

> Document all REST endpoints in the src/api/ directory
  in OpenAPI 3.0 spec.

Changelog Generation

> Analyze the last 10 commits and write CHANGELOG entries.
  Use the Keep a Changelog format.

14. Claude Code vs Competing Tools Comparison

The AI coding tool market is approximately $34.58B in size as of 2026, with 62% of professional developers using AI coding tools. Here are comparisons of the major tools.

Detailed Comparison Table

ItemClaude CodeGitHub CopilotCursorWindsurfOpenAI Codex
FormCLI + ExtensionIDE ExtensionIndependent IDEIndependent IDECloud Agent
ModelsClaude onlyMulti-modelMulti-modelMulti-modelGPT/Codex only
AgentsTask/SubagentCopilot AgentComposer AgentCascade/FlowsCloud Sandbox
ParallelUp to 10Multi-agentSingle AgentSingle AgentIsolated containers
Pricing20Pro/20 Pro / 100 Max$10-39/mo$20-40/mo$15/mo+API-based
SWE-bench57.5% (best)---77.3% (Terminal)
StrengthsTerminal integration, MCPEcosystem, 4.7M usersCode indexing, UIFlows context retentionIsolated sandbox
GitHub Share4% of commitsLargest---

Ideal Usage Scenarios for Each Tool

When to Choose Claude Code

  • Working with terminal-centric workflows
  • Integrating AI into CI/CD pipelines
  • Needing external tool integration via MCP
  • Frequent large-scale refactoring or multi-file work
  • Working on SSH remote servers or Docker containers

When to Choose GitHub Copilot

  • Working primarily within the GitHub ecosystem
  • When the entire team needs to use the same tool
  • Wanting to start at free or low cost
  • Focusing on inline completion in VS Code

When to Choose Cursor

  • Preferring GUI-based development
  • When codebase indexing and semantic search are important
  • Wanting to flexibly switch between multiple AI models
  • When inline editing and Tab completion speed are important

Practical Combination Recommendation

Many developers combine multiple tools depending on the situation.

Daily coding:         Cursor (inline completion) + Claude Code (complex tasks)
Code review:          Claude Code (GitHub Actions auto-review)
Refactoring:          Claude Code (large-scale terminal work)
Quick prototyping:    Cursor (quick iteration via GUI)
CI/CD automation:     Claude Code (headless mode)

15. Cost Optimization Tips

Understanding the Fee Structure

Claude Code costs vary depending on the plan you use.

Subscription Plans

PlanMonthly FeeClaude Code IncludedFeatures
Free$0Not includedCannot use Claude Code
Pro$20Included (usage limit)Suitable for general users
Max 5x$100Included (5x Pro)Suitable for intermediate users
Max 20x$200Included (20x Pro)Suitable for power users

Direct API Usage (Console)

ModelInput (1M tokens)Output (1M tokens)Cache ReadCache Write
Opus$15$75$1.50$18.75
Sonnet$3$15$0.30$3.75
Haiku$0.80$4$0.08$1.00

According to Anthropic, the average is approximately 6perdeveloperperday,with906 per developer per day, with 90% of users under 12 per day.

Cost Saving Strategies

1. Appropriate Model Selection

Simple tasks (file search, simple edits):    Haiku  -> 75% cost savings
General tasks (coding, debugging):           Sonnet -> Default
Complex tasks (architecture, refactoring):   Opus   -> Only when needed

2. Active Use of /compact

# Check session cost
/cost

# Compress conversation
/compact

# Check cost after compression -- typically 40-60% token savings
/cost

3. Leverage Prompt Caching

Claude Code automatically applies prompt caching. Repeated system prompts and CLAUDE.md content are cached for cost reduction. Cache read cost is only 10% of the input cost.

4. Leverage Auto-Compaction

When the context limit is reached, conversations are automatically summarized. Trust this, but start a new session with /clear during major topic changes to ensure important context is not lost.

5. Write Specific Prompts

Specific requests reduce unnecessary exploration and save tokens compared to vague requests.

Bad: "Improve this code"
Good: "Optimize the N+1 query in the getUserById function in src/api/users.ts using Prisma include"

6. Plan Selection Guide

Under 50M tokens/month:     Pro ($20) or API pay-as-you-go
50-200M tokens/month:       Max 5x ($100) -- most efficient
Over 200M tokens/month:     Max 20x ($200) or Enterprise

16. Troubleshooting Guide

Common Issues and Solutions

Issue 1: "command not found: claude"

The most common issue after installation.

# Check PATH
which claude

# Check npm global path
npm list -g --depth=0

# Reinstall
npm install -g @anthropic-ai/claude-code

# Native reinstall
curl -fsSL https://claude.ai/install.sh | bash

# Restart shell
exec zsh  # or exec bash

Issue 2: Authentication Error

# Logout and re-authenticate
claude auth logout
claude auth login

# When using API key, check environment variable
echo $ANTHROPIC_API_KEY

# API key validity test
claude "Hello" --verbose

Issue 3: Node.js Version Compatibility

# Check Node.js version
node --version

# If below v18, update
nvm install 18
nvm use 18

# Or switch to native installation (no Node.js dependency)
curl -fsSL https://claude.ai/install.sh | bash

Issue 4: MCP Server Connection Failure

# Diagnose with MCP debug mode
claude --mcp-debug

# Check MCP server list
claude mcp list

# Check specific server logs
claude mcp logs my-server

# Restart server
claude mcp remove my-server
claude mcp add my-server --type stdio --command node /path/to/server.js

Issue 5: Context Window Exceeded

# Symptom: Response quality degradation, forgetting previous context

# Solution 1: Compress conversation
/compact

# Solution 2: Start new session
/clear

# Solution 3: Split work with Task tool (each Task has independent context)
> Split this task into 3 sub-tasks and process them

Issue 6: Slow Response Speed

# Change model (Opus -> Sonnet -> Haiku)
/model

# Remove unnecessary MCP servers
claude mcp list
claude mcp remove unused-server

# Clear cache
claude cache clear

Diagnostic Checklist

When issues occur, diagnose in the following order.

# 1. Check installation status
claude --version

# 2. Automatic environment diagnostics
claude doctor

# 3. Verbose log output
claude --verbose "test"

# 4. MCP server diagnostics
claude --mcp-debug

# 5. Check settings file
cat ~/.claude/settings.json

# 6. Network check
curl -I https://api.anthropic.com

17. Claude Agent SDK: Programmatic Usage

To use Claude Code's capabilities programmatically, use the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).

Installation and Basic Usage

npm install @anthropic-ai/claude-agent-sdk
import { query } from '@anthropic-ai/claude-agent-sdk'

// Basic query
const response = await query({
  prompt: 'Analyze security vulnerabilities in the src/auth directory',
  model: 'claude-sonnet-4-6',
  maxTokens: 4096,
})

for await (const message of response) {
  console.log(message)
}

Key APIs

APIDescription
query()Streaming prompt execution
tool()Custom tool definition (Zod schema-based)
createSdkMcpServer()In-process MCP server creation

CI/CD Pipeline Example

import { query } from '@anthropic-ai/claude-agent-sdk'

async function reviewPR(diff: string): Promise<string> {
  const response = await query({
    prompt: `Review the following PR diff:\n${diff}`,
    model: 'claude-sonnet-4-6',
    systemPrompt:
      'You are a senior software engineer. Review from security, performance, and code quality perspectives.',
    permissions: { allowRead: true, allowWrite: false, allowBash: false },
  })

  let result = ''
  for await (const message of response) {
    result += message.content
  }
  return result
}

18. References

Official Documentation

GitHub

npm

API and Pricing

Community