Claude Code
Workshop

Agentic Coding for Modern Engineers

Engineering Team Training

What is Claude Code?

Understanding agentic coding and how it transforms the way we build software.

Claude Code: Your AI Pair Programmer

A command-line tool that brings agentic AI directly into your terminal

Agentic Coding

Unlike traditional autocomplete, Claude Code can autonomously navigate your codebase, edit multiple files, run commands, and execute complex multi-step tasks.

Terminal-Native Experience

Works directly in your terminal where you already live. No context switching, no browser tabs—just you and your code.

Full Codebase Understanding

Claude Code reads and understands your entire project structure, dependencies, and coding patterns to provide contextual assistance.

Agentic vs Traditional AI Coding

Traditional AI Assistants: You ask a question, get a response, copy-paste code, manually apply changes, and repeat.

Agentic Coding: You describe a goal, and the AI autonomously explores files, makes edits, runs tests, and iterates until the task is complete.

Claude Code can create branches, commit changes, run your test suite, and even debug failing tests—all from a single prompt.

# Traditional approach
"How do I add auth to my app?"
# Copy response, paste, debug...

# Agentic approach
claude
"Add JWT authentication to my Express API with refresh tokens"

# Claude Code: reads codebase,
# creates files, installs deps,
# updates routes, runs tests ✓

Anthropic's LLM Family

Understanding the models that power Claude Code and when to use each one.

The Claude 4.5 Model Family

Choose the right model for your use case

Balanced

Claude Sonnet 4.5

Excellent balance of speed and capability. Great for everyday coding tasks and Claude Code default.

claude-sonnet-4-5-20250929
Fastest

Claude Haiku 4.5

Lightning fast responses for simple tasks. Ideal for quick lookups and simple generations.

claude-haiku-4-5-20251001

Installing Claude Code

Get up and running on macOS with Homebrew in minutes.

macOS Installation with Homebrew

Claude Code is available as a Homebrew cask, making installation simple and fast.

Prerequisites:

• Homebrew package manager
• Anthropic API key or Claude Pro/Max subscription

# Install Claude Code with Homebrew
brew install --cask claude-code

# Navigate to your project
cd your-project

# Start Claude Code
claude

# First run will prompt for auth

IDE Integration

Bring Claude Code capabilities directly into your favorite editor.

Editor Extensions & Plugins

Seamless integration with your development environment

VS Code

Official Claude extension with inline suggestions, chat panel, and full Claude Code integration.

Zed

Native Claude integration built into Zed. Enable via Settings → AI → Claude.

JetBrains IDEs

Works with IntelliJ, PyCharm, WebStorm. Install via JetBrains Marketplace.

>

Terminal

Works in any terminal—iTerm2, Warp, Alacritty, or your preferred app.

Claude Code Sub-Agents

Specialized AI assistants for complex workflows and parallel task execution.

What are Sub-Agents?

Specialized AI assistants with independent context and focused capabilities

Separate Context Windows

Each sub-agent maintains its own conversation context, preventing context pollution in your main Claude session while handling specialized tasks.

Custom System Prompts

Define specific roles, expertise areas, and workflows. Sub-agents can be code reviewers, debuggers, web search specialists, or domain experts.

Configurable Tool Access

Granular control over which tools each agent can use. Security agents get read-only access, while developer agents get full file editing capabilities.

Built-in Sub-Agents

Explore: Fast, read-only codebase search and analysis using Haiku model for speed. Perfect for quick lookups.

Plan: Research-focused agent using Sonnet model for gathering codebase context and creating implementation plans.

General-Purpose: Handles complex multi-step tasks with access to all available tools and the Sonnet model.

# Claude automatically delegates
# to appropriate sub-agents

"Where are errors handled?"
# → Explore agent

"Plan authentication system"
# → Plan agent

"Implement JWT with tests"
# → General-purpose agent

Available Tools for Agents

When creating custom sub-agents, you can select which tools they have access to. This provides granular control over agent capabilities.

File Operations:

Read: Read file contents
Write: Create new files
Edit: Modify existing files
Glob: Pattern-based file search

Code Operations:

Grep: Search code with regex
Bash: Execute shell commands

Advanced Tools:

WebSearch: Search the web for current information
WebFetch: Fetch and analyze web content
Task: Launch other sub-agents

---
name: security-auditor
description: Security review
tools:
  - Read
  - Grep
  - Glob
model: sonnet
---

# Read-only access
# No Write or Edit tools

Creating Custom Sub-Agents

Use the /agents command for guided setup

Step 1: Launch /agents Command

In Claude Code, type /agents to open the interactive menu. Choose "Create new agent" to start the setup wizard.

Step 2: Configure Agent Properties

Define the agent name (e.g., "web-search-specialist"), description (when Claude should use it), select which tools the agent can access (Read, Write, Edit, Bash, etc.), and optionally specify the AI model to use.

Step 3: Write System Prompt

Create the agent's behavior in .claude/agents/agent-name.md with YAML frontmatter and custom instructions.

Step 4: Test & Iterate

Claude will automatically use your custom agent based on its description. Refine the prompt and tool access as needed.

Example: Web Search Specialist

A real sub-agent from this workshop repository that handles internet research and fact-checking.

File: .claude/agents/web-search-specialist.md

Purpose: Retrieve current information, verify facts, and find documentation.

---
name: web-search-specialist
description: Use when you need
  current info from the internet
tools: Read, WebFetch, WebSearch
model: sonnet
---

You are an elite Web Search
Specialist for rapid info
retrieval from the internet.

# Core Responsibilities
1. Rapid Search Execution
2. Intelligent Query Formulation
3. Source Quality Assessment

Why Use Sub-Agents?

Unlock parallel processing, specialization, and cleaner workflows

Parallel Processing

Multiple agents can work on different files simultaneously. One agent reviews code while another writes tests.

Context Clarity

Each agent maintains focused conversations. No muddled context from unrelated tasks polluting your main session.

Specialization

Domain-specific expertise with optimized prompts. Higher success rates for specialized tasks like security audits or SEO.

Reusability

Build once, use everywhere. Share agents across projects via ~/.claude/agents/ or commit to repos for team collaboration.

Custom Commands

Automate workflows with slash commands and intelligent orchestration.

Built-in Slash Commands

Essential commands available out of the box

/help • /status • /config

Get help, check system status, and manage settings

/model • /context • /cost

Switch AI models, visualize context usage, track token costs

/review • /security-review

Request code reviews and comprehensive security audits

/agents • /todos • /memory

Manage sub-agents, track tasks, edit project memory files

Creating Custom Commands

Project-level: .claude/commands/ — Shared via git with your team

User-level: ~/.claude/commands/ — Personal across all projects

Filename becomes command name: deploy.md → /deploy

---
description: Deploy to production
argument-hint: [environment]
allowed-tools: Bash(git:*),
  Bash(npm:*)
model: sonnet
---

Deploy to $ARGUMENTS environment:

1. Run tests: !`npm test`
2. Build: !`npm run build`
3. Deploy with verification
4. Update deployment docs

Arguments & Advanced Features

Dynamic commands with context injection

$ARGUMENTS Variable

Access all arguments as a single string: /fix-issue 123 → $ARGUMENTS = "123"

Positional Arguments

Individual access like shell scripts: /review-pr 42 high → $1=42, $2=high

Inline Bash with !`command`

Execute bash commands and inject output into context: !`git status`

File References with @

Reference files directly: @src/utils/helpers.js for auto-completion and inclusion

Orchestrating Sub-Agents

Commands can invoke sub-agents for specialized tasks, creating powerful multi-agent workflows.

Automatic: Claude delegates based on agent descriptions

Explicit: "Use the code-reviewer sub-agent"

---
description: Full code review
---

Execute review workflow:

1. Use code-analyzer to
   find issues

2. Use optimizer to fix
   performance problems

3. Use security-auditor
   for vulnerability scan

4. Generate final report

Workflow Patterns

Chain commands and sub-agents for complex automation

TDD Cycle

Orchestrate test-writer → implementer → refactoring specialist for test-driven development

Feature Pipeline

Backend architect → Database designer → Frontend developer → Test automator → Deploy

Smart Fix

Analyze issue type dynamically and route to appropriate specialist agent for resolution

Security Audit

Dependency scanner → Code reviewer → Secret detector → Vulnerability report generator

Project Memory & CLAUDE.md

Give Claude persistent context about your codebase, conventions, and workflows.

What is CLAUDE.md?

A markdown file that becomes part of Claude's system prompt, providing persistent context about your project.

Hierarchical Loading:

User-level: ~/.claude/CLAUDE.md
Project-level: ./CLAUDE.md
Subdirectory: ./subdir/CLAUDE.md

Claude automatically loads all applicable files, with more specific contexts taking precedence.

Always Available

Context persists across all chat sessions, no need to repeat yourself

Team Alignment

Share coding conventions, architecture patterns, and team standards automatically

Improved Accuracy

Studies show 5-10% accuracy improvement with well-crafted project memory

The /init Command

Claude can automatically analyze your codebase and generate a starter CLAUDE.md file for you.

# In your project directory
claude /init

# Claude will analyze:
• Project structure
• Languages & frameworks
• Existing conventions
• Common patterns

# Then generate CLAUDE.md

What Gets Generated:

Tech Stack Overview

Languages, frameworks, and key dependencies

Project Structure

Directory layout and file organization

Common Patterns

Detected coding conventions and architectural patterns

Development Commands

Build, test, run scripts from package.json or Makefile

What to Include in CLAUDE.md

Customize your memory file with information that helps Claude work better with your specific codebase.

Code Style Guidelines

Formatting rules, naming conventions, preferred patterns

Architecture Decisions

Component patterns, state management, API design

Common Commands

Development workflows, test runners, deployment

Team Preferences

Testing approach, documentation style, review process

## Code Style

Use functional components
with TypeScript strict mode.

// Prefer
export const Button = () => {}

// Avoid
class Button extends React

## Testing

• Use Vitest for unit tests
• Playwright for E2E
• Aim for 80% coverage

## Commands

npm run dev - Start dev
npm test - Run tests
npm run build - Production

Example: Phoenix Projects

Phoenix (Elixir) projects auto-generate an AGENT.md file with helpful context.

Key Sections:

• Framework-specific patterns (LiveView, Contexts)
• Directory structure conventions
• Database migration workflow
• Testing best practices
• Common Mix commands

## Elixir guidelines

Lists do not support index access

# INVALID
i = 0
mylist = ["blue", "green"]
mylist[i]

# VALID - use Enum.at
Enum.at(mylist, i)

# Variables are immutable
# Bind expression results

# INVALID: rebind inside
if connected?(socket) do
  socket = assign(socket, :val, val)
end

# VALID: bind result
socket = if connected?(socket) do
  assign(socket, :val, val)
end

CLAUDE.md Best Practices

Tips for creating effective project memory files

Be Specific

Include concrete examples of preferred patterns, not just general guidelines

Keep It Current

Update memory files when conventions change or new patterns are adopted

Layer Appropriately

User-level for personal preferences, project-level for team standards

Include Examples

Show preferred vs. avoided patterns with code snippets for clarity

Document Gotchas

Note project-specific quirks, workarounds, or common pitfalls to avoid

Link to Docs

Reference external documentation, ADRs, or wiki pages for deeper context

Claude Code Hooks

Automate workflows with deterministic control over Claude's behavior.

What Are Hooks?

Hooks are shell commands or LLM prompts that execute automatically at specific points in Claude Code's lifecycle.

Why Use Hooks?

Deterministic Control

Guarantee behavior without relying on AI memory or prompts

Workflow Automation

Auto-format code, run tests, enforce policies automatically

Tool Integration

Connect Claude to linters, formatters, CI/CD pipelines

Security & Compliance

Block dangerous operations, validate inputs, audit actions

# .claude/settings.json
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "prettier --write"
      }]
    }]
  }
}

Available Hook Triggers

10 event types covering the entire Claude Code lifecycle

PreToolUse

Before tool execution - validate inputs, block operations

PostToolUse

After tool completes - format code, run tests, log actions

PermissionRequest

On permission dialogs - auto-approve/deny based on policy

UserPromptSubmit

Before prompt processing - add context, validate requests

Notification

On notifications - customize delivery, send to external systems

SessionStart

Session begins - load context, initialize environment

SessionEnd

Session terminates - cleanup, archive artifacts, logging

Stop

Agent finishes - quality gates, force continuation

SubagentStop

Subagent completes - control multi-agent workflows

PreCompact

Before history compaction - preserve critical context

Example: Auto-Format JS/TS

Automatically format JavaScript and TypeScript files after editing with Prettier.

Configuration:

1. Hook triggers on PostToolUse
2. Matches Edit|Write tools
3. Reads file path from stdin JSON
4. Runs Prettier on matching files
5. Silent failure (|| true) won't block Claude

# .claude/settings.json
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "jq -r '.tool_input.file_path // empty' | while read f; do [[ \"$f\" =~ \\.(js|jsx|ts|tsx)$ ]] && npx prettier --write \"$f\" 2>/dev/null || true; done"
      }]
    }]
  }
}

# Alternative: use script
"command": "~/.claude/hooks/format.sh"

Creating Hooks

Method 1: /hooks Command

1. Type /hooks in Claude Code
2. Select event type (PostToolUse, etc.)
3. Add matcher pattern (Edit|Write)
4. Enter command or script path
5. Choose global or project scope

Method 2: Manual Setup

# Create directories
mkdir -p .claude/hooks

# Create script
touch .claude/hooks/my-hook.sh
chmod +x .claude/hooks/my-hook.sh

# Edit settings.json
vim .claude/settings.json

File Structure:

project/
├── .claude/
│   ├── settings.json
│   ├── settings.local.json
│   └── hooks/
│       ├── format.sh
│       └── lint.sh
└── .gitignore

Hook Script Template:

#!/usr/bin/env bash
set -euo pipefail

# Parse stdin JSON
input=$(cat)
file=$(echo "$input" | jq -r '.tool_input.file_path // empty')

# Your logic
[[ -n "$file" ]] && prettier --write "$file"

exit 0

Hook Best Practices

Security, reliability, and performance guidelines

Parse stdin as JSON

Use cat | jq -r '.tool_input.file_path' instead of environment variables (they're unreliable)

Silent failures for formatters

Use || true and 2>/dev/null to prevent hooks from blocking Claude on errors

Validate inputs

Check for path traversal (../), sensitive files (.env), dangerous patterns

Quote variables

Always use "$file_path" not $file_path to prevent shell injection

Exit code 0 = success

Exit 0 to continue, exit 2 to block with error message in stderr

Use Ctrl+O for debugging

Enable verbose mode to see hook execution logs and errors

Model Context Protocol

Connect Claude Code to external tools, data sources, and where your data lives.

MCP Architecture

MCP uses a client-server architecture with three key components.

Host (Claude Code)

The AI application you interact with. Manages multiple clients and provides the user interface.

MCP Client

Connector that communicates with one MCP server. Provides isolation and security.

MCP Server

Provides tools, resources, and prompts. Examples: GitHub, Filesystem, PostgreSQL.

┌────────────────────────┐
│ HOST (Claude Code) │
│ │
│ ┌────────┐ ┌────────┐│
│ │Client 1│ │Client 2││
│ └───┬────┘ └───┬────┘│
└──────┼──────────┼──────┘
       │ │
    JSON-RPC JSON-RPC
       │ │
   ┌───▼───┐ ┌───▼───┐
   │Server │ │Server │
   │GitHub │ │ DB │
   └───────┘ └───────┘

Communication:
• JSON-RPC 2.0 protocol
• STDIO or HTTP transport
• One client per server
• Host manages all connections

Adding MCP Servers

Method 1: CLI (Recommended)

# HTTP servers (remote)
claude mcp add --transport http \\
  github https://mcp.github.com

# STDIO servers (local)
claude mcp add filesystem -- \\
  npx @modelcontextprotocol/\\
  server-filesystem /path/to/dir

After adding:
1. Restart Claude Code
2. Verify with claude mcp list
3. Check status with /mcp

Method 2: Config File

# Location (macOS):
~/Library/Application Support/\\
Claude/claude_desktop_config.json

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/\\
        server-github"
      ],
      "env": {
        "GITHUB_TOKEN": "xxx"
      }
    }
  }
}

Managing MCP Servers

Use the /mcp command to enable/disable servers during your session.

# In Claude Code, type:
/mcp

# Interactive menu shows:
✓ github (enabled)
✓ filesystem (enabled)
○ postgres (disabled)
○ slack (disabled)

# Click to toggle on/off
# No restart needed!

Why Disable Servers?

Save Tokens

Each server consumes context window space even when not used

Improve Performance

Fewer active servers = faster startup and response times

Task Focus

Enable only servers relevant to your current work

Token Usage Impact

The Problem: MCP servers consume tokens from your 200k context window.

• 20 servers = 66,000+ tokens
• Single server = 14,000 tokens
• Loaded even if not used
• Less room for actual work

Solution: Use /context to monitor usage.

# Type in Claude Code:
/context

# Shows detailed breakdown

Example /context Output:

Context Usage Summary
════════════════════════════

Total: 45,231 / 200,000 (22.6%)

Breakdown:
├─ Built-in Tools: 8,450 (4.2%)
├─ MCP Servers: 18,720 (9.4%)
│  ├─ github: 6,234
│  ├─ linear: 14,214
│  └─ filesystem: 2,272
├─ Conversation: 12,580 (6.3%)
├─ Memory Files: 3,481 (1.7%)
└─ Workspace: 2,000 (1.0%)

⚠️ Linear using 7% of context!

Tip: Disable high-usage servers with /mcp

Popular MCP Servers

Common servers to extend Claude Code capabilities

Filesystem

Read/write files, manage directories, search project files

GitHub

Manage issues, PRs, repositories, search code, CI/CD automation

Git

Commit history, branches, staging, repository analysis

PostgreSQL

Database queries, schema inspection, data manipulation

Memory

Knowledge graph-based persistent memory across sessions

Brave Search

Privacy-focused web and local search for research

Slack

Send messages, read channels, team communication automation

Puppeteer

Browser automation, screenshots, web scraping, testing

Claude Code Skills

Modular instruction packages that activate automatically to enhance Claude's capabilities.

What Are Skills?

Specialized instruction packages that expand Claude's capabilities

Progressive Disclosure

Skills inject ~400 tokens of context only when needed. Claude autonomously detects when a skill is relevant and activates it automatically.

Folder-Based System

Each skill lives in ~/.claude/skills/<name>/ with a SKILL.md file containing YAML frontmatter and markdown instructions.

Solves "Distributional Convergence"

Without skills, AI-generated designs converge to similar patterns. Skills provide domain expertise to create distinctive, production-grade outputs.

The Design Skill

Transforms generic AI interfaces into distinctive, production-grade designs through four key vectors.

Typography:

Dynamic font pairing, hierarchy, responsive sizing

Color & Theme:

Sophisticated palettes, semantic color systems, dark mode

Motion:

Purposeful animations, micro-interactions, transitions

Backgrounds:

Gradients, textures, depth, visual interest

---
name: design
description: Frontend design
---

# Applied automatically when
# Claude detects UI/design work

Before Design Skill:
• Generic blue buttons
• System fonts (Arial, sans-serif)
• Flat white backgrounds
• No animations or transitions

After Design Skill:
• Custom color palettes
• Professional font pairings
• Depth with gradients/shadows
• Smooth micro-interactions
• Production-ready aesthetics

Installing & Using Skills

Skills are automatically activated when Claude detects relevant context. No explicit invocation needed.

Installation: Use the claude skill install command to add skills from the official registry or custom sources.

Automatic Activation: Claude analyzes your request and codebase, then activates relevant skills autonomously.

# Install a skill
claude skill install design

# List installed skills
claude skill list

# Skills activate automatically
claude
"Build a landing page for our SaaS product"

# Design skill activates ✓
# Creates production-grade UI

Available Skills

Official skills for common development and productivity tasks

design

Frontend design expertise - typography, color, motion, backgrounds

xlsx

Excel spreadsheet manipulation and data analysis

pptx

PowerPoint presentation creation and formatting

docx

Word document generation and editing

pdf

PDF parsing, extraction, and manipulation

brand-guidelines

Enforce brand consistency across outputs

Creating Custom Skills

Build team-specific skills for your frameworks, conventions, and workflows.

Structure: Each skill is a folder with a SKILL.md file containing YAML frontmatter and instructions.

Best Practices:
• Keep skills focused on one domain
• Include concrete examples
• ~400 tokens max for efficiency
• Test with representative tasks

# ~/.claude/skills/react-patterns/SKILL.md

---
name: react-patterns
description: Team React conventions
---

# React Best Practices

## Component Structure
- Use functional components
- Custom hooks in hooks/ folder
- Zustand for global state

## Naming Conventions
- PascalCase for components
- camelCase for functions
- useX for custom hooks

# Activated when editing .tsx/.jsx

Git Worktrees for Parallel Development

Multiply your productivity by running multiple Claude Code instances simultaneously.

What are Git Worktrees?

Multiple working directories from a single repository

Multiple Branches, No Switching

Git worktrees allow you to check out multiple branches simultaneously in different directories. No more git stash or git checkout when switching tasks.

Shared Repository, Isolated Files

All worktrees share the same Git repository objects (saving disk space), but each has its own independent working directory with different file states.

Perfect for AI Agents

Run multiple Claude Code instances in parallel—each working on a different feature in its own isolated worktree without interfering with each other.

Essential Git Worktree Commands

Master these commands to manage multiple parallel development streams efficiently.

Each worktree is a separate directory with its own checked-out branch. Perfect for having Claude Code work on multiple features simultaneously.

# Create a new worktree
git worktree add ../feature-auth feature-auth

# Create worktree with new branch
git worktree add -b new-feature ../new-feature

# List all worktrees
git worktree list

# Remove a worktree
git worktree remove ../feature-auth

# Clean up stale worktree metadata
git worktree prune

Parallel Development Workflow

Transform sequential AI iteration into parallel exploration

Multi-Feature Development

Create separate worktrees for each feature. Launch Claude Code in each directory—one agent refactors authentication while another builds data visualization. No context switching.

Parallel Implementation Exploration

Create multiple worktrees from the same starting point. Run different Claude instances implementing the same feature in different ways. Compare results and merge the best approach.

Context Preservation

Each Claude Code session maintains its own deep, focused context about a specific task. Treat AI coding sessions like long-running processes with ongoing dialogues.

Emergency Hotfixes

Need to fix a production bug? Create a hotfix worktree instantly without disrupting your feature work. No stashing, no commits, no interruptions.

Git Worktree Best Practices

Maximize productivity while keeping your workflow clean

Organize with Consistent Naming

Use clear naming conventions like project-feature-name. Create a .worktrees/ directory to keep all worktrees organized and add it to .gitignore.

Keep the Main Branch Clean

Use your primary repository directory for the main/master branch as a reference. Do all feature work in separate worktrees to avoid accidental commits to main.

Limit Active Worktrees

Don't create 20+ worktrees. Create them for active tasks, then remove them when done. Use git worktree prune regularly to clean up stale metadata.

Consider Resource Usage

Multiple Claude Code instances consume API credits and system resources. Balance parallelization with your available resources and budget.

Quick Cleanup Pattern

When a task completes: cd back to main, git worktree remove the directory, then git branch -d if the branch was merged.

Conclusion? You are nearly ready to be 10x engineers 😂

Understanding Your Context Window

Claude Code has a 200,000 token context window. Every piece of information consumes tokens from this budget.

Use /context command to see your current token usage breakdown across all components.

Token Budget Breakdown:
• System prompt: ~3,200 tokens (1.6%)
• System tools: ~12,000 tokens (6%)
• MCP servers: ~66,000 tokens (33%)
• Reserved: ~45,000 tokens (22.5%)
• Available: ~42,000 tokens (~21%)
• Your conversation: remaining space

Context Window (200K tokens)

┌─────────────────────────────────┐
│ System (1.6%) ░░│
├─────────────────────────────────┤
│ Tools (6%) ░░░░░░│
├─────────────────────────────────┤
│ MCP Servers (33%) ░░░░░░░░░░░░░│
│ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│
├─────────────────────────────────┤
│ Reserved (22.5%) ░░░░░░░░░░░░░░│
│ ░░░░░░░░░░░░░░░░░░│
├─────────────────────────────────┤
│ Your Conversation (~37%) │
│ │
│ Available for messages, │
│ file reads, agent outputs │
│ │
└─────────────────────────────────┘

# Check your usage
/context

⚠️ MCP servers are the biggest consumer
Each server adds 14K-82K+ tokens

What is Auto-Compact?

Automatic conversation summarization to prevent context overflow

Triggers at ~95% Capacity

When your context window reaches approximately 190,000 tokens (~95% full), Claude Code automatically summarizes the conversation to free up space.

Preserves Recent Context

Auto-compact keeps recent messages intact and summarizes older parts of the conversation. Critical information and code changes are preserved.

Manual Trigger Available

Use /compact command to manually trigger summarization anytime you want to free up context space proactively.

Prevents Crashes

Without auto-compact, hitting the 200K token limit would crash the session. Summarization prevents data loss and maintains continuity.

Context Management Best Practices

Preserve your precious context budget

Be Selective with MCP Servers

Each MCP server can consume 14K-82K+ tokens. Only enable servers you actively need. Use /mcp command to disable unused servers.

Don't Overuse Agents

While agents only use ~0.3% per invocation, frequent delegation adds up. Use agents for complex tasks, but handle simple operations directly.

Monitor with /context

Regularly check /context to see token breakdown. Understand what's consuming your budget and optimize accordingly.

Read Files Strategically

Large file reads consume conversation tokens. Use grep/glob to narrow down before reading entire files. Be mindful of reading many files at once.

Compact Proactively

Before starting a major task, use /compact to summarize and free up space for the work ahead.

Enjoy your journey!

1 / 63