Claude Code
The complete guide to mastering Claude Code - from absolute beginner to power user.
Chapter 0: Welcome - What is Claude Code?
Think of Claude Code as your AI coding buddy - a super-smart friend who lives right in your computer terminal (or VS Code) and helps you build anything you can imagine.
Claude Code is like having a senior developer sitting next to you who:
- Understands what you want to build from plain English descriptions
- Writes code for you
- Fixes bugs
- Explains complicated stuff in simple words
- Works on any project, any size, any language
The Magic Secret
You don't need to know how to code. You just need to know how to explain what you want in plain English!
Real Example from Anthropic
At Anthropic, the Legal team (with zero coding experience) built a communication app for a family member with speaking difficulties in just 1 hour using Claude Code. The Product Design team went from "I've never coded" to "I'm implementing complex state management changes" in days.
What Can You Build?
- Websites and web applications
- Tools that automate boring tasks
- Scripts to organize your files
- Data analysis dashboards
- Mobile apps, games, and more
Ready to get started? Let's install Claude Code and build something amazing!
Test your knowledge!
Take Chapter 0 Quiz โChapter 1: Getting Started
Installing Claude Code is simple. We'll walk through it step-by-step.
Step 1: Install Node.js
Think of Node.js as the "engine" that makes Claude Code run on your computer.
- Go to nodejs.org
- Click the big green "Download" button (choose the LTS version)
- Run the installer and keep clicking "Next"
- Done! Node.js is now installed
Step 2: Install Claude Code
Terminal Way (Mac/Linux)
Open your Terminal app and paste this command:
curl -fsSL https://claude.ai/install.sh | bash
Terminal Way (Windows)
Open PowerShell and paste this:
irm https://claude.ai/install.ps1 | iex
VS Code Extension
- Open VS Code
- Click the Extensions icon (squares on the left sidebar)
- Search for "Claude Code"
- Click "Install"
- Look for the Claude icon in your sidebar!
Step 3: Log In
Terminal
- Type:
claude - Press Enter
- It will ask you to log in - choose "Claude.ai" (recommended)
- Your browser will open - log in there
- Return to terminal - you're ready!
VS Code
- Click the Claude icon in your sidebar
- Click "Sign In"
- Browser opens - log in
- Done!
Verify Installation
Test that everything works:
claude --version
You should see a version number (like 1.0.0). If you do, congratulations! Claude Code is installed.
What's next? In Chapter 2, we'll build your first project!
Test your knowledge!
Take Chapter 1 Quiz โChapter 2: Your First Project
Let's build something! In this chapter, you'll create your first project with Claude Code - a simple "Hello World" webpage. By the end, you'll understand how to start Claude, give it instructions, and see it create files for you.
Step 1: Create a Project Folder
First, let's make a folder for your project. Think of this as your project's home.
Terminal Way
# Create a folder called "my-first-project"
mkdir my-first-project
# Go into that folder
cd my-first-project
VS Code Way
- Open VS Code
- Click "File" โ "Open Folder"
- Create a new folder called "my-first-project"
- Open that folder
Step 2: Start Claude Code
Terminal Way
Make sure you're inside your project folder, then type:
claude
You'll see Claude wake up and say hello! It might look something like this:
Claude Code v1.0.0
Ready to help! What would you like to build?
VS Code Way
- Look for the Claude icon in your left sidebar
- Click it
- Claude will open in a panel - ready to chat!
Step 3: Ask Claude to Build Something
Now for the magic! Let's ask Claude to create a simple webpage. Type this (or something similar in your own words):
Create a simple HTML webpage that says "Hello World" with a colorful gradient background and a button that shows an alert when clicked.
What happens next?
- Claude will think about what you asked
- It will propose creating an HTML file
- It will show you the code it wants to write
- It will ask for permission to create the file
Step 4: Approve Claude's Changes
Claude is polite - it won't change your files without asking! You'll see something like:
I'll create a file called index.html
[Allow] [Deny]
Click or type Allow (or just press Enter if "Allow" is highlighted).
Boom! ๐ฅ Claude just created your first file!
Step 5: Open Your Webpage
Terminal Way
# Mac
open index.html
# Windows
start index.html
# Linux
xdg-open index.html
VS Code Way
- Right-click on
index.htmlin the file explorer - Choose "Open with Live Server" (if you have the extension)
- Or just find the file on your computer and double-click it
Your browser will open and you'll see your webpage! Try clicking the button - it should show an alert!
Understanding What Just Happened
Let's break down the magic:
- You spoke in English - No code required!
- Claude understood - It knew you wanted HTML, CSS, and JavaScript
- Claude created files - It wrote all the code for you
- You approved - You stayed in control
- It worked! - You now have a real webpage
Real Example from Anthropic
The Data Science team at Anthropic used Claude Code to build a complete 5,000-line TypeScript dashboard application despite knowing "very little JavaScript and TypeScript." They gave Claude control to build entire React apps from scratch!
Try It Again!
Now that you've seen it work, try asking Claude to modify your page:
- "Change the background to a blue gradient"
- "Add a header that says 'My First Project'"
- "Make the button bigger and green"
- "Add a counter that increases each time I click the button"
Each time, Claude will:
- Read your current file
- Understand what you want changed
- Show you the changes
- Ask for permission
- Update the file
Tips for Your First Projects
- Be specific - "Make it blue" is good, but "Make the background a light blue gradient" is better
- One thing at a time - Ask for one change before asking for the next
- Look at the code - Claude shows you what it's writing. You'll start learning just by reading!
- Experiment! - You can't break anything. If something goes wrong, just ask Claude to fix it
Common Questions
What if I don't like what Claude created?
Just tell Claude! Say "Actually, can you make it different?" and describe what you want instead.
Can I edit the files myself?
Absolutely! You can edit files in any text editor, and Claude will see your changes next time you ask it something.
What if Claude asks to install something?
For simple HTML projects like this, it won't. But for bigger projects, it might ask to install libraries or tools. It's usually safe to allow these - Claude will explain what each thing does.
Congratulations!
You just built your first project with Claude Code! You've learned:
- How to create a project folder
- How to start Claude Code
- How to give Claude instructions
- How to approve changes
- How to view your creation
Ready to learn more? In Chapter 3, we'll dive deeper into how to "talk" to Claude effectively - learning about the @ symbol, screenshots, and advanced prompting techniques.
Test your knowledge!
Take Chapter 2 Quiz โChapter 3: Talking to Claude
Now that you've built your first project, let's learn how to communicate with Claude like a pro. Good communication = better results!
The Golden Rule
Talk to Claude like you're talking to a smart friend who's helping you code.
Be specific, be clear, but you don't need to be formal. Just explain what you want in plain English!
The @ Symbol - Your Superpower
The @ symbol is like pointing at something. It tells Claude "Look at THIS specific thing!"
How to Use @
When you type @, Claude shows you a list of files in your project. Pick one, and Claude will read it before answering.
Example without @:
"Add a button to the page"
Claude thinks: "Which page? Let me guess..."
Example with @:
"@index.html Add a button to the page"
Claude thinks: "Got it! I'll add a button to index.html!"
Terminal Way
claude
# When Claude is ready, type:
@index.html can you add a navigation menu?
VS Code Way
- Type your message in the Claude panel
- Type
@and a dropdown appears - Select the file you want Claude to look at
- Continue your message
What Can You @ ?
- Files:
@index.html,@app.js - Folders:
@src/(Claude looks at all files inside) - Multiple files:
@index.html @styles.css
Using Screenshots and Images
A picture is worth a thousand words! Claude can "see" images and understand what you want.
What You Can Show Claude
- Design mockups ("Make it look like this")
- Error messages (screenshots of bugs)
- UI references ("Copy this style")
- Diagrams (flowcharts, wireframes)
- Existing websites ("Clone this layout")
How to Share Images
Terminal Way:
# Take a screenshot, save it to your project folder
# Then reference it:
@screenshot.png can you recreate this design?
VS Code Way:
- Copy an image (Cmd/Ctrl + C)
- Click in the Claude chat
- Paste (Cmd/Ctrl + V)
- Add your message
- Press Enter!
Real Example from Anthropic
The Product Design team at Anthropic pastes mockup images into Claude Code and gets fully functional prototypes in minutes. They say: "Use Command+V to paste screenshots - Claude excels at reading designs and generating functional code."
Writing Effective Prompts
Here's how to get exactly what you want from Claude:
1. Be Specific
Vague: "Make it better"
Specific: "Make the text bigger, change the color to blue, and center it on the page"
2. Break Big Tasks Into Steps
Too big: "Build a complete e-commerce website"
Better:
- "Create a homepage with a hero section"
- "Add a product grid below the hero"
- "Add a shopping cart button"
- And so on...
3. Give Context
Without context: "Add validation"
With context: "Add email validation to the signup form - check that it contains @ and a domain"
4. Explain the "Why"
Just what: "Add a loading spinner"
What + why: "Add a loading spinner because the API call takes 2 seconds and users need feedback"
When Claude understands why, it makes better decisions!
Examples of Great Prompts
Example 1: Building a Feature
@app.js I want to add a dark mode toggle button in the header.
When clicked, it should:
- Change the background to dark gray
- Change text to white
- Save the preference so it persists when the page reloads
- Use smooth transitions for the color changes
Example 2: Fixing a Bug
@script.js The search function isn't working when I type special
characters like & or #. Can you fix it so it handles all characters
correctly?
Example 3: Refactoring Code
@components/ This code is getting messy. Can you:
1. Split the large UserProfile component into smaller components
2. Add comments explaining what each part does
3. Follow React best practices
Example 4: Using Images
@design-mockup.png Can you create an HTML/CSS layout that
matches this design? The header should be sticky, and the cards
should be responsive (3 columns on desktop, 1 on mobile).
Communication Tips from Anthropic Teams
From the API team: "Treat Claude as an iterative partner, not a one-shot solution. Start with minimal information and let Claude guide you."
From the Security team: "Let Claude talk first. Tell it to 'commit your work as you go' and let it work autonomously with periodic check-ins."
From the Legal team: "Use screenshots liberally to show what you want interfaces to look like. Visual communication is faster than describing in text."
From the Growth Marketing team: "Work step-by-step rather than asking for one-shot solutions. Break complex tasks into smaller pieces."
What NOT to Do
- Don't assume Claude remembers everything - Use @ to point to files
- Don't ask 10 things at once - One request at a time
- Don't be afraid to correct - Just say "Actually, can you change..."
- Don't use code in your prompts - Describe what you want, not how to code it
Special Phrases That Work Well
These phrases help Claude understand your intent:
- "Can you..." - Polite and clear
- "I want to..." - States your goal
- "This isn't working..." - Flags problems
- "Can you explain..." - Asks for learning
- "Similar to... but..." - References examples
- "Step by step..." - Requests breakdown
Quick Reference
| Want to... | Say this... |
|---|---|
| Point to a file | @filename.ext |
| Point to multiple files | @file1.js @file2.js |
| Point to a folder | @foldername/ |
| Share an image | Paste it (Cmd/Ctrl + V) |
| Get an explanation | "Can you explain how this works?" |
| Fix a bug | "This isn't working: [describe issue]" |
Practice Exercise
Try these prompts in your project from Chapter 2:
- Use @:
@index.html can you add a footer with your name? - Be specific:
Change the button color to #3498db (blue) and make it rounded with 8px border radius - Give context:
Add a click counter that shows how many times the button was clicked - this will help users see the button is working
Key Takeaways
- Use
@to point Claude to specific files - Share screenshots and images with copy-paste
- Be specific about what you want
- Break big tasks into smaller steps
- Explain the "why" behind your requests
- Treat Claude like a collaborative partner
- Don't be afraid to iterate and refine
Next up: Chapter 4 - Modes & Commands. Learn about Claude's different "modes" (Ask, Plan, Edit) and powerful slash commands that supercharge your workflow!
Test your knowledge!
Take Chapter 3 Quiz โChapter 4: Modes & Commands
Claude Code has different "modes" - think of them as different personalities or ways of working. Each mode is perfect for different tasks. Plus, you have powerful slash commands that give you superpowers!
Understanding Modes
Imagine you're working with a friend. Sometimes you want them to:
- Just answer questions (Ask Mode)
- Think through a plan first (Plan Mode)
- Actually make changes (Edit Mode - default)
- Think really deeply (Extended Thinking)
That's exactly what modes do!
Ask Mode - Questions Only
What it does: Claude answers questions but doesn't change any files.
When to use it:
- Learning how code works
- Understanding errors
- Exploring a new codebase
- Getting explanations
How to Use Ask Mode
Terminal Way:
# Press Shift + Tab while Claude is waiting
# The prompt changes to indicate Ask Mode
# Or type:
/ask
# Then ask your question:
How does this authentication system work?
VS Code Way:
- Look for the mode selector at the top of Claude panel
- Click and choose "Ask"
- Type your question
Example Questions for Ask Mode:
@app.js Can you explain what this function does?
@database.js Why are we using connection pooling here?
What's the difference between let and const in JavaScript?
@config/ Can you explain this configuration structure?
Plan Mode - Think First, Code Later
What it does: Claude creates a detailed plan before writing any code.
When to use it:
- Starting big features
- Complex refactoring
- Architecture decisions
- When you want to review the approach first
How to Use Plan Mode
Terminal Way:
# Start Claude in plan mode:
claude --plan
# Or switch to plan mode during a session:
/plan
# Then describe what you want:
I want to add user authentication with email and password
VS Code Way:
- Select "Plan" from the mode dropdown
- Describe your feature
- Claude will outline the steps
- Review the plan
- Approve to start implementation
What happens:
- Claude breaks down your request into steps
- Shows you the plan
- Asks if you approve
- If yes, starts implementing step by step
Real Example from Anthropic
The Security Engineering team at Anthropic uses Plan Mode extensively: "Instead of asking targeted questions, we now tell Claude to 'commit your work as you go' and let it work with plan mode, checking in periodically."
Edit Mode (Default) - Get Things Done
What it does: Claude actively reads files, writes code, and makes changes.
When to use it:
- Building features
- Fixing bugs
- Day-to-day coding
- Quick changes
This is the default mode - you're already using it! When you start Claude normally, you're in Edit Mode.
Example:
@index.html Add a dark mode toggle button in the header
Claude will immediately propose the changes and ask for permission.
Extended Thinking - Deep Reasoning
What it does: Claude thinks really deeply about complex problems before answering.
When to use it:
- Architectural decisions
- Complex algorithms
- Performance optimization
- System design
- Debugging mysterious issues
How to Use Extended Thinking
Terminal Way:
# Enable extended thinking:
claude --extended-thinking
# Or during a session:
/think
# Then pose your complex problem:
How should I architect a real-time chat system that scales to
10,000 concurrent users?
What happens:
Claude will spend more time reasoning through the problem, considering multiple approaches, trade-offs, and edge cases before responding. You'll see it "thinking" longer than usual.
Slash Commands - Your Superpowers
Slash commands are quick shortcuts that control Claude. They all start with /
Essential Slash Commands
| Command | What it does |
|---|---|
/help |
Shows all available commands |
/clear |
Starts a fresh conversation (like opening a new tab) |
/compact |
Summarizes current conversation to save memory |
/exit |
Quits Claude Code |
/ask |
Switches to Ask Mode |
/plan |
Switches to Plan Mode |
/think |
Enables Extended Thinking |
/clear - Fresh Start
Use this when you want to:
- Change topics completely
- Start a new feature
- Reset the conversation
/clear
# Now ask something completely different:
Let's build a todo list app
/compact - Summarize & Continue
Long conversation? Claude's memory getting full? Use /compact to summarize everything so far.
# After working for a while:
/compact
# Claude will:
# 1. Summarize what you've built
# 2. Remember key decisions
# 3. Free up memory
# 4. Continue with full context
Pro tip: Use /compact every 30-45 minutes during long sessions!
/help - Quick Reference
/help
# Shows:
# - All available commands
# - Keyboard shortcuts
# - Current mode
# - Tips and tricks
Keyboard Shortcuts
Speed up your workflow with these shortcuts:
| Shortcut | Action |
|---|---|
| Shift + Tab | Toggle Ask Mode |
| Cmd/Ctrl + K | Clear conversation |
| Cmd/Ctrl + L | Focus on input |
| Enter | Approve changes (when highlighted) |
| Esc | Cancel/Deny changes |
Choosing the Right Mode
Use Ask Mode when:
- You just want to learn
- Exploring unfamiliar code
- Understanding errors
- You don't want any files changed
Use Plan Mode when:
- Starting something big
- You want to review the approach first
- Complex features with many steps
- Making architectural decisions
Use Edit Mode when:
- Building features
- Fixing bugs
- Making changes
- Day-to-day development
Use Extended Thinking when:
- Really hard problems
- System architecture
- Performance optimization
- Complex algorithms
Practical Examples
Scenario 1: Learning a New Codebase
# Switch to Ask Mode
/ask
# Then explore:
@src/ What does this application do?
@routes/ How is routing handled?
@database/ Explain the database schema
Scenario 2: Building a New Feature
# Start with Plan Mode
/plan
I want to add a user profile page with:
- Avatar upload
- Bio editing
- Settings panel
# Review the plan, then let Claude implement
Scenario 3: Long Session
# After 45 minutes of work:
/compact
# Summary created, continue working:
Now let's add the email notification feature
Scenario 4: Complex Architecture
# Enable Extended Thinking
/think
How should I design a caching layer that works with both
Redis and in-memory cache, with automatic failover?
Tips from Anthropic Teams
From the Product Development team: "For critical features touching business logic, work synchronously in Edit Mode with detailed prompts. For experimental features, use Plan Mode first with auto-accept for autonomous loops."
From the RL Engineering team: "Use a checkpoint-heavy workflow. Commit regularly, try one-shot first in Edit Mode, then switch to Plan Mode if it doesn't work the first time."
Common Mode Switching Patterns
Pattern 1: Explore โ Plan โ Build
# 1. Understand (Ask Mode)
/ask
@codebase/ How is authentication currently handled?
# 2. Plan (Plan Mode)
/plan
I want to add OAuth support
# 3. Build (Edit Mode - happens automatically after plan approval)
Pattern 2: Build โ Compact โ Continue
# Build for a while in Edit Mode...
# (30-45 minutes pass)
# Compact to free memory:
/compact
# Continue building:
Now add the admin dashboard
Key Takeaways
- Ask Mode - Learn without changing files
- Plan Mode - Think first, code later
- Edit Mode - Default, active coding
- Extended Thinking - Deep reasoning for complex problems
- Use
/clearfor fresh starts - Use
/compactevery 30-45 minutes - Use
/helpwhen you forget commands - Shift + Tab for quick Ask Mode
Coming next: Chapter 5 - Memory & Organization. Learn about claude.md files, how Claude remembers your preferences, and organizing your projects for maximum efficiency!
Test your knowledge!
Take Chapter 4 Quiz โChapter 5: Memory & Organization
Claude Code has a memory system that helps it remember your preferences, coding style, and project details. Think of it like teaching Claude how YOU like to work!
The claude.md File - Claude's Memory Notebook
The claude.md file is where you write instructions for Claude. Every time Claude starts in your project, it reads this file first!
Think of it like this: If Claude is your coding buddy, claude.md is the notepad where you've written "here's how I like things done."
Where claude.md Lives
Project Memory (Specific to one project)
Location: .claude/claude.md (in your project folder)
Use for: Project-specific rules, coding standards, architecture notes
my-project/
โโโ .claude/
โ โโโ claude.md โ Project-specific memory
โโโ src/
โโโ package.json
Personal Memory (All your projects)
Location: ~/.claude/claude.md (your home directory)
Use for: Your general preferences, favorite tools, common patterns you use
Which One Wins?
If you have both, Claude reads them in this order:
- Personal memory (~/.claude/claude.md) - Your global preferences
- Project memory (.claude/claude.md) - Project-specific rules override
What to Put in claude.md
Coding Style Preferences
# My Coding Style
- Use single quotes for strings in JavaScript
- Always add comments explaining "why", not "what"
- Prefer functional components over class components in React
- Keep functions under 20 lines
- Use descriptive variable names (no single letters except for loops)
Project Architecture
# Project Structure
This is a React + Node.js application.
Frontend: /client (React, TypeScript)
Backend: /server (Node.js, Express)
Database: PostgreSQL
## Important Files
- /server/routes/api.js - All API endpoints
- /client/src/App.jsx - Main app component
- /shared/types.ts - Shared TypeScript types
Common Commands & Tools
# Development Commands
To start the app: npm run dev
To run tests: npm test
To build: npm run build
We use:
- ESLint for linting
- Prettier for formatting
- Jest for testing
Things to Avoid
# Don't Do These Things
- Don't use var (use const or let)
- Don't commit directly to main branch
- Don't install packages without asking first
- Don't change the database schema without migration files
Real Example from Anthropic
The Data Infrastructure team says: "The better you document your workflows, tools, and expectations in claude.md files, the better Claude Code performs. This made Claude excel at routine tasks like setting up new data pipelines when you have existing patterns."
Creating Your First claude.md
Terminal Way
cd my-project
mkdir -p .claude
cat > .claude/claude.md << 'EOF'
# My Project
This is a simple web app project.
## Coding Style
- Use 2 spaces for indentation
- Add semicolons at end of statements
- Use const by default, let when needed
## Project Structure
- index.html - Main page
- styles.css - All styling
- script.js - JavaScript logic
EOF
VS Code Way
- In your project, create a folder called
.claude - Inside it, create a file called
claude.md - Write your preferences in plain English
- Save it
- Next time you start Claude, it will read it!
Settings Files - Advanced Memory
Beyond claude.md, you can configure Claude's behavior with settings files.
Settings Hierarchy (Priority Order)
- Project local:
.claude/settings.local.json(personal, not shared with team) - Project shared:
.claude/settings.json(shared with team via git) - Personal:
~/.claude/settings.json(your global settings)
Common Settings
{
"model": "claude-sonnet-4",
"permissions": {
"allow": ["read", "write"],
"deny": ["network"]
},
"env": {
"NODE_ENV": "development"
}
}
Practical Examples
Example 1: React Project claude.md
# React Todo App
Built with React 18 + TypeScript + Vite
## Code Style
- Use function components with hooks
- One component per file
- Props interfaces in same file as component
- Use descriptive prop names
## File Structure
- /src/components - All React components
- /src/hooks - Custom hooks
- /src/types - TypeScript types
- /src/utils - Helper functions
## Testing
- Every component needs a test file
- Use React Testing Library
- Test user interactions, not implementation
## Don't
- Don't use class components
- Don't use index.tsx as component names
- Don't put logic in components (use hooks)
Example 2: API Project claude.md
# REST API Server
Node.js + Express + MongoDB
## API Conventions
- Use RESTful routes
- Always return proper status codes
- Include error messages in responses
- Log all errors to console
## Security
- Never commit .env file
- Always validate input
- Use JWT for authentication
- Rate limit all endpoints
## Database
- Use Mongoose models
- Keep models in /models folder
- Migrations in /migrations folder
Example 3: Personal ~/.claude/claude.md
# My Global Preferences
## General
- I prefer detailed explanations
- Always ask before installing new packages
- Show me what changed before committing
## Code Style
- Use modern ES6+ JavaScript
- Prefer async/await over promises
- Add JSDoc comments for functions
- Use meaningful variable names
## Tools I Use
- VS Code as editor
- Git for version control
- npm for packages
- Chrome for testing
Tips from Anthropic Teams
From the RL Engineering team: "Add instructions to your claude.md to prevent repeated mistakes. For example: 'run pytest not run, and don't cd unnecessarily - just use the right path.' This significantly improved consistency."
From the Security team: "Use custom slash commands extensively (stored in commands/). We use 50% of all custom commands in the entire monorepo. These streamline specific workflows."
From the Data Infrastructure team: "Share team usage sessions to spread best practices. Show each other your claude.md files - you'll discover patterns you hadn't thought of."
Organization Best Practices
Keep It Simple
- Start small (5-10 lines)
- Add more as you find patterns
- Don't write a novel - bullet points work best
Update Regularly
- When Claude makes a mistake you want to prevent
- When you establish a new pattern
- When team conventions change
Be Specific
- "Write good code"
- "Functions should be under 20 lines"
Explain Why
- "Don't use var"
- "Don't use var (we use const/let for block scoping)"
What NOT to Put in claude.md
- Secrets or passwords (use .env files)
- Very long documentation (link to docs instead)
- Repetitive instructions (Claude learns patterns)
- Temporary notes (use comments in code)
Testing Your claude.md
After creating your claude.md, test it:
claude
Ask Claude: "Can you summarize our project conventions?"
Claude will reference your claude.md and tell you what it knows!
Version Control
Should you commit claude.md to git?
Project claude.md: YES! Share it with your team.
git add .claude/claude.md
git commit -m "Add project conventions for Claude"
Personal settings.local.json: NO! Keep it private.
# Add to .gitignore
.claude/settings.local.json
Quick Reference
| File | Location | Purpose |
|---|---|---|
claude.md |
.claude/ |
Project memory (share with team) |
claude.md |
~/.claude/ |
Personal memory (just you) |
settings.json |
.claude/ |
Project settings (share with team) |
settings.local.json |
.claude/ |
Personal project settings (private) |
settings.json |
~/.claude/ |
Global personal settings |
Key Takeaways
-
claude.mdis Claude's memory - teach it your preferences - Project memory in
.claude/, personal in~/.claude/ - Write in plain English, use bullet points
- Include: coding style, project structure, things to avoid
- Update it as you find patterns
- Commit project
claude.mdto git (share with team) - Keep personal settings private
- Start simple, grow over time
Next: Chapter 6 - Agents. Learn how to create specialized AI helpers that work on specific tasks while you focus on the big picture!
Test your knowledge!
Take Chapter 5 Quiz โChapter 6: Agents - Your AI Team
Imagine having multiple AI assistants, each specialized in different tasks, all working for you at the same time. That's what agents are! They're like having a whole team of Claude helpers.
What Are Agents?
Think of agents like this: If Claude Code is your coding buddy, agents are specialized teammates who are experts in specific areas.
For example:
- UI Designer Agent - Focuses only on making things look good
- Testing Agent - Writes tests for your code
- Bug Hunter Agent - Finds and fixes bugs
- Documentation Agent - Writes clear documentation
Each agent has its own personality, focus, and instructions!
Why Use Agents?
Parallel Work
You can have multiple agents working on different tasks at the same time. While one agent writes tests, another can work on UI improvements.
Specialized Focus
An agent trained for testing won't get distracted by design. It stays laser-focused on its job.
Separate Contexts
Each agent has its own memory and context. If one gets confused, it doesn't affect the others.
Real Example from Anthropic
The Data Infrastructure team uses agents for parallel task management: "When working on long-running data tasks, they open multiple instances of Claude Code in different repositories for different projects. Each instance maintains full context, so when they switch back after hours or days, Claude remembers exactly what they were doing."
How to Create an Agent
Terminal Way
claude
/agent create testing-expert
Describe your agent's role:
You are a testing expert. Focus on writing comprehensive tests using Jest. Always test edge cases. Never modify production code - only write tests.
VS Code Way
- Open Claude panel
- Look for "Agents" menu or button
- Click "Create New Agent"
- Give it a name:
testing-expert - Write instructions for what this agent should do
- Save it
Agent Configuration
Agents are stored as markdown files in .claude/agents/
Creating an Agent File
Location: .claude/agents/testing-expert.md
---
name: testing-expert
description: Writes comprehensive tests for all code
color: blue
---
# Testing Expert Agent
You are a specialized testing agent.
## Your Role
- Write unit tests using Jest
- Test all edge cases
- Check error handling
- Ensure high code coverage
## Rules
- Never modify production code
- Only work in test files
- Use descriptive test names
- Test both success and failure cases
## Tools You Can Use
- Read code files to understand what to test
- Write test files
- Run tests to verify they work
Agent Frontmatter Options
name- Unique identifier (lowercase, hyphens)description- What this agent doescolor- Visual identifier (blue, green, red, yellow, purple)model- Which AI model to use (optional)allowed-tools- Restrict what the agent can do (optional)
Using Agents
Start an Agent
claude --agent testing-expert
Now this Claude session is the testing expert!
It will follow the instructions you gave it.
Switch Between Agents
claude
/agent switch ui-designer
Now you're talking to the UI designer agent!
List Your Agents
/agent list
Available agents:
- testing-expert (blue)
- ui-designer (green)
- bug-hunter (red)
- docs-writer (yellow)
Practical Agent Examples
Example 1: UI Designer Agent
File: .claude/agents/ui-designer.md
---
name: ui-designer
description: Focuses on beautiful, accessible UI design
color: green
---
# UI Designer Agent
## Your Expertise
- CSS and styling
- Responsive design
- Accessibility (WCAG standards)
- User experience
## Your Goals
- Make interfaces beautiful and usable
- Ensure mobile responsiveness
- Use consistent spacing and typography
- Follow modern design principles
## What You Don't Do
- Don't modify backend logic
- Don't write tests
- Don't change database code
## Tools
- Modern CSS (Flexbox, Grid)
- Tailwind CSS if available
- CSS animations
- Color theory
Example 2: Bug Hunter Agent
File: .claude/agents/bug-hunter.md
---
name: bug-hunter
description: Finds and fixes bugs with precision
color: red
---
# Bug Hunter Agent
## Your Mission
Find and fix bugs efficiently.
## Your Process
1. Read error messages carefully
2. Trace the code flow
3. Identify the root cause
4. Fix it with minimal changes
5. Test the fix
## What Makes You Different
- You're paranoid about edge cases
- You think about error handling
- You consider race conditions
- You check for null/undefined
- You validate inputs
## Rules
- Always explain what caused the bug
- Make minimal changes to fix it
- Add defensive code to prevent similar bugs
- Suggest tests to catch this type of bug
Example 3: Documentation Agent
File: .claude/agents/docs-writer.md
---
name: docs-writer
description: Writes clear, helpful documentation
color: yellow
---
# Documentation Agent
## Your Purpose
Make code understandable to everyone.
## What You Write
- README files
- API documentation
- Code comments
- Usage examples
- Setup instructions
## Your Style
- Use simple language
- Include examples
- Be thorough but concise
- Think about beginners
- Use bullet points
## Documentation Checklist
- What does this code do?
- Why does it exist?
- How do you use it?
- What are the gotchas?
- Are there examples?
Workflow: Using Multiple Agents
Scenario: Building a New Feature
Step 1: Plan with Main Claude
claude
/plan
I want to add a user login feature with email and password
Step 2: Build with Main Claude
Build the login functionality
(Main Claude implements the core feature)
Step 3: UI Polish with Designer Agent
claude --agent ui-designer
Make the login form beautiful and responsive
(UI agent focuses on styling)
Step 4: Add Tests with Testing Agent
claude --agent testing-expert
Write comprehensive tests for the login feature
(Testing agent writes all tests)
Step 5: Document with Docs Agent
claude --agent docs-writer
Document the login feature - how to use it, what it does
(Docs agent creates clear documentation)
Agent Best Practices
Keep Agents Focused
- "General purpose agent that does everything"
- "Testing agent that only writes tests"
Give Clear Instructions
- Explain what they should do
- Explain what they shouldn't do
- Provide examples of good work
Use Color Coding
Colors help you visually identify which agent you're talking to:
- ๐ต Blue - Testing, QA
- ๐ข Green - UI, Frontend
- ๐ด Red - Debugging, Fixes
- ๐ก Yellow - Documentation
- ๐ฃ Purple - Backend, API
Start Small
Create 2-3 agents first. See how they work. Add more as needed.
Advanced: Agent Restrictions
You can limit what tools an agent can use for safety and focus:
---
name: read-only-reviewer
description: Reviews code but never changes anything
allowed-tools: [read, grep]
---
# Code Reviewer Agent
You can only read code and search for patterns.
You cannot edit, write, or delete files.
Review the code and provide suggestions, but don't make changes.
Tips from Anthropic Teams
From the Product Development team: "Use agents for peripheral features and prototyping. Enable 'auto-accept mode' (shift+tab) and set up autonomous loops where Claude writes code, runs tests, and iterates continuously. For core business logic, work synchronously."
From the Growth Marketing team: "Break complex workflows into specialized sub-agents. Instead of one agent handling everything, create separate agents for specific tasks (like our headline agent vs. description agent). This makes debugging easier and improves output quality."
From the API Knowledge team: "Use agents when rotating to new teams. You can quickly navigate unfamiliar codebases and contribute meaningfully without extensive colleague consultation."
Common Agent Patterns
Pattern 1: The Assembly Line
Main Claude: Builds the feature
โ
UI Agent: Makes it pretty
โ
Testing Agent: Adds tests
โ
Docs Agent: Documents it
Pattern 2: Parallel Specialists
Terminal 1: Frontend Agent (works on React)
Terminal 2: Backend Agent (works on API)
Terminal 3: Testing Agent (writes tests for both)
All working at the same time!
Pattern 3: The Reviewer
You write code
โ
Review Agent looks at it
โ
Suggests improvements
โ
You approve/reject suggestions
Troubleshooting Agents
Agent Doing Too Much?
Make instructions more restrictive. Add a "What You Don't Do" section.
Agent Not Specialized Enough?
Add more specific examples and rules. Show it what good output looks like.
Agents Conflicting?
Use them one at a time, or clearly separate their responsibilities.
Key Takeaways
- Agents are specialized AI helpers for specific tasks
- Create agents in
.claude/agents/as markdown files - Use frontmatter for name, description, color
- Keep agents focused on one area
- Use color coding for visual identification
- Start an agent with
claude --agent name - Switch agents with
/agent switch name - Run multiple agents in parallel for complex projects
- Give clear instructions about what they should and shouldn't do
Next: Chapter 7 - MCP Servers. Learn how to give Claude superpowers by connecting it to external tools like web browsers, databases, and APIs!
Test your knowledge!
Take Chapter 6 Quiz โChapter 7: MCP Servers - Superpowers
Imagine giving Claude Code the ability to control a web browser, search the entire internet, or connect to your company's database. That's what MCP Servers do - they're like plugins that give Claude superpowers!
What is MCP?
MCP stands for Model Context Protocol. Think of it like this:
Without MCP: Claude can only read and write files on your computer.
With MCP: Claude can control browsers, search the web, query databases, fetch APIs, and much more!
Simple Analogy
Imagine Claude is a person sitting at a desk. By default, Claude can only work with papers (files) on that desk. MCP servers are like giving Claude:
- A phone (to call APIs)
- A computer with internet (to browse the web)
- Access to filing cabinets (databases)
- Tools and equipment (specialized software)
Popular MCP Servers
1. Playwright MCP - Web Browser Control
What it does: Lets Claude control a real web browser - click buttons, fill forms, take screenshots.
Use cases:
- Testing your website automatically
- Scraping data from websites
- Automating repetitive web tasks
- Taking screenshots of web pages
2. Filesystem MCP - Enhanced File Operations
What it does: Advanced file operations beyond basic read/write.
Use cases:
- Searching through large codebases
- Batch file operations
- File system monitoring
3. Database MCP Servers
What they do: Connect to databases like PostgreSQL, MySQL, SQLite, BigQuery.
Use cases:
- Running database queries
- Analyzing data directly
- Generating reports
- Database migrations
4. Exa MCP - AI-Powered Search
What it does: Search the entire internet with AI-powered relevance.
Use cases:
- Research current events
- Find documentation
- Gather information on topics
5. GitHub MCP - Repository Management
What it does: Full GitHub integration - PRs, issues, code search.
Use cases:
- Creating pull requests
- Managing issues
- Searching across repositories
- Automating GitHub workflows
Real Example from Anthropic
The Growth Marketing team built a custom Meta Ads MCP server: "We created an MCP server integrated with Meta Ads API to query campaign performance, spending data, and ad effectiveness directly within Claude Desktop app, eliminating the need to switch between platforms for performance analysis."
Installing an MCP Server
Let's install the Playwright MCP server as an example.
Step 1: Check Prerequisites
Most MCP servers require Node.js. You already have this if you installed Claude Code!
Step 2: Install the MCP Server
Terminal Way:
# Navigate to your project
cd my-project
# Install Playwright MCP server
npx -y @modelcontextprotocol/create-server playwright
# This creates a local MCP server for Playwright
VS Code Way:
- Open VS Code terminal (View โ Terminal)
- Run the same npx command above
- The extension will detect the new MCP server
Step 3: Configure Claude to Use It
Location: Add to your settings file
Project settings: .claude/settings.json
Personal settings: ~/.claude/settings.json
{
"mcpServers": {
"playwright": {
"command": "node",
"args": ["path/to/playwright-mcp/index.js"]
}
}
}
Step 4: Restart Claude Code
# Exit and restart
exit
# Start again
claude
Claude will now have access to Playwright capabilities!
Using an MCP Server
Example: Web Automation with Playwright
claude
# Ask Claude to use the browser:
Can you open https://example.com, take a screenshot, and check if
the page loads correctly?
What happens:
- Claude recognizes you want browser automation
- It uses the Playwright MCP server
- Opens a browser, navigates to the URL
- Takes a screenshot
- Analyzes the page and reports back
Example: Database Queries with BigQuery MCP
claude
# Ask Claude to query your data:
Can you query our BigQuery database and show me the top 10
customers by revenue this month?
Claude will execute the SQL query and show you results!
Security Considerations
MCP servers have access to powerful tools. Be careful!
From Anthropic's Data Infrastructure Team:
"We recommend using MCP servers rather than the BigQuery CLI to maintain better security control over what Claude Code can access, especially for handling sensitive data that requires logging or has potential privacy concerns."
Security Best Practices:
- Review permissions: Know what each MCP server can access
- Use project-level MCP servers: Limit scope to specific projects
- Audit logs: Many MCP servers support logging - enable it
- Sensitive data: Use MCP servers with authentication for databases
- Read-only when possible: Give read-only database access if writes aren't needed
Common MCP Servers
| MCP Server | What it does |
|---|---|
| Playwright | Web browser automation and testing |
| Filesystem | Advanced file operations |
| PostgreSQL | PostgreSQL database access |
| SQLite | SQLite database operations |
| BigQuery | Google BigQuery data warehouse |
| GitHub | GitHub API integration |
| Slack | Send messages to Slack channels |
| Exa | AI-powered web search |
| AWS | AWS services integration |
Creating a Custom MCP Server
You can create your own MCP server to connect Claude to any tool or API!
When to Create a Custom MCP Server:
- Your company has internal APIs Claude should access
- You use a service that doesn't have an MCP server yet
- You want to add custom functionality
Basic Structure
An MCP server is just a Node.js program that follows the MCP protocol.
my-custom-mcp/
โโโ package.json
โโโ index.js โ Main server file
โโโ README.md
Simple Example: Weather API MCP Server
// index.js
import { MCPServer } from '@modelcontextprotocol/sdk';
const server = new MCPServer({
name: 'weather-api',
version: '1.0.0'
});
// Define a tool that Claude can use
server.tool('get-weather', {
description: 'Get weather for a city',
parameters: {
city: { type: 'string', description: 'City name' }
},
handler: async ({ city }) => {
// Call weather API
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.json();
return data;
}
});
server.listen();
Now Claude can call your weather API!
MCP Server Configuration
Full Settings Example
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-playwright"],
"env": {
"BROWSER": "chromium"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/mydb"
}
},
"my-custom-server": {
"command": "node",
"args": ["./mcp-servers/weather/index.js"]
}
}
}
Configuration Options:
command- The executable to run (node, npx, python, etc.)args- Arguments to pass to the commandenv- Environment variables (API keys, database URLs)
Real-World Use Cases
Use Case 1: Automated Testing
claude
# With Playwright MCP:
Please test our signup flow:
1. Go to localhost:3000/signup
2. Fill in the form with test data
3. Click submit
4. Verify we reach the dashboard
5. Take screenshots of each step
Use Case 2: Data Analysis
claude
# With BigQuery MCP:
Query our sales database and create a report showing:
- Total revenue by product category
- Month-over-month growth
- Top 5 customers
Then save it as a CSV file
Use Case 3: Documentation Search
claude
# With Exa MCP:
Search the internet for examples of implementing OAuth2 with Node.js
and Express. Find the 5 most relevant tutorials.
Use Case 4: GitHub Automation
claude
# With GitHub MCP:
Search all open issues in our repo labeled "bug" and "high-priority"
Create a summary report with links to each issue
Troubleshooting MCP Servers
MCP Server Not Found
Problem: Claude says it doesn't have access to the MCP server.
Solution:
- Check your settings.json configuration
- Verify the command path is correct
- Restart Claude Code after configuration changes
Permission Denied
Problem: MCP server can't access resources.
Solution:
- Check API keys in environment variables
- Verify database credentials
- Ensure the MCP server has proper file permissions
Server Crashes
Problem: MCP server stops working mid-operation.
Solution:
- Check logs (usually in
~/.claude/logs/) - Verify all dependencies are installed
- Test the MCP server independently
Tips from Anthropic Teams
From the Data Infrastructure team: "Use MCP servers instead of CLI for sensitive data. They maintain better security control over what Claude Code can access, especially for handling sensitive data that requires logging or has potential privacy concerns."
From the Growth Marketing team: "We created custom MCP servers for our ad platforms (Meta Ads, Google Ads). This eliminated context switching between tools and saved hours every week on performance analysis."
From the Legal team: "As product lawyers, we immediately identify security implications of deep MCP integrations. Make sure to document what each MCP server can access and review it with your security team."
MCP Server Best Practices
Start Small
- Install one MCP server at a time
- Test it thoroughly before adding more
- Understand what each server can do
Document Access
- Keep a list of which MCP servers have access to what
- Document API keys and credentials securely
- Share configuration with team members
Use Environment Variables
- Never hardcode API keys in settings.json
- Use .env files for secrets
- Add .env to .gitignore
Monitor Usage
- Enable logging on MCP servers
- Review logs regularly
- Watch for unexpected behavior
Finding More MCP Servers
Official MCP Repository
Visit the Model Context Protocol GitHub organization for official servers:
github.com/modelcontextprotocol
Community MCP Servers
Search npm for community-built MCP servers:
npm search mcp-server
Company-Specific Servers
Many companies build internal MCP servers for their tools. Check with your engineering team!
Key Takeaways
- MCP servers give Claude access to external tools and services
- Popular servers: Playwright (browser), Exa (search), databases, GitHub
- Install with npx and configure in settings.json
- Security matters - use MCP servers for better access control
- Can create custom MCP servers for internal APIs
- Start with one server, test thoroughly, then add more
- Use environment variables for API keys and credentials
- Document what each MCP server can access
- Enable logging for security and debugging
- Real-world impact: Anthropic teams save hours weekly with MCP automation
Next: Chapter 8 - Skills . Learn about modular expertise packages that give Claude specialized knowledge for tasks like PowerPoint creation, Excel analysis, PDF processing, and more!
Test your knowledge!
Take Chapter 7 Quiz โChapter 8: Skills - Expertise Packages
Imagine teaching Claude to become an expert in specific areas - like a PowerPoint wizard, an Excel master, or a PDF processing specialist. That's what Skills are! They're like installing expertise packages that make Claude instantly knowledgeable in specialized tasks.
What Are Skills?
Think of skills like this: If Claude is a smart assistant, skills are like training manuals for specific jobs.
Without skills: Claude has general knowledge but might need detailed instructions for specialized tasks.
With skills: Claude becomes an instant expert - knows best practices, common patterns, and can handle complex specialized tasks autonomously.
Simple Analogy
Imagine hiring someone who's generally smart. Skills are like sending them to specialized training:
- Excel Skill = Sending them to Excel certification course
- PDF Skill = Teaching them document processing expertise
- PowerPoint Skill = Making them a presentation design expert
- Custom Skills = Teaching them your company's specific workflows
Pre-Built Skills
Claude Code comes with several ready-to-use skills for common tasks:
1. PDF Skill
What it does: Expert at reading, creating, and manipulating PDF files.
Use cases:
- Extract text from PDFs
- Merge multiple PDFs
- Split PDFs into pages
- Add watermarks
- Convert PDFs to other formats
2. Excel Skill
What it does: Advanced Excel operations, formulas, and data analysis.
Use cases:
- Create complex spreadsheets
- Write advanced formulas (VLOOKUP, pivot tables)
- Data analysis and visualization
- Automate spreadsheet tasks
- Generate reports from data
3. PowerPoint Skill
What it does: Create professional presentations programmatically.
Use cases:
- Generate slide decks from data
- Create templates
- Batch create presentations
- Update existing presentations
- Export to different formats
4. Word Processing Skill
What it does: Create and manipulate Word documents.
Use cases:
- Generate reports
- Create templates
- Mail merge operations
- Document formatting
- Convert between formats
Where Skills Live
Skills can be stored in three places:
1. Personal Skills (Just You)
Location: ~/.claude/skills/
Use for: Skills you use across all your projects
~/.claude/
โโโ skills/
โโโ excel-expert/
โโโ pdf-processor/
โโโ my-custom-skill/
2. Project Skills (This Project Only)
Location: .claude/skills/
Use for: Project-specific expertise
my-project/
โโโ .claude/
โ โโโ skills/
โ โโโ company-branding/
โ โโโ data-pipeline/
โโโ src/
3. Plugin-Bundled Skills
Location: Installed with plugins
Use for: Skills from the marketplace or third-party packages
Installing a Pre-Built Skill
Terminal Way
# Install a skill globally (for all projects)
claude skill install pdf
# Install a skill for current project only
claude skill install excel --project
# List available skills
claude skill list
VS Code Way
- Open Claude Code panel
- Click "Skills" menu
- Browse available skills
- Click "Install" on the skill you want
- Choose "Global" or "Project" scope
Using Skills
Once a skill is installed, Claude automatically knows when to use it!
Example: Using PDF Skill
claude
# Claude automatically uses the PDF skill:
Can you extract all the text from report.pdf and save it as a
markdown file?
What happens:
- Claude recognizes this is a PDF task
- Loads the PDF skill expertise
- Uses best practices for PDF processing
- Extracts text efficiently
- Formats it as clean markdown
Example: Using Excel Skill
claude
# Claude uses Excel skill:
Create a sales report spreadsheet with:
- Monthly revenue by product
- Charts showing trends
- Summary statistics
- Conditional formatting for top performers
Claude will create a professional Excel file with all these features!
Creating a Custom Skill
You can create your own skills for specialized tasks specific to your work or company.
When to Create a Custom Skill:
- You have company-specific workflows that repeat
- There's domain knowledge Claude should always use
- You want to standardize how Claude handles certain tasks
- You have best practices to encode
Skill Structure
A skill is just a folder with a special markdown file:
my-custom-skill/
โโโ SKILL.md โ The skill definition
โโโ examples/ โ Optional: example code
โโโ templates/ โ Optional: templates to use
Creating Your First Skill
Terminal Way:
# Create a new skill
mkdir -p ~/.claude/skills/company-branding
cd ~/.claude/skills/company-branding
# Create the SKILL.md file
cat > SKILL.md << 'EOF'
---
name: company-branding
description: Expert at applying our company brand guidelines
version: 1.0.0
---
# Company Branding Skill
You are an expert at our company's brand guidelines.
## Brand Colors
- Primary: #0071e3 (Blue)
- Secondary: #1d1d1f (Dark Gray)
- Background: #ffffff (White)
- Text: #1d1d1f (Dark Gray)
## Typography
- Headings: Inter font, 600 weight
- Body: Inter font, 400 weight
- Code: SF Mono font
## Logo Usage
- Always use PNG format with transparency
- Minimum size: 120px width
- Clear space: Logo height/2 on all sides
- Never distort or recolor
## Voice & Tone
- Professional but friendly
- Clear and concise
- Avoid jargon
- Use active voice
## When Creating Documents
1. Apply brand colors consistently
2. Use approved fonts
3. Include logo in header
4. Follow spacing guidelines
5. Maintain visual hierarchy
EOF
VS Code Way:
- Create folder:
.claude/skills/company-branding/ - Create file:
SKILL.mdinside that folder - Write your skill definition (see example above)
- Save it
- Restart Claude Code
SKILL.md File Format
Frontmatter (Required)
---
name: skill-name
description: What this skill does
version: 1.0.0
tags: [optional, tags, here]
author: Your Name (optional)
---
Skill Content (Markdown)
Write instructions in plain English:
- What: What this skill teaches Claude
- When: When Claude should use this knowledge
- How: Best practices and patterns
- Examples: Show what good output looks like
Real-World Custom Skill Examples
Example 1: API Documentation Skill
---
name: api-docs
description: Generate API documentation following our standards
version: 1.0.0
---
# API Documentation Skill
## When Documenting APIs
### Structure
Every endpoint needs:
1. HTTP method and path
2. Description (one sentence)
3. Authentication requirements
4. Request parameters (with types)
5. Request body schema (if POST/PUT)
6. Response schema
7. Example requests
8. Example responses
9. Error codes
### Format
Use this template:
\`\`\`markdown
## GET /api/users/:id
Retrieves a single user by ID.
**Authentication:** Required (Bearer token)
**Parameters:**
- \`id\` (string, required) - User ID
**Response:**
\`\`\`json
{
"id": "123",
"name": "John Doe",
"email": "john@example.com"
}
\`\`\`
**Errors:**
- \`404\` - User not found
- \`401\` - Unauthorized
\`\`\`
### Best Practices
- Always include examples
- Document all error cases
- Use consistent terminology
- Keep descriptions concise
Example 2: Testing Standards Skill
---
name: testing-standards
description: Write tests following our team conventions
version: 1.0.0
---
# Testing Standards Skill
## Test Organization
### File Structure
- Unit tests: \`__tests__/unit/\`
- Integration tests: \`__tests__/integration/\`
- E2E tests: \`__tests__/e2e/\`
### Naming Convention
- Test files: \`*.test.js\`
- Describe blocks: Feature/component name
- Test names: Should statements
### Example Structure
\`\`\`javascript
describe('UserService', () => {
describe('createUser', () => {
it('should create a user with valid data', async () => {
// Arrange
const userData = { name: 'John', email: 'john@example.com' };
// Act
const user = await UserService.createUser(userData);
// Assert
expect(user).toBeDefined();
expect(user.email).toBe('john@example.com');
});
it('should throw error for invalid email', async () => {
const userData = { name: 'John', email: 'invalid' };
await expect(UserService.createUser(userData))
.rejects.toThrow('Invalid email');
});
});
});
\`\`\`
## Test Coverage Requirements
- Minimum 80% coverage
- 100% coverage for critical paths
- Test happy path AND error cases
- Mock external dependencies
## What to Test
DO test:
- Business logic
- Edge cases
- Error handling
- User inputs
- API responses
DON'T test:
- Third-party libraries
- Framework internals
- Trivial getters/setters
Example 3: Data Pipeline Skill
---
name: data-pipeline
description: Build data pipelines following our ETL patterns
version: 1.0.0
---
# Data Pipeline Skill
## Pipeline Architecture
Every pipeline has three stages:
1. **Extract** - Get data from source
2. **Transform** - Clean and process
3. **Load** - Save to destination
## Standard Pattern
\`\`\`python
class DataPipeline:
def extract(self):
# Get data from source
# Always handle connection errors
# Log extraction metrics
pass
def transform(self, data):
# Validate data schema
# Clean null values
# Apply business rules
# Log transformation stats
pass
def load(self, data):
# Write to destination
# Use transactions
# Verify write success
# Log load metrics
pass
def run(self):
try:
data = self.extract()
transformed = self.transform(data)
self.load(transformed)
except Exception as e:
self.handle_error(e)
\`\`\`
## Error Handling
- Always wrap in try/except
- Log errors with context
- Send alerts for failures
- Clean up resources
## Logging Requirements
- Log start/end of each stage
- Log row counts
- Log processing time
- Log any errors with stack trace
## Testing Pipelines
- Test each stage independently
- Mock external connections
- Test with sample data
- Verify output schema
Managing Skills
List Installed Skills
# Terminal
claude skill list
# Shows:
# - Skill name
# - Description
# - Location (global/project)
# - Version
Remove a Skill
# Remove global skill
claude skill uninstall pdf
# Remove project skill
claude skill uninstall company-branding --project
Update a Skill
Just edit the SKILL.md file and restart Claude Code!
# Edit the skill
code ~/.claude/skills/my-skill/SKILL.md
# Restart Claude to reload
exit
claude
Skill Best Practices
Keep Skills Focused
- "general-coding-skill" (too broad)
- "react-component-patterns" (specific)
Include Examples
Show Claude what good output looks like. Examples are more powerful than descriptions.
Use Clear Structure
- Use headings (h2, h3)
- Use bullet points
- Use code blocks for examples
- Be specific, not vague
Update Regularly
As you discover patterns or mistakes, update your skills to encode that knowledge.
Share with Team
Commit project skills to git so your team benefits from the same expertise.
Skills vs Other Features
| Feature | Purpose | Best For |
|---|---|---|
| Skills | Domain expertise and knowledge | Teaching Claude how to do specialized tasks |
| Agents | Specialized AI personalities | Different roles (UI designer, tester, etc.) |
| MCP Servers | External tool access | Connecting to APIs, databases, browsers |
| Custom Commands | Shortcuts and automation | Frequently repeated tasks |
| claude.md | Project context and rules | General project guidelines |
When Skills Activate
Claude automatically uses skills based on your request:
- Keyword triggers: Mentions of "PDF", "Excel", "presentation" activate relevant skills
- File extensions: Working with .pdf, .xlsx files triggers skills
- Context: Claude infers when specialized knowledge is needed
- Always available: Skills are part of Claude's context throughout the session
Troubleshooting Skills
Skill Not Being Used
Problem: Claude doesn't seem to use your skill.
Solutions:
- Check the skill is installed:
claude skill list - Verify SKILL.md format (frontmatter required)
- Restart Claude Code
- Be more explicit in your request (mention skill keywords)
Skill Conflicts
Problem: Multiple skills provide conflicting advice.
Solutions:
- Make skills more specific (narrow their scope)
- Add "When to use this skill" section
- Remove or update conflicting skills
Key Takeaways
- Skills teach Claude specialized expertise (PDF, Excel, PowerPoint, etc.)
- Pre-built skills available, or create custom ones
- Install with
claude skill install name - Skills stored in
~/.claude/skills/(global) or.claude/skills/(project) - Create custom skills with SKILL.md file
- Include frontmatter (name, description, version)
- Write clear instructions with examples
- Skills activate automatically based on context
- Keep skills focused on specific domains
- Share project skills with team via git
- Update skills as you learn new patterns
Next: Chapter 9 - Custom Commands . Learn how to create personal shortcuts and slash commands that automate your most common workflows!
Test your knowledge!
Take Chapter 8 Quiz โChapter 9: Custom Commands - Your Shortcuts
Imagine if you could create your own magic words that make Claude do exactly what you want, instantly. That's what Custom Commands are! They're like creating your own personal shortcuts - type a slash command, and Claude follows your custom instructions.
What Are Custom Commands?
Think of custom commands like this: If Claude Code is a smart assistant, custom commands are like teaching it your personal shortcuts.
Without custom commands: You type the same long instructions repeatedly.
With custom commands: You type /mycommand and Claude knows exactly what to do!
Simple Analogy
Imagine you have a coworker who helps you. Every day, you say: "Please review this code, check for bugs, verify tests exist, ensure it follows our style guide, and create a summary."
With custom commands, you just say: /review - and they know to do all those steps!
Real Example from Anthropic
The Security Engineering team uses custom commands extensively: "Security engineering uses 50% of all custom slash command implementations in the entire monorepo. These custom commands streamline specific workflows and speed up repeated tasks."
Built-In Commands vs Custom Commands
Built-In Commands (You already know these)
/help- Show help/clear- Clear conversation/compact- Summarize context/ask- Switch to Ask Mode/plan- Switch to Plan Mode/exit- Quit Claude Code
Custom Commands (You create these!)
/review- Your code review process/deploy- Your deployment checklist/docs- Generate docs your way/test- Your testing workflow/pr- Create PR with your template
Where Custom Commands Live
Project Commands (This Project)
Location: .claude/commands/
Use for: Project-specific workflows
my-project/
โโโ .claude/
โ โโโ commands/
โ โโโ review.md
โ โโโ deploy.md
โ โโโ test.md
โโโ src/
Personal Commands (All Your Projects)
Location: ~/.claude/commands/
Use for: Commands you use everywhere
~/.claude/
โโโ commands/
โโโ explain.md
โโโ optimize.md
โโโ debug.md
Creating Your First Custom Command
Example: Code Review Command
Terminal Way:
mkdir -p .claude/commands
cat > .claude/commands/review.md << 'EOF'
---
name: review
description: Comprehensive code review with our standards
---
Please perform a thorough code review:
1. **Code Quality**
- Check for code smells
- Verify naming conventions
- Look for unnecessary complexity
- Check for duplicate code
2. **Testing**
- Verify tests exist
- Check test coverage
- Look for edge cases that need tests
3. **Security**
- Check for security vulnerabilities
- Verify input validation
- Look for SQL injection risks
- Check authentication/authorization
4. **Performance**
- Identify performance bottlenecks
- Look for inefficient queries
- Check for memory leaks
5. **Documentation**
- Verify function comments exist
- Check if README needs updates
- Look for unclear code that needs comments
6. **Summary**
- List all issues found
- Prioritize by severity (high/medium/low)
- Suggest specific fixes
Use a professional but friendly tone.
EOF
VS Code Way:
- Create folder:
.claude/commands/ - Create file:
review.md - Add the content above
- Save it
- Restart Claude Code (or type
/reload)
Using Your Command
claude
/review
Claude will now perform the comprehensive review you defined!
Command File Format
Frontmatter (Required)
---
name: command-name
description: What this command does
---
Optional Frontmatter
---
name: command-name
description: What this command does
mode: edit # Force specific mode (ask/plan/edit)
args: # Accept arguments
- name: filename
description: File to process
required: true
- name: format
description: Output format
required: false
default: markdown
---
Command Content
Write clear instructions for Claude in plain English or markdown.
Real-World Custom Command Examples
Example 1: Deployment Checklist Command
---
name: deploy
description: Pre-deployment checklist and validation
---
# Deployment Checklist
Please verify the following before deployment:
## 1. Code Quality
- [ ] All tests passing
- [ ] No console.logs or debug statements
- [ ] No commented-out code
- [ ] All TODOs resolved or documented
## 2. Build & Dependencies
- [ ] Run build successfully
- [ ] Check for outdated dependencies
- [ ] Verify package-lock.json is committed
- [ ] No security vulnerabilities (npm audit)
## 3. Environment & Config
- [ ] Environment variables documented
- [ ] Config files updated for production
- [ ] Secrets properly stored (not in code)
- [ ] Database migrations ready
## 4. Documentation
- [ ] README updated with new features
- [ ] API docs updated
- [ ] CHANGELOG.md updated
- [ ] Deployment instructions current
## 5. Monitoring & Rollback
- [ ] Health check endpoint works
- [ ] Logging configured
- [ ] Rollback plan documented
- [ ] Team notified of deployment
After checking all items, provide a summary of:
- Ready to deploy (all checks pass)
- Warnings (minor issues to be aware of)
- Blockers (must fix before deploying)
Example 2: Bug Investigation Command
---
name: debug
description: Systematic bug investigation process
args:
- name: issue
description: Description of the bug
required: true
---
# Debug Issue: {{issue}}
Please investigate this bug systematically:
## Step 1: Reproduce
- Understand the expected behavior
- Identify steps to reproduce
- Confirm I can reproduce it
## Step 2: Locate
- Search codebase for relevant code
- Identify which files/functions are involved
- Trace the execution flow
## Step 3: Analyze
- Read the relevant code carefully
- Identify the root cause
- Check for related issues
- Look for edge cases
## Step 4: Propose Fix
- Suggest specific code changes
- Explain why this fixes the issue
- Consider side effects
- Suggest tests to prevent regression
## Step 5: Validate
- Verify fix addresses root cause
- Check if fix introduces new issues
- Confirm edge cases are handled
Provide clear explanations at each step.
Example 3: Documentation Generator Command
---
name: docs
description: Generate comprehensive documentation
args:
- name: target
description: What to document (file, function, or project)
required: true
- name: style
description: Documentation style (api, guide, or reference)
required: false
default: guide
---
# Generate Documentation: {{target}}
Style: {{style}}
Please create comprehensive documentation:
## For Functions/Classes:
- Purpose and description
- Parameters with types and descriptions
- Return value with type and description
- Usage examples (at least 2)
- Edge cases and error handling
- Related functions/classes
## For Files/Modules:
- Overview and purpose
- Key exports
- Dependencies
- Usage examples
- Common patterns
## For Projects:
- Overview and goals
- Getting started guide
- Installation instructions
- Configuration options
- API reference
- Examples and tutorials
- Troubleshooting section
Use clear, beginner-friendly language with plenty of examples.
Example 4: Pull Request Command
---
name: pr
description: Create a well-formatted pull request
---
# Create Pull Request
Please help create a pull request:
## 1. Analyze Changes
- Review all modified files
- Identify what changed and why
- Group related changes together
## 2. Generate PR Title
- Format: `[Type] Brief description`
- Types: Feature, Fix, Refactor, Docs, Test, Chore
- Keep under 72 characters
- Be specific and clear
## 3. Write PR Description
Use this template:
\`\`\`markdown
## Summary
[Brief overview of changes]
## Changes Made
- [Bullet point list of changes]
## Why These Changes?
[Explain the motivation]
## Testing
- [ ] Unit tests added/updated
- [ ] Manual testing completed
- [ ] Edge cases covered
## Checklist
- [ ] Code follows style guide
- [ ] Tests pass
- [ ] Documentation updated
- [ ] No console logs or debug code
- [ ] Reviewed own changes
## Screenshots
[If UI changes, include screenshots]
## Related Issues
Closes #[issue number]
\`\`\`
## 4. Suggest Reviewers
Based on the files changed, suggest appropriate reviewers.
## 5. Create PR
Use the gh CLI to create the pull request with the generated title and description.
Example 5: Test Generator Command
---
name: test
description: Generate comprehensive tests for code
args:
- name: file
description: File to test
required: true
---
# Generate Tests for: {{file}}
Please create comprehensive tests:
## Test Coverage Strategy
1. **Happy Path Tests**
- Test with valid inputs
- Verify expected outputs
- Cover main use cases
2. **Edge Cases**
- Empty inputs
- Null/undefined values
- Boundary values
- Large inputs
3. **Error Cases**
- Invalid inputs
- Expected failures
- Error messages
4. **Integration**
- Mock external dependencies
- Test interactions
- Verify side effects
## Test Structure
- Use descriptive test names
- Follow AAA pattern (Arrange, Act, Assert)
- One assertion per test when possible
- Group related tests with describe blocks
## Code Coverage Goal
Aim for 80%+ coverage including:
- All public functions
- Main code paths
- Error handling
- Edge cases
Generate complete, runnable test code.
Commands with Arguments
Using Arguments in Commands
Arguments make commands flexible. Use {{argument_name}} placeholders:
---
name: analyze
description: Analyze a specific aspect of code
args:
- name: aspect
description: What to analyze (performance, security, readability)
required: true
- name: file
description: File to analyze
required: true
---
Analyze {{file}} focusing on {{aspect}}.
Provide specific recommendations for improvement.
Calling Commands with Arguments
claude
/analyze performance src/app.js
/analyze security api/users.js
Optional Arguments with Defaults
---
name: export
description: Export data in specified format
args:
- name: source
description: Data source file
required: true
- name: format
description: Export format
required: false
default: json
---
Export data from {{source}} as {{format}} format.
Advanced Command Patterns
Multi-Step Workflow Command
---
name: release
description: Complete release workflow
---
# Release Workflow
Execute these steps in order:
1. **Version Bump**
- Ask me what version number (major/minor/patch)
- Update package.json version
- Update CHANGELOG.md
2. **Final Checks**
- Run all tests
- Run build
- Check for uncommitted changes
3. **Git Operations**
- Create release branch
- Commit changes with version message
- Create git tag
4. **Documentation**
- Generate release notes from commits
- Update README if needed
- Check docs are current
5. **Confirmation**
- Show summary of changes
- Ask for confirmation before pushing
- Push to remote if approved
IMPORTANT: Wait for my approval before each major step.
Interactive Command
---
name: scaffold
description: Interactive project scaffolding
---
# Scaffold New Feature
Let's create a new feature together. I'll ask you questions:
1. **Feature Name**: What's the feature name?
- Wait for response
2. **Type**: What type? (component/service/page/util)
- Wait for response
3. **Dependencies**: Any external dependencies?
- Wait for response
4. **Tests**: Generate tests? (yes/no)
- Wait for response
Based on your answers, I'll create:
- Main implementation file
- Test file (if requested)
- Documentation stub
- Import/export updates
After creating files, I'll show you what was created.
Managing Custom Commands
List Available Commands
# In Claude Code
/help
Shows all built-in and custom commands
Reload Commands
After creating or editing a command:
# Restart Claude Code
exit
claude
# Or reload without restarting
/reload
Share Commands with Team
Project commands are in .claude/commands/ - commit them to git!
git add .claude/commands/
git commit -m "Add custom commands for team"
git push
Command Best Practices
1. Make Commands Specific
-
/do(too vague) -
/review-security(clear purpose)
2. Use Clear Names
- Use descriptive names that explain what the command does
- Use hyphens for multi-word commands:
/create-api-endpoint - Keep names short but meaningful
3. Include Good Descriptions
The description shows in /help - make it clear!
4. Structure Commands Well
- Use headings and numbered steps
- Break complex tasks into stages
- Include checkboxes for checklists
- Provide examples where helpful
5. Test Your Commands
After creating a command, test it in different scenarios to ensure it works as expected.
6. Update Regularly
As your workflow evolves, update commands to reflect new best practices.
Tips from Anthropic Teams
From the Security Engineering team: "We use custom slash commands extensively - 50% of all custom commands in our monorepo. These streamline specific workflows and dramatically speed up repeated tasks. Create commands for anything you do more than once a week."
From the Growth Marketing team: "We break complex workflows into specialized commands. Instead of one massive command, create separate commands for each step. This makes debugging easier and improves output quality."
From the Legal team: "Use commands to encode compliance workflows. We have commands for privacy review, security assessment, and legal approval that ensure we never skip steps."
Common Command Patterns
| Pattern | Example Command | Use Case |
|---|---|---|
| Checklist | /deploy |
Pre-flight checks before action |
| Investigation | /debug |
Systematic problem solving |
| Generator | /scaffold |
Create files from templates |
| Analyzer | /review |
Evaluate and provide feedback |
| Transformer | /refactor |
Modify existing code |
| Workflow | /release |
Multi-step processes |
Troubleshooting Commands
Command Not Found
Problem: Claude doesn't recognize your command.
Solutions:
- Check file is in
.claude/commands/or~/.claude/commands/ - Verify filename matches command name (e.g.,
review.mdfor/review) - Check frontmatter format is correct
- Restart Claude Code or run
/reload
Arguments Not Working
Problem: Arguments not being substituted.
Solutions:
- Use double curly braces:
{{arg_name}} - Check argument names match in frontmatter and content
- Verify required arguments are provided when calling
Command Too Long
Problem: Command exceeds context limits.
Solutions:
- Break into smaller, focused commands
- Use multiple commands in sequence
- Reference external documentation instead of including everything
Key Takeaways
- Custom commands create shortcuts for repeated tasks
- Store in
.claude/commands/(project) or~/.claude/commands/(personal) - Use
/command-nameto invoke - Require frontmatter with name and description
- Support arguments with
{{argument_name}}placeholders - Security team uses 50% of all custom commands at Anthropic
- Make commands specific and well-structured
- Share project commands via git
- Common patterns: checklists, investigations, generators, analyzers
- Test and update commands regularly
- Break complex workflows into multiple focused commands
Next: Chapter 10 - Hooks . Learn how to automate actions with event-driven hooks that trigger before and after Claude's tool usage!
Test your knowledge!
Take Chapter 9 Quiz โChapter 10: Hooks - Event Automation
Imagine if Claude could automatically do things when certain events happen - like running tests before committing code, or sending you a notification when a long task finishes. That's what Hooks are! They're like setting up automatic reactions to events in Claude Code.
What Are Hooks?
Think of hooks like this: If Claude Code is a smart assistant, hooks are like giving it instructions: "Whenever X happens, automatically do Y."
Without hooks: You have to remember to do things manually.
With hooks: Claude automatically does things at the right moment!
Simple Analogy
Imagine you have a smart home. Hooks are like automation rules:
- ๐ช "When I leave home, lock the doors" = Hook that runs on exit
- "When it gets dark, turn on lights" = Hook that triggers on time
- ๐ "When doorbell rings, send notification" = Hook that reacts to events
Claude Code hooks work the same way - they automatically do things when events happen!
Types of Hooks
1. Tool Hooks (Before/After Claude Uses Tools)
- PreToolUse - Before Claude uses any tool
- PostToolUse - After Claude uses any tool
Example uses: Logging, validation, notifications
2. Session Hooks (Session Lifecycle)
- SessionStart - When you start Claude Code
- SessionEnd - When you exit Claude Code
Example uses: Setup, cleanup, time tracking
3. Permission Hooks (When Claude Asks Permission)
- PermissionRequest - Before showing permission prompt
- PermissionGranted - After you approve
- PermissionDenied - After you deny
Example uses: Auto-approve trusted actions, logging decisions
4. Command Hooks (Custom Command Events)
- PreCommand - Before a slash command runs
- PostCommand - After a slash command completes
Example uses: Command timing, analytics
5. Notification Hooks (User Notifications)
- OnNotification - When Claude wants to notify you
Example uses: Custom notification systems (Slack, email)
Where Hooks Live
Project Hooks
Location: .claude/hooks/
my-project/
โโโ .claude/
โ โโโ hooks/
โ โโโ pre-tool-use.sh
โ โโโ post-tool-use.sh
โ โโโ session-start.sh
โโโ src/
Personal Hooks
Location: ~/.claude/hooks/
~/.claude/
โโโ hooks/
โโโ session-start.sh
โโโ notification.sh
Creating Your First Hook
Example 1: Auto-Run Tests Before Commit
Terminal Way:
mkdir -p .claude/hooks
cat > .claude/hooks/pre-tool-use.sh << 'EOF'
#!/bin/bash
# Check if Claude is about to use the Bash tool to commit
if [[ "$CLAUDE_TOOL" == "bash" ]] && echo "$CLAUDE_TOOL_INPUT" | grep -q "git commit"; then
echo " Running tests before commit..."
npm test
if [ $? -ne 0 ]; then
echo " Tests failed! Commit blocked."
exit 1 # This stops the commit
fi
echo " Tests passed! Proceeding with commit."
fi
EOF
chmod +x .claude/hooks/pre-tool-use.sh
VS Code Way:
- Create folder:
.claude/hooks/ - Create file:
pre-tool-use.sh - Add the content above
- Make it executable (Terminal:
chmod +x .claude/hooks/pre-tool-use.sh) - Restart Claude Code
How It Works:
Now when Claude tries to commit code:
- Hook detects git commit command
- Automatically runs tests
- If tests fail, blocks the commit
- If tests pass, allows commit
Hook Environment Variables
Claude Code provides information to your hooks through environment variables:
| Variable | What it contains |
|---|---|
CLAUDE_HOOK |
Hook name (PreToolUse, PostToolUse, etc.) |
CLAUDE_TOOL |
Tool being used (bash, read, write, edit) |
CLAUDE_TOOL_INPUT |
Input to the tool |
CLAUDE_TOOL_OUTPUT |
Output from tool (PostToolUse only) |
CLAUDE_SESSION_ID |
Unique session identifier |
CLAUDE_WORKING_DIR |
Current working directory |
Real-World Hook Examples
Example 2: Notification on Long Task Completion
#!/bin/bash
# File: .claude/hooks/post-tool-use.sh
# Track when task started (using temp file)
START_FILE="/tmp/claude_task_start_$CLAUDE_SESSION_ID"
# Calculate duration
if [ -f "$START_FILE" ]; then
START_TIME=$(cat "$START_FILE")
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))
# If task took more than 30 seconds, send notification
if [ $DURATION -gt 30 ]; then
# macOS notification
osascript -e "display notification \"Task completed in ${DURATION}s\" with title \"Claude Code\""
# Or Linux notification
# notify-send "Claude Code" "Task completed in ${DURATION}s"
# Or play a sound
# afplay /System/Library/Sounds/Glass.aiff
fi
rm "$START_FILE"
fi
# Record start time for next task
date +%s > "$START_FILE"
Example 3: Auto-Format Code Before Writing
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
# If Claude is about to write a JavaScript/TypeScript file
if [[ "$CLAUDE_TOOL" == "write" ]] && echo "$CLAUDE_TOOL_INPUT" | grep -qE '\.(js|ts|jsx|tsx)$'; then
FILE_PATH=$(echo "$CLAUDE_TOOL_INPUT" | grep -oE '[^ ]+\.(js|ts|jsx|tsx)')
echo " Auto-formatting code with Prettier..."
# Save the content to temp file, format it, then let Claude write
# (This is a simplified example - actual implementation may vary)
echo " Code formatted and ready to write"
fi
Example 4: Log All File Changes
#!/bin/bash
# File: .claude/hooks/post-tool-use.sh
LOG_FILE=".claude/changes.log"
# Log any file operations
if [[ "$CLAUDE_TOOL" == "write" ]] || [[ "$CLAUDE_TOOL" == "edit" ]]; then
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
echo "[$TIMESTAMP] $CLAUDE_TOOL: $CLAUDE_TOOL_INPUT" >> "$LOG_FILE"
# Extract filename
FILE=$(echo "$CLAUDE_TOOL_INPUT" | head -n 1)
echo " Logged change to $FILE"
fi
Example 5: Slack Notification on Session Start
#!/bin/bash
# File: .claude/hooks/session-start.sh
# Send Slack notification when you start coding
SLACK_WEBHOOK="your-webhook-url-here"
PROJECT_NAME=$(basename "$CLAUDE_WORKING_DIR")
MESSAGE="Started Claude Code session in project: $PROJECT_NAME"
curl -X POST "$SLACK_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"$MESSAGE\"}"
echo "๐ Notified team that you're coding"
Example 6: Time Tracking
#!/bin/bash
# File: .claude/hooks/session-start.sh
echo "$(date +%s)" > /tmp/claude_session_start_$CLAUDE_SESSION_ID
#!/bin/bash
# File: .claude/hooks/session-end.sh
START_FILE="/tmp/claude_session_start_$CLAUDE_SESSION_ID"
if [ -f "$START_FILE" ]; then
START=$(cat "$START_FILE")
END=$(date +%s)
DURATION=$((END - START))
MINUTES=$((DURATION / 60))
# Log time to file
PROJECT=$(basename "$CLAUDE_WORKING_DIR")
DATE=$(date "+%Y-%m-%d")
echo "$DATE,$PROJECT,$MINUTES minutes" >> ~/.claude/time_tracking.csv
echo "โฑ๏ธ Session lasted $MINUTES minutes"
rm "$START_FILE"
fi
Example 7: Security Check Before File Write
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
# Prevent writing sensitive files
if [[ "$CLAUDE_TOOL" == "write" ]]; then
# Check if trying to write sensitive files
if echo "$CLAUDE_TOOL_INPUT" | grep -qE '(\.env|credentials|secrets|private)'; then
echo "โ ๏ธ WARNING: Attempting to write sensitive file"
echo " Blocked for security"
exit 1 # Block the operation
fi
# Check content for potential secrets
if echo "$CLAUDE_TOOL_INPUT" | grep -qE '(password|api_key|secret|token).*='; then
echo "โ ๏ธ WARNING: Content may contain secrets"
echo "Please review carefully before proceeding"
fi
fi
Example 8: Auto-Commit After Multiple Changes
#!/bin/bash
# File: .claude/hooks/post-tool-use.sh
CHANGE_COUNT_FILE="/tmp/claude_changes_$CLAUDE_SESSION_ID"
# Count file modifications
if [[ "$CLAUDE_TOOL" == "write" ]] || [[ "$CLAUDE_TOOL" == "edit" ]]; then
# Increment counter
if [ -f "$CHANGE_COUNT_FILE" ]; then
COUNT=$(cat "$CHANGE_COUNT_FILE")
else
COUNT=0
fi
COUNT=$((COUNT + 1))
echo "$COUNT" > "$CHANGE_COUNT_FILE"
# Auto-commit after 5 changes
if [ $COUNT -ge 5 ]; then
echo "๐ฆ Auto-committing after $COUNT changes..."
git add .
git commit -m "Auto-commit: $COUNT files changed by Claude Code"
# Reset counter
echo "0" > "$CHANGE_COUNT_FILE"
fi
fi
Hook Configuration File
For more complex hooks, you can use a configuration file:
Location: .claude/hooks.json
{
"hooks": {
"PreToolUse": {
"enabled": true,
"script": ".claude/hooks/pre-tool-use.sh",
"timeout": 30000
},
"PostToolUse": {
"enabled": true,
"script": ".claude/hooks/post-tool-use.sh"
},
"SessionStart": {
"enabled": true,
"script": ".claude/hooks/session-start.sh"
},
"SessionEnd": {
"enabled": true,
"script": ".claude/hooks/session-end.sh"
},
"PermissionRequest": {
"enabled": true,
"script": ".claude/hooks/permission.sh",
"autoApprove": ["read"]
}
}
}
Hook Return Codes
Hooks control Claude's behavior through exit codes:
| Exit Code | Meaning | Effect |
|---|---|---|
0 |
Success | Continue normally |
1 |
Error/Block | Stop the action |
2 |
Warning | Show warning but continue |
Example: Conditional Blocking
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
if [[ "$CLAUDE_TOOL" == "bash" ]] && echo "$CLAUDE_TOOL_INPUT" | grep -q "rm -rf"; then
echo "โ ๏ธ Dangerous command detected: rm -rf"
echo "Are you sure? This could delete important files!"
# In automated hooks, you might want to block:
exit 1 # Block the operation
# Or warn and continue:
# exit 2 # Show warning but allow
fi
exit 0 # Allow by default
Hook Best Practices
1. Keep Hooks Fast
- Hooks run synchronously - slow hooks slow down Claude
- Use background jobs for long operations
- Set timeouts in hooks.json
2. Handle Errors Gracefully
#!/bin/bash
# Always check if required tools exist
if ! command -v npm &> /dev/null; then
echo "npm not found, skipping test hook"
exit 0 # Don't block if tool missing
fi
# Use error handling
set -e # Exit on error
trap 'echo "Hook failed at line $LINENO"' ERR
3. Log for Debugging
#!/bin/bash
LOG_FILE=".claude/hooks.log"
echo "[$(date)] PreToolUse: $CLAUDE_TOOL" >> "$LOG_FILE"
# Your hook logic here
echo "[$(date)] PreToolUse completed" >> "$LOG_FILE"
4. Make Hooks Configurable
#!/bin/bash
# Allow configuration via environment variables
AUTO_TEST=${CLAUDE_AUTO_TEST:-true}
TEST_COMMAND=${CLAUDE_TEST_COMMAND:-"npm test"}
if [ "$AUTO_TEST" = "true" ]; then
$TEST_COMMAND
fi
5. Document Your Hooks
Add comments explaining what each hook does and why:
#!/bin/bash
# Hook: pre-tool-use.sh
# Purpose: Run tests before git commits
# Blocks commit if tests fail
# Usage: Automatic, no configuration needed
# Dependencies: npm, git
Advanced Hook Patterns
Conditional Hook Execution
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
# Only run on work hours (9am-5pm weekdays)
HOUR=$(date +%H)
DAY=$(date +%u)
if [ $DAY -ge 6 ] || [ $HOUR -lt 9 ] || [ $HOUR -ge 17 ]; then
echo "Outside work hours - skipping strict checks"
exit 0
fi
# Run strict checks during work hours
# ... your strict validation here ...
Hook Chaining
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
# Run multiple checks in sequence
HOOKS_DIR=".claude/hooks/pre-tool-use.d"
if [ -d "$HOOKS_DIR" ]; then
for hook in "$HOOKS_DIR"/*.sh; do
if [ -x "$hook" ]; then
echo "Running $(basename $hook)..."
"$hook"
if [ $? -ne 0 ]; then
echo "Hook $(basename $hook) failed"
exit 1
fi
fi
done
fi
Hook with User Prompt
#!/bin/bash
# File: .claude/hooks/pre-tool-use.sh
# Ask user for confirmation on dangerous operations
if [[ "$CLAUDE_TOOL" == "bash" ]] && echo "$CLAUDE_TOOL_INPUT" | grep -q "git push.*--force"; then
echo "โ ๏ธ You're about to force push!"
read -p "Are you sure? (yes/no): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
echo " Force push cancelled"
exit 1
fi
fi
Troubleshooting Hooks
Hook Not Running
Problem: Your hook doesn't execute.
Solutions:
- Check file is executable:
chmod +x .claude/hooks/your-hook.sh - Verify file name matches hook type exactly
- Check shebang line:
#!/bin/bash - Look for errors in
.claude/hooks.log
Hook Slowing Down Claude
Problem: Hook takes too long.
Solutions:
- Run slow operations in background:
long_command & - Set timeout in hooks.json
- Cache results when possible
- Use PostToolUse instead of PreToolUse
Hook Failing Silently
Problem: Hook fails but you don't see errors.
Solutions:
- Add logging to your hook
- Check stderr:
2>&1 | tee -a hook.log - Test hook manually:
bash .claude/hooks/your-hook.sh
Security Considerations
Important: Hooks run with your permissions and can execute any code!
Safe Hook Practices:
- Review all hook scripts before using
- Don't copy hooks from untrusted sources
- Use relative paths, not absolute
- Validate all environment variables
- Add hooks to .gitignore if they contain secrets
What to Avoid:
- Don't store passwords in hooks
- Don't run hooks as root/sudo
- Don't make external network calls without validation
- Don't modify files outside project directory
Key Takeaways
- Hooks automate actions when events happen
- 5 types: Tool, Session, Permission, Command, Notification
- Store in
.claude/hooks/(project) or~/.claude/hooks/(personal) - Hooks are shell scripts with specific names
- Must be executable:
chmod +x hook.sh - Access event data via environment variables
- Exit code 0 = continue, 1 = block, 2 = warn
- Keep hooks fast - slow hooks slow down Claude
- Use for: testing, logging, notifications, validation
- Always handle errors gracefully
- Review hooks for security before using
Next: Chapter 11 - Plugins . Learn about the Claude Code plugin ecosystem - installing, using, and creating plugins that extend functionality!
Test your knowledge!
Take Chapter 10 Quiz โChapter 11: Plugins - Extend Everything
Imagine if Claude Code could be customized with ready-made packages that add new features instantly - like an app store for your AI coding assistant. That's what Plugins are! They bundle Skills, Commands, Hooks, and MCP servers into one easy-to-install package.
What Are Plugins?
Think of plugins like this: If Claude Code is your smartphone, plugins are like apps you download from the app store.
Without plugins: You manually set up skills, commands, hooks, and MCP servers one by one.
With plugins: Install one package and get everything you need instantly!
Simple Analogy
Imagine building a car:
- Without plugins: Buy each part separately - engine, wheels, seats, radio - and assemble everything yourself
- ๐ With plugins: Buy a complete "Sports Package" that includes performance engine, racing wheels, sport seats, and upgraded audio - all pre-configured!
Plugins bundle related features into one package!
What's Inside a Plugin?
A plugin can include any combination of:
- Skills - Domain expertise (e.g., React best practices)
- Commands - Slash commands (e.g., /react-component)
- Hooks - Automation (e.g., auto-lint on save)
- MCP Servers - External tools (e.g., Figma integration)
- Templates - File templates
- Configuration - Pre-configured settings
Example Plugin Bundles
React Developer Plugin might include:
- React component patterns skill
- /component command to scaffold components
- /test-component command
- Hook to auto-format JSX on save
- Component templates
DevOps Plugin might include:
- Kubernetes expertise skill
- /deploy command with checklist
- /logs command to analyze logs
- Hook to validate YAML files
- MCP server for cloud provider APIs
Finding Plugins
Claude Code Marketplace
The official marketplace for vetted, high-quality plugins.
Terminal Way
# Browse available plugins
claude plugin search
# Search for specific plugins
claude plugin search react
# Get plugin details
claude plugin info @claude/react-tools
VS Code Way
- Open Claude Code panel
- Click "Plugins" or "Marketplace"
- Browse or search for plugins
- Click on a plugin to see details
- Click "Install" to add it
Installing Plugins
From the Marketplace
Terminal Way:
# Install a plugin globally (available in all projects)
claude plugin install @claude/react-tools
# Install for current project only
claude plugin install @claude/react-tools --project
# Install specific version
claude plugin install @claude/react-tools@1.2.0
VS Code Way:
- Find the plugin in marketplace
- Click "Install"
- Choose scope (Global or Project)
- Wait for installation to complete
- Restart Claude Code if prompted
From npm
Many community plugins are published on npm:
# Install from npm
claude plugin install npm:claude-plugin-eslint
# Or directly with npm, then link
npm install -g claude-plugin-eslint
claude plugin link claude-plugin-eslint
From Local Directory
For development or private plugins:
# Install from local folder
claude plugin install ./path/to/my-plugin
# Or create a symlink for development
claude plugin link ./path/to/my-plugin
Using Installed Plugins
Once installed, plugins work automatically!
Example: After Installing React Plugin
claude
# Skills are automatically available
"Create a React component following best practices"
โ Claude uses React plugin's expertise
# Commands are available
/component UserProfile
โ Scaffolds a new component
/test-component UserProfile
โ Generates tests
# Hooks run automatically
โ JSX auto-formats when you save files
Managing Plugins
List Installed Plugins
# See all installed plugins
claude plugin list
# Output shows:
# @claude/react-tools@1.2.0 (global)
# @company/internal-tools@2.0.1 (project)
# npm:claude-plugin-eslint@3.1.0 (global)
Update Plugins
# Update specific plugin
claude plugin update @claude/react-tools
# Update all plugins
claude plugin update --all
# Check for updates
claude plugin outdated
Uninstall Plugins
# Remove a plugin
claude plugin uninstall @claude/react-tools
# Remove from project only
claude plugin uninstall @company/internal-tools --project
Enable/Disable Plugins
# Disable temporarily without uninstalling
claude plugin disable @claude/react-tools
# Re-enable
claude plugin enable @claude/react-tools
Creating Your Own Plugin
You can create plugins for your team or to share with the community!
Plugin Structure
my-awesome-plugin/
โโโ plugin.json โ Plugin manifest (required)
โโโ README.md โ Documentation
โโโ skills/ โ Skills to include
โ โโโ my-skill/
โ โโโ SKILL.md
โโโ commands/ โ Custom commands
โ โโโ my-command.md
โ โโโ another-command.md
โโโ hooks/ โ Automation hooks
โ โโโ pre-tool-use.sh
โ โโโ post-tool-use.sh
โโโ mcp/ โ MCP server configurations
โ โโโ my-server.json
โโโ templates/ โ File templates
โโโ component.tsx
Plugin Manifest (plugin.json)
Every plugin needs a manifest file:
{
"name": "@myorg/my-awesome-plugin",
"version": "1.0.0",
"description": "Awesome tools for awesome developers",
"author": "Your Name ",
"license": "MIT",
"keywords": ["react", "typescript", "development"],
"claude": {
"minVersion": "1.0.0",
"maxVersion": "2.0.0"
},
"dependencies": {
"@claude/react-tools": "^1.2.0"
},
"skills": ["skills/my-skill"],
"commands": ["commands/*.md"],
"hooks": ["hooks/*.sh"],
"mcp": ["mcp/*.json"],
"templates": ["templates/"]
}
Manifest Fields Explained
| Field | Required | Description |
|---|---|---|
name |
Yes | Unique plugin name (use @scope/name for npm) |
version |
Yes | Semantic version (1.0.0) |
description |
Yes | What the plugin does |
author |
No | Plugin creator |
claude.minVersion |
No | Minimum Claude Code version |
dependencies |
No | Other plugins this depends on |
skills |
No | Skills to include (glob patterns) |
commands |
No | Commands to include |
Creating a Simple Plugin
Example: React Component Plugin
Step 1: Create Plugin Structure
mkdir react-component-plugin
cd react-component-plugin
mkdir -p skills/react-patterns commands templates
Step 2: Create plugin.json
cat > plugin.json << 'EOF'
{
"name": "@myorg/react-component-plugin",
"version": "1.0.0",
"description": "Tools for creating React components",
"author": "Your Name",
"license": "MIT",
"keywords": ["react", "component", "typescript"],
"skills": ["skills/react-patterns"],
"commands": ["commands/*.md"],
"templates": ["templates/"]
}
EOF
Step 3: Add a Skill
cat > skills/react-patterns/SKILL.md << 'EOF'
---
name: react-patterns
description: React component best practices
version: 1.0.0
---
# React Component Patterns
## Component Structure
- Use functional components with hooks
- Keep components small (under 200 lines)
- One component per file
- Props interface at top
## Naming Conventions
- Components: PascalCase (UserProfile.tsx)
- Props: ComponentNameProps
- Hooks: use prefix (useUserData)
## Best Practices
- Always type props with TypeScript
- Use const for components
- Destructure props
- Add prop validation
EOF
Step 4: Add a Command
cat > commands/component.md << 'EOF'
---
name: component
description: Create a new React component
args:
- name: name
description: Component name
required: true
---
# Create React Component: {{name}}
Please create a React component with:
1. **TypeScript file**: {{name}}.tsx
2. **Props interface**: {{name}}Props
3. **Functional component** using const
4. **Default export**
5. **Basic JSDoc comment**
Follow our React patterns skill guidelines.
EOF
Step 5: Add a Template
cat > templates/component.tsx << 'EOF'
import React from 'react';
interface {{ComponentName}}Props {
// Add your props here
}
/**
* {{ComponentName}} component
*/
export const {{ComponentName}}: React.FC<{{ComponentName}}Props> = (props) => {
return (
{/* Component content */}
);
};
export default {{ComponentName}};
EOF
Step 6: Test Your Plugin
# Install locally
claude plugin install .
# Test it
claude
/component MyNewComponent
Publishing Plugins
To npm
# Prepare for publishing
npm init -y # If you haven't already
npm version 1.0.0
# Publish to npm
npm publish
# Users can then install:
# claude plugin install npm:@myorg/react-component-plugin
To Claude Marketplace
- Create account on Claude Code marketplace
- Submit plugin for review
- Wait for approval (typically 1-2 days)
- Plugin becomes available to all users
To GitHub
# Create GitHub repo
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourname/plugin.git
git push -u origin main
# Users can install from GitHub:
# claude plugin install github:yourname/plugin
Popular Plugin Examples
Official Plugins
- @claude/react-tools - React development utilities
- @claude/typescript-tools - TypeScript helpers
- @claude/python-tools - Python development
- @claude/devops-tools - DevOps workflows
- @claude/testing-tools - Test generation and running
Community Plugins
- claude-plugin-eslint - ESLint integration
- claude-plugin-prettier - Code formatting
- claude-plugin-docker - Docker helpers
- claude-plugin-aws - AWS tools
- claude-plugin-figma - Figma integration
Plugin Configuration
Users can configure plugins in their settings:
Location: .claude/settings.json
{
"plugins": {
"@claude/react-tools": {
"enabled": true,
"config": {
"componentStyle": "functional",
"useTypeScript": true,
"includeTests": true
}
},
"@myorg/custom-plugin": {
"enabled": true,
"config": {
"apiKey": "${API_KEY}",
"endpoint": "https://api.example.com"
}
}
}
}
Reading Configuration in Your Plugin
In your plugin code, access configuration via environment variables:
#!/bin/bash
# In a hook script
# Access plugin config
COMPONENT_STYLE=${CLAUDE_PLUGIN_CONFIG_componentStyle:-functional}
USE_TYPESCRIPT=${CLAUDE_PLUGIN_CONFIG_useTypeScript:-true}
echo "Creating $COMPONENT_STYLE component with TypeScript: $USE_TYPESCRIPT"
Plugin Best Practices
1. Follow Naming Conventions
- Official plugins:
@claude/plugin-name - Organization plugins:
@orgname/plugin-name - Community plugins:
claude-plugin-name
2. Provide Good Documentation
Include a detailed README.md with:
- What the plugin does
- Installation instructions
- Usage examples
- Configuration options
- Changelog
3. Version Properly
Use semantic versioning (semver):
- Major (1.0.0 โ 2.0.0): Breaking changes
- Minor (1.0.0 โ 1.1.0): New features, backwards compatible
- Patch (1.0.0 โ 1.0.1): Bug fixes
4. Test Thoroughly
- Test on different operating systems
- Test with different Claude Code versions
- Test installation and uninstallation
- Test with other plugins
5. Handle Dependencies
{
"dependencies": {
"@claude/react-tools": "^1.2.0"
},
"peerDependencies": {
"node": ">=14.0.0"
}
}
6. Provide Configuration Options
Make your plugin configurable so users can customize behavior.
7. Keep It Focused
- "Everything for all developers" plugin
- "React TypeScript component tools" plugin
Plugin Security
Important: Plugins can execute code with your permissions!
Before Installing Plugins:
- Check plugin author and source
- Read reviews and ratings
- Review plugin permissions
- Check last update date
- Look at number of downloads
Red Flags:
- ๐ฉ No source code available
- ๐ฉ Asks for unnecessary permissions
- ๐ฉ No documentation or examples
- ๐ฉ Poor reviews or reports of issues
- ๐ฉ Not updated in over a year
For Plugin Creators:
- Never include secrets in plugin code
- Validate all user inputs
- Request minimal permissions
- Document security considerations
- Keep dependencies updated
Troubleshooting Plugins
Plugin Won't Install
Problem: Installation fails.
Solutions:
- Check Claude Code version:
claude --version - Verify plugin compatibility in plugin.json
- Check internet connection (for marketplace/npm)
- Try with sudo/admin if permission denied
Plugin Not Working
Problem: Installed but features don't work.
Solutions:
- Verify plugin is enabled:
claude plugin list - Restart Claude Code
- Check plugin configuration in settings.json
- Look for errors in
~/.claude/logs/
Plugin Conflicts
Problem: Multiple plugins interfere with each other.
Solutions:
- Disable one plugin at a time to identify conflict
- Check if plugins provide conflicting commands
- Update plugins to latest versions
- Report issue to plugin authors
Plugin Development Tips
Use Plugin Templates
# Create from official template
claude plugin create my-plugin --template official
# This scaffolds a complete plugin structure
Test Locally First
# Link plugin for development
cd my-plugin
claude plugin link .
# Make changes and test
# Restart Claude Code to see changes
Use Semantic Release
Automate versioning and publishing:
# Install semantic-release
npm install --save-dev semantic-release
# Configure in package.json
{
"release": {
"branches": ["main"]
}
}
Key Takeaways
- Plugins bundle Skills, Commands, Hooks, MCP servers, and templates
- Install from marketplace, npm, or local directory
- Use
claude plugin install nameto add plugins - Manage with
list,update,disable,uninstall - Create plugins with plugin.json manifest
- Plugin structure: skills, commands, hooks, mcp, templates folders
- Publish to npm, GitHub, or Claude Marketplace
- Follow naming conventions and semantic versioning
- Always review plugins for security before installing
- Keep plugins focused on specific use cases
- Test thoroughly across different environments
Next: Chapter 12 - Output Styles. Learn how to customize Claude's communication style and response format to match your preferences!
Test your knowledge!
Take Chapter 11 Quiz โChapter 12: Output Styles - Customize Claude's Voice
Imagine if you could teach Claude to communicate exactly the way you prefer - more concise, more detailed, more technical, or more friendly. That's what Output Styles are! They let you customize how Claude talks to you, formats responses, and presents information.
What Are Output Styles?
Think of output styles like this: If Claude is a person talking to you, output styles are like telling them your communication preferences.
Without output styles: Claude uses default communication - moderate length, balanced technical detail.
With output styles: Claude adapts to YOUR preferences - as brief or detailed as you want!
Simple Analogy
Imagine you have a friend who explains things to you. Output styles are like saying:
- "Give me bullet points, I'm in a hurry" = Concise style
- "Explain everything in detail, I'm learning" = Detailed style
- "Use technical terms, I'm experienced" = Technical style
- "Keep it casual and friendly" = Casual style
Built-In Output Styles
Claude Code comes with several pre-made styles:
1. Default Style
What it's like: Balanced - moderate length, clear explanations, professional tone.
Best for: General use, most situations
2. Concise Style
What it's like: Brief, direct, bullet points, minimal explanations.
Best for: When you're experienced and just need quick answers
Example response:
Created UserProfile.tsx with:
- Props interface
- Functional component
- TypeScript types
- Default export
Next: Add tests?
3. Detailed Style
What it's like: Comprehensive, thorough explanations, step-by-step, lots of context.
Best for: Learning, complex topics, beginners
Example response:
I've created UserProfile.tsx for you. Let me explain what I did:
1. Props Interface (UserProfileProps):
- This defines the shape of data the component expects
- TypeScript will check that you pass the right props
- Adding props here makes them available in the component
2. Functional Component:
- Used React.FC type for type safety
- Destructured props for cleaner code
- Arrow function syntax (modern React pattern)
3. Component Structure:
- Returns JSX (looks like HTML)
- Wrapped in a div container
- Ready for you to add your UI elements
4. Export:
- Default export allows flexible imports
- Named export also available for convenience
Would you like me to add tests for this component next?
4. Technical Style
What it's like: Uses technical jargon, assumes expertise, focuses on implementation details.
Best for: Experienced developers, system architecture, performance optimization
Example response:
Implemented UserProfile.tsx:
- React.FC with generic Props interface
- Memoization-ready structure
- Props destructuring for O(1) access
- TSX syntax with strict typing
- ES6 default export with named export fallback
Optimizations applied:
- No inline function definitions (prevents re-renders)
- Props interface separate from component (tree-shaking eligible)
Ready for memo() wrapping if needed.
5. Beginner-Friendly Style
What it's like: Simple language, explains terms, lots of analogies, encouraging tone.
Best for: Learning to code, new to the language/framework
Example response:
Great! I've created your UserProfile component. Let me break this down in simple terms:
Think of a component like a Lego block - you can use it to build your app.
What we created:
Props: Think of these like settings you can adjust (like volume on a speaker)
Component: The actual piece that shows up on your page
TypeScript: This helps catch mistakes before they happen (like spell-check!)
The cool part: You can now use this component anywhere in your app, just like using a Lego block multiple times in different places!
Want to learn about adding tests next? (Tests make sure your code works correctly)
6. Casual Style
What it's like: Friendly, conversational, uses contractions, less formal.
Best for: Comfortable, relaxed coding sessions
Example response:
Done! Created your UserProfile component ๐
Here's what I put in there:
- Props interface (so TypeScript knows what to expect)
- The main component (using modern functional style)
- Types for everything (keeps things safe)
- Export statements (so you can import it elsewhere)
Pretty straightforward stuff. Want me to add tests too?
Using Output Styles
Setting Your Preferred Style
Terminal Way:
# Set global style (applies to all projects)
claude config set output-style concise
# Set for current session only
claude --output-style detailed
# Set for specific project
cd my-project
claude config set output-style technical --local
VS Code Way:
- Open Claude Code settings (gear icon)
- Look for "Output Style" dropdown
- Select your preferred style
- Changes apply immediately
Switching Styles Mid-Session
claude
# Start with default style
"Create a React component"
# Switch to concise
/style concise
# Continue - now Claude is brief
"Add props to it"
# Switch to detailed for learning
/style detailed
# Continue - now Claude is thorough
"How does this component work?"
Creating Custom Output Styles
You can create your own styles that match your exact preferences!
Where Custom Styles Live
Personal styles: ~/.claude/styles/
Project styles: .claude/styles/
Custom Style Structure
my-style/
โโโ STYLE.md โ Style definition file
Creating Your First Custom Style
Example: "Senior Dev" Style
Terminal Way:
mkdir -p ~/.claude/styles/senior-dev
cat > ~/.claude/styles/senior-dev/STYLE.md << 'EOF'
---
name: senior-dev
description: For experienced senior developers
---
# Senior Developer Output Style
## Communication Rules
### Length & Format
- Keep responses under 200 words unless asked for more
- Use bullet points for lists
- Code first, explanation after
- Skip obvious explanations
### Technical Level
- Use correct technical terminology
- Reference design patterns by name
- Assume knowledge of common frameworks
- Don't explain basic concepts
### Code Style
- Show complete, production-ready code
- Include error handling
- Add TypeScript types
- Follow industry best practices
- No "TODO" comments
### What to Include
Implementation details
Performance considerations
Edge cases
Security implications
Testing suggestions
### What to Skip
Basic syntax explanations
Framework introductions
Overly detailed comments
Beginner tips
## Example Responses
### Good:
"Implemented singleton pattern with lazy initialization. Thread-safe via double-checked locking. Memory overhead: ~50 bytes. Consider object pooling if instantiation > 1000/sec."
### Avoid:
"I created a singleton pattern. A singleton is a design pattern that restricts the instantiation of a class to one instance. This is useful when..."
## Tone
- Direct and efficient
- Peer-to-peer (not teacher-student)
- Focus on "why" not "what"
- Assume competence
EOF
VS Code Way:
- Create folder:
~/.claude/styles/senior-dev/ - Create file:
STYLE.md - Add the content above
- Save and restart Claude Code
Using Your Custom Style
# Set it as your default
claude config set output-style senior-dev
# Or use it temporarily
claude --output-style senior-dev
STYLE.md File Format
Frontmatter (Required)
---
name: style-name
description: Brief description of this style
author: Your Name (optional)
version: 1.0.0 (optional)
---
Content Sections (Recommended)
- Communication Rules: How to format responses
- Technical Level: What expertise to assume
- Tone: Friendly, formal, casual, etc.
- What to Include: Topics to cover
- What to Skip: Things to avoid
- Examples: Show good vs bad responses
Real-World Custom Style Examples
Example 1: "Code Review" Style
---
name: code-review
description: For thorough code reviews
---
# Code Review Output Style
## Purpose
Provide comprehensive, constructive code reviews.
## Format
Always structure reviews as:
### 1. Summary
- Overall assessment (2-3 sentences)
- Key strengths
- Main concerns
### 2. Critical Issues (๐ด)
Issues that must be fixed:
- Security vulnerabilities
- Bugs or logic errors
- Breaking changes
- Performance bottlenecks
### 3. Improvements (๐ก)
Should be addressed:
- Code smells
- Maintainability concerns
- Missing tests
- Documentation gaps
### 4. Suggestions (๐ข)
Nice to have:
- Style improvements
- Optimization opportunities
- Alternative approaches
### 5. Praise ()
What was done well:
- Good patterns used
- Clear code
- Solid architecture
## Tone
- Constructive, never condescending
- Explain WHY, not just WHAT
- Suggest solutions, not just problems
- Acknowledge good work
- Frame as learning opportunity
## Code Examples
Always provide:
- Current code snippet
- Improved version
- Brief explanation of why better
## Avoid
Nitpicking formatting (unless severe)
Vague feedback like "this is bad"
Suggesting changes without explaining benefits
Overwhelming with too many minor issues
Example 2: "Quick Learner" Style
---
name: quick-learner
description: Fast-paced learning with examples
---
# Quick Learner Output Style
## Philosophy
Learn by doing. Show, don't tell.
## Format
### 1. Answer First
Start with the solution immediately.
### 2. Example Code
Show complete, working code example.
### 3. Key Points
3-5 bullet points explaining key concepts.
### 4. Try It
Suggest immediate hands-on exercise.
### 5. Next Steps
One follow-up concept to learn next.
## Length
- Total response: 150-250 words
- Code examples: Complete but minimal
- Explanations: Essential only
## Tone
- Energetic and encouraging
- "Let's try this!"
- Focus on building confidence
- Celebrate small wins
## Example Response Structure
\`\`\`javascript
// Working code here
const example = () => {
// Implementation
};
\`\`\`
Key points:
โข Point 1
โข Point 2
โข Point 3
Try it: [Specific exercise]
Next: [Related concept to learn]
## Avoid
Long theory before practice
Overwhelming with options
Academic explanations
Discouraging complexity warnings
Example 3: "Documentation" Style
---
name: documentation
description: Clear, comprehensive documentation format
---
# Documentation Output Style
## Purpose
Generate clear, user-facing documentation.
## Structure
Every response follows this template:
### Overview
One paragraph explaining what this is and why it exists.
### Installation / Setup
Step-by-step instructions with commands.
### Basic Usage
Simplest possible example.
### API / Reference
Complete list of options, parameters, methods.
### Examples
3-5 real-world examples from simple to complex.
### Common Issues
Troubleshooting guide.
### See Also
Related documentation links.
## Writing Guidelines
### Clarity
- Use present tense
- Active voice
- Short sentences (max 20 words)
- Define all terms
- No assumptions about knowledge
### Format
- Use headings liberally
- Include code blocks
- Add tables for parameters
- Use lists for steps
- Include examples inline
### Completeness
Every code example must:
- Be complete (no "...")
- Be tested and working
- Include imports
- Show expected output
- Include error cases
## Tone
- Professional but friendly
- Patient and thorough
- Neutral (no opinions)
- Helpful (anticipate questions)
Example 4: "Pair Programming" Style
---
name: pair-programming
description: Like coding with a partner
---
# Pair Programming Output Style
## Approach
We're coding together, collaboratively.
## Communication Pattern
### Think Aloud
- Share thought process
- Explain decisions as they're made
- Discuss trade-offs
- Ask for your input
### Iterate Together
- Propose solution
- Wait for feedback
- Refine based on discussion
- Build incrementally
### Check Understanding
- "Does this make sense?"
- "What do you think about...?"
- "Should we...?"
- "Any concerns with this approach?"
## Response Format
1. **Current Goal**
State what we're trying to accomplish
2. **Approach**
Propose how to do it
3. **Code**
Implement together
4. **Verification**
"Let's check this works..."
5. **Next**
"What should we tackle next?"
## Tone
- Collaborative ("we", not "I")
- Thinking out loud
- Open to alternatives
- Respectful of your input
- Build on your ideas
## Example
"Okay, so we need to validate user input.
I'm thinking we could use a schema validator like Zod - it gives us type safety and clear error messages. What do you think?
[Wait for response consideration]
Let's start with the basics:
\`\`\`typescript
// Basic schema
\`\`\`
Does this structure work for you? Should we add more validation rules?"
## Avoid
Dictating solutions
Moving too fast
Ignoring your suggestions
Completing without discussion
Example 5: "Teaching" Style
---
name: teaching
description: Comprehensive teaching with learning checks
---
# Teaching Output Style
## Educational Approach
Build understanding from fundamentals.
## Structure
### 1. Connect to Known
Start with something familiar.
### 2. Introduce Concept
Explain the new idea clearly.
### 3. Show Example
Concrete, simple example.
### 4. Build Complexity
Add layers gradually.
### 5. Common Mistakes
Show what NOT to do and why.
### 6. Practice Exercise
Give them something to try.
### 7. Check Understanding
Ask questions to verify learning.
## Explanation Technique
### Use Analogies
Every abstract concept gets a real-world comparison.
### Layer Information
- First: What it is
- Second: Why it exists
- Third: How it works
- Fourth: When to use it
### Predict Questions
Answer obvious questions before they're asked.
### Show Evolution
Show code improving from bad โ good โ great.
## Examples Format
### Bad Example
\`\`\`javascript
// Problematic code
\`\`\`
Why this is problematic: [Explanation]
### Better Example
\`\`\`javascript
// Improved code
\`\`\`
What we fixed: [Explanation]
### Best Practice
\`\`\`javascript
// Production-ready code
\`\`\`
Why this is ideal: [Explanation]
## Tone
- Patient and encouraging
- Never condescending
- Celebrate understanding
- Frame mistakes as learning
- "Great question!"
- "Let's explore why..."
## Pacing
- Never rush
- Check understanding frequently
- Repeat key points differently
- Provide memory aids
- Build confidence gradually
## Avoid
Assuming knowledge
Skipping fundamentals
Using jargon without definition
Moving on before understanding confirmed
Style Configuration Options
You can configure additional style settings in your settings file:
Location: .claude/settings.json
{
"outputStyle": {
"default": "concise",
"perContext": {
"codeReview": "code-review",
"learning": "detailed",
"pairing": "pair-programming"
},
"formatting": {
"maxLineLength": 80,
"codeBlockLanguage": "typescript",
"includeEmojis": false,
"bulletStyle": "โข"
}
}
}
Context-Aware Styles
You can set different styles for different contexts:
# In your .claude/settings.json
{
"outputStyle": {
"default": "concise",
"contextRules": [
{
"when": "mode === 'ask'",
"style": "detailed"
},
{
"when": "tool === 'review'",
"style": "code-review"
},
{
"when": "fileType === 'test'",
"style": "technical"
}
]
}
}
Style Best Practices
1. Be Specific
- "Be helpful"
- "Respond in 3-5 bullet points maximum"
2. Show Examples
Always include "good" vs "avoid" examples in your style.
3. Consider Your Use Case
- Solo coding: Concise or technical
- Learning: Detailed or beginner-friendly
- Team reviews: Code-review style
- Documentation: Documentation style
4. Test Your Style
# Try your style with different prompts
claude --output-style my-custom-style
# Ask various types of questions to see how it responds
"Explain React hooks"
"Review this code"
"Create a component"
5. Iterate and Improve
As you use your style, refine it based on what works and what doesn't.
Managing Styles
List Available Styles
# See all styles (built-in + custom)
claude style list
# Output:
# Built-in styles:
# default, concise, detailed, technical,
# beginner-friendly, casual
#
# Custom styles:
# senior-dev, code-review, quick-learner
View Style Details
# See what a style does
claude style show senior-dev
# Shows the STYLE.md content
Set Default Style
# Set globally
claude config set output-style concise
# Set for project
cd my-project
claude config set output-style detailed --local
Reset to Default
# Go back to default style
claude config set output-style default
Troubleshooting Styles
Style Not Working
Problem: Claude doesn't follow your custom style.
Solutions:
- Check STYLE.md file has correct frontmatter
- Verify file location (
~/.claude/styles/name/STYLE.md) - Restart Claude Code
- Make style rules more specific
Style Too Strict
Problem: Claude's responses feel too constrained.
Solutions:
- Add "Use judgment when appropriate" clause
- Switch to less strict style for complex topics
- Use
/style defaulttemporarily
Conflicting Styles
Problem: Different preferences for different contexts.
Solution: Use context-aware styles in settings.json
Key Takeaways
- Output styles customize how Claude communicates
- Built-in styles: default, concise, detailed, technical, beginner-friendly, casual
- Set with
claude config set output-style name - Switch mid-session with
/style name - Create custom styles in
~/.claude/styles/name/STYLE.md - Include frontmatter with name and description
- Define: communication rules, technical level, tone, examples
- Show "good" vs "avoid" examples in your style
- Use context-aware rules for different situations
- Test and iterate on custom styles
- Choose style based on use case (learning vs productivity)
Next: Chapter 13 - Common Workflows. Learn the most frequent development patterns and how Claude Code streamlines bug fixing, refactoring, testing, and more!
Test your knowledge!
Take Chapter 12 Quiz โChapter 13: Common Workflows
Think of Claude Code as your development partner who knows all the common patterns. Just like a restaurant has a flow for taking orders, cooking food, and serving customers, software development has common workflows for fixing bugs, improving code, and shipping features. Let's learn the most frequent patterns that'll make up 80% of your daily work!
Bug Fixing Workflow
When something breaks, Claude Code becomes your debugging detective. Instead of spending hours tracking down issues, you work together systematically.
The 5-Step Bug Fix Pattern
Step 1: Show Claude the Bug
Terminal Way
claude
# Then type:
I'm getting this error when users click the login button:
[paste error message]
Can you help me find and fix it?
VS Code Way
- Click Claude icon in sidebar
- Take screenshot of error (Cmd/Ctrl+Shift+4 on Mac)
- Paste screenshot into Claude chat
- Type: "What's causing this error?"
Step 2: Let Claude Investigate
Claude will automatically search your codebase for the problem. It'll find the file, read the code, and trace through the logic.
Step 3: Review Claude's Diagnosis
Claude explains what's wrong in simple terms: "The login button calls handleLogin(), but that function expects a 'username' parameter. Your form is sending 'email' instead."
Step 4: Let Claude Fix It (or Guide You)
# Ask Claude:
Can you fix this bug?
# Or if you want to learn:
Can you show me how to fix it and explain why?
Step 5: Test the Fix
# Ask Claude to test:
Can you run the tests to verify this works?
# Claude will automatically:
# 1. Run your test suite
# 2. Check if the bug is fixed
# 3. Report any new issues
Real Example from Anthropic Security Team
The Challenge: Production incident with a mysterious crash. Stack traces showed errors deep in infrastructure code.
What They Did: Pasted the stack trace into Claude Code and asked: "Trace the control flow through this error."
Result: Bug fixed in 5 minutes instead of 15 minutes of manual code scanning. Claude found the issue was in a configuration file three layers deep that humans would've taken much longer to locate.
Tip: The Security team now debugs infrastructure issues 3x faster because Claude can trace through complex codebases instantly.
Refactoring Workflow
Refactoring means "making code better without changing what it does." It's like reorganizing your closet - everything still fits, but it's easier to find and use. Claude Code excels at this!
Pattern 1: Extract Function/Component
When code gets messy, break it into smaller pieces.
Terminal Way
claude
# Select the messy code section, then:
This function is doing too much. Can you:
1. Extract the validation logic into a separate function
2. Extract the API call into another function
3. Make the main function cleaner and easier to read
VS Code Way
- Highlight the code you want to extract
- Open Claude panel
- Right-click โ "Ask Claude about selection"
- Type: "Extract this into a reusable function"
Pattern 2: Rename Variables/Functions
Bad names confuse everyone. Good names explain themselves.
claude
# Example request:
Can you rename these variables to be more descriptive?
- Change 'x' to 'userAge'
- Change 'fn' to 'calculateTotalPrice'
- Change 'data' to 'customerOrders'
Make sure to update all references across the codebase.
Pattern 3: Simplify Complex Logic
claude
# Point Claude to messy code:
This function has nested if statements 5 levels deep.
Can you simplify this using early returns or guard clauses?
Keep the same behavior but make it more readable.
Real Example from Anthropic Data Science Team
The Challenge: Merge conflicts and "semi-complicated file refactoring" too complex for editor macros but not large enough for major development effort.
What They Did: Used Claude Code like a "slot machine" - commit current state, let Claude work autonomously for 30 minutes, then either accept the solution or restart fresh if it doesn't work.
Result: 2-4x time savings on routine refactoring tasks. Tedious work that was manageable manually now completed much faster.
Tip: They emphasize starting from a clean git state and committing checkpoints regularly so they can easily revert any incorrect changes.
Testing Workflow
Tests are like safety nets - they catch bugs before users see them. Claude Code makes writing tests 10x faster.
Pattern 1: Test-Driven Development (TDD)
Write tests BEFORE writing code. Sounds backwards, but it works!
Terminal Way
claude
I want to add a 'calculateDiscount' function that:
- Takes price and discount percentage
- Returns discounted price
- Throws error if discount > 100%
Can you write the tests first, then implement the function?
VS Code Way
- Create new file:
calculateDiscount.test.js - Open Claude panel
- Describe what the function should do
- Ask: "Write comprehensive tests for this"
- After tests pass, ask: "Now implement the function"
Pattern 2: Generate Tests for Existing Code
Already wrote code? Claude can create tests for it.
claude
# Point to your function:
@src/utils/formatDate.js
Can you write comprehensive unit tests for this function?
Include:
- Happy path (normal usage)
- Edge cases (null, undefined, invalid dates)
- Boundary conditions (year 2000, leap years)
- Error handling
Pattern 3: Run Tests and Fix Failures
claude
# Ask Claude to run tests:
Run the test suite for me.
# If tests fail:
Claude: "3 tests failed. Would you like me to fix them?"
You: "Yes, fix the failures and explain what was wrong"
Real Example from Anthropic Inference Team
The Challenge: Writing unit tests after implementing core functionality was mentally exhausting and often missed edge cases.
What They Did: After writing a function, they ask Claude: "Write comprehensive unit tests for this." Claude automatically includes missed edge cases.
Result: What would normally take significant mental energy now takes minutes. Tests act like a "coding assistant they can review" - comprehensive coverage without the mental burden.
Real Example from Anthropic Claude Code Team
The Challenge: Building new features required extensive testing to maintain code quality.
What They Did: Created "self-sufficient loops" where Claude verifies its own work by running builds, tests, and lints automatically. They ask Claude to generate tests BEFORE writing code.
Result: Claude works longer autonomously and catches its own mistakes. Enhanced code quality through automated testing while reducing manual effort.
Pull Request Workflow
Pull Requests (PRs) are how you propose code changes to a team. Claude Code can create PRs, write descriptions, and even respond to review comments automatically.
Pattern 1: Create a Pull Request
Terminal Way
# After making changes:
claude
# Inside Claude chat:
I've finished implementing the user profile feature.
Can you:
1. Review my changes
2. Create a pull request
3. Write a clear PR description with what changed and why
VS Code Way
- Make your code changes
- Open Claude panel
- Type: "Create a PR for my changes"
- Claude will:
- Review your git diff
- Generate PR title and description
- Create the PR on GitHub
- Add relevant labels
Pattern 2: Respond to PR Review Comments
Teammates left feedback on your PR? Claude can address it automatically.
claude
# Show Claude the PR comments:
My teammate said: "Can you add error handling to the login function?"
Can you:
1. Add the error handling
2. Commit the changes
3. Reply to the comment saying it's done
Pattern 3: Review Someone Else's PR
claude
# Give Claude the PR link or number:
Can you review PR #243?
Look for:
- Potential bugs
- Security issues
- Performance problems
- Code style inconsistencies
Provide constructive feedback.
Real Example from Anthropic Claude Code Team
The Challenge: PR reviews often included simple requests like formatting issues or function renaming that interrupted workflow.
What They Did: Set up GitHub Actions integration so Claude automatically addresses Pull Request comments like formatting issues or function renaming without manual intervention.
Result: Handles routine bug fixes identified in pull request reviews automatically. Team can focus on complex problems while Claude handles the simple stuff.
Documentation Workflow
Good documentation helps everyone understand your code. Claude Code makes documentation painless.
Pattern 1: Generate README Files
Terminal Way
claude
# In your project directory:
Can you create a README.md for this project?
Include:
- What the project does
- How to install dependencies
- How to run it
- Examples of common use cases
- How to run tests
VS Code Way
- Right-click project folder
- Select "New File" โ
README.md - Open Claude panel
- Type: "Generate a comprehensive README for this project"
Pattern 2: Add Code Comments
claude
# Point to complex code:
@src/algorithms/sortingEngine.js
This code is hard to understand.
Can you add:
- Function documentation (JSDoc format)
- Inline comments explaining complex logic
- Examples of input/output
Pattern 3: Create API Documentation
claude
# For your API endpoints:
Can you document all API endpoints in this project?
For each endpoint include:
- HTTP method (GET, POST, etc.)
- URL path
- Request parameters
- Response format
- Example usage with curl
- Possible error codes
Real Example from Anthropic Security Team
The Challenge: Needed to create markdown runbooks and troubleshooting guides from multiple documentation sources.
What They Did: Had Claude Code ingest multiple documentation sources and create condensed markdown runbooks, troubleshooting guides, and overviews.
Result: Use these condensed documents as context for debugging real issues. More efficient workflow than searching through full knowledge bases.
Tip: Beyond coding, Claude Code excels at synthesizing documentation. Provide writing samples and formatting preferences to get documents you can immediately use in Slack, Google Docs, and other tools.
Real Example from Anthropic RL Engineering Team
The Challenge: Documentation was often an afterthought, slowing down maintenance and onboarding.
What They Did: Ask Claude Code to automatically add helpful comments after implementing changes.
Result: Documentation acceleration - comments save significant time. Note: Sometimes Claude adds comments in odd places or uses questionable code organization, so review is still needed.
๐งน Code Cleanup Workflow
Over time, codebases get messy. Claude Code helps you clean up technical debt.
Pattern 1: Remove Dead Code
claude
# Ask Claude to scan:
Can you find unused functions, variables, and imports in this project?
List what can be safely removed.
Pattern 2: Update Dependencies
claude
# Check for outdated packages:
Check package.json for outdated dependencies.
What needs updating? Are there any breaking changes I should know about?
Pattern 3: Fix Linting Errors
claude
# Run linter and let Claude fix issues:
Run eslint and fix all the errors automatically.
Explain any changes you make.
Deployment Workflow
Getting code from your computer to production servers.
Pattern 1: Pre-Deployment Checklist
claude
I'm ready to deploy to production.
Can you verify:
1. All tests pass
2. No console.log statements in production code
3. Environment variables are configured
4. Database migrations are ready
5. No TODO comments about critical issues
Pattern 2: Deploy and Monitor
claude
# After deployment:
Can you check the deployment logs for errors?
Monitor the health endpoint for the next 5 minutes and let me know if anything fails.
Code Review Workflow
Before merging code, someone reviews it for quality and correctness.
Pattern: Self-Review Before Sharing
claude
# Before creating PR:
Can you review my changes and tell me:
1. Any potential bugs?
2. Security vulnerabilities?
3. Performance concerns?
4. Code style issues?
5. Missing test coverage?
Be thorough and critical.
Real Example from Anthropic Product Design Team
The Challenge: Complex copy changes (like removing "research preview" messaging) required coordination with legal and finding all instances across the codebase.
What They Did: Used Claude Code to find all instances, review surrounding copy, coordinate changes with legal in real-time, and implement updates.
Result: Week-long back-and-forth process completed in two 30-minute calls. What normally took a week of coordination now done in hours.
Migration Workflow
Updating from old technology to new technology.
Pattern: Gradual Migration
claude
# Example: React class components to hooks
Can you convert this class component to a functional component with hooks?
Make sure:
1. All lifecycle methods are preserved
2. State management works identically
3. Tests still pass
4. Add comments explaining the conversion
Real Example from Anthropic Product Design Team
The Challenge: Non-developers needed to make "large state management changes that you typically wouldn't see a designer making."
What They Did: Used Claude Code to directly implement front-end polish and state management changes (typefaces, colors, spacing) without extensive back-and-forth with engineers.
Result: 2-3x faster execution. Changes that previously required extensive documentation and multiple feedback rounds now implemented directly. Designers achieve exact quality they envision.
Performance Optimization Workflow
Making code run faster and use less resources.
Pattern 1: Profile and Identify Bottlenecks
claude
# Give Claude performance data:
This page takes 8 seconds to load.
Here's the Chrome DevTools performance profile: [paste or screenshot]
What's causing the slowness? How can we optimize it?
Pattern 2: Optimize Specific Functions
claude
@src/utils/searchAlgorithm.js
This function is called 10,000 times per second and it's slowing down the app.
Can you optimize it for speed?
Consider using caching, better algorithms, or data structure improvements.
Feature Development Workflow
Building something new from scratch.
The Complete Feature Flow
Step 1: Plan in Ask Mode
claude --ask
I want to add a "favorite items" feature where users can:
- Click a heart icon to favorite an item
- See all favorites in a dedicated page
- Remove items from favorites
What's the best approach? What files do I need to modify?
Step 2: Build in Edit Mode
claude
# Let Claude build it:
Implement the favorites feature we discussed.
Update the UI, add the database schema, create API endpoints, and add tests.
Step 3: Test
# Claude automatically runs tests
# You manually test the UI
# Ask Claude to fix any issues
Step 4: Document
claude
Update the README to explain the new favorites feature.
Add code comments to the complex parts.
Step 5: Review and Ship
claude
Create a pull request for the favorites feature.
Include before/after screenshots in the PR description.
Real Example from Anthropic Claude Code Team
The Challenge: Building Vim mode wasn't a priority, but they wanted the feature.
What They Did: Asked Claude to build the entire Vim key bindings feature autonomously using "auto-accept mode" (Shift+Tab).
Result: 70% of the final implementation came from Claude's autonomous work, requiring only a few iterations to complete. Successfully implemented a complex feature that would have taken weeks of manual coding.
Tip: The team emphasizes starting from a clean git state and committing checkpoints regularly so they can easily revert if Claude goes off track.
Learning Workflow
Understanding unfamiliar code or technologies.
Pattern 1: Explain Unfamiliar Code
claude
# Point to confusing code:
@src/lib/cryptography.js
I don't understand what this code does.
Can you explain it like I'm 10 years old?
What's the purpose? How does it work?
Pattern 2: Learn New Technology
claude
I need to add GraphQL to this project but I've never used it.
Can you:
1. Explain what GraphQL is and how it works
2. Show me how to set it up in this project
3. Create a simple example query
4. Teach me best practices
Real Example from Anthropic Inference Team
The Challenge: Team members without machine learning backgrounds needed to understand model-specific functions and settings.
What They Did: Depend on Claude to explain machine learning concepts. Ask: "What does this model function do?"
Result: Research time reduced by 80%. What would require an hour of Google searching and reading documentation now takes 10-20 minutes.
Real Example from Anthropic API Knowledge Team
The Challenge: Working across large, complex codebases meant constantly encountering unfamiliar code sections and spending significant time understanding which files to examine.
What They Did: Use Claude Code as their "first stop" for any task, asking it to identify which files to examine for bug fixes, feature development, or analysis.
Result: Eliminated context-switching overhead. Instead of copying code snippets and dragging files into Claude.ai while explaining problems extensively, they ask questions directly in Claude Code. Significant time savings.
Onboarding Workflow
Getting new team members up to speed quickly.
Pattern: New Developer Setup
claude
I just joined this project. Can you:
1. Explain the overall architecture
2. Show me where the main features are located
3. Identify the most important files I should read
4. Explain the development workflow (how to run, test, deploy)
5. Point out any gotchas or common mistakes
Real Example from Anthropic Data Infrastructure Team
The Challenge: New data scientists joining the team needed to navigate a massive codebase and understand complex data pipeline dependencies.
What They Did: Direct new hires to use Claude Code to navigate the codebase. Claude reads their Claude.md files (documentation), identifies relevant files for specific tasks, and explains data pipeline dependencies.
Result: Accelerated onboarding. New data analysts and team members can quickly understand complex systems and contribute meaningfully without extensive guidance. Replaces traditional data catalogs and discoverability tools.
Workflow Best Practices
1. Start with a Clean Git State
Before letting Claude make big changes, commit your current work. This makes it easy to rollback if something goes wrong.
git add .
git commit -m "Before refactoring"
# Now let Claude work
2. Work Incrementally
Don't ask Claude to build everything at once. Break large tasks into smaller steps.
# Bad:
Build a complete e-commerce platform with authentication, payment processing, inventory management, and admin dashboard.
# Good:
Step 1: Set up basic authentication
Step 2: Add product listing page
Step 3: Implement shopping cart
Step 4: Add payment integration
3. Review Claude's Work
Claude is smart, but not perfect. Always review changes before committing, especially for:
- Security-sensitive code (authentication, payments)
- Database schema changes
- Performance-critical sections
- Public-facing features
4. Use Claude.md for Project Context
The more Claude knows about your project, the better it performs.
# In .claude/claude.md:
# Project: TaskMaster Pro
## Tech Stack
- Frontend: React + TypeScript
- Backend: Node.js + Express
- Database: PostgreSQL
- Testing: Jest
## Code Style Preferences
- Use functional components (not class components)
- Prefer async/await over .then()
- Always include error handling
- Write tests for all features
## Common Commands
- `npm run dev` - Start development server
- `npm test` - Run test suite
- `npm run lint` - Check code style
5. Create Custom Slash Commands for Frequent Tasks
If you do something repeatedly, make it a command.
# .claude/commands/test-and-fix.md
---
description: Run tests and fix any failures
---
1. Run the test suite
2. If tests fail, analyze the failures
3. Fix the failing tests
4. Re-run tests to verify
5. Commit the fixes with a clear message
6. Let Claude Document As It Goes
claude
While you're implementing the payment feature,
please add code comments explaining:
- Why you made specific decisions
- What each function does
- Any edge cases to be aware of
Workflow Combinations
Real work often combines multiple workflows. Here's how they fit together:
Typical Development Day:
- Morning: Fix bug reported overnight (Bug Fixing Workflow)
- Mid-morning: Review teammate's PR (Code Review Workflow)
- Afternoon: Build new feature (Feature Development Workflow)
- Late afternoon: Write tests for new feature (Testing Workflow)
- Before leaving: Create PR and update documentation (PR + Documentation Workflow)
Sprint Planning:
- Review technical debt โ Code Cleanup Workflow
- Prioritize features โ Planning in Ask Mode
- Break down large tasks โ Feature Development Workflow
- Assign work โ Use agents for parallel development
Common Workflow Summary
| Workflow | When to Use | Key Command |
|---|---|---|
| Bug Fixing | Something is broken | Show Claude error + ask to fix |
| Refactoring | Code works but is messy | Extract/rename/simplify |
| Testing | Need quality assurance | Write comprehensive tests |
| Pull Requests | Ready to merge changes | Create PR with description |
| Documentation | Need to explain code | Generate README/comments |
| Code Cleanup | Remove technical debt | Find unused code/Fix linting |
| Deployment | Ship to production | Pre-deploy checklist |
| Code Review | Before merging | Review my changes critically |
| Migration | Update technology | Convert X to Y gradually |
| Performance | Code is too slow | Profile + optimize bottlenecks |
| Feature Development | Building something new | Plan โ Build โ Test โ Document |
| Learning | Don't understand code | Explain like I'm 10 |
| Onboarding | New to the project | Explain architecture + workflow |
Key Takeaways
- Common workflows make up 80% of development work
- Bug fixing is systematic: show error โ investigate โ fix โ test
- Refactoring improves code without changing behavior (extract, rename, simplify)
- TDD (Test-Driven Development) means writing tests before code
- Generate tests for existing code to catch edge cases automatically
- Pull Requests can be created, reviewed, and updated by Claude
- Documentation is painless - READMEs, comments, API docs generated automatically
- Code cleanup removes dead code, updates dependencies, fixes linting
- Start with clean git state so you can rollback if needed
- Work incrementally - break large tasks into smaller steps
- Always review Claude's changes, especially security-sensitive code
- Use claude.md to give Claude project context and preferences
- Create custom slash commands for tasks you repeat frequently
- Combine workflows - real work uses multiple patterns together
- Anthropic teams report 2-4x time savings on routine tasks
- Security team debugs 3x faster with Claude Code
- Legal team (non-developers) built working apps in 1 hour
Next: Chapter 14 - Git & GitHub. Master version control, GitHub Actions, and collaborative development workflows with Claude Code!
Test your knowledge!
Take Chapter 13 Quiz โChapter 14: Git & GitHub
Think of Git as a time machine for your code. Every time you save a "checkpoint" (called a commit), Git remembers what your code looked like at that moment. Made a mistake? Travel back in time! Want to try something risky? Create a parallel universe (called a branch)! Claude Code makes Git super easy - you just tell Claude what you want to do in plain English.
Why Git Matters
Imagine writing an essay without "Save" or "Undo" - terrifying, right? Git is like having infinite undo, plus the ability to:
- Save checkpoints - Never lose work again
- Experiment safely - Try new ideas without breaking what works
- Collaborate - Multiple people work on the same project
- See history - Who changed what, when, and why
- Revert mistakes - Go back to when things worked
Getting Started with Git
Check if Git is Installed
Terminal Way
git --version
# If you see a version number, you're good!
# If not, download from git-scm.com
VS Code Way
- Open VS Code Terminal (View โ Terminal)
- Type:
git --version - Press Enter
Tell Git Who You Are (One-Time Setup)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
๐ฆ Git Basics with Claude Code
Pattern 1: Starting a New Project
When you start a new project, you need to "initialize" Git - basically tell Git to start watching this folder.
Terminal Way
# Navigate to your project folder
cd my-project
# Initialize Git
git init
# Or let Claude do it:
claude
# Then ask:
Can you initialize git for this project?
VS Code Way
- Open your project folder in VS Code
- Click Source Control icon (left sidebar - looks like a branch)
- Click "Initialize Repository"
- Or open Claude panel and ask: "Initialize git for me"
Pattern 2: Making Your First Commit
A "commit" is like taking a snapshot of your code. It's a checkpoint you can return to later.
The Manual Way
# See what changed
git status
# Add files to the snapshot (stage them)
git add .
# Take the snapshot (commit)
git commit -m "Initial commit - added homepage"
The Claude Way (Much Easier!)
claude
# Just ask Claude:
Can you commit my changes with a good commit message?
# Claude will:
# 1. Check what you changed
# 2. Write a clear commit message describing the changes
# 3. Create the commit
VS Code Way
- Click Source Control icon
- See your changed files listed
- Click "+" next to files to stage them (or stage all)
- Type commit message in the box
- Click the checkmark (โ) to commit
- Or ask Claude: "Commit my changes with a descriptive message"
Real Example from Anthropic Claude Code Team
The Workflow: The team emphasizes "Let Claude talk first" - they tell Claude to "commit your work as you go" during autonomous coding sessions.
Result: More comprehensive solutions because Claude commits logical checkpoints automatically. If something goes wrong, easy to rollback to the last good commit.
Tip: Always start from a clean git state before letting Claude make big changes. This makes it easy to revert if needed.
๐ฟ Branches: Parallel Universes for Your Code
Think of branches like parallel universes. The main branch (usually called main or master) is your "real" code that works. When you want to try something new, create a branch - a copy where you can experiment safely.
Pattern 1: Creating a New Branch
Terminal Way
# Create and switch to a new branch
git checkout -b feature/add-login
# Now you're in the "feature/add-login" universe
# Any changes you make won't affect the main branch
The Claude Way
claude
# Ask Claude:
Create a new branch called "feature/add-login" and switch to it
VS Code Way
- Look at bottom-left corner (shows current branch)
- Click the branch name
- Select "Create new branch"
- Type branch name:
feature/add-login - Press Enter
Pattern 2: Switching Between Branches
# Switch to main branch
git checkout main
# Switch to feature branch
git checkout feature/add-login
# Or ask Claude:
claude
Switch to the main branch
Pattern 3: Merging Branches
When your feature is done, you "merge" the branch back into main - bringing the changes from your experimental universe into the real one.
# First, switch to main
git checkout main
# Then merge your feature
git merge feature/add-login
# Or let Claude handle it:
claude
Merge my feature/add-login branch into main
Working with GitHub
GitHub is like Google Drive for code. It stores your code online so you can:
- Access it from anywhere
- Share it with teammates
- Collaborate with others
- Back up your work
Pattern 1: Creating a GitHub Repository
Manual Way
- Go to github.com
- Click the "+" in top-right corner
- Select "New repository"
- Fill in name and description
- Click "Create repository"
The Claude Way
claude
# Claude can use GitHub CLI (gh):
Create a new GitHub repository called "my-awesome-project"
# Claude will:
# 1. Create the repo on GitHub
# 2. Connect your local code to it
# 3. Push your code up
Pattern 2: Pushing Code to GitHub
"Pushing" means sending your commits from your computer to GitHub.
Terminal Way
# First time only - connect to GitHub:
git remote add origin https://github.com/username/repo-name.git
# Push your code:
git push -u origin main
The Claude Way
claude
# Just ask:
Push my code to GitHub
# Claude will figure out the right commands
VS Code Way
- Click Source Control icon
- Click the three dots (โขโขโข) menu
- Select "Push"
- Or ask Claude in the panel: "Push to GitHub"
Pattern 3: Pulling Changes from GitHub
"Pulling" means getting the latest code from GitHub to your computer. Important when working with teammates!
# Get latest changes
git pull
# Or ask Claude:
claude
Pull the latest changes from GitHub
Pull Requests (PRs)
A Pull Request is like saying: "Hey team, I made some changes. Can you review them before we add them to the main code?"
The Complete PR Flow with Claude
Step 1: Create a Feature Branch
claude
Create a branch called "feature/dark-mode" and switch to it
Step 2: Make Your Changes
claude
Add dark mode support to the app
Step 3: Commit Changes
claude
Commit these changes with a good message
Step 4: Push to GitHub
claude
Push this branch to GitHub
Step 5: Create Pull Request
claude
Create a pull request for this feature.
Title it "Add dark mode support"
Write a description explaining:
- What this adds
- How to test it
- Any screenshots
Real Example from Anthropic Claude Code Team
The Challenge: PR reviews included simple requests (formatting, renaming) that interrupted workflow.
What They Did: Set up GitHub Actions integration where Claude automatically addresses PR comments without manual intervention.
Example: Teammate comments "Can you rename this function?" โ Claude reads the comment โ Makes the change โ Commits โ Replies "Done!" All automatic.
Result: Team focuses on complex problems while Claude handles routine PR feedback.
GitHub Actions with Claude Code
GitHub Actions are like robots that automatically run tasks when certain things happen (like when you push code or create a PR).
Common Automation Examples
Example 1: Auto-Run Tests on Every PR
claude
# Ask Claude to set this up:
Can you create a GitHub Action that:
1. Runs all tests whenever someone creates a PR
2. Posts the results as a comment
3. Blocks merging if tests fail
Example 2: Auto-Deploy to Production
claude
Create a GitHub Action that:
1. Deploys to production when code is merged to main
2. Runs only if all tests pass
3. Notifies the team in Slack
Example 3: Claude Bot Responds to PR Comments
claude
Set up a GitHub Action where:
1. When someone comments on a PR with "@claude [request]"
2. Claude reads the request
3. Makes the changes
4. Commits and pushes
5. Replies to the comment
Real Example from Anthropic Product Development Team
The Setup: GitHub Actions trigger Claude Code to automatically handle simple PR feedback like formatting issues or function renaming.
How It Works:
- Developer opens PR
- Teammate reviews and comments: "Fix indentation in main.js"
- GitHub Action triggers Claude
- Claude reads comment, fixes indentation, commits, pushes
- Claude replies to comment: " Fixed indentation"
Impact: Developers stay in flow state. No context switching for trivial fixes.
๐ Advanced Git Workflows
Workflow 1: Fixing Merge Conflicts
Merge conflicts happen when two people change the same line of code. Git doesn't know which version to keep, so it asks you.
The Traditional Way (Confusing!)
# You see something like:
<<<<<<< HEAD
const name = "Alice";
=======
const name = "Bob";
>>>>>>> feature-branch
# You have to manually pick which one to keep
The Claude Way (Easy!)
claude
# Just ask:
I have merge conflicts. Can you help resolve them?
Keep the changes from feature-branch where they make sense.
# Claude will:
# 1. Understand both versions
# 2. Pick the right one (or combine them)
# 3. Clean up the conflict markers
# 4. Test that everything still works
Workflow 2: Cherry-Picking Commits
Sometimes you want just ONE commit from another branch, not the whole branch.
claude
# Ask Claude:
Cherry-pick commit abc123 from the feature-branch
# Claude will grab just that one commit and apply it
Workflow 3: Reverting Bad Commits
Made a mistake? Undo it!
# Undo the last commit (keeps changes)
git reset HEAD~1
# Undo the last commit (deletes changes - careful!)
git reset --hard HEAD~1
# Or ask Claude:
claude
Undo my last commit but keep the changes so I can fix them
# Or:
Undo my last 3 commits completely
Workflow 4: Stashing Changes
Need to switch branches but not ready to commit? "Stash" your changes - like putting them in a temporary drawer.
# Save current changes temporarily
git stash
# Switch branches
git checkout other-branch
# Come back later
git checkout original-branch
# Get your changes back
git stash pop
# Or ask Claude:
claude
Stash my current changes, I need to switch branches
Git Best Practices with Claude
1. Write Good Commit Messages
Bad commit messages make history useless. Good ones tell a story.
Bad:
"fixed stuff"
"updates"
"asdfasdf"
Good:
"Add user authentication with JWT tokens"
"Fix memory leak in image processing"
"Update API endpoint to handle edge cases"
# Let Claude write them:
claude
Commit my changes with a clear, descriptive message
2. Commit Often, Push Regularly
# Commit after completing each logical chunk
# Think: "If I break this, can I easily go back?"
claude
Commit my work so far with the message "Complete login form validation"
3. Keep Main Branch Clean
Never work directly on the main branch. Always use feature branches.
Good workflow:
main branch โ feature branch โ work โ PR โ merge back to main
Bad workflow:
work directly on main โ commit โ push โ break production
4. Pull Before You Push
# Always get latest changes before pushing yours
git pull
git push
# Or ask Claude:
claude
Pull the latest changes, then push mine
5. Use .gitignore
Don't commit everything! Some files should stay on your computer.
claude
# Ask Claude to set this up:
Create a .gitignore file that ignores:
- node_modules
- .env files
- .DS_Store
- build folder
- Any files with passwords or API keys
Common Git Scenarios
Scenario 1: "I Committed to the Wrong Branch!"
claude
# Ask Claude:
I just committed to main but I meant to commit to feature-branch.
Can you move this commit to the right branch?
Scenario 2: "I Want to Undo My Last Commit"
claude
Undo my last commit but keep the changes
Scenario 3: "I Need to See What Changed"
claude
Show me what changed in the last 5 commits
Scenario 4: "Someone Else Changed the Same File"
claude
I have merge conflicts in auth.js.
Can you resolve them by keeping my authentication logic
but using their error handling?
Scenario 5: "I Need to Find When a Bug Was Introduced"
claude
The login button worked 2 weeks ago but is broken now.
Can you use git bisect to find which commit broke it?
GitHub Power Features
Feature 1: GitHub Issues
Issues are like to-do items for your project.
claude
# Using GitHub CLI:
Create a GitHub issue titled "Add password reset feature"
with description explaining what we need
Feature 2: GitHub Projects
Organize issues into a kanban board (To Do โ In Progress โ Done).
claude
Move issue #42 from "To Do" to "In Progress" on our project board
Feature 3: GitHub Discussions
Like a forum for your project.
claude
Create a GitHub Discussion asking:
"Should we support dark mode or let users customize any color?"
Feature 4: Code Review Comments
claude
Review PR #123 and add comments on:
- Code quality
- Security concerns
- Performance issues
- Best practice violations
Git Security Best Practices
1. Never Commit Secrets
NEVER commit:
- API keys
- Passwords
- Database credentials
- .env files
- Private keys
Instead:
# Add them to .gitignore
# Use environment variables
# Store secrets in secure vaults
claude
Check if I accidentally committed any secrets or API keys
2. Use SSH Keys for GitHub
claude
# Ask Claude to help set this up:
Set up SSH keys for GitHub so I don't have to type my password every time
3. Sign Your Commits (Advanced)
claude
Set up GPG commit signing so people know my commits are really from me
Useful Git Commands Reference
| Task | Command | Claude Way |
|---|---|---|
| Check status | git status |
"What files have I changed?" |
| See changes | git diff |
"Show me what I changed" |
| Commit all changes | git add . && git commit -m "msg" |
"Commit my changes" |
| Create branch | git checkout -b name |
"Create branch called [name]" |
| Switch branch | git checkout name |
"Switch to [name] branch" |
| Merge branch | git merge name |
"Merge [name] into current branch" |
| Push to GitHub | git push |
"Push to GitHub" |
| Pull from GitHub | git pull |
"Pull latest changes" |
| Clone repository | git clone url |
"Clone [repo URL]" |
| See commit history | git log |
"Show commit history" |
| Undo last commit | git reset HEAD~1 |
"Undo last commit" |
| Stash changes | git stash |
"Stash my changes" |
| Create PR | gh pr create |
"Create a pull request" |
Learning Path
Beginner (Week 1):
- Initialize git in a project
- Make commits with Claude's help
- Push to GitHub
Intermediate (Week 2-3):
- Create and merge branches
- Handle simple merge conflicts
- Create pull requests
Advanced (Month 2+):
- Set up GitHub Actions
- Use git bisect to find bugs
- Cherry-pick commits
- Rebase branches
Key Takeaways
- Git is a time machine - save checkpoints, travel back, experiment safely
- Commits are snapshots - logical units of work with descriptive messages
- Branches are parallel universes - experiment without breaking main code
- GitHub is cloud storage for code - backup, share, collaborate
- Pull Requests are code review requests before merging
- GitHub Actions automate tasks (tests, deployments, PR responses)
- Claude handles git commands - just describe what you want in plain English
- Always work on branches - keep main branch clean and working
- Commit often - small, logical checkpoints are better than huge commits
- Pull before push - get latest changes first to avoid conflicts
- Write good commit messages - future you will thank present you
- Use .gitignore - never commit secrets, dependencies, or build files
- Claude can resolve merge conflicts - explain which version to keep
- GitHub CLI (gh) enables PR creation and management from terminal
- Anthropic teams use Claude for auto-commits during coding sessions
- Start from clean git state before big changes - easy rollback
- Git is collaborative - multiple developers work on same project safely
Next: Chapter 15 - Context & Performance. Learn how Claude Code manages context windows, optimization techniques, and how to work efficiently with large codebases!
Test your knowledge!
Take Chapter 14 Quiz โChapter 15: Context & Performance
Think of Claude Code's context window as its "working memory" - like how much information you can hold in your head while solving a problem. Claude Code has a HUGE working memory (200,000 tokens - about 150,000 words, or roughly 300 pages of text!). With Claude Sonnet 4, that jumps to 1 million tokens! This chapter teaches you how to use that memory efficiently so Claude stays fast and helpful even in massive projects.
Understanding Context
Imagine you're helping a friend with homework. If they show you:
- Just the problem โ You can help, but might miss important background
- The problem + the chapter โ You give better answers
- The problem + the chapter + the whole textbook โ Perfect understanding, but takes longer to read through everything
Claude Code works the same way. More context = better answers, but also = more time to process.
What Counts as Context?
Everything Claude "sees" uses context tokens:
- Your messages - Every question you ask
- Claude's responses - Every answer Claude gives
- Files read - Code files Claude looks at (using
@filename) - Search results - When Claude searches your codebase
- Tool outputs - Results from running commands
- Memory files - Your claude.md, settings, custom commands
Token Counting (Rough Guide)
# Approximate token usage:
1 token โ 4 characters โ 0.75 words
Examples:
"Hello world" = ~3 tokens
Small file (100 lines) = ~500-1000 tokens
Medium file (500 lines) = ~2500-5000 tokens
Large file (2000 lines) = ~10,000-20,000 tokens
Context Limits by Model
| Model | Context Window | What This Means |
|---|---|---|
| Claude Sonnet 3.5 | 200,000 tokens | ~150,000 words (~300 pages) |
| Claude Sonnet 4 | 1,000,000 tokens | ~750,000 words (~1,500 pages) |
| Claude Haiku | 200,000 tokens | ~150,000 words (~300 pages) |
Checking Context Usage
Want to see how much context you're using?
Terminal Way
claude
# Inside a session, ask:
How much context am I using right now?
# Claude will tell you:
# "You're using 45,000 out of 200,000 tokens (22.5%)"
VS Code Way
- Look at the bottom-right of VS Code
- You'll see a token counter (if enabled)
- Or ask Claude in the panel: "How much context am I using?"
The /compact Command
When your conversation gets too long, use /compact - it's like creating a summary of everything so far, then starting fresh with that summary.
How /compact Works
Think of it like taking notes in class:
- Before: 50 pages of detailed lecture notes
- /compact: Condense to 5 pages of key points
- After: Continue with the condensed notes, freeing up space for new information
Using /compact
Terminal Way
claude
# During a session, type:
/compact
# Claude will:
# 1. Summarize the conversation so far
# 2. Save important context
# 3. Clear old messages
# 4. Continue with the summary
When to Use /compact
- After completing a major feature (before starting the next one)
- When Claude says "I'm approaching my context limit"
- After long debugging sessions with lots of back-and-forth
- When switching topics in the same session
- Every few messages (too often loses important details)
- In the middle of actively working on something
Real Example from Anthropic Data Infrastructure Team
The Challenge: Working on long-running data tasks across multiple repositories with Claude Code instances that needed to maintain context for hours or even days.
What They Did: Open multiple instances of Claude Code in different repositories for different projects. Each instance maintains full context independently.
The Workflow: When switching back after hours or days, Claude remembers exactly what they were doing and where they left off, enabling true parallel workflow management without context loss.
Key Strategy: Use /compact strategically when finishing one part of a task before starting another within the same session.
Prompt Caching
Prompt caching is like bookmarking frequently-used pages. If Claude reads the same large file multiple times in a conversation, it "caches" (saves) that file so it doesn't have to re-read it every time.
How Caching Helps
Without Caching:
You: "Read database.js and explain the schema"
Claude: *reads 5000-line file* "Here's the schema..."
You: "Now check if database.js handles errors properly"
Claude: *reads same 5000-line file again* "Yes, it does..."
You: "Update database.js to add logging"
Claude: *reads same 5000-line file AGAIN* "Here's the update..."
With Caching:
You: "Read database.js and explain the schema"
Claude: *reads 5000-line file, caches it* "Here's the schema..."
You: "Now check if database.js handles errors properly"
Claude: *uses cached version - instant!* "Yes, it does..."
You: "Update database.js to add logging"
Claude: *uses cached version - instant!* "Here's the update..."
What Gets Cached Automatically
- Large files you reference with
@filename - Your claude.md and settings files
- Frequently accessed project files
- System prompts and instructions
Caching Best Practices
Good: Reference the same files multiple times in a session
Good: Keep claude.md comprehensive (it gets cached)
Good: Use @filename instead of copy-pasting code
Avoid: Constantly switching between completely different files
Avoid: Copying huge code blocks into messages (reference files instead)
Performance Optimization Strategies
Strategy 1: Be Specific About What to Read
Slow:
"Look at my entire codebase and find the bug"
Fast:
"Check src/auth/login.js for the authentication bug"
Even Better:
"In src/auth/login.js, the handleLogin function around line 45
has a bug with password validation"
Strategy 2: Use Agents for Exploration
Instead of asking Claude to search through everything in the main conversation, use agents:
claude
# Main conversation stays focused
# Agent does the searching
Can you create an agent to:
1. Search for all uses of the old API
2. Report back which files need updating
Strategy 3: Break Large Tasks into Sessions
One massive session:
Session 1: Refactor entire app (runs out of context)
Multiple focused sessions:
Session 1: Refactor authentication module
Session 2: Refactor database layer
Session 3: Refactor API endpoints
Strategy 4: Use claude.md Effectively
Put repetitive information in claude.md so you don't have to repeat it:
# In .claude/claude.md
## Architecture Overview
- Frontend: React + TypeScript
- Backend: Node.js + Express
- Database: PostgreSQL with Prisma ORM
- Testing: Jest + React Testing Library
## Common File Locations
- Components: src/components/
- API Routes: src/api/routes/
- Database Models: src/models/
- Tests: src/__tests__/
## Coding Standards
- Use functional components (not class components)
- All API calls go through src/api/client.js
- Error handling: always use try-catch with proper logging
- Tests: write tests for all new features
Now Claude knows all this automatically without you repeating it!
Strategy 5: Reference Files, Don't Copy-Paste
Wasteful:
[Paste 500 lines of code]
"Can you add error handling to this?"
Efficient:
"@src/utils/dataProcessor.js can you add error handling?"
Working with Large Codebases
Pattern 1: Start Broad, Then Narrow
# Step 1: Get overview
claude --ask
"What's the architecture of this project?"
# Step 2: Find relevant area
"Which files handle user authentication?"
# Step 3: Narrow down
"In src/auth/login.js, how does password validation work?"
# Step 4: Make changes
"Add two-factor authentication to the login flow"
Pattern 2: Use Search Tools Strategically
claude
# Instead of reading all files:
Can you search for all files that import 'oldLibrary'
and tell me which ones need updating?
# Claude uses grep/search tools, not reading every file
Pattern 3: Multiple Claude Instances
For really large projects, open multiple terminal windows:
# Terminal 1: Frontend work
cd project/frontend
claude
# Terminal 2: Backend work
cd project/backend
claude
# Terminal 3: Database migrations
cd project/database
claude
Each has its own context window!
Real Example from Anthropic Data Science Team
The Challenge: Building complex TypeScript applications with minimal JavaScript knowledge, dealing with merge conflicts and large file refactoring.
The "Slot Machine" Approach:
- Commit current state (clean git checkpoint)
- Let Claude work autonomously for 30 minutes
- Review: either accept the solution or
git resetand start fresh
Why This Works: Starting fresh from a checkpoint is often faster than trying to fix Claude's mistakes. The clean slate gives Claude full context without confusion.
Result: 2-4x time savings. Built 5,000-line TypeScript applications despite minimal experience.
Context Management Best Practices
1. Start Fresh for New Features
# Finished Feature A? Start new session for Feature B
exit
# New session
claude
"I'm working on Feature B now. Here's what I need..."
2. Keep Conversations Focused
Unfocused:
"Fix the login bug, then add dark mode, also update the README,
and can you explain how React hooks work?"
Focused:
Session 1: "Fix the login bug in src/auth/login.js"
Session 2: "Add dark mode support"
Session 3: "Update README with new features"
3. Use /compact at Natural Breaks
Good times to /compact:
- Just finished debugging a complex issue
- Switching from frontend to backend work
- Completed one feature, starting another
- After a long exploration session
Bad times to /compact:
- Middle of implementing a feature
- Claude is actively debugging something
- Just started the conversation
4. Let Claude Manage Context
claude
# Claude is smart about context:
"I notice we're getting close to the context limit.
Should I compact the conversation before continuing?"
# Trust Claude's suggestions!
5. Use Agents for Heavy Lifting
# Keep main conversation light
# Use agents for heavy tasks
claude
Create an agent to:
1. Scan all 200 files for the old API pattern
2. Create a report of what needs updating
3. Estimate the work required
# Agent uses its own context window
Speed Optimization Tips
Tip 1: Use Extended Thinking Selectively
# Extended thinking is thorough but slower
claude --extended-thinking
"Design the architecture for our new microservices"
# Regular mode is faster for routine tasks
claude
"Add a button to the homepage"
Tip 2: Batch Related Questions
Slow (3 separate context loads):
"What does login.js do?"
"What does auth.js do?"
"What does session.js do?"
Fast (1 context load):
"Explain what these authentication files do:
- login.js
- auth.js
- session.js"
Tip 3: Use Haiku for Simple Tasks
# Haiku is faster for simple tasks
claude --model claude-3-haiku-20240307
"Fix this typo in README.md"
# Sonnet for complex tasks
claude --model claude-sonnet-4-20250514
"Refactor the entire authentication system"
Tip 4: Preload Important Files in claude.md
# In .claude/claude.md:
## Important Files
See these files for context:
- @src/config/app.js - Main configuration
- @src/utils/helpers.js - Utility functions
- @src/types/index.ts - TypeScript types
# Now Claude has this context from the start!
Debugging Context Issues
Problem 1: "I Don't Have Enough Context"
Claude says: "I don't have enough context to answer that."
Solutions:
# Solution 1: Reference specific files
"Check @src/api/users.js for the user creation logic"
# Solution 2: Provide more background
"We're using Express.js with MongoDB. The user creation
happens in the /api/users POST endpoint. Here's the error: [paste error]"
# Solution 3: Point to documentation
"See .claude/claude.md for the project architecture"
Problem 2: Claude Forgot Something Important
This happens when: Conversation is very long and Claude needs to /compact
Solutions:
# Solution 1: Remind Claude
"Remember, we're using JWT tokens for authentication
(we discussed this earlier)"
# Solution 2: Use /compact
/compact
# Then re-state important context
# Solution 3: Put it in claude.md
# Edit .claude/claude.md to include this information permanently
Problem 3: Performance is Slow
Possible causes:
- Context window is nearly full
- Claude is reading too many files
- Network latency
Solutions:
# Solution 1: Check context usage
"How much context am I using?"
# Solution 2: Compact if high
/compact
# Solution 3: Be more specific
"Look at the entire frontend"
"Look at src/components/LoginForm.jsx"
# Solution 4: Start fresh
exit
claude # New session
Context Usage Examples
Example 1: Small Project
Project: Simple website (10 files, ~2,000 lines total)
Context usage: 5,000-10,000 tokens (~5%)
Can fit: Entire codebase + long conversation
Strategy: Load everything, no optimization needed
Example 2: Medium Project
Project: Web app (100 files, ~20,000 lines total)
Context usage: 40,000-80,000 tokens (~20-40%)
Can fit: Key files + focused conversation
Strategy: Use @filename references, /compact occasionally
Example 3: Large Project
Project: Enterprise app (1,000+ files, 200,000+ lines)
Context usage: Can't fit everything at once
Strategy:
- Multiple sessions for different modules
- Use agents for codebase exploration
- Keep claude.md comprehensive
- Use /compact frequently
- Be very specific about file locations
Real Example from Anthropic API Knowledge Team
The Challenge: Working across large, complex codebases with unfamiliar sections. Significant time spent understanding which files to examine for any given task.
The Solution: Use Claude Code as the "first stop" for any task - ask it to identify which files to examine for bug fixes, feature development, or analysis.
The Benefit: Instead of copying code snippets and dragging files into Claude.ai while explaining problems extensively, they ask questions directly in Claude Code.
Result: Eliminated context-switching overhead. Engineers rotating to new teams can quickly navigate unfamiliar codebases and contribute meaningfully without extensive colleague consultation.
Context Strategies by Use Case
Bug Fixing
Strategy: Narrow and deep
1. Identify the bug location first
2. Load only relevant files (@filename)
3. Keep conversation focused on that bug
4. Start new session for next bug
New Feature Development
Strategy: Plan first, then focused sessions
1. Planning session (--ask mode): architecture decisions
2. /compact after planning
3. Implementation session: build the feature
4. /compact before testing
5. Testing session: write and run tests
Refactoring
Strategy: Module by module
1. Session 1: Refactor module A
2. Session 2: Refactor module B
3. Session 3: Refactor module C
(Don't try to refactor everything in one session)
Learning/Exploring
Strategy: Use agents + Ask mode
1. Create exploration agent
2. Agent reports back with findings
3. Use --ask mode for follow-up questions
4. Keep main conversation summary-focused
Key Takeaways
- Context window is Claude's "working memory" - 200K tokens (Sonnet 3.5) or 1M tokens (Sonnet 4)
- Everything counts - messages, files, tool outputs all use context
- /compact summarizes conversations to free up context - use at natural breaks
- Prompt caching automatically saves frequently-used files for instant reuse
- Be specific about files - "@filename" beats reading entire directories
- Use agents for heavy exploration work - they have separate context
- Multiple sessions for large projects - frontend, backend, database separately
- claude.md optimization - put common info there, it gets cached
- Reference, don't copy-paste - use @filename instead of pasting code
- Start fresh for new features - clean context = better results
- Keep conversations focused - one topic per session works best
- Let Claude manage - trust its suggestions about compacting
- Batch related questions - faster than multiple separate asks
- Use Haiku for simple tasks - faster for routine work
- Anthropic teams use multiple instances for parallel work without context loss
- "Slot machine" approach - commit, let Claude work, accept or reset
- Large codebases require strategic context management - can't load everything
Next: Chapter 16 - Security. Learn about permissions, sandbox mode, enterprise security features, and how to keep your code and data safe while using Claude Code!
Test your knowledge!
Take Chapter 15 Quiz โChapter 16: Security
Think of security like locking your house. You want helpful people (like Claude Code) to assist you inside, but you don't want them accidentally leaving the door open for bad things to happen. This chapter teaches you how to use Claude Code safely - giving it the access it needs to help, while protecting your sensitive information and keeping your code secure.
Why Security Matters
When you use Claude Code, you're giving an AI assistant access to your code. That's incredibly powerful, but requires thoughtful security:
- Code visibility - Claude can read your files
- File modifications - Claude can edit and create files
- Command execution - Claude can run terminal commands
- External access - Claude can use MCP servers to access databases, APIs, etc.
The good news? Claude Code has multiple layers of security built-in to keep you safe!
Permission System
Claude Code uses a permission system - like how your phone asks "Allow Camera Access?" before an app can use your camera. Every time Claude wants to do something potentially risky, it asks for your permission first.
What Requires Permission?
- Reading files - Claude must ask before reading sensitive files
- Writing/editing files - You approve every file change
- Running commands - Terminal commands require approval
- Installing packages - npm install, pip install, etc.
- Network access - Accessing external URLs or APIs
- Git operations - Commits, pushes, branch changes
Permission Levels
# Default: Always ask
Claude: "May I read src/auth/login.js?"
You: Press Enter to approve, or reject
# Allow for session: Remember for this conversation
Claude: "May I run 'npm test'?"
You: Choose "Allow for session" - won't ask again this session
# Always allow: Trust this action permanently
You: Choose "Always allow" - Claude can do this anytime
(Be careful with this one!)
How to Configure Permissions
Terminal Way
# View current permissions
claude config get permissions
# Set permission level (ask/auto-allow/auto-deny)
claude config set permissions.read_files ask
claude config set permissions.run_commands ask
claude config set permissions.write_files ask
VS Code Way
- Open Settings (Cmd/Ctrl + ,)
- Search for "Claude Code"
- Find "Permissions" section
- Configure: Ask, Auto-allow, or Auto-deny for each permission type
Real Example from Anthropic Data Infrastructure Team
The Security Requirement: When handling sensitive data with potential privacy concerns, they needed better control over what Claude Code could access.
What They Did: Used MCP servers instead of the BigQuery CLI to maintain better security control. MCP servers provide structured access with logging capabilities.
Benefit: Every data access is logged. They can audit exactly what Claude accessed and when, meeting compliance requirements while still getting AI assistance.
Recommendation: For sensitive data, use MCP servers rather than giving Claude direct CLI access. Better security, better logging, better control.
Sandbox Mode
Sandbox mode is like giving Claude a "practice area" where it can try things without affecting your real code. Think of it as a playground - Claude can build sandcastles there, but it won't mess up your actual house.
What is Sandbox Mode?
In sandbox mode:
- Claude can read files
- Claude can suggest changes
- Claude CANNOT actually modify files
- Claude CANNOT run commands
- Claude CANNOT install packages
When to Use Sandbox Mode
Use sandbox mode when:
- Exploring a new codebase
- Getting code reviews/suggestions
- Learning how something works
- You want to approve every change manually
Don't use sandbox mode when:
- You want Claude to implement features
- You trust the project and want speed
- You're working on your own personal project
Enabling Sandbox Mode
Terminal Way
# Start Claude in sandbox mode
claude --sandbox
# Or configure it permanently
claude config set sandbox_mode true
VS Code Way
- Open Claude Code settings
- Find "Sandbox Mode"
- Toggle ON
- Restart VS Code
Never Commit Secrets
This is THE most important security rule: NEVER commit passwords, API keys, or secrets to git.
What Are "Secrets"?
๐จ NEVER commit these:
- API keys (OpenAI, AWS, Stripe, etc.)
- Passwords
- Database connection strings with passwords
- Private keys (SSH, SSL certificates)
- OAuth tokens
- .env files containing secrets
- Credentials of any kind
Why This Matters
Once something is committed to git:
- It's in your git history FOREVER (even if you delete it later)
- Anyone with access to the repo can see it
- If the repo is public, the ENTIRE WORLD can see it
- Bots scan GitHub 24/7 looking for leaked credentials
The Right Way: Environment Variables
Step 1: Create a .env file (for local development)
# .env file (NEVER commit this!)
DATABASE_PASSWORD=super_secret_123
API_KEY=sk-abc123xyz789
STRIPE_SECRET=sk_live_xxxxx
Step 2: Add .env to .gitignore
# .gitignore
.env
.env.local
.env.*.local
*.key
*.pem
credentials.json
Step 3: Use environment variables in code
// JavaScript/Node.js
const apiKey = process.env.API_KEY;
const dbPassword = process.env.DATABASE_PASSWORD;
# Python
import os
api_key = os.environ.get('API_KEY')
db_password = os.environ.get('DATABASE_PASSWORD')
Step 4: Create .env.example (safe to commit)
# .env.example (this is safe to commit)
DATABASE_PASSWORD=your_password_here
API_KEY=your_api_key_here
STRIPE_SECRET=your_stripe_secret_here
Ask Claude to Check
claude
# Ask Claude to scan for accidentally committed secrets:
Can you check if I've accidentally committed any secrets, API keys,
passwords, or credentials to git?
# Claude will:
# 1. Search your git history
# 2. Look for common secret patterns
# 3. Warn you if it finds anything suspicious
If You Already Committed a Secret
๐จ Don't panic, but act quickly:
# Step 1: IMMEDIATELY rotate the compromised credential
# (Change the password, regenerate the API key)
# Step 2: Remove it from git history
claude
I accidentally committed my API key in commit abc123.
Can you help me remove it from git history using git filter-branch?
# Step 3: Force push the cleaned history
git push --force
# Step 4: Tell your team to re-clone the repo
MCP Server Security
MCP servers give Claude access to external tools (databases, APIs, file systems). This is powerful but requires security considerations.
MCP Security Best Practices
1. Only Install Trusted MCP Servers
Good sources:
- Official Anthropic MCP servers
- Well-maintained open source servers (check GitHub stars/activity)
- MCP servers from your own organization
Avoid:
- Random MCP servers with no documentation
- Servers with no recent updates
- Servers from unknown authors
2. Limit MCP Server Permissions
# Configure MCP servers with minimal necessary permissions
# Example: Filesystem MCP server
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/safe/path"],
"permissions": {
"read": ["~/projects/my-app"],
"write": ["~/projects/my-app/generated"],
"denied": ["~/.ssh", "~/.env", "/etc"]
}
}
}
}
3. Use Read-Only MCP Servers When Possible
# For data analysis, use read-only database access
{
"mcpServers": {
"database": {
"command": "database-mcp-server",
"args": ["--read-only", "--connection", "postgres://readonly:..."],
"permissions": {
"read": true,
"write": false,
"execute": false
}
}
}
}
Real Example from Anthropic Security Engineering Team
The Challenge: Infrastructure changes requiring security approval created bottlenecks. The security team needed to quickly review Terraform plans without slowing down development.
The Solution: Copy Terraform plans into Claude Code and ask "what's this going to do? Am I going to regret this?"
Security Benefits:
- Tighter feedback loops - reviews happen in minutes, not hours
- Claude spots potential issues (like overly permissive IAM roles)
- Security team can approve changes faster
- Developers aren't blocked waiting for security review
Result: Reduced developer blocks while maintaining security standards. The team reviews infrastructure changes faster without compromising on thoroughness.
Enterprise Security Features
1. Audit Logging
Track every action Claude Code takes for compliance and security auditing.
# Enable audit logging
claude config set audit_logging true
claude config set audit_log_path ~/.claude/audit.log
# Logs include:
# - Every file read/written
# - Every command executed
# - Every MCP server access
# - Timestamps and user info
2. Network Restrictions
Control which external services Claude Code can access.
# Allow only specific domains
claude config set allowed_domains "api.anthropic.com,github.com,npmjs.com"
# Block all external network access
claude config set network_access false
3. File Access Restrictions
Restrict which directories Claude Code can access.
# Limit to specific directories
claude config set allowed_paths "~/projects,~/work"
# Explicitly deny sensitive directories
claude config set denied_paths "~/.ssh,~/.aws,~/.config"
4. Organization Policies
For teams and enterprises, enforce security policies across all users.
# .claude/organization.json
{
"name": "Acme Corp",
"security": {
"require_code_review": true,
"block_secret_commits": true,
"enforce_sandbox_mode": false,
"allowed_mcp_servers": ["filesystem", "github"],
"audit_logging": {
"enabled": true,
"retention_days": 90
},
"network_restrictions": {
"allowed_domains": [
"api.anthropic.com",
"github.com",
"internal.acme.com"
]
}
}
}
Security Checklist
Before Starting a Project
โ Create .gitignore file
โ Add .env to .gitignore
โ Set up environment variables for secrets
โ Configure Claude Code permissions
โ Review which MCP servers you need
โ Enable audit logging (if required)
During Development
โ Never paste secrets in chat messages
โ Review file changes before accepting
โ Check git commits before pushing
โ Use sandbox mode when exploring unfamiliar code
โ Keep MCP server permissions minimal
Before Pushing to Git
โ Run: claude "Check if I accidentally committed any secrets"
โ Review git diff carefully
โ Ensure .env files are gitignored
โ Verify no credentials in code
โ Check that tests pass
โ Scan for TODO comments about security
๐จ Common Security Mistakes
Mistake 1: Committing .env Files
Wrong:
git add .
git commit -m "Update config"
# Just committed .env with all your secrets!
Right:
# Add .env to .gitignore FIRST
echo ".env" >> .gitignore
git add .gitignore
git commit -m "Ignore .env files"
# Now you can safely git add everything else
Mistake 2: Hardcoding Secrets
Wrong:
const apiKey = "sk-abc123xyz789"; // NEVER do this!
Right:
const apiKey = process.env.API_KEY;
Mistake 3: Overly Permissive MCP Servers
Wrong:
{
"mcpServers": {
"filesystem": {
"args": ["/"], // Access to ENTIRE filesystem!
"permissions": {
"read": true,
"write": true // Can write ANYWHERE!
}
}
}
}
Right:
{
"mcpServers": {
"filesystem": {
"args": ["~/projects/my-app"], // Only this project
"permissions": {
"read": true,
"write": ["~/projects/my-app/src"] // Only write to src
}
}
}
}
Mistake 4: Auto-Allowing All Permissions
Wrong:
claude config set permissions auto-allow # Dangerous!
Right:
# Let Claude ask for permission each time
claude config set permissions ask
# Or allow specific safe operations
claude config set permissions.read_files auto-allow
claude config set permissions.run_commands ask # Still ask for commands
Security Tools
1. Secret Scanning
claude
# Ask Claude to scan for secrets:
Can you scan my codebase for:
- API keys
- Passwords
- Private keys
- AWS credentials
- Database connection strings
- Any other secrets
Check both code files AND git history.
2. Git History Cleanup
claude
# Remove secrets from git history:
I need to remove [secret] from my git history.
It appears in commits abc123 through xyz789.
Can you use git filter-branch to clean this up?
3. Security Audit
claude
# Get a security audit:
Can you audit my project for security issues?
Check for:
- Hardcoded secrets
- Insecure dependencies
- Missing .gitignore entries
- Potential SQL injection
- XSS vulnerabilities
- Authentication issues
๐ Security Best Practices
1. Principle of Least Privilege
Only give Claude the minimum permissions needed for the task.
2. Review Before Accepting
Always review code changes before accepting them, especially for security-critical files.
3. Use Environment Variables
Never hardcode secrets. Always use environment variables.
4. Keep Dependencies Updated
claude
# Regularly check for security updates:
Can you check for outdated dependencies with security vulnerabilities?
Run npm audit (or pip check, cargo audit, etc.)
5. Enable Audit Logging
For professional projects, enable audit logging to track all Claude Code actions.
6. Use Separate Environments
# Development
.env.development (local secrets)
# Staging
.env.staging (staging secrets)
# Production
.env.production (production secrets - NEVER commit!)
Each environment has different credentials!
7. Regular Security Reviews
# Weekly/monthly:
claude
Run a security check:
1. Scan for secrets in code
2. Check for vulnerable dependencies
3. Review .gitignore completeness
4. Audit MCP server permissions
5. Check authentication implementations
Security Learning Resources
For Beginners
- Start with: Never commit secrets
- Learn: Environment variables
- Practice: Review every file change
For Intermediate Users
- Master: Permission system
- Understand: MCP server security
- Implement: Audit logging
For Advanced Users
- Set up: Organization policies
- Configure: Network restrictions
- Audit: Git history for secrets
Key Takeaways
- Permission system asks before Claude reads files, runs commands, or modifies code
- Three permission levels: Always ask, Allow for session, Always allow
- Sandbox mode lets Claude suggest but not execute changes - safe exploration
- NEVER commit secrets - API keys, passwords, credentials must stay out of git
- Use environment variables - .env files (gitignored) for all secrets
- Create .env.example - template showing what variables are needed (safe to commit)
- If you commit a secret - rotate it immediately, clean git history, force push
- MCP server security - limit permissions, use read-only when possible, trust sources
- Data Infrastructure team uses MCP servers for better security and logging
- Security Engineering team reviews Terraform plans faster with Claude
- Audit logging tracks all Claude actions for compliance
- Network restrictions control which external services Claude can access
- File access restrictions limit which directories Claude can read/write
- Organization policies enforce security across team members
- Review before accepting - always check code changes, especially security-critical
- Principle of least privilege - minimal permissions needed for the task
- Regular security audits - scan for secrets, check dependencies, review permissions
Next: Chapter 17 - CLI Reference. Complete guide to all command-line flags, arguments, and advanced usage patterns for power users!
Test your knowledge!
Take Chapter 16 Quiz โChapter 17: CLI Reference
Think of this chapter as your Claude Code command dictionary - a complete reference guide for every flag, argument, and option available. Just like a cookbook has all the recipes in one place, this chapter has all the commands you might need. Perfect for quick lookups and discovering advanced features!
Basic Usage
# Start Claude Code in current directory
claude
# Start in a specific directory
claude /path/to/project
# Start with a specific question
claude "How do I add authentication to this app?"
Mode Flags
--ask (Ask Mode)
Get answers and suggestions without making changes to code.
claude --ask
# Use for: Planning, asking questions, getting advice
# Claude will: Answer questions, explain code, suggest approaches
# Claude won't: Make file changes, run commands
--plan (Plan Mode)
Create a detailed implementation plan before coding.
claude --plan
# Use for: Breaking down large features, project planning
# Claude will: Create step-by-step plans, suggest architecture
# After plan: Ask if you want to proceed with implementation
--extended-thinking
Enable deeper reasoning for complex problems.
claude --extended-thinking
# Use for: Complex architecture decisions, tricky bugs
# Takes longer but: More thorough analysis, better solutions
# Example: "Design a scalable microservices architecture"
Configuration Flags
--model
Choose which Claude model to use.
# Use Claude Sonnet 4 (most powerful, largest context)
claude --model claude-sonnet-4-20250514
# Use Claude Sonnet 3.5 (default, balanced)
claude --model claude-3-5-sonnet-20241022
# Use Claude Haiku (faster, lightweight)
claude --model claude-3-haiku-20240307
--api-key
Provide your Anthropic API key.
# One-time use
claude --api-key sk-ant-your-key-here
# Better: Set environment variable
export ANTHROPIC_API_KEY=sk-ant-your-key-here
claude
--config-file
Use a custom configuration file.
claude --config-file ~/.claude/custom-config.json
# Useful for: Different profiles, team settings
Behavior Flags
--output-style
Set Claude's communication style.
# Use a built-in style
claude --output-style concise
claude --output-style technical
claude --output-style beginner-friendly
# Use a custom style
claude --output-style my-style
# Looks for: ~/.claude/styles/my-style/STYLE.md
--sandbox
Run in sandbox mode (read-only, suggestions only).
claude --sandbox
# Claude can: Read files, suggest changes
# Claude can't: Modify files, run commands
# Use for: Exploring unfamiliar codebases, code reviews
--verbose
Show detailed information about what Claude is doing.
claude --verbose
# Shows: File reads, tool calls, reasoning steps
# Useful for: Debugging, understanding Claude's process
--debug
Enable debug mode with even more information.
claude --debug
# Shows: API calls, token usage, internal state
# Use for: Troubleshooting issues, reporting bugs
File & Directory Flags
--add-dir
Include additional directories in context.
# Add a related directory
claude --add-dir ../shared-utils
# Add multiple directories
claude --add-dir ../lib --add-dir ../types
--exclude
Exclude files or directories from context.
# Exclude specific patterns
claude --exclude "*.test.js" --exclude "node_modules"
# Exclude large files
claude --exclude "*.log" --exclude "dist/"
--gitignore
Respect .gitignore files (default: true).
# Default behavior (respects .gitignore)
claude
# Ignore .gitignore (not recommended)
claude --no-gitignore
Session Flags
--resume / -r
Resume your last conversation.
# Resume last session
claude --resume
claude -r
# Resume specific session by ID
claude --resume abc123
--continue / -c
Continue from where you left off.
# Continue previous conversation
claude --continue
claude -c
--new
Force a new session (don't resume).
claude --new
# Use when: You want a fresh start, even if previous session exists
--session-name
Give your session a memorable name.
claude --session-name "auth-feature"
# Later: Resume by name
claude --resume auth-feature
Output Flags
--print / -p
Print output without starting interactive session.
# Get quick answer
claude --print "What's the syntax for async/await in Python?"
# One-shot command
claude -p "Explain this error: [paste error]"
--json
Output in JSON format (for scripting).
claude --json --print "List all functions in main.js"
# Output: {"response": "...", "files": [...], ...}
--quiet / -q
Minimize output (only show essential information).
claude --quiet
# Hides: Thinking indicators, progress messages
# Shows: Only final results
Security Flags
--permissions
Set permission level for this session.
# Ask before every action (safest)
claude --permissions ask
# Auto-approve all actions (use with caution!)
claude --permissions auto-allow
# Deny all actions (read-only)
claude --permissions auto-deny
--audit-log
Enable audit logging for this session.
claude --audit-log ~/.claude/audit.log
# Logs: All file reads/writes, commands, timestamps
Network Flags
--offline
Run without external network access (except Anthropic API).
claude --offline
# Blocks: MCP servers, external APIs, web fetches
# Allows: Core Claude Code functionality
--proxy
Use a proxy server for API requests.
claude --proxy http://proxy.company.com:8080
# Use for: Corporate networks, VPNs
Advanced Flags
--max-tokens
Limit the maximum tokens per response.
# Shorter responses
claude --max-tokens 1000
# Longer responses (up to model limit)
claude --max-tokens 4096
--temperature
Control randomness in responses (0.0 to 1.0).
# More deterministic (default: 0.7)
claude --temperature 0.0
# More creative
claude --temperature 1.0
--timeout
Set request timeout in seconds.
# Longer timeout for complex tasks
claude --timeout 300
# Shorter timeout
claude --timeout 30
Information Flags
--version / -v
Show Claude Code version.
claude --version
claude -v
--help / -h
Show help information.
claude --help
claude -h
# Help for specific command
claude config --help
--list-models
List available models.
claude --list-models
# Shows: All Claude models you can use
--list-sessions
List recent sessions.
claude --list-sessions
# Shows: Session IDs, names, timestamps
Config Commands
claude config get
View configuration settings.
# View all settings
claude config get
# View specific setting
claude config get model
claude config get output_style
claude config get permissions
claude config set
Change configuration settings.
# Set default model
claude config set model claude-sonnet-4-20250514
# Set default output style
claude config set output_style concise
# Set permissions
claude config set permissions ask
# Set audit logging
claude config set audit_logging true
claude config reset
Reset configuration to defaults.
# Reset all settings
claude config reset
# Reset specific setting
claude config reset model
claude config list
List all available configuration options.
claude config list
MCP Commands
claude mcp list
List installed MCP servers.
claude mcp list
# Shows: Server names, status, permissions
claude mcp install
Install an MCP server.
# Install from npm
claude mcp install @modelcontextprotocol/server-filesystem
# Install from GitHub
claude mcp install github:user/repo
claude mcp remove
Remove an MCP server.
claude mcp remove filesystem
claude mcp configure
Configure MCP server settings.
claude mcp configure filesystem
# Opens editor to configure permissions, paths, etc.
Environment Variables
ANTHROPIC_API_KEY
Your Anthropic API key (required).
export ANTHROPIC_API_KEY=sk-ant-your-key-here
CLAUDE_CODE_HOME
Custom home directory for Claude Code files.
export CLAUDE_CODE_HOME=~/.my-claude
CLAUDE_CODE_MODEL
Default model to use.
export CLAUDE_CODE_MODEL=claude-sonnet-4-20250514
CLAUDE_CODE_OUTPUT_STYLE
Default output style.
export CLAUDE_CODE_OUTPUT_STYLE=concise
CLAUDE_CODE_PERMISSIONS
Default permission level.
export CLAUDE_CODE_PERMISSIONS=ask
NO_COLOR
Disable colored output.
export NO_COLOR=1
DEBUG
Enable debug mode.
export DEBUG=claude-code:*
Common Combinations
Quick One-Shot Question
claude --print "How do I center a div in CSS?"
Safe Exploration of New Codebase
claude --sandbox --ask
Deep Architecture Planning
claude --plan --extended-thinking
Fast Lightweight Tasks
claude --model claude-3-haiku-20240307
Maximum Context for Large Projects
claude --model claude-sonnet-4-20250514 --add-dir ../lib
Secure Team Environment
claude --permissions ask --audit-log ~/.claude/audit.log
Resume Last Session Verbosely
claude --resume --verbose
Debugging with Full Information
claude --debug --verbose
Complete Flag Reference
| Flag | Short | Description |
|---|---|---|
--ask |
- | Ask mode (no code changes) |
--plan |
- | Plan mode (create implementation plan) |
--extended-thinking |
- | Enable deeper reasoning |
--model |
- | Choose Claude model |
--api-key |
- | Anthropic API key |
--config-file |
- | Custom config file path |
--output-style |
- | Set communication style |
--sandbox |
- | Read-only sandbox mode |
--verbose |
- | Show detailed output |
--debug |
- | Enable debug mode |
--add-dir |
- | Add directory to context |
--exclude |
- | Exclude files/directories |
--gitignore |
- | Respect .gitignore (default) |
--resume |
-r |
Resume last session |
--continue |
-c |
Continue from last point |
--new |
- | Force new session |
--session-name |
- | Name the session |
--print |
-p |
Print output (non-interactive) |
--json |
- | Output in JSON format |
--quiet |
-q |
Minimal output |
--permissions |
- | Set permission level |
--audit-log |
- | Enable audit logging |
--offline |
- | Disable external network |
--proxy |
- | Use proxy server |
--max-tokens |
- | Limit response length |
--temperature |
- | Control randomness (0.0-1.0) |
--timeout |
- | Request timeout (seconds) |
--version |
-v |
Show version |
--help |
-h |
Show help |
--list-models |
- | List available models |
--list-sessions |
- | List recent sessions |
Key Takeaways
- Basic usage:
claudestarts in current directory - Mode flags: --ask (questions), --plan (planning), --extended-thinking (complex)
- Models: Sonnet 4 (1M context), Sonnet 3.5 (200K), Haiku (fast)
- Sandbox mode: --sandbox for safe exploration
- Sessions: --resume/-r to continue, --session-name to organize
- Print mode: --print/-p for one-shot questions
- Permissions: --permissions ask/auto-allow/auto-deny
- Audit logging: --audit-log for compliance tracking
- Config commands: get, set, reset, list
- MCP commands: list, install, remove, configure
- Environment variables: ANTHROPIC_API_KEY, CLAUDE_CODE_MODEL, etc.
- Combine flags: Mix and match for specific workflows
- --verbose and --debug: Understand what Claude is doing
- --add-dir: Include additional directories in context
- Output styles: --output-style to customize communication
Next: Chapter 18 - Best Practices. Learn proven tips, patterns, and workflows from Anthropic teams and power users to maximize your productivity with Claude Code!
Test your knowledge!
Take Chapter 17 Quiz โChapter 18: Best Practices - Wisdom from the Pros
You've learned all the features. Now let's learn the wisdom.
This chapter shares proven tips, patterns, and workflows from Anthropic's internal teams who use Claude Code every day. Think of it as learning from people who've already made the mistakes so you don't have to.
Real impact from Anthropic teams:
- Security team: Debugging 3x faster (15 min โ 5 min)
- Growth Marketing: Ad creation 8x faster (2 hours โ 15 min)
- Product Design: Weeks to hours (7 days โ 2 calls)
- Data Science: Built 5,000-line app with minimal JS knowledge
- Legal team: Built accessibility app in 1 hour (zero coding exp)
- Inference team: Research time reduced 80% (1 hour โ 10-20 min)
Let's learn how they did it.
The Golden Rules
1. Quality Over Speed
The mistake: Rushing Claude, accepting first answer, moving on.
The wisdom: Take time. Claude gets better with iteration.
Analogy: Imagine cooking. First attempt = edible. Third attempt = delicious. Claude is the same - first try works, third try excels.
How Anthropic teams do it:
- API Knowledge team: "Treat it as an iterative partner, not a one-shot solution"
- Security team: "Let Claude talk first, then steer with periodic check-ins"
- Product Design: "2-3 rounds of refinement for visual polish"
Example workflow:
# Round 1: Get basic implementation
You: "Add authentication to the API endpoint"
Claude: [Writes basic auth]
# Round 2: Improve security
You: "Make it more secure - add rate limiting"
Claude: [Adds rate limiting]
# Round 3: Polish
You: "Add better error messages for users"
Claude: [Polishes error handling]
# Result: Production-ready code
2. Start Fresh for New Topics
The mistake: Using same session for everything. Context gets messy.
The wisdom: Start new session when switching topics.
Analogy: Your desk. Working on taxes? Clear the desk. Now starting art project? Clear it again. Claude needs clear workspace too.
When to start fresh:
- Switching from backend to frontend work
- Moving from bug fixing to new feature
- Context feels cluttered or Claude seems confused
- Starting completely different project
Terminal Way:
# Exit current session
Type: exit
# Start fresh in same project
claude
# Or start with specific name
claude --session-name "bug-fix-auth"
VS Code Way:
- In Claude panel, click the "New Session" button (top-right)
- Or close Claude panel and reopen: Cmd+Shift+P โ "Claude Code: Open"
3. Write Detailed Claude.md Files
The mistake: Empty or vague claude.md files. Claude guesses wrong.
The wisdom: "The better you document, the better Claude performs" - Data Infrastructure team
Analogy: Hiring someone to clean your house. Option A: No instructions (they guess). Option B: Detailed notes about where things go (they excel). Claude.md = your detailed notes.
What to include:
- Project overview: What does this project do?
- Code style: Tabs or spaces? Naming conventions?
- Testing approach: How to run tests? What framework?
- Common tasks: How to add new feature? Deploy?
- Quirks: Anything unusual about the codebase?
- Preferences: "I prefer verbose code with comments"
Real example from RL Engineering team:
# Claude.md
## Project: RL Training System
## Commands
- Run tests: `pytest` (NOT `python -m pytest`)
- Don't use `cd` - just use full paths
## Code Style
- Use type hints everywhere
- Add docstrings to all functions
- Prefer functional programming
## Common Mistakes to Avoid
- Don't modify the global state
- Always use context managers for file operations
- Test edge cases (empty arrays, None values)
## When Working With Me
- I'm learning ML, so explain model concepts
- Show me the "why" not just the "what"
- Commit work frequently so I can review
4. Use Specific, Detailed Prompts
The mistake: Vague requests. "Fix the bug" or "Make it better."
The wisdom: "The better and more detailed your prompt, the more you can trust Claude" - Product Development team
Analogy: Restaurant order. "I want food" (chef confused) vs "Grilled salmon with lemon, asparagus, hold the butter" (chef delivers exactly what you want).
Bad vs Good prompts:
| Bad (Vague) | Good (Specific) |
|---|---|
| "Fix the login bug" | "The login form accepts empty passwords. Add validation to require minimum 8 characters and show error message below the field." |
| "Make the app faster" | "The user list takes 5 seconds to load. Add pagination (20 items per page) and cache the results for 5 minutes." |
| "Add tests" | "Add unit tests for the calculateDiscount function. Test: 1) normal discount 2) discount = 0 3) discount = 100 4) negative price." |
| "Update the docs" | "Add a 'Getting Started' section to README.md covering: installation steps, first run, example usage. Write for complete beginners." |
5. Commit Checkpoints Frequently
The mistake: Let Claude work for hours without commits. Lose track of changes.
The wisdom: "Start from clean git state, commit checkpoints regularly" - Product Development team
Analogy: Video games. Save point every 5 minutes = safe. Save once at end = disaster if boss defeats you.
How Data Science team does it ("Slot Machine" approach):
# 1. Save current state
git add .
git commit -m "Working state before Claude refactor"
# 2. Let Claude work 30 minutes
You: "Refactor this component to use React hooks"
[Claude works autonomously]
# 3. Review result
# Option A: Looks good โ keep it
git add .
git commit -m "Refactored to hooks"
# Option B: Not good โ reset
git reset --hard HEAD
# Try again with better prompt
Checkpoint frequency guide:
- Every feature: After each complete feature works
- Before experiments: Before trying risky refactoring
- Every 30 minutes: If letting Claude work autonomously
- Before breaks: Before lunch, end of day
Task Classification: When to Guide vs Let Go
One of the most important skills: knowing when to supervise closely vs when to let Claude work autonomously.
Let Claude Work Autonomously (Auto-Accept Mode)
Good for:
- Peripheral features (not core business logic)
- Prototypes and experiments
- Test generation
- Documentation writing
- Repetitive refactoring (renaming, restructuring)
- Building in unfamiliar tech (you'll review anyway)
How Product Development team does it:
# Enable auto-accept mode in Claude Code
# Press: Shift + Tab (toggles auto-accept)
You: "Build vim key bindings for the editor"
# Claude works autonomously for 2 hours
# Result: 70% of final implementation done
Real example: Product Development team built entire Vim mode feature using autonomous mode. "Roughly 70% of final implementation came from Claude's autonomous work, requiring only a few iterations to complete."
Supervise Closely (Synchronous Mode)
Good for:
- Core business logic
- Security-critical code
- Payment processing
- Authentication systems
- Data migrations
- Production bug fixes
How Product Development team does it:
You: "Update the authentication middleware to handle OAuth2.
Follow our existing pattern in auth/providers/.
Use the SecurityService for token validation.
Add rate limiting (10 requests/minute).
Log all failed attempts."
# Monitor in real-time
# Steer when needed: "Use the existing RateLimiter class"
# Review each file before accepting
Decision Framework
| Question | Autonomous | Supervised |
|---|---|---|
| Is it core business logic? | No | Yes |
| What if it breaks? | Low impact | High impact |
| How familiar are you? | Unfamiliar (learning) | Expert (must be right) |
| Time sensitivity? | Can iterate | Must be fast |
| Rollback easy? | Yes (git reset) | No (production) |
Creating Self-Sufficient Loops
The pattern: Let Claude verify its own work automatically.
Analogy: Student doing homework. Option A: Show you each answer (slow). Option B: You give answer key, student checks themselves (fast, learns more).
Setup Verification Loop
You: "Add a new API endpoint for user search.
After you write the code:
1. Run the linter (npm run lint)
2. Run the tests (npm test)
3. If anything fails, fix it and try again
4. Keep going until all checks pass
5. Then show me the final result"
# Claude will work autonomously:
# โ Write code
# โ Run lint โ Fix issues
# โ Run tests โ Fix failures
# โ Iterate until everything passes
# โ Present final result
Test-First Loop
Security team's approach:
You: "I need a function to validate credit card numbers.
First, write the tests for:
- Valid card numbers
- Invalid length
- Invalid characters
- Luhn algorithm check
Then implement the function to pass all tests."
# Result: Better code because Claude knows the exact requirements upfront
Why this works: "Instead of design doc โ janky code โ refactor โ give up on tests, they now ask Claude for pseudocode, guide it through test-driven development" - Security team
Context Management Strategies
1. The Broad-to-Narrow Approach
For large codebases, start general then zoom in:
# Step 1: Broad overview
You: "What does this codebase do? What are the main components?"
# Step 2: Identify area
You: "Where is the user authentication handled?"
# Step 3: Zoom in
You: "Show me how password reset works"
# Step 4: Make changes
You: "Add email verification to password reset"
2. Use Agents for Parallel Work
Data Infrastructure team approach:
# Terminal 1: Backend work
cd ~/project/backend
claude --session-name "api-work"
# Terminal 2: Frontend work
cd ~/project/frontend
claude --session-name "ui-work"
# Terminal 3: Documentation
cd ~/project/docs
claude --session-name "docs"
# Each instance maintains full context
# Switch between them without losing place
3. Smart /compact Usage
When to compact:
- Just finished a large task, starting something new
- Conversation has lots of old/irrelevant context
- Claude seems to be forgetting things
When NOT to compact:
- In middle of debugging (need full history)
- Working on interconnected changes
- Following up on previous discussion
Domain-Specific Tips
For Non-Developers (Product Design, Legal, Marketing)
1. Get setup help from engineers
- Have dev teammates help with initial repo setup
- Get permissions configured correctly
- Learn basic git commands (commit, reset)
2. Customize your personal memory
# ~/.claude/personal.md
Hi Claude! Important things about working with me:
- I'm a designer with little coding experience
- Explain technical concepts in simple terms
- Make changes incrementally (small steps)
- Always tell me what you're doing and why
- If something could break, warn me first
- I learn by doing, so encourage me to try things
3. Use images extensively
Paste mockups, screenshots, design specs directly into chat. Claude excels at reading visual designs.
Real example: Product Design team - "By pasting mockup images into Claude Code, they generate fully functional prototypes that engineers can immediately understand."
For Data Scientists / ML Engineers
1. Build permanent tools, not throwaway notebooks
Instead of one-off Jupyter notebooks, have Claude build React dashboards you can reuse.
Real example: Data Science team built 5,000-line TypeScript dashboard "despite knowing very little JavaScript and TypeScript."
2. Interrupt for simplicity
"Don't hesitate to stop Claude and ask 'why are you doing this? Try something simpler.' The model tends toward more complex solutions by default." - Data Science team
For Security / Infrastructure Teams
1. Feed Claude screenshots and logs
"When Kubernetes clusters went down, they fed screenshots of dashboards into Claude Code, which guided them through Google Cloud's UI menu by menu." - Data Infrastructure team
2. Use custom slash commands extensively
"Security engineering uses 50% of all custom slash command implementations in the entire monorepo. These custom commands streamline specific workflows." - Security team
# .claude/commands/check-terraform.md
---
description: Review Terraform plan for security issues
---
Review this Terraform plan for security concerns:
- Overly permissive IAM roles
- Public access that should be private
- Missing encryption
- Hardcoded secrets
Terraform plan:
{{CLIPBOARD}}
For Growth / Marketing Teams
1. Identify API-enabled repetitive tasks
"Look for workflows involving repetitive actions with tools that have APIs (ad platforms, design tools, analytics platforms). These are prime candidates for automation." - Growth Marketing team
2. Break workflows into specialized sub-agents
"Create separate agents for specific tasks (like their headline agent vs description agent). This makes debugging easier and improves output quality." - Growth Marketing team
Real impact: Growth Marketing team - "Ad copy creation reduced from 2 hours to 15 minutes, freeing up time for strategic work. 10x increase in creative output."
Common Mistakes to Avoid
1. Not Reading Claude's Explanations
Mistake: Just looking at code changes, skipping Claude's text.
Fix: Claude explains the "why." Read it. You'll learn and catch issues earlier.
2. Using Same Session for Everything
Mistake: One session for backend, frontend, docs, debugging all mixed together.
Fix: Start fresh when switching contexts. Use named sessions.
3. Ignoring Failed Tests
Mistake: "Tests are failing but the feature works, ship it!"
Fix: Let Claude fix the tests. Setup self-verification loops.
4. Not Using Claude.md Files
Mistake: Expecting Claude to guess your preferences and patterns.
Fix: Write detailed claude.md. Data Infrastructure team: "The better you document your workflows, tools, and expectations, the better Claude Code performs."
5. Giving Up After First Failure
Mistake: Claude's first try doesn't work, decide "Claude can't do this."
Fix: Iterate. API Knowledge team: "Treat it as an iterative partner, not a one-shot solution." RL Engineering team: "Works on first attempt about one-third of the time, requiring either additional guidance or manual intervention."
6. Not Committing Before Experiments
Mistake: Let Claude refactor complex code without git checkpoint.
Fix: "Checkpoint-heavy workflow. Regularly commit your work as Claude makes changes so you can easily roll back when experiments don't work out." - RL Engineering team
7. Using MCP Without Security Review
Mistake: Installing MCP servers that access sensitive data without checking permissions.
Fix: Data Infrastructure team: "Use MCP servers instead of CLI for sensitive data to maintain better security control over what Claude Code can access."
Power User Techniques
1. Planning in Claude.ai, Building in Claude Code
Legal team's workflow:
# Step 1: Plan in Claude.ai (conversational)
"I want to build a tool that helps lawyers find the right
specialist at our company. Like a smart phone tree. It should
ask questions and route to the right person..."
[Have full conversation, iterate on the idea]
# Step 2: Get implementation plan
"Summarize everything we discussed into a detailed prompt
with step-by-step instructions for Claude Code"
# Step 3: Execute in Claude Code
[Paste the plan]
"Build this, working step by step. After each step, show me
the result so I can see progress."
2. Documentation Synthesis
Security team approach:
You: "Read these 3 documentation sources:
- @incident-response.md
- @kubernetes-troubleshooting.md
- @security-runbook.md
Create a condensed troubleshooting guide for when pods fail
to start. Focus on security-related issues. Format as a
checklist I can follow during incidents."
# Result: Custom runbook perfectly tailored to your needs
3. Leveraging Extended Thinking for Planning
# Terminal
claude --extended-thinking
You: "I need to refactor our authentication system to support
multiple OAuth providers while maintaining backward compatibility.
Think through the architecture before implementing."
# Claude thinks deeply (30-60 seconds)
# Then provides comprehensive architecture plan
# Review the plan first
# Then: "Looks good, let's implement Step 1"
4. Using Hooks for Workflow Automation
# .claude/hooks/pre-tool-use.sh
#!/bin/bash
# Automatically commit before Claude edits files
if [[ "$TOOL_NAME" == "Edit" || "$TOOL_NAME" == "Write" ]]; then
git add .
git commit -m "Auto-checkpoint before Claude edit" --no-verify
fi
5. Team Knowledge Sharing Sessions
Data Infrastructure team tip:
"The team held sessions where members demonstrated their Claude Code workflows to each other. This helped spread best practices and showed different ways to use the tool they might not have discovered on their own."
Try it:
- Weekly team demo: "Show your best Claude Code win this week"
- Share custom slash commands
- Share claude.md patterns
- Share "I didn't know you could do that!" moments
Measuring Your Progress
How do you know you're getting better at using Claude Code?
Beginner โ Intermediate
- Writing clear, specific prompts
- Using claude.md files in projects
- Know when to start fresh session
- Comfortable with basic @ symbol usage
- Can commit and reset when needed
Intermediate โ Advanced
- Using agents for parallel work
- Created custom slash commands
- Installed and use 2+ MCP servers
- Know when to supervise vs let Claude work autonomously
- Using personal memory effectively
- Comfortable with extended thinking mode
Advanced โ Power User
- Created custom output styles
- Using hooks for workflow automation
- Building custom skills or plugins
- Created self-verification loops
- Teaching others effective Claude Code usage
- Contributing patterns back to team/community
Key Takeaways
- Quality over speed: Iterate for better results, treat Claude as partner
- Start fresh: New session for new topics keeps context clean
- Document thoroughly: Detailed claude.md files = better Claude performance
- Be specific: Detailed prompts โ better results, trust
- Checkpoint frequently: Commit before experiments, git reset when needed
- Task classification: Autonomous for periphery, supervised for core
- Self-verification loops: Let Claude run tests, fix issues, iterate
- Test-driven approach: Write tests first for better code
- Context strategies: Broad-to-narrow, agents for parallel, smart /compact
- Domain tips: Non-devs use images, data scientists build permanent tools
- Security awareness: Review MCP permissions, custom commands for workflows
- Marketing automation: Find API-enabled tasks, specialized sub-agents
- Avoid mistakes: Read explanations, fresh sessions, fix tests, use claude.md
- Plan in Claude.ai: Brainstorm conversationally, then execute in Claude Code
- Extended thinking: Use for complex planning before implementation
- Team learning: Share workflows, commands, discoveries with teammates
- Interrupt for simplicity: Stop Claude if solution too complex
- Track progress: Beginner โ Intermediate โ Advanced โ Power User
- Real impact: 3x debugging speed, 8x ad creation, weeks to hours
- Persistence pays off: Works first try 1/3 of time, iterate for success
Final Wisdom from the Pros
From Product Design team:
"Two distinct user experiences: Developers get 'augmented workflow' (faster execution), while non-technical users get 'holy crap, I'm a developer workflow' (entirely new capabilities previously impossible)."
From Legal team:
"Overcome the urge to hide 'toy' projects or unfinished work - sharing prototypes helps others see possibilities and sparks innovation across departments that don't typically interact."
From Data Science team:
"Treat it like a slot machine. Save your state, let it run for 30 minutes, then either accept the result or start fresh rather than trying to wrestle with corrections. Starting over often has a higher success rate."
From Security team:
"Let Claude talk first. Instead of asking targeted questions for code snippets, tell Claude Code to 'commit your work as you go' and let it work autonomously with periodic check-ins, resulting in more comprehensive solutions."
From Inference team:
"Test knowledge base functionality first. Try asking various questions to see if Claude can answer faster than Google search. If it's faster and more accurate, it's a valuable time-saving tool for your workflow."
Next: Chapter 19 - Troubleshooting. What to do when things don't work as expected, how to debug issues, and solutions to common problems!
Test your knowledge!
Take Chapter 18 Quiz โChapter 19: Troubleshooting - Fixing Common Issues
Things go wrong. It's normal. This chapter helps you fix them.
Analogy: Think of this as your "emergency toolkit" - when something breaks, you look here first. Like a car manual's troubleshooting section, but for Claude Code.
We've organized problems by category so you can quickly find solutions.
Installation & Setup Issues
Problem: "claude: command not found"
What happened: Your terminal doesn't know where Claude Code is installed.
Solution 1 (Mac/Linux):
# Add Claude to your PATH
echo 'export PATH="$HOME/.claude/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
# Or if using bash
echo 'export PATH="$HOME/.claude/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
# Test it
claude --version
Solution 2 (Windows):
- Open "Edit System Environment Variables"
- Click "Environment Variables"
- Under "User variables", select "Path" and click "Edit"
- Click "New" and add:
C:\Users\YourName\.claude\bin - Click "OK" on all dialogs
- Restart your terminal
Problem: "API key not found"
What happened: Claude Code doesn't have your Anthropic API key.
Solution:
# Set your API key
claude config set api-key YOUR_API_KEY_HERE
# Or set it as environment variable
export ANTHROPIC_API_KEY="your-key-here"
# Verify it's set
claude config get api-key
Problem: "Node.js version too old"
What happened: Claude Code needs Node.js 18 or newer.
Check your version:
node --version
# Should show v18.0.0 or higher
Solution: Download latest Node.js from nodejs.org and install it.
Problem: VS Code Extension Not Working
Solution 1: Reload VS Code
- Press Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows)
- Type: "Developer: Reload Window"
- Press Enter
Solution 2: Reinstall Extension
- Go to Extensions panel (Cmd+Shift+X)
- Find "Claude Code"
- Click "Uninstall", wait for it to complete
- Click "Install"
- Reload VS Code
Authentication & Permission Issues
Problem: "Permission denied" for File Operations
What happened: Claude doesn't have permission to read/write files.
Solution 1: Check permissions mode
# Check current setting
claude config get permissions
# Set to ask mode (recommended)
claude config set permissions ask
# Or if you trust the project
claude config set permissions auto-allow
Solution 2: Check file permissions
# Make sure you own the files
ls -la
# Fix permissions if needed (Mac/Linux)
chmod u+rw filename.txt
Problem: Claude Won't Run Bash Commands
What happened: Bash tool is disabled or requires approval.
Solution:
# Enable bash commands in settings
# Edit: ~/.claude/settings.json
{
"permissions": {
"bash": "ask" // or "auto-allow" if you trust it
}
}
Problem: "Rate limit exceeded"
What happened: You've sent too many requests to the API too quickly.
Solution:
- Wait 1-2 minutes before trying again
- Avoid rapid-fire messages
- Use
/compactto reduce context size (fewer tokens = lower rate limit impact) - Check your API plan limits at console.anthropic.com
Context & Memory Issues
Problem: Claude "Forgot" Earlier Conversation
What happened: Context window filled up, older messages dropped.
Analogy: Your backpack is full. To add new books, you must remove old ones.
Solution 1: Use /compact
# In Claude Code chat
/compact
# Claude will summarize and compress old context
Solution 2: Put important info in claude.md
# Create .claude/claude.md
# Add important context that should never be forgotten
## Important Context
- User prefers Python 3.11
- Always use type hints
- Project uses pytest for testing
- Backend API is at http://localhost:8000
Solution 3: Start fresh session
# Exit and restart
exit
claude
Problem: Claude Seems Confused or Off-Track
What happened: Context has conflicting information or too much noise.
Solution 1: Start fresh
# The nuclear option - start clean
exit
claude --session-name "fresh-start"
Solution 2: Be explicit
You: "Ignore everything above. Let me clarify:
- We're working on the login feature
- The bug is in auth.js line 42
- Password validation is accepting empty strings
- Fix: Add check for empty password before validation"
Problem: "Context limit exceeded"
What happened: Your conversation is too long for the model's context window.
Solution 1: Use /compact
/compact
Solution 2: Switch to larger context model
# Sonnet 4 has 1M token context (vs Sonnet 3.5's 200K)
claude --model sonnet-4
Solution 3: Start new session
exit
claude
Problem: Claude.md Changes Not Taking Effect
What happened: Claude cached old version or file isn't in right location.
Solution 1: Check file location
# Project-level (most common)
.claude/claude.md
# Personal (global)
~/.claude/personal.md
# Verify it's there
ls -la .claude/
Solution 2: Restart session
exit
claude
# Claude.md is loaded at session start
Performance Issues
Problem: Claude Is Very Slow
What happened: Large context, complex task, or API congestion.
Solution 1: Use faster model for simple tasks
# Haiku is 3x faster for simple tasks
claude --model haiku
# Or switch mid-session
/model haiku
Solution 2: Reduce context
# Compact conversation
/compact
# Or start fresh
exit
claude
Solution 3: Use --extended-thinking selectively
# Don't use extended thinking for simple questions
# Only use it for complex problems
# Bad: "What's the syntax for a for loop?" --extended-thinking
# Good: "Design architecture for distributed system" --extended-thinking
Solution 4: Check API status
Visit status.anthropic.com to see if there are API issues.
Problem: Response Keeps Timing Out
Solution: Increase timeout
# Set longer timeout (in milliseconds)
claude --timeout 120000 # 2 minutes
# Or in settings
{
"timeout": 120000
}
Problem: High Token Usage / Expensive
What happened: Large context or many messages.
Solution 1: Use /compact regularly
# After completing a task
/compact
Solution 2: Switch to cheaper models
# Haiku is cheapest for simple tasks
claude --model haiku
# Cost comparison (per 1M tokens):
# Sonnet 4: $3 input / $15 output
# Sonnet 3.5: $3 input / $15 output
# Haiku: $0.25 input / $1.25 output
Solution 3: Start fresh sessions
# Don't carry old context unnecessarily
exit
claude
Code & Tool Errors
Problem: Claude's Code Has Bugs
What happened: AI isn't perfect. Sometimes makes mistakes.
Solution 1: Show Claude the error
You: "That code has a bug. When I run it, I get this error:
TypeError: cannot read property 'name' of undefined
The issue is on line 23. Can you fix it?"
Solution 2: Ask Claude to test first
You: "Before showing me the code, write the code AND
run the tests to make sure it works. Only show me the
final version after tests pass."
Solution 3: Set up verification loops
You: "Add a new feature. After writing code:
1. Run eslint to check for issues
2. Run the test suite
3. If anything fails, fix it
4. Repeat until everything passes
5. Then show me"
Problem: "Tool execution failed"
What happened: Claude tried to use a tool (Read, Write, Bash) but it failed.
Solution 1: Check permissions
# Make sure permissions aren't set to deny
claude config get permissions
# Should be "ask" or "auto-allow"
claude config set permissions ask
Solution 2: Check file paths
You: "The file path is wrong. The correct path is:
/Users/yourname/project/src/app.js
(Use this exact path)"
Solution 3: Use --verbose to see what's happening
claude --verbose
# Shows detailed tool execution info
Problem: Bash Commands Not Working
What happened: Command syntax wrong or environment issue.
Solution 1: Test command manually
# Copy the command Claude tried
# Run it yourself in terminal
# See what error you get
# Then tell Claude the error
Solution 2: Check working directory
You: "First, run 'pwd' to show current directory.
Then run 'ls' to show what files are here.
Then run the command."
Solution 3: Use absolute paths
# Instead of relative paths
python test.py # Might fail
# Use absolute paths
python /Users/name/project/test.py # More reliable
Problem: Git Operations Failing
Solution 1: Check git status first
You: "Before committing, run 'git status' to see what's changed"
Solution 2: Configure git if needed
# Set git identity (needed for commits)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
Solution 3: Use sandbox mode for experiments
# Safe testing without affecting real repo
claude --sandbox
MCP Server Issues
Problem: MCP Server Won't Install
Solution 1: Check if already installed
# List installed servers
claude mcp list
Solution 2: Install manually
# Install from npm
npm install -g @modelcontextprotocol/server-name
# Then configure in Claude
claude mcp install server-name
Solution 3: Check permissions
# You might need sudo (Mac/Linux)
sudo npm install -g @modelcontextprotocol/server-name
Problem: MCP Server Not Responding
Solution 1: Restart Claude
exit
claude
Solution 2: Check server configuration
# View config
claude mcp list
# Reconfigure if needed
claude mcp configure server-name
Solution 3: Check server logs
# Enable debug mode
claude --debug
# Shows MCP server communication
Problem: "MCP server requires additional permissions"
What happened: Server needs access to files, network, or other resources.
Solution: Review and approve permissions
- Read what permissions the server wants
- Only approve if you trust the server
- Use
permissions: askmode to review each request
Debugging Techniques
Use --verbose Flag
See exactly what Claude is doing behind the scenes:
claude --verbose
# Shows:
# - Tool calls
# - File reads/writes
# - API requests
# - Context usage
Use --debug Flag
Even more detailed information:
claude --debug
# Shows:
# - Full API payloads
# - Token counts
# - Timing information
# - MCP server communication
Check Session History
# List recent sessions
claude --list-sessions
# Resume a previous session to review what happened
claude --resume SESSION_NAME
Use Audit Logs
For compliance or debugging complex issues:
# Enable audit logging
claude --audit-log ./audit.log
# Review logs later
cat audit.log
Test in Sandbox Mode
Safe environment for troubleshooting:
# No permanent changes
claude --sandbox
# Perfect for testing problematic commands
Common Error Messages Decoded
| Error Message | What It Means | Solution |
|---|---|---|
| "API key invalid" | Wrong API key or expired | claude config set api-key NEW_KEY |
| "Model not found" | Typo in model name | Use: sonnet-4, sonnet-3.5, or haiku |
| "Session not found" | Session was deleted or expired | Start new session: claude |
| "File not found" | Path is wrong or file deleted | Check path with ls, use absolute path |
| "Permission denied" | Don't have access to file/folder | Fix: chmod u+rw file or change permissions setting |
| "Network error" | Can't reach Anthropic API | Check internet, check status.anthropic.com |
| "Context too large" | Hit token limit | Use /compact or start fresh session |
| "Rate limit exceeded" | Too many requests too fast | Wait 1-2 minutes, then try again |
| "Tool execution timeout" | Command took too long | Use --timeout 120000 for longer timeout |
When All Else Fails
1. Restart Everything
# Exit Claude
exit
# Close terminal
# Open new terminal
# Start fresh
claude
2. Reset Configuration
# Reset all settings to defaults
claude config reset
# Then reconfigure
claude config set api-key YOUR_KEY
claude config set permissions ask
3. Reinstall Claude Code
Terminal Way (Mac/Linux):
# Uninstall
npm uninstall -g @anthropic-ai/claude-code
# Reinstall
curl -fsSL https://claude.ai/install.sh | bash
VS Code Way:
- Uninstall extension
- Reload VS Code
- Reinstall extension
4. Check System Requirements
- Node.js 18 or higher:
node --version - Internet connection working
- API key is valid
- Enough disk space (at least 1GB free)
- Firewall not blocking claude.ai
5. Use --print Mode for Simple Questions
If interactive mode is buggy, try print mode:
claude --print "How do I fix this error: [paste error]"
# Gets answer without starting full session
6. Get Help
- Check docs: docs.claude.com/claude-code
- Community forum: Ask other users for help
- Report bugs: github.com/anthropics/claude-code/issues
- Support: support@anthropic.com (for account/billing issues)
Prevention Tips
Avoid problems before they start:
1. Save Often with Git
# Before letting Claude make big changes
git add .
git commit -m "Checkpoint before Claude work"
# If things go wrong
git reset --hard HEAD
2. Use Named Sessions
# Organize work
claude --session-name "bug-fix-login"
claude --session-name "feature-dashboard"
# Easy to resume later
claude --resume bug-fix-login
3. Start Fresh Between Projects
# Don't carry context from project A to project B
exit
cd ~/project-b
claude
4. Keep Claude Code Updated
# Check for updates regularly
claude --version
# Update when available
npm update -g @anthropic-ai/claude-code
5. Review Changes Before Accepting
Don't blindly accept all changes. Review what Claude did:
# After Claude edits files
git diff
# Review changes before committing
Key Takeaways
- "command not found": Add Claude to PATH in ~/.zshrc or ~/.bashrc
- "API key not found": Set with
claude config set api-key - Claude forgot context: Use
/compactor put important info in claude.md - Claude seems confused: Start fresh session with clear, explicit instructions
- "Context limit exceeded": Use
/compactor switch to Sonnet 4 (1M context) - Slow responses: Use Haiku for simple tasks, reduce context with /compact
- Timing out: Increase timeout with
--timeout 120000 - High token costs: Use
/compact, start fresh sessions, use Haiku when possible - Code has bugs: Show Claude the error, ask it to test first, set up verification loops
- "Tool execution failed": Check permissions, verify file paths, use --verbose
- Bash not working: Test manually, check working directory, use absolute paths
- MCP server issues: Check with
claude mcp list, restart Claude, review permissions - Debug mode: Use --verbose or --debug to see what's happening
- Test safely: Use
--sandboxmode for experiments - Audit trail: Use
--audit-logfor compliance and debugging - Prevention: Save with git, use named sessions, start fresh between projects
- Nuclear option: Exit, restart terminal, start fresh session
- Get help: docs.claude.com, community forum, GitHub issues
Quick Reference: Troubleshooting Commands
# Debug and diagnosis
claude --verbose # See detailed tool execution
claude --debug # See everything (API calls, tokens, timing)
claude --list-sessions # View session history
claude --audit-log file # Enable compliance logging
# Configuration fixes
claude config get KEY # Check a setting
claude config set KEY VALUE # Update a setting
claude config reset # Reset to defaults
claude config list # Show all settings
# Context management
/compact # Compress conversation
exit # Leave and start fresh
claude --model sonnet-4 # Switch to larger context
# Permission fixes
claude config set permissions ask # Review each request
--sandbox # Safe testing mode
# Performance
claude --model haiku # Faster, cheaper model
--timeout 120000 # Longer timeout (2 min)
# MCP troubleshooting
claude mcp list # Show installed servers
claude mcp configure NAME # Reconfigure server
claude mcp remove NAME # Uninstall server
# Emergency resets
git reset --hard HEAD # Undo all changes
npm update -g @anthropic-ai/claude-code # Update Claude
npm uninstall -g @anthropic-ai/claude-code # Reinstall
Next: Chapter 20 - Next Steps. Where to go from here, additional resources, joining the community, and continuing your Claude Code journey!
Test your knowledge!
Take Chapter 19 Quiz โChapter 20: Next Steps - Your Journey Continues
Congratulations! You've completed the Claude Code tutorial.
You started knowing nothing. Now you know everything - from installation to best practices, from basic commands to advanced workflows.
Analogy: Think of this tutorial as learning to drive. You now have your license. But the real learning happens on the road. This chapter is your roadmap for what comes next.
What You've Learned
Let's celebrate how far you've come:
- Basics: Installation, first project, talking to Claude
- Core Features: Modes, commands, memory system, @ symbol
- Advanced Tools: Agents, MCP servers, skills, hooks, plugins
- Workflows: Bug fixing, refactoring, git operations, testing
- Optimization: Context management, performance, security
- Mastery: Best practices, troubleshooting, CLI reference
You're now in the top 1% of Claude Code users. Most people never learn this much. Be proud.
Your Learning Path Forward
Level 1: Practice the Basics (Week 1-2)
Goal: Make Claude Code your daily habit.
Tasks:
- Use Claude Code for at least 1 task every day
- Create claude.md files in 3 different projects
- Practice using @ symbol to reference files
- Try all 4 modes: Ask, Plan, Edit, Extended Thinking
- Make your first git commit with Claude's help
Success metric: You reach for Claude Code without thinking about it.
Level 2: Build Real Projects (Week 3-4)
Goal: Ship something real.
Project ideas:
- Personal website: Portfolio with your projects
- Automation script: Organize files, rename photos, backup data
- API wrapper: Simple tool that calls a public API
- Dashboard: Visualize your data (finances, fitness, productivity)
- Chrome extension: Add feature to your browser
Success metric: You built something that solves a real problem you have.
Level 3: Master Advanced Features (Month 2)
Goal: Unlock power user status.
Tasks:
- Install and use 3 MCP servers
- Create 5 custom slash commands
- Set up at least 1 hook for automation
- Use agents for parallel work on a project
- Create a custom output style
- Build a personal skill package
Success metric: Your Claude Code setup is personalized to your workflow.
Level 4: Contribute & Share (Month 3+)
Goal: Give back to the community.
Ways to contribute:
- Share your custom commands on GitHub
- Write a blog post about your Claude Code workflow
- Create a video tutorial for beginners
- Answer questions in community forums
- Build and share an MCP server
- Report bugs or suggest features
Success metric: You've helped someone else learn Claude Code.
Additional Resources
Official Documentation
- Claude Code Docs: docs.claude.com/claude-code - Complete reference
- API Documentation: docs.anthropic.com - For API usage
- MCP Documentation: modelcontextprotocol.io - Protocol specs
- Release Notes: Follow updates and new features
Community & Support
- Discord Community: Chat with other users, share tips
- GitHub Discussions: Ask questions, share projects
- Reddit r/ClaudeCode: Community tips and tricks
- Twitter/X: Follow @AnthropicAI for updates
Learning Resources
- YouTube Tutorials: Search "Claude Code tutorial"
- Anthropic YouTube: Official videos and demos
- Blog Posts: Real-world use cases and workflows
- GitHub Examples: Sample projects and templates
Tools & Extensions
- VS Code Extension: Already covered, keep it updated
- MCP Server Gallery: Browse available servers
- Plugin Marketplace: Discover new capabilities
- Skill Library: Pre-built expertise packages
Career Applications
Claude Code is more than a tool - it's a career multiplier.
For Developers
- Ship features faster: 2-3x productivity increase
- Learn new languages quickly: Build in unfamiliar tech stacks
- Handle more projects: Parallel work with agents
- Better code quality: Automated testing and reviews
- Faster debugging: 3x faster issue resolution
Real example: Anthropic Security team - "Debugging that normally takes 10-15 minutes now takes about 5 minutes."
For Non-Developers
- Build without coding knowledge: Like Legal team (1 hour app)
- Automate repetitive tasks: Marketing team (8x faster)
- Create prototypes: Design team (weeks to hours)
- Analyze data: Build custom dashboards
- Learn to code: Best coding teacher you've ever had
Real example: Anthropic Product Design team - "Non-technical users get 'holy crap, I'm a developer workflow' - entirely new capabilities previously impossible."
Resume & Portfolio
How to showcase Claude Code skills:
- List projects you built with Claude Code
- Mention "AI-assisted development workflow"
- Highlight custom tools you created (MCP servers, skills)
- Include productivity metrics (e.g., "Increased development velocity 3x")
- Share open-source contributions using Claude Code
Challenge Projects
Ready to push your limits? Try these progressively harder projects:
Beginner Challenges
-
Personal Dashboard
Build a webpage showing your daily stats (weather, calendar, tasks).
Skills practiced: HTML/CSS, API integration, data display -
File Organizer
Script that sorts your Downloads folder by file type.
Skills practiced: File operations, bash scripting, automation -
Task Tracker
Simple command-line app to track your todos.
Skills practiced: Data persistence, CLI interfaces, CRUD operations
Intermediate Challenges
-
Custom MCP Server
Build an MCP server that integrates with your favorite API.
Skills practiced: MCP protocol, server development, API integration -
Browser Extension
Chrome/Firefox extension that enhances a website you use daily.
Skills practiced: JavaScript, browser APIs, UI/UX -
Data Visualization Dashboard
Interactive charts from your personal data (fitness, finances, etc.).
Skills practiced: D3.js/Chart.js, data processing, React/Vue
Advanced Challenges
-
Full-Stack Web App
Build a complete app with auth, database, and deployment.
Skills practiced: Backend/frontend, databases, cloud deployment -
CI/CD Pipeline
Set up automated testing, linting, and deployment for a project.
Skills practiced: GitHub Actions, testing, DevOps -
Custom Skill Package
Create a complete skill package for a specialized domain.
Skills practiced: Skill design, documentation, packaging
Tips for Long-Term Success
1. Build a Second Brain
Document your learnings:
- Keep a "Today I Learned" file
- Save useful prompts in a personal library
- Document your custom commands and why you made them
- Create templates for common project types
2. Stay Updated
Claude Code evolves quickly:
- Update regularly:
npm update -g @anthropic-ai/claude-code - Follow Anthropic announcements
- Check release notes for new features
- Experiment with new capabilities as they drop
3. Join the Community
Learning is social:
- Share your wins and struggles
- Help beginners when you can
- Ask questions when stuck
- Collaborate on open-source projects
4. Teach Others
Best way to master something? Teach it.
- Show a colleague how to use Claude Code
- Write a blog post about what you learned
- Create a video tutorial
- Give a talk at your company or meetup
5. Keep Experimenting
Never stop exploring:
- Try new MCP servers each month
- Experiment with different prompting styles
- Build something weird just for fun
- Push Claude to its limits (safely in sandbox mode!)
Frequently Asked Questions
Q: Will AI replace developers?
A: No. AI augments developers, it doesn't replace them. Think of Claude Code like a calculator - it makes math faster, but you still need to know what calculation to do. Developers who use AI will replace developers who don't.
Q: Should I mention Claude Code in job interviews?
A: Yes! Frame it as "AI-assisted development" or "modern productivity tools." Focus on what you built, not just that you used AI. Example: "I built a full-stack app in 2 weeks using AI-assisted development, handling both frontend and backend despite being primarily a frontend developer."
Q: How much should I rely on Claude vs coding myself?
A: Use Claude for speed, but understand the code. Read what Claude writes. Ask it to explain. Over time, you'll learn patterns and need Claude less for simple tasks, more for complex ones. It's a learning accelerator, not a crutch.
Q: What if Claude makes mistakes in production code?
A: You're responsible for code quality, not Claude. Always review changes, run tests, use verification loops. Claude is a tool - would you blame your keyboard for a typo? Set up safety nets: tests, code review, staging environments.
Q: Is it cheating to use Claude Code for homework/bootcamp?
A: Depends on context. Using it to understand concepts = learning. Using it to copy answers = cheating. Good rule: If you can explain the code Claude wrote, you learned. If you can't, you cheated yourself out of learning. Always check your institution's AI policy.
Q: What's the best model for daily use?
A: Start with Sonnet 3.5 (balanced). Use Haiku for simple tasks (faster, cheaper). Use Sonnet 4 or extended thinking for complex problems (better reasoning, larger context). Switch based on task difficulty.
Q: How do I avoid getting stuck in "prompt engineering hell"?
A: Be specific upfront. Don't vague-prompt then iterate 10 times. Spend 2 minutes writing a clear prompt vs 20 minutes fixing vague results. Use claude.md to avoid repeating context. Start fresh when confused.
Final Words
You started this tutorial as a beginner. You're finishing it as a practitioner.
The difference between knowing and mastering is doing. Reading this tutorial was step one. Now comes step two: building real things.
Three truths to remember:
- You will get stuck. That's normal. Use the troubleshooting chapter, ask the community, keep going. Every expert was once stuck exactly where you are.
- You will make mistakes. That's learning. Commit often, use git, embrace the iterations. The Data Science team's "slot machine" approach exists because mistakes are part of the process.
- You will succeed. The Legal team built an accessibility app in 1 hour with zero coding experience. The Product Design team went from non-developers to implementing complex state management. If they can do it, you can too.
This isn't the end. It's the beginning.
Claude Code is evolving every month. New features drop constantly. The community grows daily. You're joining at an exciting time.
Five years from now, you'll look back at this moment and smile. "That's when everything changed," you'll think. "That's when I realized I could build anything."
Because now you can.
Your Next Action
Don't close this tab and forget. Take action right now:
- Open your terminal
- Type
claude - Say: "Help me build [something you've been wanting to create]"
- And start
The best time to start was yesterday. The second best time is now.
Key Takeaways
- You've learned everything: From basics to mastery in 20 chapters
- Learning path: Practice basics โ build projects โ master advanced โ contribute
- Resources available: Official docs, community, tutorials, tools
- Career multiplier: 2-3x productivity for devs, "holy crap" moment for non-devs
- Challenge projects: Beginner โ Intermediate โ Advanced with specific ideas
- Long-term success: Build second brain, stay updated, teach others
- AI augments, not replaces: You're responsible for quality and understanding
- Frame it positively: "AI-assisted development" is a modern skill
- Understand the code: Use Claude to learn faster, not avoid learning
- Start with Sonnet 3.5: Balanced performance, switch based on task
- Be specific upfront: Clear prompts save iteration time
- Getting stuck is normal: Every expert was once where you are
- Mistakes are learning: Commit often, iterate freely
- You will succeed: Others with zero experience have done amazing things
- This is the beginning: Claude Code evolves constantly, you're joining at exciting time
- Take action now: Don't just read, start building immediately
Congratulations on completing the Claude Code Tutorial!
Now go build something amazing.
Don't forget to check out the BONUS Cheat Sheet below for quick reference!
Test your knowledge!
Take Chapter 20 Quiz โBONUS: The Ultimate Claude Code Cheat Sheet
Welcome to your quick reference guide!
You've read 20 chapters. You understand the concepts. Now you need speed.
Analogy: Think of this chapter as your "cheat codes" for a video game. You've learned how to play. These are the shortcuts that let you play like a pro.
How to use this cheat sheet:
- Use Cmd+F / Ctrl+F to search
- Bookmark this page for quick access
- Print it and keep it at your desk
- Save it on your phone for mobile reference
Quick Navigation
Installation & Launch
Fast navigation
Terminal power
Session control
Advanced options
Organization
AI helpers
Integrations
Security setup
Automation
Customization
Quick fixes
Installation & Getting Started
Installation Commands
| Platform | Command | Notes |
|---|---|---|
| macOS/Linux (Recommended) | curl -fsSL https://claude.ai/install.sh | bash |
Fastest, most reliable |
| macOS (Homebrew) | brew install --cask claude-code |
If you use Homebrew |
| Windows (PowerShell) | irm https://claude.ai/install.ps1 | iex |
Run as Administrator |
| NPM (All platforms) | npm install -g @anthropic-ai/claude-code |
Requires Node.js 18+ |
| VS Code Extension | Search "Claude Code" in Extensions | Beta, integrates with editor |
First Commands
| Task | Command |
|---|---|
| Check version | claude --version |
| Check health | claude /doctor |
| Login | claude /login |
| Update | claude update |
| Start in project | cd your-project && claude |
| Start with prompt | claude "explain this project" |
Keyboard Shortcuts
Terminal Shortcuts
| Shortcut | Action | Use When |
|---|---|---|
| Esc | Interrupt Claude | Stop current operation |
| Esc Esc | Open rewind menu | Undo changes |
| Ctrl+C | Cancel operation | Stop immediately |
| Ctrl+D | Exit Claude Code | Close session |
| Ctrl+R | Full output/context | See complete response |
| Ctrl+V | Paste image | Share screenshot |
| Shift+Tab | Auto-accept ("yolo mode") | Trust Claude completely |
| Shift+Tab Tab | Plan mode | Ask Claude to plan first |
| Tab | Auto-complete | Complete command |
| Up / Down | Command history | Navigate previous commands |
| \ + Enter | Line break | Multi-line prompt |
@ |
Mention files/folders | Reference specific files |
! |
Bash mode prefix | Run inline bash commands |
VS Code Shortcuts
| Shortcut (Mac) | Shortcut (Windows/Linux) | Action |
|---|---|---|
| Cmd+Shift+P | Ctrl+Shift+P | Command palette โ "Claude Code" |
| Cmd+Esc | Ctrl+Esc | Quick launch Claude Code |
| Cmd+Option+K | Alt+Ctrl+K | Insert file references |
CLI Commands
Basic Usage
| Command | Description | Example |
|---|---|---|
claude |
Start interactive REPL | cd myproject && claude |
claude "query" |
Start with initial prompt | claude "explain this code" |
claude -p "query" |
Print mode (SDK), execute and exit | claude -p "summarize README" |
claude -c |
Continue most recent session | claude -c |
claude -c -p "query" |
Continue via SDK | claude -c -p "fix the bugs" |
claude -r "id" "query" |
Resume specific session | claude -r "abc123" "continue" |
claude --resume abc123 |
Resume with flag | claude --resume abc123 |
cat file.txt | claude -p |
Process piped content | git diff | claude -p "explain" |
Configuration Commands
| Command | Description | Example |
|---|---|---|
claude config list |
View all settings | claude config list |
claude config get <key> |
Get setting value | claude config get model |
claude config set <key> <value> |
Set setting value | claude config set model sonnet |
claude config add <key> <value> |
Add to list setting | claude config add allowedTools "Read" |
claude config remove <key> <value> |
Remove from list | claude config remove allowedTools "Write" |
MCP Server Commands
| Command | Description | Example |
|---|---|---|
claude mcp add <name> <cmd> |
Add stdio MCP server | claude mcp add github -- npx github-mcp |
claude mcp add --transport http <name> <url> |
Add HTTP MCP server | claude mcp add --transport http api https://api.example.com |
claude mcp add --transport sse <name> <url> |
Add SSE MCP server | claude mcp add --transport sse events https://events.example.com |
claude mcp list |
List configured servers | claude mcp list |
claude mcp get <name> |
Get server details | claude mcp get github |
claude mcp remove <name> |
Remove server | claude mcp remove github |
claude mcp add marketplace <repo> |
Add plugin marketplace | claude mcp add marketplace your-org/plugins |
Slash Commands (In-Session)
System & Session Control
| Command | Description | When to Use |
|---|---|---|
/help |
Show available commands | Learn what's available |
/exit |
Exit the REPL | Close session |
/clear |
Clear conversation history | Start fresh, reduce context |
/compact [instructions] |
Summarize conversation | Long conversation, hitting limit |
/status |
Version, model, account info | Check current setup |
/cost |
Show token usage & cost | Track spending |
/usage |
Plan usage limits | Check remaining credits |
/context |
Visualize context usage | See what's in context |
Setup & Configuration
| Command | Description | When to Use |
|---|---|---|
/init |
Initialize project (creates CLAUDE.md) | New project setup |
/config |
Open settings interface | Change configuration |
/doctor |
Check installation health | Troubleshoot issues |
/login |
Switch Anthropic accounts | Use different account |
/logout |
Sign out | Switch users |
/model |
Select/change AI model | Switch between Sonnet/Haiku/Opus |
/terminal-setup |
Install key bindings | Set up Shift+Enter |
Memory & Organization
| Command | Description | When to Use |
|---|---|---|
/memory |
Edit CLAUDE.md files | Update project instructions |
/add-dir |
Add working directories | Access additional folders |
/todos |
List current todo items | See what Claude is tracking |
/export |
Export conversation | Save session for later |
Development & Review
| Command | Description | When to Use |
|---|---|---|
/review |
Request code review | Get feedback on code |
/pr_comments |
View pull request comments | Review PR feedback |
/rewind |
Undo changes (code/conversation) | Mistake was made |
/bashes |
List background tasks | Check running commands |
/sandbox |
Enable isolated bash execution | Safe command testing |
/vim |
Enter vim editing mode | Vim users |
Advanced Features
| Command | Description | When to Use |
|---|---|---|
/agents |
Manage custom AI subagents | Create specialized helpers |
/mcp |
Manage MCP server connections | Connect external tools |
/hooks |
Manage event hooks | Automate on events |
/output-style |
Set output display style | Customize Claude's responses |
/permissions |
View/update access rules | Configure security |
/privacy-settings |
Manage privacy options | Control data sharing |
/statusline |
Configure status line UI | Customize display |
Help & Feedback
| Command | Description | When to Use |
|---|---|---|
/bug |
Report bugs to Anthropic | Found an issue |
/help |
Get usage help | Need guidance |
CLI Flags (Advanced Options)
Input/Output Control
| Flag | Description | Example |
|---|---|---|
-p |
Print mode (SDK), execute and exit | claude -p "explain code" |
--output-format |
Set output format (text/json/stream-json) | claude -p --output-format json "query" |
--input-format |
Set input format | claude -p --input-format stream-json |
--json-schema |
Get validated JSON output | claude -p --json-schema schema.json "query" |
Session Management
| Flag | Description | Example |
|---|---|---|
-c, --continue |
Continue most recent conversation | claude -c |
-r, --resume <id> |
Resume specific session | claude -r abc123 |
--max-turns <N> |
Limit agentic turns | claude -p --max-turns 3 "query" |
--session-name <name> |
Name the session | claude --session-name "bug-fix" |
Context & Directories
| Flag | Description | Example |
|---|---|---|
--add-dir <paths...> |
Add working directories | claude --add-dir ../apps ../lib |
Model & Prompts
| Flag | Description | Example |
|---|---|---|
--model <name> |
Specify model (sonnet/haiku/opus) | claude --model haiku |
--system-prompt <text> |
Replace entire system prompt (dangerous) | claude --system-prompt "You are..." |
--system-prompt-file <path> |
Load system prompt from file | claude --system-prompt-file prompt.txt |
--append-system-prompt <text> |
Add to default prompt (safer) | claude --append-system-prompt "Always use TypeScript" |
Tools & Permissions
| Flag | Description | Example |
|---|---|---|
--allowedTools |
Allow specific tools without prompting | claude --allowedTools "Bash(git:*)" "Read" |
--disallowedTools |
Block specific tools | claude --disallowedTools "Bash(rm:*)" |
--permission-mode |
Set initial permission state | claude --permission-mode ask |
--permission-prompt-tool |
Prompt for specific tool | claude --permission-prompt-tool mcp_auth |
--dangerously-skip-permissions |
Skip all permission prompts (use carefully!) | claude --dangerously-skip-permissions |
Agents & Subagents
| Flag | Description | Example |
|---|---|---|
--agents <config> |
Define custom subagents | claude --agents agents.json |
Debugging & Logging
| Flag | Description | Example |
|---|---|---|
--verbose |
Enable detailed logging | claude --verbose |
--debug |
Enable debug mode | claude --debug |
File & Directory Structure
Project-Level Files (.claude/)
| Location | Purpose | Shared? |
|---|---|---|
.claude/settings.json |
Team/project settings (commit to git) | Team |
.claude/settings.local.json |
Personal overrides (git-ignored) | Personal |
CLAUDE.md |
Project memory/instructions | Team |
.claude/commands/ |
Custom slash commands | Team |
.claude/agents/ |
Custom subagents | Team |
.claude/skills/ |
Custom skills | Team |
.claude/output-styles/ |
Custom output styles | Team |
User-Level Files (~/.claude/)
| Location | Purpose | Scope |
|---|---|---|
~/.claude/settings.json |
Personal default settings | All projects |
~/.claude/CLAUDE.md |
Personal memory (name, preferences) | All projects |
~/.claude/commands/ |
Personal slash commands | All projects |
~/.claude/agents/ |
Personal subagents | All projects |
~/.claude/skills/ |
Personal skills | All projects |
~/.claude/output-styles/ |
Personal output styles | All projects |
~/.claude/mcp-servers.json |
MCP server configurations | All projects |
System-Level Files
| Location | Purpose | Priority |
|---|---|---|
/etc/claude-code/managed-settings.json |
Enterprise managed settings (highest priority) | ๐ Highest |
Settings Priority (Highest to Lowest)
/etc/claude-code/managed-settings.json(Enterprise).claude/settings.local.json(Personal project).claude/settings.json(Team project)~/.claude/settings.json(Personal defaults)
Agents & Skills
Agent/Subagent Commands
| Command | Description | Example |
|---|---|---|
/agents |
Manage subagents | /agents |
| Invoke in prompt | Use agent in conversation | "Use the code-reviewer agent to review this PR" |
Built-in Subagent Types
| Agent Type | Purpose | Best For |
|---|---|---|
general-purpose |
All-around development tasks | Complex research, multi-step workflows |
Explore |
Fast codebase exploration | Finding files, searching code, understanding structure |
Creating Custom Agents
Location: .claude/agents/my-agent.md or ~/.claude/agents/my-agent.md
---
name: code-reviewer
description: Expert code review specialist
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer.
When invoked:
1. Run git diff to see changes
2. Review for quality and security
3. Provide organized feedback
Skills System
Location: .claude/skills/skill-name/SKILL.md or ~/.claude/skills/skill-name/SKILL.md
---
name: generating-commit-messages
description: Generates clear commit messages from diffs
allowed-tools: Bash(git diff:*)
---
# Generating Commit Messages
## Instructions
1. Run `git diff --staged`
2. Suggest concise commit message
3. Follow conventional commits format
Pre-built Skills (Examples)
- PowerPoint: Create presentations
- Excel: Spreadsheet manipulation
- Word: Document creation
- PDF: PDF processing
- Custom: Create your own!
MCP Servers (Integrations)
Popular MCP Servers
| Integration | Use Case | Example Command |
|---|---|---|
| GitHub | PRs, issues, code review | "Query my open PRs" |
| Sentry | Error monitoring | "Check latest Sentry errors" |
| PostgreSQL | Database queries | "Query users table" |
| Playwright | Browser automation | "Run browser tests" |
| Jira | Issue tracking | "Create Jira ticket" |
| Slack | Team communication | "Send Slack message" |
| Notion | Documentation | "Update Notion docs" |
| Figma | Design files | "Fetch Figma designs" |
| Google Drive | File storage | "Search Drive files" |
| Linear | Project management | "Create Linear issue" |
| Stripe | Payment data | "Query Stripe customers" |
| Supabase | Backend as service | "Query Supabase data" |
MCP Authentication
- Use
/mcpcommand to authenticate - Servers prompt for credentials on first use
- Credentials stored securely
MCP Scopes
| Scope | Visibility | When to Use |
|---|---|---|
local |
Personal use only | Private integrations |
project |
Entire team | Shared project resources |
user |
Your projects | Personal cross-project tools |
Permissions & Security
Permission Actions
| Action | Meaning | When to Use |
|---|---|---|
allow |
Auto-approve tool usage | Safe, trusted operations |
ask |
Prompt before allowing | Review before execution |
deny |
Block tool usage | Dangerous operations |
Basic Permissions Example (settings.json)
{
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(git status)",
"Bash(git diff)",
"Read"
],
"ask": [
"Bash(git push:*)",
"Bash(npm install *)",
"Write(*)"
],
"deny": [
"Read(./.env*)",
"Read(./secrets/**)",
"Bash(rm -rf:*)",
"Bash(curl:*)"
]
}
}
Strict Permissions Example
{
"permissions": {
"ask": ["Bash(*)", "Write(*)", "Edit(*)"],
"deny": [
"Read(./.env*)",
"Read(./secrets/**)",
"Read(./**/*.key)",
"Read(./**/*.pem)",
"WebFetch",
"Bash(curl:*)",
"Bash(wget:*)",
"Bash(ssh:*)"
]
}
}
Tool Patterns
| Pattern | Matches | Example |
|---|---|---|
Bash(*) |
All bash commands | Any terminal command |
Bash(git:*) |
All git commands | git status, git push |
Bash(git status) |
Exact match only | Only git status |
Read(*) |
Read any file | All files |
Read(./.env*) |
Read .env files | .env, .env.local |
Write(*.md) |
Write markdown files | Any .md file |
Security Best Practices
- Always deny reading secrets:
.env,credentials,*.key,*.pem - Ask for destructive operations:
rm,git push,npm install - Allow safe reads: Source code, documentation
- Deny external calls in production:
curl,wget,WebFetch - Review before allowing writes: Use
"ask"for Write/Edit
Hooks (Event Automation)
Available Hook Events
| Event | Triggers When | Common Uses |
|---|---|---|
PreToolUse |
Before Claude uses a tool | Validation, preparation |
PostToolUse |
After tool execution | Formatting, linting, cleanup |
UserPromptSubmit |
When you submit a message | Auto-context, preprocessing |
SessionStart |
New session begins | Setup, initialization |
SessionEnd |
Session closes | Cleanup, summary |
PermissionRequest |
Permission asked | Auto-approve workflows |
Notification |
Important event occurs | Alerts, logging |
Stop |
User stops Claude (Esc) | Emergency cleanup |
SubagentStop |
Subagent finishes | Post-agent processing |
PreCompact |
Before /compact runs | Save important context |
Hook Types
| Type | Description | Example |
|---|---|---|
command |
Run shell command | Format code, run linter |
prompt |
Add to Claude's context | Include recent commits |
Example: Auto-Format Files After Edit
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $FILE_PATH"
}
]
}
]
}
}
Example: Auto-Include Git Context
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Recent commits:\n!`git log --oneline -5`"
}
]
}
]
}
}
Example: Notification on Errors
{
"hooks": {
"Notification": [
{
"matcher": "error",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude hit an error!\"'"
}
]
}
]
}
}
Hook Variables
| Variable | Description | Available In |
|---|---|---|
$FILE_PATH |
Path to affected file | PostToolUse (Edit/Write) |
$TOOL_NAME |
Name of tool used | PreToolUse, PostToolUse |
$USER_PROMPT |
User's message | UserPromptSubmit |
Output Styles
Built-in Output Styles
| Style | Description | When to Use |
|---|---|---|
default |
Standard Claude responses | General development |
concise |
Short, direct answers | Quick fixes, simple tasks |
verbose |
Detailed explanations | Learning, complex problems |
educational |
Teaching-focused responses | Learning new concepts |
Switching Output Styles
# Via slash command
/output-style concise
# Via settings.json
{
"outputStyle": "verbose"
}
Creating Custom Output Style
Location: .claude/output-styles/my-style.md or ~/.claude/output-styles/my-style.md
---
name: senior-dev
description: Responses from senior developer perspective
---
# Senior Developer Style
When responding:
- Be direct and assume expertise
- Skip basic explanations
- Focus on trade-offs and best practices
- Mention potential pitfalls
- Suggest architectural improvements
Code examples should be production-ready.
Models & Performance
Available Models
| Model | Context Window | Speed | Best For |
|---|---|---|---|
| Sonnet 4 | 1M tokens | Moderate | Large codebases, complex reasoning |
| Sonnet 3.5 | 200K tokens | Fast | General development (default) |
| Haiku | 200K tokens | Very Fast | Simple tasks, quick fixes |
| Opus | 200K tokens | Slower | Complex problems requiring deep thought |
Switching Models
# Via slash command
/model sonnet
/model haiku
/model opus
# Via CLI flag
claude --model haiku "quick question"
# Via settings.json
{
"model": "claude-sonnet-3-5-20241022"
}
Model Selection Strategy
- Haiku: Simple fixes, quick questions, repetitive tasks
- Sonnet 3.5: Most daily development work (default)
- Sonnet 4: Large codebases, need massive context
- Opus/Extended Thinking: Complex architecture, difficult bugs
Context Management
| Command | Purpose | When to Use |
|---|---|---|
/clear |
Reset conversation | New topic, reduce context |
/compact [instructions] |
Summarize conversation | Hitting context limit |
/context |
View context usage | Check how much space used |
--max-turns N |
Limit agent turns | Control token usage |
Git & GitHub Workflows
Common Git Commands with Claude
| Task | Prompt Example |
|---|---|
| Create commit | "Create a commit with these changes" |
| Review PR | "Review this PR for security and performance" |
| Create PR | "Create a PR for this feature branch" |
| Fix conflicts | "Help me resolve these merge conflicts" |
| Generate changelog | "Generate changelog from recent commits" |
| Explain diff | "Explain what changed in this commit" |
Git Worktrees (Advanced)
# Create worktree for parallel work
git worktree add ../feature-branch feature-branch
# List worktrees
git worktree list
# Remove worktree
git worktree remove ../feature-branch
# Use with Claude for parallel development
cd ../feature-branch && claude "work on feature"
cd ../main-branch && claude "fix bugs"
GitHub CLI (gh) Integration
# Create PR
gh pr create --title "Feature" --body "Description"
# View PR comments
gh pr view 123 --comments
# Review PR
gh pr review 123 --approve
# Create issue
gh issue create --title "Bug" --body "Description"
Quick Troubleshooting
Common Error Messages
| Error | Meaning | Quick Fix |
|---|---|---|
command not found: claude |
Not installed or PATH issue | Reinstall or add to PATH |
Authentication failed |
Invalid API key | Run claude /login |
Context window exceeded |
Too much context | Use /compact or /clear |
Rate limit exceeded |
Too many requests | Wait or check /usage |
Permission denied |
Blocked by permissions | Check /permissions |
MCP server not responding |
Server connection issue | claude mcp list, restart server |
Tool execution failed |
Command error | Check command syntax, permissions |
Session not found |
Invalid session ID | Use -c instead of -r |
Claude.md not loading |
Wrong location or syntax | Check file is named CLAUDE.md |
Emergency Fixes
| Problem | Solution |
|---|---|
| Claude is confused/off-track | /clear โ start fresh |
| Claude made bad changes | Esc Esc โ rewind menu |
| Can't install via npm | Use curl install method instead |
| Slow responses | Switch to Haiku: /model haiku |
| Context issues | /compact or new session |
| Everything broken | claude /doctor โ check health |
Diagnostic Commands
# Check installation health
claude /doctor
# Check version
claude --version
# View current config
claude config list
# Enable verbose logging
claude --verbose
# Enable debug mode
claude --debug
# Check MCP servers
claude mcp list
# Check permissions
/permissions
Productivity Tips & Tricks
Speed Tips
| Tip | How | Benefit |
|---|---|---|
| Use @ symbol | @filename.js "explain this" |
Direct file reference |
| Pipe commands | git diff | claude -p "explain" |
Instant analysis |
| Use Haiku for simple tasks | /model haiku |
3x faster responses |
| Create custom commands | .claude/commands/ |
One-word shortcuts |
| Use agents for parallel work | Multiple agents at once | Work on multiple tasks |
| Auto-accept for trusted tasks | Shift+Tab | Skip confirmations |
| Start with planning | "First, make a plan" | Better results |
| Batch related tasks | "Fix all type errors" | Single session |
Quality Tips
- Write detailed CLAUDE.md: More context = better results
- Be specific in prompts: "Add error handling to login function" vs "fix this"
- Use verification loops: "After fixing, run tests and show results"
- Start fresh between topics:
/clearprevents confusion - Test Claude's changes: Always review before committing
- Use Extended Thinking for hard problems: Complex bugs, architecture decisions
- Request code style: "Use functional programming" or "Add detailed comments"
Workflow Tips
- Start sessions with context: "I'm working on auth feature. Here's the plan..."
- Commit frequently: Small commits = easy rollback
- Use agents for research: "Use Explore agent to find all API endpoints"
- Create specialized agents: code-reviewer, test-writer, documenter
- Automate with hooks: Auto-format, auto-lint, auto-test
- Track costs: Use
/costto monitor spending - Break large tasks: "First implement core logic. Then add error handling. Then tests."
Advanced Usage Patterns
Automation Scripts
#!/bin/bash
# Auto code review script
# Get changes
git diff HEAD~1 > changes.diff
# Security review
claude -p "Review for security issues" < changes.diff > security.md
# Performance review
claude -p "Review for performance issues" < changes.diff > performance.md
# Combine reports
cat security.md performance.md > full-review.md
echo "Review complete! Check full-review.md"
CI/CD Integration
# .github/workflows/claude-review.yml
name: Claude Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Claude
run: npm install -g @anthropic-ai/claude-code
- name: Review PR
run: |
git diff origin/main | claude -p \\
"Review this PR for issues" \\
--output-format json > review.json
- name: Comment on PR
run: |
gh pr comment ${{ github.event.number }} \\
--body-file review.json
Multi-Agent Parallel Workflow
# Start multiple agents in parallel
claude --agents agents.json "Use frontend agent to build UI" &
claude --agents agents.json "Use backend agent to build API" &
claude --agents agents.json "Use test agent to write tests" &
# Wait for all to complete
wait
echo "All agents finished!"
Custom Slash Command for Git Commit
File: .claude/commands/commit.md
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
argument-hint: [message]
description: Create a git commit
---
## Context
- Current git status: !`git status`
- Current git diff: !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`
## Your task
Based on the above changes, create a single git commit.
Use this message if provided: $ARGUMENTS
Headless Mode for Automation
# Non-interactive execution
claude -p "analyze this codebase" --output-format json > analysis.json
# Process JSON output
cat analysis.json | jq '.summary'
# Resume and continue
SESSION_ID=$(cat analysis.json | jq -r '.session_id')
claude --resume $SESSION_ID -p "now generate tests" --output-format json
# Stream output for long tasks
claude -p "large task" --output-format stream-json | while read line; do
echo "Progress: $line"
done
# Limit turns for cost control
claude -p --max-turns 5 "focused task"
Rewind Patterns
# Undo last change
# Press: Esc Esc
# Or use: /rewind
# Types of rewind:
# - Automatic: Undo to last checkpoint
# - Conversation: Keep code, reset conversation
# - Code: Keep conversation, revert code changes
# - Full: Reset both code and conversation
Final Pro Tips
The Power User Checklist
- CLAUDE.md in every project - Document preferences, quirks, commands
- Custom commands for repeated tasks - Review, test, deploy, commit
- Agents for specialized work - Code reviewer, documenter, refactorer
- MCP servers for integrations - GitHub, Sentry, Slack, databases
- Hooks for automation - Auto-format, auto-lint, notifications
- Permissions configured - Deny secrets, ask for destructive ops
- Right model for the task - Haiku for speed, Sonnet for balance, Opus for complexity
- Start fresh between topics -
/clearprevents confusion - Specific, detailed prompts - More context = better results
- Commit often - Easy rollback with git
Print-Friendly Quick Reference
Pro tip: Press Cmd+P (Mac) or Ctrl+P (Windows/Linux) to print this cheat sheet. Save as PDF for offline reference or print and keep at your desk!
Bookmark This Page
Press Cmd+D (Mac) or Ctrl+D (Windows/Linux) to bookmark this page. You'll come back here often - guaranteed!
You're Now a Claude Code Master!
You have everything you need. 20 chapters of deep learning. One comprehensive cheat sheet.
Now go build something incredible.
Made with โค๏ธ for Claude Code learners | Keep this cheat sheet handy - you'll use it every day!
Quick Start Reminder
cd your-project && claude
That's all it takes. Open terminal, navigate to your project, type claude.
Everything you learned is waiting for you.
Test your knowledge!
Take Chapter 21 Quiz โTutorial Complete! - 20 Chapters + Bonus Cheat Sheet
You are now a Claude Code master. Go build the future!