Learn Claude Code

Master AI-powered coding with Claude Code. This comprehensive tutorial takes you from beginner to advanced, with interactive examples, quizzes, and real-world use cases.

What You'll Learn

  • Set up and use Claude Code effectively
  • Master context management and memory
  • Create custom commands and workflows
  • Work with MCP servers and sub-agents
  • Integrate with GitHub for team collaboration
  • Apply professional best practices

Learning Format: Each chapter includes simple explanations, both Terminal and VS Code instructions, real examples, and a quiz to test your knowledge.


Chapter 0: Welcome - What is Claude Code?

Quick Summary: Discover what Claude Code is, why it's useful, and how it can help you code faster and smarter.

Time to complete: 5 minutes

What you'll learn:

  • What Claude Code is and how it works
  • Who can benefit from using it
  • Key features that make it powerful
  • How to get help when you need it

What is Claude Code?

Claude Code is an AI-powered coding assistant that helps you write, understand, and improve code. Think of it like having an expert programmer sitting next to you, ready to help whenever you need it.

Simple Analogy: Imagine you're building with LEGO blocks. Claude Code is like a friend who:

  • Shows you which blocks to use
  • Helps you fix mistakes
  • Explains how the blocks fit together
  • Suggests better ways to build

But instead of LEGO blocks, you're working with code!


Who is Claude Code For?

Claude Code helps many different people:

  • Beginners: Learning to code for the first time
  • Students: Working on school projects
  • Professional Developers: Building real applications
  • Teams: Collaborating on large projects
  • Anyone: Who wants to code faster and better

You don't need to be an expert. Claude Code meets you where you are.


Why Use Claude Code?

Here's what makes Claude Code special:

1. Faster Development

Write code in minutes instead of hours. Claude Code helps you:

  • Generate code from descriptions
  • Fix bugs quickly
  • Add new features easily

2. Better Understanding

Learn as you code. Claude Code explains:

  • What your code does
  • Why something works (or doesn't)
  • How to improve your code

3. Fewer Mistakes

Catch errors before they become problems. Claude Code helps:

  • Find bugs in your code
  • Suggest better solutions
  • Follow best practices

4. Works Your Way

Use Claude Code however you like:

  • In your terminal (command line)
  • In VS Code (text editor)
  • With your keyboard only
  • On any operating system

How Does Claude Code Work?

Claude Code uses advanced AI to understand what you need. Here's the simple process:

  1. You Ask: Tell Claude what you want to do
  2. Claude Thinks: The AI figures out the best solution
  3. You Get Help: Claude provides code, explanations, or fixes
  4. You Review: Check the results and make changes if needed

Important: You're always in control. Claude Code suggests and helps, but you decide what to use.


Real-World Example: How Teams Use Claude Code

Story: The Anthropic Team

The team that created Claude Code uses it every day. Here's how:

  • Morning: Use /status to check their setup
  • Starting Work: Run /init to create project documentation
  • Coding: Ask Claude to help write, test, and review code
  • Learning: Use Claude to understand new codebases
  • Collaborating: Share knowledge with the team through Claude's help

Result: They build features faster and with fewer bugs.


Getting Help in Claude Code

Claude Code has built-in help for when you're stuck:

Terminal Way

# Get help with all commands
/help

# Check your current setup
/status

# Get your current directory
cwd

VS Code Way

  1. Open the Command Palette (Cmd+Shift+P on Mac, Ctrl+Shift+P on Windows)
  2. Type "Claude: Help"
  3. Press Enter
  4. Browse the help documentation

Pro Tip: The /help command is your friend. Use it whenever you forget a command or need guidance.


Your First Steps with Claude Code

Ready to start? Here's what beginners should do first:

  1. Install Claude Code (we'll cover this in Chapter 1)
  2. Run /help to see available commands
  3. Check /status to verify your setup
  4. Try asking Claude a simple question about your code
  5. Experiment! The best way to learn is by trying

Common Questions About Claude Code

Q: Do I need to be good at coding to use Claude Code?
A: No! Claude Code helps beginners learn while they code. Start simple and grow from there.

Q: Will Claude Code write all my code for me?
A: Claude Code is a helper, not a replacement. It suggests and assists, but you make the decisions. This keeps you learning and in control.

Q: Is Claude Code free?
A: Claude Code has different plans. Some features are free, and others require a subscription for more usage. Check the latest pricing on the official website.

Q: What languages does Claude Code support?
A: Claude Code works with many programming languages including JavaScript, Python, Java, C++, and more. If you can code it, Claude can help with it.

Q: Can I use Claude Code for school projects?
A: Yes! Just remember to understand the code Claude helps you write. Learning is the goal, not just getting answers.


What Makes Claude Code Different?

Compared to other AI coding tools, Claude Code stands out because:

  • Context Awareness: Understands your entire project, not just one file
  • Clear Explanations: Doesn't just give code, explains why it works
  • Safe Suggestions: Follows best practices and security guidelines
  • Your Choice: Never forces changes, always asks for permission
  • Team Friendly: Integrates with Git, GitHub, and team workflows

Important Things to Remember

Be Specific When You Ask

Claude Code works best when you're clear about what you need. Instead of saying:

❌ "Fix my code"

Say this:

✅ "Fix the error in the login function on line 45"

Why? Specific requests get specific, helpful answers.

Always Review Claude's Suggestions

Claude Code is smart, but not perfect. Always:

  • Read the code Claude generates
  • Test it to make sure it works
  • Ask questions if you don't understand
  • Make changes if needed

Remember: You're the programmer. Claude is your assistant.


Key Takeaways

Let's review what you learned in this chapter:

  • Claude Code is an AI assistant that helps you write, understand, and improve code
  • Anyone can use it - from beginners to professional developers
  • It makes coding faster by generating code, fixing bugs, and explaining concepts
  • You stay in control - Claude suggests, you decide
  • Get help anytime with the /help and /status commands
  • Be specific when asking Claude for help to get the best results

What's Next?

Now that you understand what Claude Code is, you're ready to install it and start coding!

Coming up in Chapter 1:

  • Installing Claude Code on your computer
  • Setting up your first project
  • Running your first commands
  • Understanding your workspace

Get excited! You're about to start an amazing coding journey.

Chapter 1: Getting Started with Claude Code

Quick Summary: Learn how to check your Claude Code setup and make your first request.

Time to Complete: 10-15 minutes

What You'll Learn

  • How to check if Claude Code is working
  • Understanding your workspace location
  • Getting help when you're stuck
  • Making your first clear request
  • Understanding basic commands

What is a CLI?

Before we start, let's understand what a CLI means.

CLI = Command Line Interface

Think of it like texting with your computer. Instead of clicking buttons and menus, you type commands. It's faster once you learn it!

Simple Analogy

Imagine two ways to order pizza:

  • Graphical (GUI): Open an app, click "Pizza", click "Large", click "Cheese", click "Order"
  • Command Line (CLI): Type "order large cheese pizza" - Done!

Both work, but CLI is faster when you know what you want.

Claude Code uses a CLI. You type what you need, and Claude helps immediately.


Checking Your Setup with /status

The first thing you should do is check if Claude Code is working correctly.

Terminal Way

# Check if Claude Code is running properly
/status

VS Code Way

If you're using the VS Code extension:

  1. Open VS Code
  2. Open the Claude Code panel (usually on the sidebar)
  3. Type /status and press Enter

What does /status show?

  • If Claude Code is installed correctly
  • Your current setup information
  • Any problems that need fixing

Pro Tip: Run /status at the start of each work session to make sure everything is ready!


Getting Help with /help

Forgot a command? Don't know what to do? The /help command is your friend!

Terminal Way

# See all available commands
/help

# Get help with a specific command
/help init

# See keyboard shortcuts
/help shortcuts

VS Code Way

  1. In the Claude Code panel, type /help
  2. Press Enter
  3. Claude will show you all available commands

Common commands you'll see:

  • /help - Show all commands
  • /status - Check your setup
  • /init - Start a new project
  • /clear - Clear the conversation
  • /exit - Exit Claude Code

Remember: Commands start with a forward slash (/). That's how Claude knows you're using a command instead of just chatting!


Understanding Your Workspace

When you work with Claude Code, you need to know where you are on your computer. This is called your workspace or current working directory.

What is a "Current Working Directory" (cwd)?

Think of your computer like a big filing cabinet. Your current working directory is which drawer you have open right now.

Simple Analogy

Imagine you're in a library:

  • The library is your computer
  • The aisle you're in is your current directory
  • The shelf you're looking at is your project folder
  • The book in your hands is the file you're editing

Claude needs to know where you are to help with the right files!

Terminal Way - Check Your Location

# On Mac/Linux - show current directory
pwd

# On Windows - show current directory
cd

VS Code Way - Check Your Location

  1. Look at the bottom blue bar in VS Code
  2. You'll see the current folder path
  3. Or look at the "Explorer" panel on the left - the top shows your current folder

Why does this matter?

  • Claude needs to know which project you're working on
  • It helps Claude find the right files
  • It prevents mistakes like editing the wrong project

Making Your First Request

Now let's ask Claude to help with something! The key is being clear and specific.

The Wrong Way (Too Vague)

❌ "Fix the code"
❌ "Make it better"
❌ "Help me"

Problem: Claude doesn't know WHAT code, WHAT to improve, or HOW to help.

The Right Way (Clear and Specific)

✅ "Can you review the login function in auth.js and suggest improvements?"
✅ "Explain how the getUserData function works"
✅ "Create a new function called calculateTotal that adds up prices"

Why this works:

  • Says WHAT file or function (auth.js, getUserData)
  • Says WHAT you want (review, explain, create)
  • Gives enough detail for Claude to understand

Simple Analogy: Giving Directions

Imagine telling a friend where to meet you:

  • Bad: "Meet me at the place"
  • Good: "Meet me at Starbucks on Main Street at 3pm"

Same with Claude - the more specific you are, the better help you get!


Three Tips for Great Requests

  1. Be Specific About Location
    • ❌ "Fix the function"
    • ✅ "Fix the login function in src/auth.js"
  2. Say What You Want Done
    • ❌ "Do something with the button"
    • ✅ "Change the button color to blue"
  3. Give Context When Needed
    • ❌ "This doesn't work"
    • ✅ "The save button doesn't work - when I click it, nothing happens"

Real-World Example: A Developer's First Day

Story: Sarah's First Day at Anthropic

Sarah joined the Anthropic team and had never used Claude Code before. Here's what she did:

8:00 AM - Check Everything Works

/status

Result: Everything working! ✓

8:05 AM - Explore Available Commands

/help

Result: Saw list of 20+ helpful commands

8:10 AM - Understand the Codebase

Can you explain what the main.js file does in this project?

Result: Got clear explanation of the code structure

9:00 AM - Fix Her First Bug

The submitForm function in contact.js shows an error when I click submit. Can you help me debug it?

Result: Claude found the issue and suggested a fix!

By lunch: Sarah had fixed 3 bugs and added a new feature. She was amazed at how Claude Code helped her be productive on day one!


Key Takeaways

  • CLI means Command Line Interface - typing commands instead of clicking
  • Use /status to check if Claude Code is working
  • Use /help to see all available commands
  • Know your current working directory (where you are on your computer)
  • Be specific and clear when asking Claude for help
  • The better your request, the better Claude's help

Common Questions

What if /status shows errors?

Don't worry! Use the /doctor command to diagnose and fix issues. It will tell you exactly what to fix.

Do I need to memorize all the commands?

No! Just remember /help. It shows you all commands when you need them. Over time, you'll naturally remember the ones you use most.

Can I use Claude Code in any project folder?

Yes! Just navigate to your project folder first (using cd command or opening it in VS Code), then start Claude Code there.

What if I'm in the wrong folder?

Use pwd (Mac/Linux) or cd (Windows) to check where you are. Then use cd path/to/project to move to the correct folder.

Is it okay to ask Claude simple questions?

Absolutely! No question is too simple. Claude is here to help you learn and grow, whether you're a beginner or expert.


Common Mistakes to Avoid

  1. Starting Claude Code in the wrong folder

    Always check your location first with pwd or cd

  2. Being too vague in requests

    Instead of "fix this", say "fix the login function in auth.js"

  3. Not using /help when stuck

    The help is built-in - use it! It's faster than searching online

  4. Forgetting to check /status

    A quick status check at the start saves debugging time later

  5. Not giving context

    Telling Claude what you're trying to achieve helps get better suggestions


What's Next?

Great work! You now know how to check your setup and make clear requests to Claude.

Coming up in Chapter 2:

  • Understanding claude.md files
  • Creating project memory
  • Using /init to document your project
  • Making Claude remember important things

Chapter 2 will teach you how to give Claude long-term memory about your projects!

Chapter 2: Memory & Files

Quick Summary: Learn how to give Claude long-term memory about your projects.

Time to Complete: 15-20 minutes

What You'll Learn

  • What is claude.md and why it's important
  • Using /init to create project memory
  • Three types of memory (Project, Local, User)
  • Adding memory with the # symbol
  • Editing memory with /memory command

What is Memory in Claude Code?

Think about how you remember things. You remember your friend's name, their birthday, and what they like. Claude Code can remember things about your projects too!

Memory = Information Claude remembers between conversations

Simple Analogy

Imagine you hire a helper for your house:

  • Without Memory: Every day you explain where the dishes go, how you like your coffee, what time you wake up
  • With Memory: You tell them once, they write it down, and remember forever

Claude's memory works the same way - tell it once, it remembers!

Why is memory important?

  • Claude remembers your project rules and preferences
  • You don't repeat the same information every session
  • Your whole team can share the same knowledge
  • Claude gives better suggestions based on your project

Understanding claude.md Files

A claude.md file is like a notebook where you write down everything Claude should remember about your project.

What's in a claude.md file?

  • Project description (what your app does)
  • Code style preferences (tabs or spaces, naming conventions)
  • Important files and their purpose
  • Rules to follow (always test before committing)
  • Team preferences and workflows

Simple Analogy: Recipe Card

Think of claude.md like a recipe card in your kitchen:

  • Ingredients: What files and tools your project uses
  • Instructions: How to build and run your project
  • Notes: Special tips and preferences
  • Warnings: Things to avoid

Anyone who reads the recipe card can cook the dish perfectly!


Using /init to Create Project Memory

The easiest way to create a claude.md file is with the /init command. It automatically scans your project and creates memory for you!

Terminal Way

# Navigate to your project folder first
cd /path/to/your/project

# Initialize claude.md
/init

VS Code Way

  1. Open your project in VS Code
  2. Open the Claude Code panel
  3. Type /init and press Enter
  4. Claude will create a claude.md file in your project root

What happens when you run /init?

  1. Claude scans your project files
  2. It figures out what kind of project it is (React, Python, etc.)
  3. It creates a claude.md file with project information
  4. It saves this file in your project folder

Pro Tip: Run /init at the start of every new project. It takes 5 seconds and saves hours of explaining!


Three Types of Memory

Claude Code has three different places to store memory. Each one serves a different purpose:

1. Project Memory (claude.md)

  • Location: ./claude.md (in your project folder)
  • Shared: Yes - committed to Git
  • Use For: Team rules, project structure, shared preferences
  • Example: "Always use TypeScript for new files"

2. Project Memory (Local)

  • Location: ./claude.local.md (in your project folder)
  • Shared: No - Git ignored
  • Use For: Personal notes, local paths, experiments
  • Example: "My API key is stored in /Users/yourname/keys/"

3. User Memory

  • Location: ~/.claude/CLAUDE.md (your home folder)
  • Shared: No - only for you
  • Use For: Global preferences across ALL projects
  • Example: "I prefer clear variable names over short ones"

Simple Analogy: Three Notebooks

  • Project Memory: Shared team notebook - everyone can read it
  • Local Memory: Your desk drawer - just for you at this project
  • User Memory: Your personal journal - follows you everywhere

Quick Guide: Team rules → Project Memory. Personal notes → Local Memory. Your preferences → User Memory.


Adding Memory with the # Symbol

You can add memory quickly by starting a message with # (hash symbol). Claude will ask where to save it!

Terminal Way

# Add a memory about code style
# Always use descriptive variable names

# Add a memory about testing
# Run tests before every commit

# Add a memory about accessibility
# Use H1-H6 headings in sequence for accessibility

VS Code Way

  1. In Claude Code panel, type your memory starting with #
  2. Example: # Always add comments to complex functions
  3. Press Enter
  4. Claude asks: "Where should I save this?"
  5. Choose: Project, Local, or User memory

When Claude asks where to save:

  1. Project Memory - For team rules everyone should follow
  2. Project Memory (Local) - For your personal project notes
  3. User Memory - For preferences across all your projects

Editing Memory with /memory

Need to change or review your memory? Use the /memory command!

Terminal Way

# Open memory editor
/memory

VS Code Way

  1. Type /memory in Claude Code panel
  2. Claude shows you three options:
    • Edit Project Memory
    • Edit Local Memory
    • Edit User Memory
  3. Select which one you want to edit
  4. Claude opens the file for you to edit

What you can do with /memory:

  • Read what's currently saved
  • Add new rules and preferences
  • Remove outdated information
  • Organize memory into sections

Best Practice: Review your memory files once a month. Remove outdated rules and add new learnings!


Real-World Example: Team Collaboration

Story: The Design System Team

A team of 5 developers was building a design system. Here's how they used memory:

Day 1 - Setup Project Memory

/init

Created claude.md with project structure and tech stack

Day 2 - Added Team Rules

# All components must have TypeScript types
# Always include accessibility attributes
# Use CSS modules for styling
# Test on mobile before submitting PR

Result: Everyone's Claude followed the same standards!

Week 2 - Personal Preferences

Each developer added local memory:

  • Sarah: "I prefer Jest for testing" (Local memory)
  • Mike: "Always show me ESLint suggestions" (User memory)
  • Team: "Use Prettier with 2-space indent" (Project memory)

Result After 1 Month:

  • 50% fewer code review comments
  • Consistent code style across the project
  • New team members onboarded in hours, not days
  • Claude gave better, context-aware suggestions

Best Practices for Memory Management

  1. Start Every Project with /init

    Takes 5 seconds, saves hours of explanation

  2. Be Specific in Memory
    • ❌ "Write good code"
    • ✅ "Use descriptive variable names (e.g., userName, not u)"
  3. Choose the Right Memory Type
    • Team rules → Project memory
    • Personal notes → Local memory
    • Your preferences → User memory
  4. Keep Memory Updated

    Remove old rules, add new learnings monthly

  5. Make Memory Actionable
    • ❌ "Care about accessibility"
    • ✅ "Add alt text to all images"

Key Takeaways

  • Memory helps Claude remember your project preferences between sessions
  • Use /init to automatically create a claude.md file
  • Three types: Project (shared), Local (personal), User (global)
  • Add quick memory with # symbol
  • Edit memory files with /memory command
  • Keep memory specific, actionable, and updated

Common Questions

Should I commit claude.md to Git?

Yes! Project memory (claude.md) should be committed so your whole team benefits. Use claude.local.md for personal notes that shouldn't be shared.

How much information should I put in memory?

Focus on important rules and preferences. If you find yourself explaining the same thing repeatedly, add it to memory. Keep it under 1-2 pages for best results.

Can I delete a memory file?

Yes! Just delete the file. If you want to start fresh, delete claude.md and run /init again.

What if team members have different preferences?

Use Project memory for team rules everyone follows. Use Local or User memory for personal preferences that don't affect the team.

Does memory slow down Claude?

No! Memory actually helps Claude work faster because it already knows your project context and doesn't need to ask questions.


Common Mistakes to Avoid

  1. Putting personal API keys in Project memory

    Never commit secrets! Use Local memory for sensitive info

  2. Writing vague memory

    Instead of "be careful", write "always validate user input"

  3. Never updating memory

    Projects evolve! Update memory when you change tools or processes

  4. Forgetting to run /init

    Start every new project with /init - it's automatic memory!

  5. Mixing up memory types

    Team rules in Project, personal notes in Local, preferences in User


What's Next?

Excellent! You now know how to give Claude long-term memory about your projects.

Coming up in Chapter 3:

  • What is context and why it matters
  • Managing context size with @ symbol
  • Using /compact to clean history
  • Best practices for context management

Chapter 3 will teach you how to give Claude the right information at the right time!

Chapter 3: Context Management

Quick Summary: Learn how to give Claude the right information at the right time.

Time to Complete: 15-20 minutes

What You'll Learn

  • What is context and why it matters
  • Using @ symbol to add files as context
  • Understanding context window limits
  • Cleaning context with /clear and /compact
  • Best practices for effective context

What is Context?

Context is all the information Claude has access to when helping you. Think of it like telling a story - the more details you provide, the better Claude understands what you need!

Context = Information that helps Claude understand your situation

Simple Analogy

Imagine asking a friend to help you find your keys:

  • No Context: "Help me find my keys" (They don't know where to look)
  • Some Context: "Help me find my keys, I was in the kitchen" (Better!)
  • Good Context: "Help me find my car keys, I was making coffee in the kitchen 10 minutes ago" (Now they know exactly what and where!)

More context = Better help!

What can be context?

  • Files you're working on
  • Previous conversation messages
  • Screenshots or images
  • Selected code snippets
  • Error messages you're seeing

Why Context Matters

The right context helps Claude give you accurate, specific help. The wrong context (or too much) can confuse things.

Good Context:

  • Claude knows exactly which file you're talking about
  • Suggestions are specific to your code
  • Answers reference your actual variable names
  • Help is relevant to your project structure

Poor Context:

  • Generic answers that might not fit your code
  • Confusion about which file you mean
  • Suggestions for the wrong programming language
  • Claude asks clarifying questions instead of helping

Golden Rule: Give Claude enough context to understand, but not so much that important details get buried!


Using @ to Add File Context

The @ symbol is your superpower for adding context! It lets you reference specific files, so Claude knows exactly what you're working on.

Terminal Way

# Reference one file
@src/components/Button.js Can you review this component?

# Reference multiple files
@src/utils/api.js @src/config.js Are these files connected?

# Reference a folder
@src/components/ What components do I have?

VS Code Way

  1. In Claude Code panel, type @
  2. Claude shows a list of files in your project
  3. Start typing to filter the list
  4. Select the file you want
  5. Claude adds it as context
  6. Continue typing your question

What happens when you use @:

  1. Claude reads the file you referenced
  2. It includes that file's content in the conversation
  3. Claude can now give specific advice about that file
  4. You can reference multiple files in one question

Pro Tip: Start typing the filename after @ and Claude will auto-complete. Much faster than typing the full path!


Adding Screenshots as Context

Sometimes an image is worth a thousand words! You can give Claude screenshots, error messages, or UI designs as context.

Terminal Way

  1. Take a screenshot (Cmd+Shift+4 on Mac, Windows+Shift+S on Windows)
  2. Drag the image file into your terminal
  3. Type your question about what you see

VS Code Way

  1. Take a screenshot
  2. Drag the image into Claude Code panel
  3. Claude can "see" the image and discuss it with you

Good uses for screenshot context:

  • Error messages in the browser
  • UI bugs or layout issues
  • Design mockups you want to implement
  • Console errors with stack traces

Understanding Context Window

Think of the context window like a whiteboard. It has a limited size - about 200,000 tokens (roughly 150,000 words).

Simple Analogy: A Whiteboard

Imagine Claude has a whiteboard to remember your conversation:

  • Empty Board: Lots of space at the start
  • Getting Full: As you chat, it fills up with notes
  • No Space Left: Eventually, there's no room for more
  • Solution: Erase old notes, keep important stuff

That's exactly how context windows work!

What fills the context window:

  • Your questions and messages
  • Claude's responses
  • Files you've referenced with @
  • Code Claude has written
  • Memory from claude.md

What happens when it's full:

  • Claude can't add more context
  • You'll see a warning message
  • Older messages might be forgotten
  • Time to clean up! (see next section)

Cleaning Context: /clear

When you're done with one task and starting another, use /clear to wipe the whiteboard clean!

Terminal Way

# Clear everything and start fresh
/clear

VS Code Way

  1. Type /clear in Claude Code panel
  2. Press Enter
  3. Conversation and context are cleared
  4. Memory (claude.md) is kept - it's permanent!

When to use /clear:

  • Switching to a completely different task
  • Working on a different part of your project
  • Context is getting messy and confusing
  • You want to start with a clean slate

What /clear does NOT delete:

  • Your files (they're safe!)
  • Memory in claude.md
  • Your project settings

Summarizing Context: /compact

What if you're in the middle of something and don't want to lose context? Use /compact to summarize and make room!

Terminal Way

# Compact the conversation into a summary
/compact

# Compact but keep important parts
/compact Don't compact the initial prompt

VS Code Way

  1. Type /compact in Claude Code panel
  2. Claude summarizes the conversation
  3. Old messages are replaced with the summary
  4. You can continue where you left off

How /compact works:

  1. Claude reads all previous messages
  2. It creates a summary of key points
  3. Old messages are removed
  4. Summary stays, giving you more room

Simple Analogy: Taking Notes

Imagine you're in a long meeting:

  • /clear: Leave the meeting and start a new one
  • /compact: Write down key points, erase old notes, continue meeting

Compact keeps the important stuff, clear starts fresh!


Other Context Commands

/exit - End Your Session

# Exit Claude Code completely
/exit

Closes Claude Code and clears everything. Use when you're done for the day.

/resume - Continue Previous Session

# See and resume previous sessions
/resume

Shows your recent sessions so you can continue where you left off.

Esc Twice - Undo/Rewind

Press Esc twice quickly to undo the last message and go back to a previous point.


Best Practices for Context

  1. Be Specific, Not Exhaustive
    • ❌ Add 20 files hoping one helps
    • ✅ Add the 2-3 files directly related to your question
  2. Use @ for Files, Not Copy-Paste
    • ❌ Copy entire file contents into chat
    • ✅ Use @filename to reference files
  3. Clear When Switching Tasks
    • Working on login → /clear → Work on checkout
    • Keeps context relevant to current task
  4. Compact for Long Sessions
    • If working on one complex feature for hours
    • Use /compact to summarize and continue
  5. Quality Over Quantity
    • Better: "The login button in @auth/LoginForm.js isn't working"
    • Worse: Add entire src folder as context

Real-World Example: Debugging Session

Story: Maria's Bug Hunt

Maria was fixing a checkout bug. Here's how she used context effectively:

9:00 AM - Starting Fresh

/clear
@components/Checkout.js The total isn't calculating correctly

Started with clean context, referenced only the relevant file

9:15 AM - Adding Related Files

@utils/pricing.js @components/Cart.js Are these connected to the bug?

Added context as she discovered connected files

10:30 AM - Context Getting Full

/compact Keep the bug description and current progress

Summarized to keep working without starting over

11:00 AM - Bug Fixed, New Task

/clear
@components/Navigation.js Now let's work on the menu

Cleared checkout context, started fresh for navigation work

Result: Fixed bug in 2 hours by keeping context focused. When she switched tasks, she cleared context to avoid confusion!


Key Takeaways

  • Context is information that helps Claude understand your situation
  • Use @ symbol to add specific files as context
  • Context window holds ~200K tokens (~150K words)
  • Use /clear to start fresh on new tasks
  • Use /compact to summarize and continue working
  • Quality context (specific files) beats quantity (all files)

Common Questions

How do I know if my context is too full?

Claude will warn you when context is getting full. You'll see a message like "Context window is 90% full." That's your signal to use /compact or /clear!

Does /clear delete my code files?

No! /clear only clears the conversation history and context. Your actual files are completely safe. Memory (claude.md) is also preserved.

Can I use @ with files that aren't in my project?

The @ symbol works best with files in your current project. For files outside your project, you can copy-paste relevant parts or save them to your project first.

What's better - /clear or /compact?

Use /clear when switching to completely different work. Use /compact when continuing on the same task but running out of space. Think: clear = new conversation, compact = summarize current one.

Can Claude see private files if I use @?

Claude only sees what you explicitly give it access to. If you don't use @ to reference a file, Claude doesn't see it. Your code stays private and local.


Common Mistakes to Avoid

  1. Adding too many files at once

    More context isn't always better. Add only files directly related to your question.

  2. Never clearing context between tasks

    Old context from previous tasks can confuse Claude. Clear when switching tasks!

  3. Copy-pasting instead of using @

    @ is more efficient and uses less context space than pasting file contents

  4. Forgetting memory is permanent

    /clear removes context but NOT memory. Update claude.md when project changes.

  5. Working until context is 100% full

    Use /compact proactively at 70-80% full, don't wait for the warning!


What's Next?

Great work! You now understand how to manage context effectively.

Coming up in Chapter 4:

  • Understanding Claude's available tools
  • The permission system explained
  • Approving and managing tool usage
  • Safety features built into Claude Code

Chapter 4 will show you how Claude's tools work and how to control them!

Chapter 4: Tools & Permissions

Quick Summary: Learn what tools Claude uses and how the permission system keeps you in control.

Time to Complete: 15-20 minutes

What You'll Learn

  • What tools are and how Claude uses them
  • Which tools require permission vs. automatic
  • How to approve and manage permissions
  • The session permission system explained
  • Best practices for safe usage

What Are Tools in Claude Code?

Tools are special abilities that Claude uses to help you code. Think of them like different tools in a toolbox - each one does a specific job.

Simple Analogy: A Mechanic's Toolbox

Imagine Claude is a mechanic helping fix your car:

  • Wrench (Read tool): Look at parts without changing anything
  • Screwdriver (Edit tool): Make small adjustments
  • Power Drill (Bash tool): Make bigger changes that need approval
  • Diagnostic Scanner (Grep tool): Find problems by searching

Some tools are safe to use anytime (looking). Others need your OK first (changing things).

Why does Claude need tools?

  • To read your code files
  • To edit and improve code
  • To run commands in your terminal
  • To search through your project
  • To create new files

Two Types of Tools

Claude Code has two categories of tools based on whether they need your permission.

Tools That DON'T Need Permission (Safe, Read-Only)

These tools just look at your code without changing anything. They're automatically allowed because they can't harm your project.

  • Read: Opens and reads file contents
  • Glob: Finds files matching patterns
  • Grep: Searches for text in files
  • Task: Creates sub-agents for specific tasks
  • TodoWrite: Creates and manages todo lists
  • NotebookRead: Reads Jupyter notebook files

Think of these as: Looking, searching, and planning tools. They don't modify anything.

Tools That REQUIRE Permission (Can Make Changes)

These tools can change your files, run commands, or interact with the web. Claude always asks before using them.

  • Edit: Modifies existing files
  • Write: Creates new files
  • Bash: Runs terminal commands
  • WebFetch: Gets information from websites
  • WebSearch: Searches the internet
  • NotebookEdit: Edits Jupyter notebooks

Think of these as: Changing, creating, and executing tools. They need your approval for safety.

Remember: You're always in control. Claude can't change anything without your permission!


How Permissions Work

When Claude wants to use a tool that needs permission, it stops and asks you first. You'll see a prompt with three options.

The Three Permission Options

Option 1: Yes

  • Approve this one action
  • Claude will ask again next time
  • Use when you want to review each change

Option 2: Yes, and don't ask again this session (Alt+M)

  • Approve this tool for the entire session
  • Claude can use this tool freely until you exit
  • Saves time when doing repetitive tasks
  • Permission resets when you close Claude Code

Option 3: No, and tell Claude what to do differently (Esc)

  • Reject the action
  • Give Claude different instructions
  • Use when Claude misunderstood your request

Simple Analogy: House Guest

Imagine Claude is a guest helping at your house:

  • Option 1 (Yes): "Sure, you can use the bathroom" (approve once)
  • Option 2 (Yes, don't ask again): "Feel free to use the kitchen anytime today" (approve for session)
  • Option 3 (No): "Actually, let's order pizza instead of cooking" (reject and redirect)

You decide what Claude can do, and when!


Session Permissions Explained

When you select "Yes, and don't ask again this session," Claude creates a special file to remember your choice.

What Happens Behind the Scenes

  1. Claude asks to use a tool (e.g., Edit)
  2. You press Alt+M (or select option 2)
  3. Claude creates .claude/settings.json in your project
  4. This file stores your permission for this session
  5. Claude can now use that tool without asking again
  6. When you exit Claude Code, the permission resets

Important: Session permissions are temporary. Next time you open Claude Code, you'll need to approve again. This is a safety feature!

# Example: What's in settings.json
{
  "permissions": {
    "Edit": "allow",
    "Bash": "allow"
  }
}

Common Tools in Action

Let's see how these tools work in real scenarios.

Scenario 1: Reviewing Code (No Permission Needed)

# Your request
Can you review the login function in auth.js?

# Claude uses these tools automatically:
1. Read tool → Opens auth.js
2. Grep tool → Searches for "login function"
3. Read tool → Analyzes the code

# No permission needed - just looking!

Scenario 2: Fixing a Bug (Permission Required)

# Your request
Fix the typo in the button text on line 45

# Claude asks permission:
"I need to use the Edit tool to fix this. May I proceed?"

# You choose:
Option 1: Yes (approve this fix)
Option 2: Alt+M (approve all edits this session)
Option 3: Esc (no, I'll do it manually)

Scenario 3: Running Tests (Permission Required)

# Your request
Run the test suite

# Claude asks permission:
"I need to use the Bash tool to run 'npm test'. May I proceed?"

# Why it needs permission:
Bash can execute any command on your computer
This could be dangerous if misused
You stay in control by approving first

Keyboard Shortcuts for Permissions

Save time with these shortcuts when Claude asks for permission:

Key Action When to Use
Enter Yes (this action only) Default, safe choice
Alt+M Yes, don't ask this session Trust this tool for now
Esc No, do something else Reject and give new instructions

Pro Tip: Use Alt+M when doing repetitive work (like fixing multiple similar bugs). It speeds up your workflow!


Real-World Example: The Developer's Daily Workflow

Story: Alex's Code Review Day

Alex is reviewing pull requests and fixing issues. Here's how tools and permissions helped:

9:00 AM - Understanding New Code

Can you explain what this payment processing file does?

→ Claude used: Read, Grep (no permission needed)
→ Result: Clear explanation of payment flow

9:30 AM - Fixing Multiple Typos

Fix the typos in these three files

→ Claude asked: May I use Edit tool?
→ Alex pressed: Alt+M (allow for session)
→ Result: All typos fixed without interruption

10:00 AM - Running Tests

Run the full test suite

→ Claude asked: May I use Bash tool?
→ Alex chose: Yes (just this once)
→ Why: Bash is powerful, Alex wanted to review each command

11:00 AM - Creating Documentation

Create a README.md file

→ Claude asked: May I use Write tool?
→ Alex pressed: Alt+M (trust for session)
→ Result: Documentation created smoothly

Result: Alex completed 8 tasks by lunch! The permission system kept him in control while letting Claude work efficiently.


Best Practices for Tools & Permissions

  1. Review What Claude Plans to Do

    Before approving, read Claude's plan. Make sure you understand the changes.

  2. Use Session Permissions for Repetitive Tasks

    Alt+M is perfect when doing similar work multiple times (fixing typos, running tests, etc.)

  3. Be Careful with Bash Tool

    Bash can run any command. Review commands carefully before approving.

  4. It's OK to Say No

    Press Esc if Claude misunderstood. Give clearer instructions and try again.

  5. Permissions Reset for Safety

    Session permissions clear when you exit. This protects you from mistakes!


Understanding Tool Safety

Simple Analogy: Levels of Trust

Think of tools like different levels of trust with a helper:

  • Read/Grep/Glob: "Look in my desk drawer" (safe, can't harm)
  • Edit: "Fix this typo in my document" (small change, you review first)
  • Write: "Create a new document" (bigger change, you approve)
  • Bash: "Run this command on my computer" (most powerful, most care needed)

The permission system matches the level of trust needed!

Why some tools need permission:

  • Edit/Write: Can modify or create files (might overwrite work)
  • Bash: Can execute any command (could delete files, install software)
  • WebFetch: Accesses internet (could expose sensitive data)

Why some tools don't need permission:

  • Read: Only looks, never changes
  • Grep: Only searches, can't modify
  • Glob: Only lists files, can't edit

Key Takeaways

  • Tools are abilities Claude uses to help with coding tasks
  • Some tools (Read, Grep, Glob) don't need permission - they just look
  • Other tools (Edit, Write, Bash) need permission - they make changes
  • Three permission options: Yes, Yes for session (Alt+M), No (Esc)
  • Session permissions reset when you exit (safety feature)
  • You're always in control - Claude can't change anything without approval

Common Questions

What happens if I deny permission?

Claude stops that action and asks for different instructions. You can press Esc and tell Claude to do something else. No harm done - you're in control!

Can I revoke session permissions?

Yes! Either exit and restart Claude Code, or manually delete the .claude/settings.json file. Session permissions always reset when you close Claude Code anyway.

Is it safe to give session permission to Bash?

Only if you trust the commands Claude will run. Bash is powerful but safe when you review what Claude plans to do first. If uncertain, approve commands one by one instead of using session permission.

Can Claude use tools without me knowing?

No! Read-only tools (Read, Grep, Glob) work automatically but can't harm your project. Tools that change things ALWAYS require your approval first. You see every action Claude wants to take.

What if I accidentally approve the wrong thing?

Press Esc twice quickly to undo and go back. Or ask Claude to reverse the change. Claude Code also has built-in safety features to prevent dangerous actions.


Common Mistakes to Avoid

  1. Blindly approving without reading

    Always read what Claude plans to do before pressing Enter. Understanding the action keeps you in control.

  2. Using session permissions for Bash without review

    Bash commands should be reviewed carefully. Session permission means Claude can run any command until you exit.

  3. Forgetting session permissions are active

    Remember: once you grant session permission, Claude uses that tool freely until exit. Exit and restart if you want stricter control again.

  4. Being afraid to say no

    It's perfectly fine to reject an action! Press Esc and give Claude clearer instructions. That's what the option is for.

  5. Not using keyboard shortcuts

    Learn Alt+M (session permission) and Esc (reject). They save time and make permissions smoother.


What's Next?

Great work! You now understand how Claude's tools work and how to control them safely.

Coming up in Chapter 5:

  • Understanding Plan and Think modes
  • When to use planning before coding
  • Using the TodoWrite tool to organize work
  • Breaking down complex tasks

Chapter 5 will teach you how to plan effectively before coding!

Chapter 5: Planning & Thinking

Quick Summary: Learn how to use Plan and Think modes to break down complex tasks before coding.

Time to Complete: 15-20 minutes

What You'll Learn

  • What Plan mode is and when to use it
  • Four levels of Think modes
  • Using Alt+M to cycle between modes
  • Breaking down complex tasks with TodoWrite
  • Best practices for planning before coding

Why Plan Before Coding?

Imagine building a house. Would you start laying bricks randomly, or would you first draw blueprints? Planning before coding is like drawing blueprints - it helps you see the big picture before diving into details.

Simple Analogy: Building a House

Two approaches to building a house:

  • Without Planning: Start building, realize you forgot a bathroom, tear down walls, rebuild, forget windows, start over...
  • With Planning: Draw blueprints, list materials, plan each room, then build smoothly following the plan

Coding works the same way. Plan first, code smoothly!

Benefits of planning:

  • Catch problems before writing code
  • Break big tasks into small steps
  • See the complete picture
  • Code faster with a clear roadmap
  • Fewer rewrites and mistakes

What is Plan Mode?

Plan mode tells Claude: "Don't write code yet. Help me plan the approach first." Claude will think through the problem and give you a step-by-step plan.

Terminal Way

# Ask Claude to plan (no code yet)
Can you plan how to create a responsive website design?

# Claude will respond with:
1. Analysis of responsive design requirements
2. Step-by-step implementation plan
3. Files to create/modify
4. Potential challenges to watch for

VS Code Way

  1. Open Claude Code panel
  2. Type your question starting with "Can you plan..."
  3. Claude enters Plan mode automatically
  4. Review the plan, then proceed with implementation

Example Plan Mode Request:

Can you plan how to add user authentication to this app?

# Claude responds with plan:
## Authentication Implementation Plan

1. **Database Setup**
   - Create users table with email, password hash, timestamps
   - Add indexes for email lookup

2. **Backend Routes**
   - POST /register - new user signup
   - POST /login - user authentication
   - POST /logout - session termination

3. **Security Measures**
   - Use bcrypt for password hashing
   - Implement JWT tokens for sessions
   - Add rate limiting to prevent brute force

4. **Frontend Components**
   - Login form with validation
   - Registration form with password strength
   - Protected route wrapper

5. **Testing Strategy**
   - Unit tests for auth functions
   - Integration tests for login flow
   - Security testing for vulnerabilities

Would you like me to proceed with implementation?

Four Levels of Think Mode

Think modes tell Claude how deeply to analyze before suggesting solutions. More thinking = better solutions for complex problems.

1. Think (Standard)

  • When to use: Simple questions, straightforward tasks
  • Speed: Fast
  • Example: "How do I center a div?"

2. Think Hard

  • When to use: Medium complexity, multiple approaches possible
  • Speed: Moderate
  • Example: "What's the best way to structure my React components?"

3. Think Harder

  • When to use: Complex problems, need to consider tradeoffs
  • Speed: Slower, thorough
  • Example: "Should I use REST or GraphQL for this API?"

4. Ultra Thinking

  • When to use: Critical decisions, architecture planning
  • Speed: Slowest, most thorough
  • Example: "Design the complete architecture for a real-time chat application"

Simple Analogy: Difficulty Levels in Games

Think of Think modes like difficulty levels:

  • Think: Easy mode - quick answers for simple problems
  • Think Hard: Medium - considers multiple options
  • Think Harder: Hard - deep analysis of tradeoffs
  • Ultra Thinking: Expert - exhaustive exploration of all possibilities

Use the level that matches your problem's complexity!


Cycling Between Modes with Alt+M

Press Alt+M to switch between Plan mode and Think modes quickly.

# Keyboard shortcut
Alt+M → Cycles through: Plan → Think → Think Hard → Think Harder → Ultra Thinking → Plan...

# How it works:
1. You're in normal mode
2. Press Alt+M → Enters Plan mode
3. Press Alt+M again → Enters Think mode
4. Keep pressing → Cycles through all modes

Why cycle modes?

  • Start with Plan for the big picture
  • Switch to Think Hard for complex parts
  • Use Ultra Thinking for critical decisions
  • Adapt the thinking level to each subtask

Using the TodoWrite Tool

The TodoWrite tool helps Claude create and manage a task list for your project. It's perfect for breaking down complex work into manageable steps.

How TodoWrite Works

  1. You ask Claude to help with a complex task
  2. Claude uses TodoWrite to create a task list
  3. Each task is marked: pending, in_progress, or completed
  4. Claude updates the list as work progresses
  5. You always see what's done and what's next
# Example: Ask Claude for help
Can you help me build a blog with user authentication?

# Claude creates TodoList:
✓ [completed] Plan blog architecture
⊙ [in_progress] Create database schema
○ [pending] Build authentication system
○ [pending] Create blog post CRUD
○ [pending] Design frontend UI
○ [pending] Write tests
○ [pending] Deploy to production

Currently working on: Creating database schema

Benefits of TodoWrite:

  • See progress at a glance
  • Know exactly what's next
  • Nothing gets forgotten
  • Clear milestones and goals
  • Easy to pick up where you left off

Real-World Example: Building a Feature

Story: Jordan's Dashboard Feature

Jordan needed to add a analytics dashboard. Here's how planning helped:

Without Planning (First Attempt - Failed):

Jordan: "Add an analytics dashboard"

→ Claude starts coding immediately
→ Built charts, then realized data structure was wrong
→ Rebuilt data layer, then realized backend API didn't support it
→ 3 hours wasted, started over

With Planning (Second Attempt - Success):

Jordan: "Can you plan how to add an analytics dashboard?" (Plan mode)

→ Claude created comprehensive plan:
  1. Define required metrics
  2. Check if backend supports queries
  3. Design data structure
  4. Plan chart components
  5. Consider performance for large datasets

→ Jordan reviewed plan, caught API limitation early
→ Fixed backend first, then built frontend
→ 1 hour total, worked perfectly

TodoWrite in Action:

✓ [completed] Plan dashboard requirements
✓ [completed] Update backend API for analytics
✓ [completed] Design data structure
⊙ [in_progress] Build chart components
○ [pending] Add date range filters
○ [pending] Implement export functionality
○ [pending] Write tests

Currently on: Building chart components (50% done)

Result: Saved 2 hours by planning first. No rewrites needed!


When to Use Each Mode

Mode Best For Example
Plan Big picture, step-by-step roadmap Plan new feature architecture
Think Simple questions, quick decisions How to center a div
Think Hard Multiple approaches, tradeoffs Choose between SQL vs NoSQL
Think Harder Complex problems, deep analysis Optimize slow database queries
Ultra Thinking Critical architecture decisions Design entire system architecture

Best Practices for Planning

  1. Plan Complex Tasks First

    If a task will take more than 30 minutes, plan it first. Small tasks can be done directly.

  2. Review Plans Before Implementation

    Read Claude's plan carefully. Catch issues in planning phase, not coding phase.

  3. Use Higher Think Modes for Critical Decisions

    Database choice, architecture decisions, security implementations → Think Harder or Ultra Thinking

  4. Break Down the TodoList

    Each todo item should be completable in one session. Big tasks should be broken into smaller pieces.

  5. Update TodoList as You Go

    When you discover new requirements, add them to the list immediately. Keep the list accurate.

Simple Analogy: GPS Navigation

Planning is like using GPS:

  • Plan Mode: See the entire route before starting
  • TodoList: Turn-by-turn directions
  • Think Modes: GPS recalculating when you hit traffic
  • Without Planning: Driving randomly hoping to find destination

You'll get there faster with a plan!


Key Takeaways

  • Plan mode creates step-by-step roadmaps before coding
  • Four Think modes: Think, Think Hard, Think Harder, Ultra Thinking
  • Use Alt+M to cycle between Plan and Think modes
  • TodoWrite tool breaks complex tasks into manageable steps
  • Planning saves time by catching problems early
  • Match thinking level to problem complexity

Common Questions

When should I use Plan mode vs just start coding?

Use Plan mode when: the task is complex, you're not sure of the best approach, or the task will take more than 30 minutes. Skip planning for simple, straightforward tasks like fixing a typo or changing a color.

Do I need to use Ultra Thinking for everything?

No! Ultra Thinking is slowest and best for critical decisions like architecture or security. Use Think or Think Hard for most daily tasks. Match the thinking level to the problem importance.

Can I modify Claude's plan?

Absolutely! Claude's plans are suggestions. Review them, modify as needed, and tell Claude about changes. You're in charge - Claude adapts to your decisions.

What if I start coding and realize I should have planned?

It's okay! Stop coding, press Alt+M to enter Plan mode, and say "Can you help me plan the rest of this feature?" Claude will create a plan for the remaining work.

Does TodoWrite work across sessions?

TodoLists are per-session. When you exit Claude Code, the list is gone. For permanent todos, ask Claude to create a TODO.md file in your project that persists.


Common Mistakes to Avoid

  1. Skipping planning for complex features

    "I'll figure it out as I go" leads to rewrites. If it's complex, plan first!

  2. Using Ultra Thinking for simple questions

    Wastes time. Save deep thinking for important decisions, use quick Think mode for simple questions.

  3. Not reviewing plans before starting

    Read Claude's plan! Catch issues early before writing code.

  4. Ignoring the TodoList

    TodoList keeps you organized. Refer to it frequently to stay on track.

  5. Planning but never executing

    Plans are useless without action. Plan, then code. Don't over-plan!


What's Next?

Excellent! You now know how to plan effectively before coding.

Coming up in Chapter 6:

  • Creating custom slash commands
  • Setting up the .claude/commands/ directory
  • Writing command files (.md format)
  • Using custom commands with /

Chapter 6 will teach you how to create your own personalized commands!

Chapter 6: Custom Slash Commands

Quick Summary: Learn how to create your own custom commands to automate repetitive tasks.

Time to Complete: 15-20 minutes

What You'll Learn

  • What slash commands are and why they're useful
  • Setting up the .claude/commands/ directory
  • Creating custom commands with .md files
  • Using / to see and run your commands
  • Real-world command examples

What Are Slash Commands?

Slash commands are shortcuts that start with / (forward slash). They trigger specific actions or prompts. Claude Code comes with built-in commands like /help, /init, and /status. But you can also create your own custom commands!

Simple Analogy: Speed Dial

Think of slash commands like speed dial on a phone:

  • Without Speed Dial: Dial 1-555-123-4567 every time you call mom
  • With Speed Dial: Press 1, instantly connects

Slash commands work the same way:

  • Without Custom Command: Type "Can you review my code for accessibility issues, check WCAG compliance, suggest improvements..." every time
  • With Custom Command: Type /accessibility-check - instant, consistent prompt

Why create custom commands?

  • Save time on repetitive requests
  • Ensure consistent prompts for your team
  • Capture best practices in reusable commands
  • Share workflows with teammates
  • Automate complex multi-step prompts

Setting Up Commands Directory

First, you need to create the directory where commands live. This is a one-time setup.

Terminal Way

# Navigate to your project
cd /path/to/your/project

# Create .claude directory if it doesn't exist
mkdir -p .claude/commands

# Verify it was created
ls -la .claude/

VS Code Way

  1. Open your project in VS Code
  2. Right-click in the Explorer panel
  3. Select "New Folder"
  4. Name it .claude
  5. Inside .claude, create another folder: commands
  6. Your structure should be: .claude/commands/

What is this directory for?

  • .claude/ - Main Claude Code configuration directory
  • .claude/commands/ - Where your custom commands live
  • Each command is a separate .md file in this folder

Creating Your First Custom Command

Commands are simple markdown files. The filename becomes the command name, and the content is the prompt Claude receives.

Example: Create an Accessibility Checker

# Create the file
# File: .claude/commands/accessibility-check.md

Review this code for accessibility issues:

1. Check for WCAG 2.1 AA compliance
2. Verify semantic HTML usage
3. Check ARIA labels and roles
4. Ensure keyboard navigation works
5. Verify color contrast ratios
6. Check alt text on images
7. Suggest specific improvements

Provide a detailed report with:
- Issues found (with line numbers)
- Severity (critical, important, minor)
- Specific fixes for each issue

How to use this command:

  1. Save the file as .claude/commands/accessibility-check.md
  2. Exit and restart Claude Code (commands load on startup)
  3. Type / in Claude Code
  4. You'll see /accessibility-check in the list
  5. Select it or type /accessibility-check
  6. Claude runs your custom prompt automatically!

Command File Structure

Let's understand how command files work:

# File naming: .claude/commands/YOUR-COMMAND-NAME.md
# The filename (without .md) becomes the command

# Examples:
accessibility-check.md    → /accessibility-check
review-pr.md              → /review-pr
write-tests.md            → /write-tests
explain-code.md           → /explain-code

# File content:
# Everything in the .md file becomes the prompt
# You can use markdown formatting
# Be specific and detailed
# Think of it as instructions to Claude

Best practices for command content:

  • Be specific and clear
  • Use numbered lists for multi-step instructions
  • Include examples if helpful
  • Specify desired output format
  • Keep commands focused on one task

Real-World Command Examples

Example 1: Code Review Command

# File: .claude/commands/review-pr.md

Review this pull request thoroughly:

**Code Quality:**
- Check for code smells and anti-patterns
- Verify proper error handling
- Look for potential bugs
- Check code duplication

**Best Practices:**
- Verify naming conventions
- Check for proper comments
- Look for TODOs or FIXMEs
- Verify consistent code style

**Performance:**
- Identify potential performance issues
- Check for unnecessary re-renders (React)
- Look for inefficient algorithms

**Security:**
- Check for security vulnerabilities
- Verify input validation
- Look for SQL injection risks
- Check authentication/authorization

Provide feedback in this format:
[GOOD] What's working well
[IMPROVE] What needs improvement
[CRITICAL] Issues that must be fixed

Example 2: Test Generation Command

# File: .claude/commands/write-tests.md

Write comprehensive tests for this code:

**Test Coverage:**
1. Happy path scenarios
2. Edge cases
3. Error handling
4. Boundary conditions

**Test Structure:**
- Use descriptive test names
- Follow AAA pattern (Arrange, Act, Assert)
- Include setup and teardown if needed
- Add comments for complex test logic

**Requirements:**
- Aim for 80%+ code coverage
- Test both success and failure cases
- Mock external dependencies
- Use appropriate assertions

Please generate tests in [Jest/Mocha/your testing framework].

Example 3: Documentation Generator

# File: .claude/commands/document-code.md

Generate comprehensive documentation for this code:

**Function/Class Documentation:**
- Purpose and description
- Parameters with types and descriptions
- Return values with types
- Usage examples
- Edge cases and gotchas

**Format:**
Use JSDoc style comments:
- @param for parameters
- @returns for return values
- @example for usage examples
- @throws for potential errors

Keep documentation:
- Clear and concise
- Beginner-friendly
- Up-to-date with code
- Include real examples

Using Your Custom Commands

Once commands are created, using them is simple!

Terminal Way

# See all available commands
/

# Use a specific command
/accessibility-check

# Commands work like built-in commands
/review-pr
/write-tests
/document-code

VS Code Way

  1. Type / in Claude Code panel
  2. Dropdown shows all commands (built-in + custom)
  3. Your custom commands appear in the list
  4. Select the command you want
  5. Claude executes the prompt from your .md file

Simple Analogy: Restaurant Menu

Slash commands are like a restaurant menu:

  • Built-in commands: Standard menu items (everyone has them)
  • Custom commands: Daily specials (unique to your restaurant)
  • / (slash): Opening the menu to see all options
  • Selecting a command: Ordering from the menu

Both built-in and custom commands appear together - one unified menu!


Real-World Example: Team Workflow

Story: The Frontend Team's Custom Commands

A 5-person team created custom commands to standardize their workflow:

Commands They Created:

  1. /component-review - Check React components for best practices
  2. /a11y-check - Accessibility audit (WCAG AA)
  3. /performance-audit - Find performance bottlenecks
  4. /write-story - Generate Storybook stories
  5. /update-docs - Update component documentation

Before Custom Commands:

  • Each developer wrote different prompts for the same task
  • Reviews were inconsistent (different checklist each time)
  • New team members didn't know what to check
  • Best practices weren't documented

After Custom Commands:

  • Everyone uses /component-review - same thorough checklist
  • Consistent code quality across the team
  • New developers just use existing commands
  • Commands themselves document best practices
  • 30% faster code reviews (no need to type repetitive prompts)

Team Commands in Git:

# .gitignore - DON'T ignore .claude/commands/
# These should be committed for the team

.claude/commands/component-review.md
.claude/commands/a11y-check.md
.claude/commands/performance-audit.md
.claude/commands/write-story.md
.claude/commands/update-docs.md

# Result: New team members get all commands automatically!

Result: Team velocity increased, quality improved, onboarding time cut in half!


Best Practices for Custom Commands

  1. Use Descriptive Names
    • /check.md (too vague)
    • /accessibility-check.md (clear purpose)
  2. Keep Commands Focused

    One command = one task. Don't combine unrelated checks into one command.

  3. Include Output Format

    Tell Claude how you want results formatted (list, table, report, etc.)

  4. Document in the Command

    Add comments at the top explaining when to use this command

  5. Commit Team Commands

    Add .claude/commands/ to git so the team shares workflows

  6. Update Commands Regularly

    As your workflow evolves, update commands to reflect new best practices


Advanced: Commands with Context

Commands can reference the current file or selection:

# File: .claude/commands/optimize-function.md

Optimize the selected function for:

1. **Performance:**
   - Reduce time complexity if possible
   - Minimize memory allocations
   - Cache repeated computations

2. **Readability:**
   - Add clear variable names
   - Break into smaller helper functions if complex
   - Add comments for non-obvious logic

3. **Maintainability:**
   - Follow project coding standards
   - Make it easier to test
   - Reduce coupling with other code

Show before/after comparison with explanations of improvements.

How this works:

  1. Select a function in your code
  2. Run /optimize-function
  3. Claude sees your selection and applies the prompt to it
  4. You get optimized code with explanations

Key Takeaways

  • Slash commands are shortcuts that start with /
  • Create custom commands in .claude/commands/ directory
  • Each command is a .md file (filename = command name)
  • File content becomes the prompt Claude receives
  • Use / to see all commands (built-in + custom)
  • Commit team commands to git for shared workflows

Common Questions

Do I need to restart Claude Code after creating a command?

Yes! Commands are loaded when Claude Code starts. After creating or modifying a command file, exit Claude Code and restart it to see your new commands in the / menu.

Can command names have spaces?

Use hyphens instead of spaces. For example: "accessibility-check.md" not "accessibility check.md". Hyphens make commands easier to type and work better with auto-complete.

Should I commit .claude/commands/ to git?

Yes for team commands! Committing them means everyone on your team gets the same commands automatically. This standardizes workflows and shares best practices. For personal commands, you can git ignore them.

Can commands call other commands?

Not directly. Each command is independent. However, you can create a command that asks Claude to perform multiple tasks, effectively combining multiple checks into one comprehensive command.

What's the difference between commands and memory?

Memory (claude.md) is always active - Claude reads it automatically. Commands are on-demand - you trigger them with /. Use memory for "always remember this" and commands for "do this when I ask."


Common Mistakes to Avoid

  1. Forgetting to restart after creating commands

    Commands load on startup. Exit and restart Claude Code to see new commands.

  2. Using spaces in command names

    Use hyphens: "write-tests.md" not "write tests.md"

  3. Making commands too broad

    Keep commands focused. Don't combine "review code, write tests, update docs" into one command.

  4. Not specifying output format

    Tell Claude how you want results. Specify "provide a list" or "create a table" etc.

  5. Creating personal commands in team projects

    Team commands should be universally useful. Personal preferences go in your personal .claude/commands/


What's Next?

Excellent! You can now create custom commands to automate your workflow.

Coming up in Chapter 7:

  • What are MCP Servers?
  • Installing MCP servers with claude mcp add
  • Popular servers: Supabase, Playwright, and more
  • Using external tools through MCP

Chapter 7 will teach you how to connect Claude to external services!

Chapter 7: MCP Servers

Quick Summary: Learn how to extend Claude Code with MCP servers to connect to external services and tools.

Time to Complete: 20-25 minutes

What You'll Learn

  • What MCP (Model Context Protocol) is and why it matters
  • Installing MCP servers with claude mcp add
  • Popular servers: Supabase, Playwright, Filesystem, and more
  • Using MCP tools in Claude Code
  • Real-world integration examples

What is MCP?

MCP stands for Model Context Protocol. It is a way for Claude Code to connect to external services and tools. Think of MCP as a universal adapter that lets Claude talk to databases, browsers, APIs, and other software.

Simple Analogy: Power Adapters

Imagine you travel to different countries:

  • Without Adapter: Your phone charger doesn't fit the wall socket
  • With Universal Adapter: One adapter works with all socket types

MCP is like a universal adapter for Claude Code:

  • Without MCP: Claude can't directly access your database, browser, or external APIs
  • With MCP: Install a server, and Claude can interact with that service

What can MCP servers do?

  • Access databases (Supabase, PostgreSQL, MongoDB)
  • Control browsers (Playwright, Puppeteer)
  • Read/write files on your computer
  • Fetch data from APIs
  • Interact with cloud services (AWS, Google Cloud)
  • And much more!

Why Use MCP Servers?

MCP servers extend Claude's abilities beyond just reading and writing code files.

Without MCP Servers:

  • Claude can only work with local files in your project
  • You manually fetch data from databases
  • You copy-paste data between tools
  • Limited to basic file operations

With MCP Servers:

  • Claude queries your database directly
  • Claude tests your website in real browsers
  • Claude interacts with cloud services
  • Claude accesses external APIs automatically

Simple Analogy: Phone Apps

Think of your phone:

  • Phone without apps: Can only make calls and send texts
  • Phone with apps: Can do banking, navigation, shopping, photo editing, etc.

MCP servers are like apps for Claude Code:

  • Claude without MCP: Can only edit local code files
  • Claude with MCP: Can access databases, browsers, APIs, cloud services, and more

Installing MCP Servers

Installing MCP servers is easy with the built-in command: claude mcp add

Terminal Way

# Install an MCP server
claude mcp add [server-name]

# Example: Install Supabase server
claude mcp add supabase

# Example: Install Playwright server
claude mcp add playwright

# See all available servers
claude mcp list

VS Code Way

  1. Open VS Code
  2. Open the Terminal (View → Terminal)
  3. Type claude mcp add [server-name]
  4. Press Enter to install
  5. Restart Claude Code to activate the server

What happens when you install an MCP server?

  1. Claude downloads the server package
  2. Creates configuration in ~/.claude/mcp-servers.json
  3. Adds new tools that Claude can use
  4. You restart Claude Code to load the new tools

Pro Tip: Always restart Claude Code after installing an MCP server. The server loads on startup, so a restart is required to see new tools!


Popular MCP Servers

Let's explore some commonly used MCP servers and what they do:

1. Supabase Server

What it does: Connects Claude to your Supabase database

  • Query database tables
  • Create, read, update, delete records
  • Run SQL queries
  • Manage database schema
# Install Supabase server
claude mcp add supabase

# Restart Claude Code
# Then you can ask:
"Show me all users from the database"
"Add a new product with name 'Widget' and price 29.99"
"Update user email where id = 5"

2. Playwright Server

What it does: Controls web browsers for testing

  • Open websites in real browsers
  • Click buttons and fill forms
  • Take screenshots
  • Test responsive design
  • Verify UI behavior
# Install Playwright server
claude mcp add playwright

# Restart Claude Code
# Then you can ask:
"Open my website and take a screenshot of the homepage"
"Test the login form with test credentials"
"Check if the mobile menu works on small screens"

3. Filesystem Server

What it does: Reads/writes files anywhere on your computer

  • Access files outside project folder
  • Read system files
  • Batch file operations
  • Search across directories
# Install Filesystem server
claude mcp add filesystem

# Restart Claude Code
# Then you can ask:
"Read the file at /Users/name/Documents/notes.txt"
"Find all .pdf files in my Downloads folder"
"Copy images from Desktop to project/assets/"

4. GitHub Server

What it does: Interacts with GitHub repositories

  • Create issues and pull requests
  • Read repository information
  • Manage branches
  • Review code changes

5. AWS Server

What it does: Manages AWS cloud services

  • Deploy applications to AWS
  • Manage S3 buckets
  • Check Lambda functions
  • View EC2 instances

Finding More Servers: Run claude mcp list to see all available servers. New servers are added regularly by the community!


Using MCP Tools

Once an MCP server is installed, Claude automatically gets new tools. You use them just by asking Claude naturally!

Example: Using Supabase Server

# After installing and restarting:
claude mcp add supabase
# Restart Claude Code

# You can now ask:
"What tables are in my database?"

# Claude uses the Supabase MCP tool automatically
# You see results like:
Tables found:
- users (5 columns)
- products (8 columns)
- orders (6 columns)

What happens behind the scenes:

  1. You ask Claude a question about your database
  2. Claude recognizes this needs database access
  3. Claude uses the Supabase MCP tool (automatically)
  4. Tool connects to your database
  5. Tool fetches the data
  6. Claude presents the results to you

Example: Using Playwright Server

# After installing and restarting:
claude mcp add playwright
# Restart Claude Code

# You can now ask:
"Open localhost:3000 and click the login button"

# Claude uses Playwright MCP tool:
1. Opens browser (Chrome, Firefox, etc.)
2. Navigates to localhost:3000
3. Finds the login button
4. Clicks it
5. Reports what happened

Simple Analogy: Voice Assistant with Smart Home

Using MCP servers is like voice assistants with smart home devices:

  • Without Smart Home: "Turn on the lights" → Assistant says "I can't do that"
  • With Smart Home: "Turn on the lights" → Assistant uses smart home integration → Lights turn on

Same with Claude and MCP:

  • Without MCP: "Show database users" → Claude says "I can't access databases"
  • With MCP: "Show database users" → Claude uses Supabase MCP → Shows users

Real-World Example: Full-Stack Development

Story: Emma's E-Commerce Project

Emma was building an e-commerce site. Here's how MCP servers helped her workflow:

Morning: Database Work (Supabase MCP)

Emma: "Show me all products with price over $100"

→ Supabase MCP tool queries database
→ Returns 23 products

Emma: "Update product 'Premium Widget' to $89.99"

→ Supabase MCP tool updates record
→ Confirms success

Afternoon: UI Testing (Playwright MCP)

Emma: "Open the site and test the checkout flow"

→ Playwright opens browser
→ Adds item to cart
→ Goes through checkout steps
→ Takes screenshots at each step
→ Reports: "Checkout works! Found 1 issue: Tax calculation shows $0"

Evening: File Management (Filesystem MCP)

Emma: "Find all product images over 1MB and compress them"

→ Filesystem MCP scans directories
→ Finds 47 large images
→ Claude writes compression script
→ Saves 15MB of space

Result: Emma completed database queries, UI testing, and file management without leaving Claude Code. Everything integrated seamlessly!


MCP Server Configuration

When you install an MCP server, configuration is stored in ~/.claude/mcp-servers.json

# Example: mcp-servers.json
{
  "servers": {
    "supabase": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-supabase"],
      "env": {
        "SUPABASE_URL": "https://your-project.supabase.co",
        "SUPABASE_KEY": "your-anon-key"
      }
    },
    "playwright": {
      "command": "npx",
      "args": ["-y", "@anthropic/mcp-server-playwright"]
    }
  }
}

What's in the config file:

  • command: How to run the server (usually npx)
  • args: Arguments passed to the command
  • env: Environment variables (API keys, URLs, etc.)

When you need to edit this file:

  • Adding API keys for services
  • Changing server URLs
  • Disabling a server temporarily
  • Configuring server-specific options

Security Tip: Never commit mcp-servers.json to git if it contains API keys or secrets. Keep this file in your home directory (it is by default) and add sensitive values to environment variables.


Permission System with MCP

Just like Claude's built-in tools, MCP tools require permission for sensitive operations.

How Permissions Work with MCP:

  1. You ask Claude to do something requiring MCP (e.g., "Query my database")
  2. Claude identifies which MCP tool to use (Supabase tool)
  3. Claude asks: "May I use the Supabase tool to query your database?"
  4. You approve: Yes, Yes for session (Alt+M), or No (Esc)
  5. Claude executes the MCP tool
  6. Results are shown to you

Why MCP tools need permission:

  • Database operations can modify data
  • Browser automation can interact with live sites
  • File operations can change your system
  • API calls might cost money or have rate limits

Remember: You are always in control. Claude cannot use MCP tools without your explicit approval, just like built-in tools!


Best Practices for MCP Servers

  1. Install Only What You Need

    Don't install every MCP server. Install only the ones relevant to your current project. Too many servers can slow down Claude Code startup.

  2. Keep API Keys Secure

    Store API keys in environment variables, not directly in mcp-servers.json. Use .env files and never commit secrets to git.

  3. Restart After Installation

    Always exit and restart Claude Code after installing or configuring MCP servers. They load on startup.

  4. Review Permissions Carefully

    MCP tools can interact with external services. Review what Claude plans to do before approving, especially for database writes or API calls.

  5. Test in Development First

    When using MCP servers with databases or APIs, test on development/staging environments before production.

  6. Document Server Usage

    Add notes to your project's claude.md about which MCP servers are needed and how to configure them. Helps team onboarding!


Troubleshooting MCP Servers

Problem: Server Not Showing Up After Installation

Solution: Did you restart Claude Code? Servers only load on startup.

Problem: MCP Tool Fails with "Connection Error"

Solution: Check your API keys and URLs in ~/.claude/mcp-servers.json. Make sure environment variables are set correctly.

Problem: Don't Know Which Server to Use

Solution: Run claude mcp list to see all available servers with descriptions. Read the server documentation for details.

Problem: Server Installed But Claude Doesn't Use It

Solution: Be specific in your request. Instead of "check database", say "query the users table in my database". Claude needs context to know when to use MCP tools.


Key Takeaways

  • MCP (Model Context Protocol) connects Claude to external services
  • Install servers with claude mcp add [server-name]
  • Popular servers: Supabase (database), Playwright (browser), Filesystem (files)
  • Always restart Claude Code after installing servers
  • MCP tools require permission like built-in tools
  • Configuration stored in ~/.claude/mcp-servers.json

Common Questions

Are MCP servers free?

MCP servers themselves are free to install. However, the services they connect to might have costs (like database hosting, API usage, cloud services). Check the pricing of the service you are connecting to.

Can I create my own MCP server?

Yes! MCP is an open protocol. You can create custom servers to connect Claude to any service. Check the MCP documentation for developer guides on building servers.

Do MCP servers work offline?

It depends on the server. Filesystem server works offline. Servers that connect to cloud services (Supabase, AWS, GitHub) require internet connection to function.

Can I uninstall an MCP server?

Yes! Run claude mcp remove [server-name] to uninstall a server. Or manually delete its entry from ~/.claude/mcp-servers.json and restart Claude Code.

Will MCP servers slow down Claude Code?

Each server adds slight startup time since they load when Claude Code starts. Install only the servers you actively use. You can always install more later when needed.


Common Mistakes to Avoid

  1. Forgetting to restart after installation

    MCP servers load on startup. Always exit and restart Claude Code after installing or configuring servers.

  2. Committing API keys to git

    Never put API keys directly in code or config files that get committed. Use environment variables instead.

  3. Installing too many servers

    Only install servers you actively use. Too many can slow startup and clutter your tool options.

  4. Being vague in requests

    Claude needs context to use MCP tools. Say "query users table" not just "check database".

  5. Testing on production first

    Always test MCP integrations on development environments before using with production databases or services.


What's Next?

Excellent! You now understand how to extend Claude Code with MCP servers.

Coming up in Chapter 8:

  • What are sub-agents?
  • Using the Task tool to launch agents
  • Specialized agent types
  • Running agents in parallel

Chapter 8 will teach you how to use specialized AI agents for complex tasks!

Chapter 8: Sub-Agents

Quick Summary: Learn how to use specialized AI agents for complex, multi-step tasks.

Time to Complete: 15-20 minutes

What You'll Learn

  • What sub-agents are and when to use them
  • Using the Task tool to launch agents
  • Available agent types (general-purpose, Explore, etc.)
  • Running agents in parallel for efficiency
  • Best practices for agent delegation

What Are Sub-Agents?

Sub-agents are specialized AI assistants that Claude can create to handle specific tasks. Think of them as expert team members that Claude delegates work to when you have complex, multi-step projects.

Simple Analogy: Movie Production

Imagine making a movie:

  • Without Specialists: Director does everything - acts, films, edits, designs costumes, composes music. Takes forever!
  • With Specialists: Director delegates to actors, cinematographer, editor, costume designer, composer. Each expert focuses on their specialty. Much faster and better quality!

Claude works the same way with sub-agents:

  • Without Sub-Agents: Claude does everything sequentially
  • With Sub-Agents: Claude delegates specialized tasks to expert agents who work independently and in parallel

Why use sub-agents?

  • Handle complex multi-step tasks autonomously
  • Run multiple operations in parallel
  • Specialized agents are better at their specific tasks
  • Keep your main conversation clean and focused
  • Agents can work in the background while you continue

The Task Tool

The Task tool is how Claude launches sub-agents. You don't call it directly - Claude uses it automatically when needed, or you can explicitly ask Claude to use an agent.

How the Task Tool Works:

  1. You give Claude a complex task
  2. Claude recognizes it would benefit from a sub-agent
  3. Claude uses the Task tool to launch a specialized agent
  4. Agent works autonomously in the background
  5. Agent returns results when done
  6. Claude incorporates results into your conversation
# You don't type this - Claude does it automatically
# But here's what happens behind the scenes:

You: "Search the codebase for all API endpoints and document them"

→ Claude thinks: This needs exploration of many files
→ Claude uses Task tool to launch "Explore" agent
→ Agent searches codebase thoroughly
→ Agent finds all endpoints
→ Agent returns comprehensive list
→ Claude formats results for you

Available Agent Types

Claude Code has several specialized agent types, each designed for specific tasks:

1. General-Purpose Agent

Best for: Complex multi-step tasks, code searches, autonomous work

  • Researches complex questions
  • Searches for code across files
  • Handles multi-step workflows
  • Has access to all tools
# When to use:
"Research how authentication works in this codebase and suggest improvements"
"Find all database queries and check for SQL injection vulnerabilities"
"Analyze the testing strategy and recommend additions"

2. Explore Agent

Best for: Fast codebase exploration, finding patterns, searching keywords

  • Quick file pattern searches (e.g., "src/components/**/*.tsx")
  • Keyword searches across code (e.g., "API endpoints")
  • Understanding codebase structure
  • Tools: Glob, Grep, Read, Bash
# When to use:
"Find all React components that use useState"
"Search for error handling patterns"
"What files contain database connections?"

Thoroughness Levels for Explore Agent:

  • quick: Basic searches, fast results
  • medium: Moderate exploration, balanced speed/thoroughness
  • very thorough: Comprehensive analysis across multiple locations

When Claude Uses Sub-Agents Automatically

Claude is smart about when to use sub-agents. Here are situations where Claude automatically launches agents:

Scenario 1: Broad Codebase Searches

You: "Where are errors handled in the client code?"

→ Claude uses Explore agent (not direct search)
→ Agent searches for error patterns
→ Agent checks multiple files
→ Returns comprehensive findings

Scenario 2: Multi-File Analysis

You: "Analyze how API endpoints work across the codebase"

→ Claude uses General-Purpose agent
→ Agent searches routes, controllers, models
→ Agent understands the flow
→ Returns architecture explanation

Scenario 3: Complex Research

You: "Research the authentication system and check for security issues"

→ Claude uses General-Purpose agent
→ Agent reads auth files
→ Agent checks for vulnerabilities
→ Agent suggests improvements
→ Returns security audit report

Simple Analogy: Restaurant Kitchen

Think of Claude as the head chef:

  • Simple order (pasta): Head chef makes it directly
  • Complex order (5-course meal): Head chef delegates to specialists - sous chef, pastry chef, grill chef - each works on their part simultaneously

Same with tasks:

  • Simple (fix typo): Claude does it directly
  • Complex (research codebase): Claude delegates to specialist agents

Explicitly Requesting Agents

You can also explicitly ask Claude to use an agent:

# Explicitly request Explore agent
"Use the Explore agent to find all TypeScript interfaces"

# Request General-Purpose agent
"Launch an agent to research the testing infrastructure"

# Specify thoroughness
"Use a very thorough Explore agent to find all authentication code"

When to explicitly request agents:

  • You know the task needs deep exploration
  • You want work done in the background
  • You need a specific thoroughness level
  • Previous attempt wasn't thorough enough

Running Agents in Parallel

One of the most powerful features: Claude can run multiple agents simultaneously!

How Parallel Agents Work:

You: "Analyze both the frontend and backend architecture in parallel"

→ Claude launches TWO agents simultaneously:
  Agent 1: Explores frontend (React components, state, routing)
  Agent 2: Explores backend (API routes, database, services)

→ Both agents work at the same time
→ Results come back when both are done
→ Claude combines findings into one report

Result: 2x faster than sequential analysis!

Benefits of parallel agents:

  • Much faster for multi-part tasks
  • Each agent focuses on one thing
  • No waiting for sequential operations
  • Better resource utilization

Pro Tip: When you have independent tasks, explicitly mention "in parallel" to ensure Claude runs agents simultaneously: "Analyze the frontend and backend in parallel."


Real-World Example: Code Refactoring

Story: Marcus's Legacy Codebase

Marcus inherited a 50,000-line codebase with no documentation. Here's how sub-agents helped:

Task 1: Understanding the Structure

Marcus: "What is the structure of this codebase?"

→ Claude launched Explore agent (medium thoroughness)
→ Agent searched directory structure
→ Agent identified patterns
→ Result: Clear map of modules, components, services

Task 2: Finding Security Issues

Marcus: "Search for potential security vulnerabilities"

→ Claude launched General-Purpose agent
→ Agent searched for SQL injection risks
→ Agent checked for XSS vulnerabilities
→ Agent looked for hardcoded secrets
→ Result: List of 12 security issues with fixes

Task 3: Parallel Analysis

Marcus: "Analyze the authentication system AND the database layer in parallel"

→ Claude launched TWO agents simultaneously:
  Agent 1: Auth system analysis
  Agent 2: Database layer analysis

→ Both completed in 3 minutes
→ Sequential would have taken 6 minutes

→ Result: Comprehensive analysis of both systems

Outcome: Marcus understood the entire codebase in 2 hours instead of 2 weeks. Found and fixed critical security issues. Sub-agents made the impossible possible!


Agent Isolation and Safety

Sub-agents work in isolation for your safety:

What Isolation Means:

  • Each agent is independent
  • Agents cannot see your main conversation
  • Agents work with limited context
  • Results are reviewed before being shown to you

Why This Matters:

  • Safety: Agents can't accidentally access sensitive conversation history
  • Focus: Agents stay focused on their specific task
  • Efficiency: Less context means faster processing
  • Control: Claude manages agent results before presenting to you

Best Practices for Sub-Agents

  1. Let Claude Decide Automatically

    Claude knows when agents are beneficial. Trust the automatic decisions for most tasks.

  2. Be Specific About Thoroughness

    For Explore agents, specify: "quick search", "medium exploration", or "very thorough analysis"

  3. Request Parallel for Independent Tasks

    Say "in parallel" when tasks are independent: "Analyze frontend and backend in parallel"

  4. Break Down Very Large Tasks

    Instead of "analyze everything", break it into specific questions for better agent focus

  5. Review Agent Results

    Agents are powerful but not perfect. Review findings and ask follow-up questions if needed


When NOT to Use Sub-Agents

Sub-agents aren't always the answer. Avoid for:

  • Simple Tasks: "Fix this typo" doesn't need an agent
  • Single File Operations: "Review login.js" - Claude can do this directly
  • Quick Questions: "What does this function do?" - Direct answer is faster
  • Specific Known Locations: "Read src/utils/api.js" - Use Read tool directly

Simple Analogy: Asking for Help

Think of when you ask for help:

  • Don't need help: "What time is it?" - Just look at your watch
  • Need help: "Plan my entire vacation to Europe" - Get a travel agent

Same with agents:

  • Don't need agent: Simple, direct tasks
  • Need agent: Complex research, multi-file analysis, broad searches

Monitoring Agent Progress

When an agent is working, Claude keeps you informed:

# You'll see messages like:
"Launching Explore agent to search the codebase..."
"Agent is analyzing 47 files..."
"Agent found 23 matching patterns..."
"Agent completed. Here are the findings..."

What you can do while agents work:

  • Continue your conversation with Claude
  • Ask other questions
  • Work on different files
  • Agents work in the background

Key Takeaways

  • Sub-agents are specialized AI assistants for complex multi-step tasks
  • Main types: General-Purpose (all tasks) and Explore (fast searches)
  • Claude uses Task tool to launch agents automatically or on request
  • Agents can run in parallel for faster results
  • Agents work in isolation for safety and focus
  • Let Claude decide when to use agents - trust the automation

Common Questions

How many agents can run at the same time?

Claude can run multiple agents in parallel. The exact number depends on system resources, but typically 2-4 agents can run simultaneously for optimal performance.

Do agents require approval like tools?

The Task tool itself doesn't require approval - it's a read-only research tool. However, if agents want to make changes (Edit, Write, Bash), those individual tools still require your permission.

Can I see what an agent is doing in real-time?

Claude provides status updates as agents work ("Agent analyzing...", "Agent found..."). You see high-level progress but not every individual action the agent takes.

What if an agent gets stuck or takes too long?

Agents have timeouts to prevent infinite loops. If an agent takes too long, Claude will notify you and you can retry with different parameters or a more specific request.

Can agents access my entire file system?

No. Agents work within your project directory by default, just like Claude. They respect the same boundaries and permission system as the main Claude instance.


Common Mistakes to Avoid

  1. Requesting agents for simple tasks

    Don't use agents for "fix typo" or "read one file". Direct actions are faster for simple tasks.

  2. Being too vague in agent requests

    Instead of "search everything", say "search for authentication code in the backend".

  3. Not specifying parallelism when needed

    Say "in parallel" explicitly if you want simultaneous execution, otherwise Claude might run tasks sequentially.

  4. Expecting agents to remember previous conversations

    Agents are isolated. They don't see your conversation history. Give them complete instructions.

  5. Not breaking down massive tasks

    Instead of "analyze the entire codebase", break it into focused questions for better results.


What's Next?

Great work! You now understand how to use sub-agents for complex tasks.

Coming up in Chapter 9:

  • Installing the GitHub app
  • Automatic PR reviews and suggestions
  • Fixing issues directly from GitHub
  • Team collaboration features

Chapter 9 will show you how Claude integrates with GitHub for team workflows!

Chapter 9: GitHub Integration

Quick Summary: Learn how Claude integrates with GitHub for automatic PR reviews, issue fixes, and team collaboration.

Time to Complete: 20-25 minutes

What You'll Learn

  • Installing the Claude Code GitHub app
  • Automatic pull request reviews and suggestions
  • Fixing GitHub issues directly with Claude
  • Using gh CLI for GitHub operations
  • Team collaboration workflows with Claude

Why Integrate Claude with GitHub?

GitHub is where teams collaborate on code. Claude Code integrates with GitHub to help your entire team work better together.

Simple Analogy: Shared Document Editor

Think of writing a document with your team:

  • Without Integration: Everyone emails Word files back and forth. Version confusion. Lost changes. No history.
  • With Integration: Google Docs - everyone edits the same document. Real-time changes. Complete history. Comments and suggestions.

Claude + GitHub works similarly:

  • Without Integration: Claude helps you locally. Manual PR reviews. Copy-paste between tools.
  • With Integration: Claude reviews PRs automatically. Fixes issues from GitHub. Team sees Claude's suggestions.

Benefits of GitHub integration:

  • Automatic PR reviews with suggestions
  • Fix GitHub issues without leaving Claude
  • Create PRs directly from Claude
  • Team collaboration on Claude's suggestions
  • Consistent code quality across the team

Using the gh CLI

The gh CLI is GitHub's official command-line tool. Claude uses it to interact with GitHub.

What is gh CLI?

gh is a command-line interface for GitHub. It lets you do GitHub operations from your terminal - create PRs, manage issues, view repositories, and more.

Terminal Way - Basic gh Commands

# Check if gh is installed
gh --version

# Login to GitHub
gh auth login

# View current repository info
gh repo view

# List pull requests
gh pr list

# View a specific PR
gh pr view 123

# Create a new PR
gh pr create --title "Add new feature" --body "Description here"

# List issues
gh issue list

# View a specific issue
gh issue view 456

VS Code Way

  1. Open VS Code terminal (View → Terminal)
  2. Type gh commands as shown above
  3. Claude can use gh commands automatically via the Bash tool

How Claude uses gh:

When you ask Claude to interact with GitHub, it uses gh CLI commands via the Bash tool. You don't need to know all the commands - just ask Claude naturally!

# Instead of typing gh commands yourself:
You: "Show me the open pull requests"

→ Claude runs: gh pr list
→ Shows you the results in a friendly format

You: "Create a PR with the changes I just made"

→ Claude runs: gh pr create with appropriate title and description
→ Returns the PR URL

Viewing Pull Requests

Claude can fetch and display PR information from GitHub.

Example: Viewing PR Details

You: "Show me PR number 42"

→ Claude runs: gh pr view 42
→ Displays:
  - PR title and description
  - Status (open, merged, closed)
  - Author and reviewers
  - Comments and reviews
  - Files changed
  - CI/CD status

Example: Listing All PRs

You: "What pull requests are currently open?"

→ Claude runs: gh pr list --state open
→ Shows table:
  #   Title                    Author    Status
  45  Add login feature        @alice    Open
  44  Fix navbar bug           @bob      Open
  43  Update dependencies      @carol    Open

Creating Pull Requests

Claude can create PRs directly from your local changes.

The PR Creation Process:

  1. You make code changes with Claude's help
  2. Changes are committed to a branch
  3. You ask Claude to create a PR
  4. Claude generates title and description
  5. Claude runs gh pr create
  6. PR is created on GitHub
You: "Create a pull request for the authentication feature"

→ Claude analyzes your commits
→ Generates PR title: "Add user authentication with JWT"
→ Writes PR description:
  ## Summary
  - Implemented JWT-based authentication
  - Added login and logout endpoints
  - Created authentication middleware

  ## Test Plan
  - Test login with valid credentials
  - Test login with invalid credentials
  - Verify protected routes require authentication

→ Runs: gh pr create --title "..." --body "..."
→ Returns: https://github.com/yourrepo/pull/46

Pro Tip: Claude follows the PR format you learned in Chapter 4 (git commits), including the footer: "Generated with Claude Code. Co-Authored-By: Claude"


Viewing and Fixing Issues

Claude can read GitHub issues and help you fix them.

Example: Fixing a GitHub Issue

You: "Show me issue #23 and fix it"

→ Claude runs: gh issue view 23
→ Reads issue:
  Title: "Login button doesn't work on mobile"
  Description: "When I click login on iPhone, nothing happens..."

→ Claude analyzes the codebase
→ Finds the issue (missing touch event handler)
→ Fixes the code
→ Creates a commit
→ Creates a PR that closes issue #23

Example: Listing Issues

You: "What bugs do we have?"

→ Claude runs: gh issue list --label bug
→ Shows:
  #25  Cart total calculates wrong     Priority: High
  #23  Login button broken on mobile   Priority: Medium
  #18  Slow page load on dashboard     Priority: Low

Real-World Example: Team Code Review

Story: The Design System Team's Review Process

A 5-person team building a component library. Here's their Claude + GitHub workflow:

Monday Morning: Lisa Creates a PR

Lisa (in Claude): "Create a PR for the new Button component"

→ Claude generates comprehensive PR description
→ Lists all changes
→ Includes component API documentation
→ Adds usage examples
→ Creates PR: github.com/team/design-system/pull/87

Monday Afternoon: Mike Reviews the PR

Mike (in Claude): "Show me PR #87"

→ Claude fetches PR details
→ Shows component changes

Mike: "Review this PR for accessibility issues"

→ Claude analyzes the Button component
→ Finds missing ARIA labels
→ Suggests keyboard navigation improvements
→ Comments on PR with suggestions

Tuesday: Lisa Fixes Issues

Lisa: "Read the comments on PR #87 and fix the accessibility issues"

→ Claude reads PR comments
→ Adds ARIA labels
→ Implements keyboard navigation
→ Commits and pushes changes
→ Comments: "Fixed accessibility issues as suggested"

Result: PR reviewed and improved in less than a day. Team collaboration seamless. Code quality maintained. Everyone on the same page!


Working with Branches

Claude helps manage Git branches for GitHub workflows.

Common Branch Operations:

# Create a new branch
You: "Create a branch for the dark mode feature"
→ Claude runs: git checkout -b feature/dark-mode

# Switch branches
You: "Switch to the main branch"
→ Claude runs: git checkout main

# View current branch
You: "What branch am I on?"
→ Claude runs: git branch --show-current

# Push branch to GitHub
You: "Push this branch to GitHub"
→ Claude runs: git push -u origin feature/dark-mode

Branch Naming Conventions:

Claude follows common naming patterns:

  • feature/ - New features (feature/dark-mode)
  • fix/ - Bug fixes (fix/login-button)
  • docs/ - Documentation (docs/api-guide)
  • refactor/ - Code refactoring (refactor/auth-logic)
  • test/ - Test additions (test/button-component)

Handling PR Comments

Claude can read and respond to PR review comments.

# View comments on a PR
You: "Show me the comments on PR #87"

→ Claude runs: gh api repos/owner/repo/pulls/87/comments
→ Displays reviewer feedback

# Address specific feedback
You: "Fix the issue mentioned in comment #3"

→ Claude reads comment #3
→ Understands the requested change
→ Makes the fix
→ Commits with message referencing the comment

Best Practices for GitHub Integration

  1. Write Clear PR Descriptions

    Let Claude generate PR descriptions - they include summary, test plan, and proper formatting

  2. Reference Issues in PRs

    Use "Closes #23" in PR description to auto-close issues when PR merges

  3. Review Before Pushing

    Always review changes locally before creating a PR. Claude helps, but you approve.

  4. Use Descriptive Branch Names

    Follow conventions: feature/, fix/, docs/ prefixes make branches clear

  5. Keep PRs Focused

    One feature or fix per PR. Smaller PRs are easier to review and merge.

  6. Respond to Reviews Promptly

    Use Claude to quickly address review comments and push updates

Simple Analogy: Restaurant Orders

Think of PRs like restaurant orders:

  • Bad: One ticket with "1 pizza, 3 salads, 2 desserts, 5 drinks" - kitchen gets confused
  • Good: Separate tickets for appetizers, mains, desserts - kitchen works efficiently

Same with PRs:

  • Bad: One PR with "add login, fix bugs, update docs, refactor code"
  • Good: Separate PRs for each concern - reviewers can focus

Team Collaboration Workflows

Workflow 1: Feature Development

  1. Create feature branch with Claude
  2. Develop feature with Claude's help
  3. Claude creates PR with comprehensive description
  4. Team reviews PR
  5. Claude helps address review comments
  6. PR merged to main

Workflow 2: Bug Fix from Issue

  1. Team member creates GitHub issue
  2. You ask Claude: "Fix issue #25"
  3. Claude reads issue, understands problem
  4. Claude fixes bug and creates PR
  5. PR description includes "Closes #25"
  6. Issue auto-closes when PR merges

Workflow 3: Code Review Collaboration

  1. Developer creates PR
  2. Reviewer uses Claude: "Review PR #87 for security"
  3. Claude analyzes code, leaves review comments
  4. Developer uses Claude to address feedback
  5. Back-and-forth until approval
  6. PR merged with confidence

Key Takeaways

  • Claude integrates with GitHub via gh CLI for team collaboration
  • Can view, create, and manage PRs directly from Claude
  • Read and fix GitHub issues without leaving Claude
  • Automatic PR descriptions with summary and test plan
  • Team can collaborate on Claude's suggestions via PR comments
  • Follow PR best practices: focused changes, clear descriptions, prompt responses

Common Questions

Do I need to install gh CLI separately?

Yes, gh CLI must be installed and authenticated. Run "gh auth login" to connect your GitHub account. Once set up, Claude can use gh commands automatically.

Can Claude approve or merge PRs?

Claude can help you review PRs and suggest approval, but YOU make the final decision to approve or merge. This keeps humans in control of important decisions.

Will Claude's PR comments be visible to my team?

Yes! When Claude comments on PRs (with your approval), those comments appear on GitHub just like any team member's comments. Your team can see and respond to Claude's suggestions.

Can Claude work with private repositories?

Yes, as long as gh CLI is authenticated with an account that has access to the private repository. Permissions are the same as your GitHub account.

How does Claude know which issue or PR to work on?

Be specific: "Show me issue #25" or "Create a PR for these changes". Claude needs the issue/PR number or clear context about what you're working on.


Common Mistakes to Avoid

  1. Forgetting to authenticate gh CLI

    Run "gh auth login" first. Without authentication, gh commands will fail.

  2. Creating PRs with too many unrelated changes

    Keep PRs focused. One feature or fix per PR makes reviews easier and merges cleaner.

  3. Not reviewing Claude's PR descriptions

    Always read the PR description Claude generates. Edit if needed before creating the PR.

  4. Ignoring CI/CD failures

    If tests fail after creating a PR, fix them before requesting review. Claude can help debug failures.

  5. Force pushing to shared branches

    Never force push to main or branches others are working on. Coordinate with your team first.


What's Next?

Excellent! You now know how to use Claude with GitHub for team collaboration.

Coming up in Chapter 10:

  • Professional development workflows
  • When to trust AI and when to verify
  • Code quality strategies
  • Balancing speed with correctness

Chapter 10 will teach you best practices for professional Claude Code usage!

Chapter 10: Best Practices

Quick Summary: Professional workflows, when to trust AI, and maintaining code quality.

Time: 20-25 minutes

The Golden Rule: You Are in Control

Claude Code is powerful, but YOU are the developer. Always read, test, and understand code before accepting.

When to Trust vs Verify

Trust More: Boilerplate, documentation, formatting, repetitive tasks

Verify Carefully: Security, database ops, business logic, performance-critical code, third-party integrations

Effective Prompting

  • Be specific with file names and line numbers
  • Provide context about what you're trying to achieve
  • Break down complex tasks into steps
  • Specify constraints and requirements

Context Management

  • Use /clear between different tasks
  • Use @ to add only relevant files
  • Use /compact for long sessions
  • Keep claude.md updated

Code Quality

  • Always test Claude's code
  • Request explanations to understand solutions
  • Ask for alternatives
  • Start simple, then enhance

Professional Workflow

Morning: /status, review claude.md, plan tasks

During: Focused sessions, /clear when switching, commit frequently

Before Push: Review all changes, run tests, create clear PR

Key Takeaways

  • You control - Claude assists
  • Trust for low-risk, verify for critical
  • Be specific in prompts
  • Manage context actively
  • Always test before deploying
  • Balance speed with quality

Bonus 1: Advanced Techniques

Quick Summary: Power user techniques for maximum productivity with Claude Code.

Advanced Context Compaction

Auto-Compact Feature: Claude Code can automatically compact context when it gets too large. This happens behind the scenes to keep your sessions running smoothly.

Manual Compaction Strategies:

  • Use /compact before starting major tasks
  • Compact after completing multi-step features
  • Keep conversations focused on one topic at a time

Multi-Agent Workflows

Parallel Research: Launch multiple agents simultaneously to research different parts of your codebase. Ask Claude to "analyze the frontend AND backend in parallel" for 2x speed.

Sequential Agents: Use agents in sequence for multi-phase projects. First agent researches architecture, second agent finds issues, third agent suggests improvements.

Structured Note-Taking

In claude.md: Use markdown headers (# ## ###) to organize information. Claude understands structure and can find information faster.

Template Structure:

  • # Project Overview
  • ## Architecture
  • ## Code Patterns
  • ## Common Tasks
  • ## Troubleshooting

MCP Server Combinations

Database + Browser: Use Supabase MCP to query data, then Playwright MCP to test how it appears in the UI.

Filesystem + GitHub: Use Filesystem MCP to analyze local files, then GitHub MCP to create issues for problems found.

Custom Command Libraries

Command Categories: Organize your .claude/commands/ into folders by purpose:

  • /review/ - code review commands
  • /test/ - testing commands
  • /deploy/ - deployment commands
  • /debug/ - debugging commands

Advanced Prompting Patterns

The Context Sandwich: Give context, make request, specify format. Example: "This is a React app using TypeScript. Refactor this component for better performance. Return only the code, no explanation."

The Checkpoint Pattern: For complex tasks, ask Claude to stop and report after each major step. "Analyze the codebase and report findings before making changes."

Session Management

Long-Running Sessions: For multi-day projects, use /compact regularly and update claude.md with progress notes so you can resume later.

Quick Tasks: For simple one-off tasks, skip the context setup and get straight to work. Save time when appropriate.

Key Takeaways

  • Use auto-compact or manual /compact to extend sessions
  • Combine multiple agents for complex workflows
  • Structure claude.md with clear headers
  • Combine MCP servers for powerful workflows
  • Organize custom commands into categories

Bonus 2: Cheat Sheet

Quick Summary: Fast reference for all Claude Code commands, shortcuts, and patterns.

Essential Commands

CommandWhat It Does
/helpShow help and documentation
/statusShow current session status
cwdShow current working directory
/clearClear conversation history
/compactCompress context to save space
/initCreate claude.md file
/memoryShow all memory files

Keyboard Shortcuts

ShortcutAction
Alt+MCycle Plan/Think modes, approve session permissions
EscReject tool permission
EnterApprove tool permission once

Symbol Reference

SymbolPurpose
@Add files to context (@file.js, @folder/)
#Reference memory file (# for claude.md)
/Run slash command (/help, /init)

MCP Server Commands

CommandWhat It Does
claude mcp add [name]Install MCP server
claude mcp listShow available servers
claude mcp remove [name]Uninstall server

GitHub Integration

CommandWhat It Does
gh auth loginAuthenticate with GitHub
gh pr createCreate pull request
gh pr view [number]View PR details
gh issue view [number]View issue details

Common Patterns

Start New Feature:

1. /clear
2. Update # with new feature details
3. @ relevant files
4. Ask Claude to plan the feature

Debug Issue:

1. @ error log and relevant code
2. Ask Claude to analyze the error
3. Review suggested fix
4. Test the solution

Code Review:

1. @ files to review
2. Ask Claude to review for specific concerns
3. Address feedback
4. Commit changes

Quick Troubleshooting

Problem: Claude doesn't remember project details

Solution: Update claude.md with # and provide context

Problem: Running out of context space

Solution: Use /compact or /clear, focus on one task

Problem: MCP server not working

Solution: Restart Claude Code, check mcp-servers.json

Problem: Tools need permission every time

Solution: Use Alt+M for session permissions

Key Takeaways

  • Use /clear between different tasks
  • Alt+M for session permissions and mode cycling
  • @ to add files, # to reference memory
  • /compact when running low on context
  • Restart after installing MCP servers

Tutorial Complete! - 13 Chapters (0-10 + 2 Bonus)

You are now a Claude Code master. Go build amazing things!