Chapter 1: Installation & Your First Real Session
Learning Objectives
- Install Claude Code CLI on Windows, macOS, or Linux and verify it works
- Understand tool-calling: why Claude uses tools instead of generating text, and how the permission system keeps you in control
- Build a GitHub Profile Analyzer as your first real project (not hello world)
- Use Claude to trace request flow in a production codebase (FastAPI)
- Master the commands that matter:
/help,/clear,/compact,/usage,/cost,/model
Appendix links: A05 Tool Calling Internals goes deeper into how Claude selects which tool to use. A11 Model Selection Guide covers Opus vs Sonnet vs Haiku in detail.
Concepts
What Is Claude Code, Really?
Skip the marketing pitch. Claude Code is a terminal-based AI that can read your files, write code, run commands, and interact with Git. It works through a tool-calling system — not magic, not autocomplete, not text generation that happens to look like code.
Here's what that means in practice:
┌───────────────────────────────────────────────────────────┐
│ Claude Code Loop │
│ │
│ 1. You type a prompt │
│ 2. Claude decides which tool to use (Read, Write, Bash…) │
│ 3. Claude shows you what it wants to do │
│ 4. You approve (y), deny (n), or always-allow (a) │
│ 5. The tool executes and Claude sees the result │
│ 6. Claude decides if it needs another tool call │
│ 7. Loop continues until the task is complete │
│ │
│ Every single action needs your OK first. │
│ No surprises. No silent file changes. │
└───────────────────────────────────────────────────────────┘If you've used GitHub Copilot, think of Claude Code as Copilot's older sibling who moved out of the IDE and into the terminal. It doesn't just autocomplete lines — it reads entire codebases, runs tests, creates branches, and opens PRs. The key architectural difference: Copilot predicts the next token in your editor. Claude Code reasons about what action to take, then asks your permission before doing it.
Research note: This "think then act" pattern is called ReAct (Reasoning + Acting) in the AI research literature. Anthropic's tool-calling implementation builds on this pattern. See A04 Agent Architecture for more.
Tool-Calling: How Claude Gets Things Done
Claude doesn't just print text. Every meaningful action goes through a tool:
| Tool | What It Does | Real Example |
|---|---|---|
| Read | Read file contents | Parse a 500-line config to find the database URL |
| Write | Create new files | Generate a migration script from scratch |
| Edit | Modify existing files | Swap out a deprecated API call with its replacement |
| Bash | Run shell commands | Execute pytest, npm test, git status |
| Glob | Find files by pattern | Locate every *.test.ts in a monorepo |
| Grep | Search file contents | Find all callers of authenticate() across the project |
Why tools instead of just generating text? Three reasons:
- Grounding: When Claude reads your actual file, it works with real data — not a hallucinated version from training data. This dramatically reduces errors.
- Auditability: Every tool call is visible. You can see exactly what Claude read, what commands it ran, and what files it changed. No black box.
- Safety: The permission system means Claude literally cannot modify your filesystem without your approval. A pure text-generation model has no such guarantee.
Going deeper: The tool selection process uses JSON Schema definitions — Claude matches your request against the available tool signatures and picks the best fit. See A05 Tool Calling Internals.
The Permission System
By default, Claude asks before doing anything. Here's what the actual permission prompt looks like:
╭──────────────────────────────────────────────────────────╮
│ Claude wants to run Bash │
│ │
│ rm -rf node_modules && npm install │
│ │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰──────────────────────────────────────────────────────────╯- y — allow this once
- n — deny this specific call
- a — always allow this type of action for the rest of the session
This is not training wheels. Even experienced users keep certain permissions gated. The permission system is Claude Code's primary safety mechanism — it prevents runaway commands, accidental deletions, and unintended side effects. You'll learn to fine-tune permissions in Ch10 Permissions & Security.
The five permission modes (preview — detailed in Ch10):
| Mode | Behavior | Best For |
|---|---|---|
| Default | Ask for everything | Learning, unfamiliar codebases |
| Trust read | Auto-allow Read/Glob/Grep, ask for writes | Daily development |
| Trust edit | Auto-allow most edits, ask for Bash | Trusted projects |
| Auto | Auto-allow everything matching your allow list | CI/CD, automated workflows |
| Full auto | Auto-allow everything | Only in sandboxed environments |
How People Access Claude Code
| Method | When to Use | Platform |
|---|---|---|
| Terminal CLI | Daily dev, full control | Windows / macOS / Linux |
| VS Code Extension | IDE integration with inline diffs | Cross-platform |
| JetBrains Plugin | IDE integration | Cross-platform |
| Desktop App | Visual diffs, scheduled tasks | macOS / Windows |
| Web Interface | Cloud sessions via claude.ai/code | Browser |
This tutorial focuses on the Terminal CLI. Other methods are covered in Chapter 11.
Demo 1: Build a GitHub Profile Analyzer
No "hello world". Your first project will actually be useful.
Goal
Clone a public GitHub profile repo, then have Claude analyze commit patterns, most-used languages, and generate a summary. This teaches you tool-calling, permissions, and multi-step workflows in one shot.
Steps
1. Install Claude Code
::: tabs @tab Windows (Git Bash / PowerShell)
# Make sure Node.js is installed
node --version # Should be >= 18
# Install Claude Code globally
npm install -g @anthropic-ai/claude-code
# Verify
claude --version@tab macOS / Linux
# Install Node.js if needed
# macOS: brew install node
# Linux: use your package manager (apt, dnf, etc.)
node --version # Should be >= 18
# Install Claude Code globally
npm install -g @anthropic-ai/claude-code
# Verify
claude --version:::
Expected output:
$ claude --version
1.0.34 (Claude Code)2. Authenticate
# Option A: API key (pay-per-token)
export ANTHROPIC_API_KEY="sk-ant-..."
# Option B: Claude Pro/Max/Team subscription
# Just run `claude` — it'll walk you through OAuth login on first launch3. Pick a Repository to Analyze
mkdir -p ~/claude-demos/demo-01 && cd ~/claude-demos/demo-01
# Clone a well-known public profile repo:
git clone https://github.com/sindresorhus/sindresorhus.git profile
cd profilePick any public GitHub profile repo. These are the repos named after the user's GitHub username — they render on the profile page.
4. Launch Claude and Analyze
claudeWhat you'll see on first launch:
$ claude
╭─────────────────────────────────────────────────────╮
│ Claude Code v1.0.34 │
│ Model: claude-sonnet-4-6 │
│ Context: 0% used (200k tokens available) │
│ │
│ /help for commands, /model to switch models │
╰─────────────────────────────────────────────────────╯
~/claude-demos/demo-01/profile >Type this at the prompt:
This is a GitHub profile README repo. I want you to:
1. Read the README and any config files
2. Check the git log for commit frequency and patterns
3. Tell me: how often is this profile updated? What tools/frameworks does the author highlight? Any interesting automation (GitHub Actions)?
4. Generate a short "profile analysis" summary I could paste into a blog postWhat happens next — the actual tool-call sequence:
> [Your prompt above]
Claude is thinking...
╭─ Read ──────────────────────────────────────────────╮
│ README.md │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰─────────────────────────────────────────────────────╯
> y
[Reading README.md... 342 lines]
╭─ Bash ──────────────────────────────────────────────╮
│ git log --oneline --since="2024-01-01" | head -20 │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰─────────────────────────────────────────────────────╯
> y
[Running command...]
a1b2c3d Update stats
d4e5f6g Add new project link
...
╭─ Glob ──────────────────────────────────────────────╮
│ .github/** │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰─────────────────────────────────────────────────────╯
> y
[Found: .github/workflows/update.yml, .github/workflows/stats.yml]
╭─ Read ──────────────────────────────────────────────╮
│ .github/workflows/update.yml │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰─────────────────────────────────────────────────────╯
> a ← (auto-allow Read for the rest of this session)
[Reading .github/workflows/update.yml... 45 lines]
## Profile Analysis: sindresorhus
**Update frequency**: ~3 commits/month, automated via GitHub Actions
**Tech highlights**: Node.js ecosystem (1000+ npm packages), Swift...
**Automation**: Two GitHub Actions workflows:
- `update.yml`: Auto-updates stats badges daily
- `stats.yml`: Generates contribution graphs weekly
...5. Take It Further
Still in the same session:
Now clone https://github.com/torvalds/linux (depth 1, just the latest commit) into a sibling directory and compare: how does Linus's commit style differ from this profile repo? Just look at the last 50 commits of each.This is where it gets interesting. Claude will juggle two repos, run git commands in each, and produce a comparison — all from a conversation.
What Just Happened?
Here's the tool-call sequence Claude used, and why it chose each tool:
Key takeaways:
- Every filesystem/shell action goes through a tool call you can see and approve
- Claude chains tools naturally — no scripting needed on your end
- Even this simple task used 4 different tools across 5 calls
- Claude chose the right tool each time: Read for files, Bash for git commands, Glob for pattern matching
Verification Checklist
- [ ]
claude --versionprints a version number - [ ] Successfully started an interactive session
- [ ] Claude analyzed at least one repo and produced useful output
- [ ] You approved tool calls and understand what each one did
- [ ] You saw the permission prompt and tried both
yandaresponses
Demo 2: Trace Request Flow in FastAPI
Now let's use Claude on a production codebase. We're going to clone fastapi/fastapi (80k+ stars) and have Claude trace how a single HTTP request flows from @app.get("/") through the middleware stack to a response.
This is the kind of task that would take you 2-3 hours of reading docs and source code. Claude does it in 5 minutes.
Goal
Understand FastAPI's request lifecycle by having Claude trace it through the actual source code — with specific file paths and line numbers.
Steps
1. Clone FastAPI
mkdir -p ~/claude-demos/demo-02 && cd ~/claude-demos/demo-02
git clone --depth 1 https://github.com/fastapi/fastapi.git
cd fastapi2. Start Claude and Dig In
claudeI just cloned the FastAPI repo. Walk me through what happens internally when this code runs:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"hello": "world"}
Specifically:
1. What does @app.get("/") actually do under the hood? Trace the decorator.
2. When a GET request hits "/", what's the code path from receiving the request to returning the JSON response?
3. Where does Starlette end and FastAPI begin?What Claude will do:
> [Your prompt above]
╭─ Glob ──────────────────────────────────────────────╮
│ fastapi/**/*.py │
╰─────────────────────────────────────────────────────╯
[Found 47 Python files]
╭─ Read ──────────────────────────────────────────────╮
│ fastapi/applications.py │
╰─────────────────────────────────────────────────────╯
[Reading... The FastAPI class inherits from Starlette...]
╭─ Grep ──────────────────────────────────────────────╮
│ "def get" in fastapi/routing.py │
╰─────────────────────────────────────────────────────╯
[Found: line 432 - def get(self, path: str, ...)]
╭─ Read ──────────────────────────────────────────────╮
│ fastapi/routing.py (lines 420-480) │
╰─────────────────────────────────────────────────────╯
## Here's the full request lifecycle:
**1. Route Registration** (`fastapi/routing.py:432`)
When you write `@app.get("/")`, FastAPI calls `APIRouter.add_api_route()`.
This creates an `APIRoute` object that wraps your function...
**2. Request Handling** (`starlette/routing.py:61`)
When a GET / arrives, Starlette's Router.route() matches the path...
**3. FastAPI's Layer** (`fastapi/routing.py:215`)
FastAPI adds dependency injection, validation, and serialization
on top of Starlette's routing...3. Go Deeper
Now show me where dependency injection happens. If I add `Depends(get_db)` to a route, what code path resolves that dependency before my function runs?Claude will trace through fastapi/dependencies/, show you the dependency solver, and explain how it builds the dependency graph. Try doing that by reading source code alone.
4. One More Thing
Find the middleware stack. If I add a CORS middleware, where in the request lifecycle does it execute relative to my route handler?What Just Happened?
Why this matters: Reading unfamiliar codebases is one of Claude Code's killer features. What you just did in 10 minutes would normally take half a day of browsing source files, reading docs, and cross-referencing StackOverflow. This works on any codebase, any language, any size.
Notice the tool selection pattern: Claude used Glob first (map the territory), then Read (examine key files), then Grep (find specific implementations), then Read again (trace the code path). This is the typical exploration pattern: map → examine → search → trace.
Verification Checklist
- [ ] Successfully cloned FastAPI
- [ ] Claude traced the
@app.get()decorator to its implementation - [ ] Claude explained the request lifecycle with specific file paths and line numbers
- [ ] You understand at a high level how FastAPI routes a request
When Things Go Wrong
Every tool has failure modes. Here are the common ones you'll encounter and how to fix them:
Authentication Failure
$ claude
Error: No API key found. Set ANTHROPIC_API_KEY or run `claude login`.Fix: Either export ANTHROPIC_API_KEY="sk-ant-..." or run claude login to authenticate via your browser (for Pro/Max/Team subscriptions).
Node.js Version Too Old
$ npm install -g @anthropic-ai/claude-code
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npmFix: Claude Code requires Node.js 18+. Update Node.js:
- macOS:
brew upgrade nodeor usenvm install 18 - Windows: Download from nodejs.org or
nvm install 18 - Linux:
nvm install 18or use your package manager
Network Timeout
> Analyze this codebase
Error: Request timed out after 30s. Check your network connection.Fix: This usually means your network is blocking API calls. Check:
- VPN or proxy settings — some corporate VPNs block Anthropic's API endpoints
- Firewall rules — ensure
api.anthropic.comis reachable - Try again — transient network issues happen
Permission Denied on Install
$ npm install -g @anthropic-ai/claude-code
npm ERR! EACCES permission deniedFix: Don't use sudo. Instead, fix npm's directory permissions:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH # Add to your .bashrc/.zshrc
npm install -g @anthropic-ai/claude-codeGoing Deeper
Essential Commands Reference
You'll use these constantly. Bookmark this table.
Session management:
| Command | What It Does | When to Use |
|---|---|---|
/help | List all commands and shortcuts | When you forget something |
/clear | Wipe the conversation | Switching to a totally different topic |
/compact | Compress context, keep essentials | When context hits ~50% (more in Ch3) |
/model | Switch between Opus / Sonnet / Haiku | Opus for hard stuff, Haiku for quick lookups |
/context | Show token usage breakdown | Before deciding whether to compact |
Billing and usage:
| Command | Who It's For | What It Shows |
|---|---|---|
/usage | Pro / Max / Team subscribers | Remaining quota for the billing period |
/cost | API key users | Token consumption and dollar cost this session |
/fast | Everyone | Toggle faster output (same model, less polish) |
/login | Everyone | Switch accounts or re-authenticate |
What /context output looks like:
> /context
Context usage: 12,847 / 200,000 tokens (6.4%)
System prompt: 2,100 tokens
CLAUDE.md: 450 tokens
Conversation: 8,200 tokens
Tool results: 2,097 tokens
Remaining: 187,153 tokensIf you're on a Pro or Max plan, check
/usageregularly. If you're on an API key,/costis your friend. Many subscription users never think about per-token pricing, but knowing where you stand prevents surprises.
Preview of advanced commands (covered later):
| Command | Purpose | Chapter |
|---|---|---|
/memory | View/manage Claude's auto-saved memories | Ch2 |
/sessions | Browse and resume past sessions | Ch3 |
/rewind | Roll back to a previous checkpoint | Ch4 |
/review | Trigger a code review | Ch4 |
/init | Auto-generate a CLAUDE.md for the current project | Ch2 |
/agents | Manage sub-agents | Ch8 |
Non-Interactive Mode (Pipe Mode)
This is where Claude Code becomes a UNIX citizen:
# One-shot question, no interactive session
claude -p "What does this project do?"
# Pipe in data
cat error.log | claude -p "What's the root cause of these errors?"
# Code review in one line
git diff | claude -p "Review these changes. Focus on security issues."
# Generate a commit message
git diff --staged | claude -p "Write a conventional commit message for these changes"Example output from pipe mode:
$ git diff --staged | claude -p "Write a conventional commit message"
feat(auth): add JWT token refresh endpoint
Adds a POST /auth/refresh endpoint that accepts a valid refresh
token and returns a new access token. Includes rate limiting
(max 10 refreshes per minute per user) and audit logging.Pipe mode is incredibly powerful for scripting. We'll build on this in Ch4 Git Workflows and Ch5 Hooks.
Model Selection
# Inside a session:
/model
# From the command line:
claude --model claude-opus-4-7 # Most capable, best for complex reasoning
claude --model claude-sonnet-4-6 # Balanced, default for most work
claude --model claude-haiku-4-5 # Fastest, good for simple lookups| Model | Best For | Speed | Cost | Context |
|---|---|---|---|---|
| Opus 4.7 | Architecture decisions, complex debugging, multi-file refactoring | Slower | Higher | 1M tokens |
| Sonnet 4.6 | Daily development, code review, feature implementation | Fast | Moderate | 200k tokens |
| Haiku 4.5 | Quick questions, file lookups, simple generation | Fastest | Lowest | 200k tokens |
Rule of thumb: Start with Sonnet. Switch to Opus when you need deeper reasoning (architecture decisions, complex debugging, or tasks requiring many steps). Switch to Haiku when you just need a quick answer.
Deep dive: See A11 Model Selection Guide for benchmarks, cost comparisons, and routing strategies used by production teams.
Keyboard Shortcuts
| Shortcut | Action |
|---|---|
Esc | Stop Claude mid-generation |
Ctrl+C | Exit Claude Code entirely |
Tab | Auto-complete file paths in prompts |
Up / Down | Browse your prompt history |
Knowledge Check
Exercise: Your First Multi-Step Build
Task
Stay in a single Claude session and do all of this:
- Have Claude create a Python script called
repo_scanner.pythat:- Takes a local git repo path as an argument
- Counts commits per author
- Lists the 5 most recently modified files
- Outputs a summary in Markdown format
- Have Claude write tests for it (pytest)
- Have Claude run the tests
- If anything fails, have Claude fix it
- Run the scanner against the FastAPI repo from Demo 2
Success Criteria
- [ ]
repo_scanner.pyexists and works - [ ] Test file exists and all tests pass
- [ ] You ran the scanner against a real repo and got meaningful output
- [ ] Entire process was done in one Claude Code session
- [ ] You watched Claude use at least 3 different tools (Write, Bash, Read)
Hint
Create a Python script called repo_scanner.py that takes a path to a git repo
as a CLI argument. It should:
- Use subprocess to run git commands
- Count commits per author (git shortlog -sn)
- Find the 5 most recently modified tracked files
- Print a markdown-formatted summary
Then write pytest tests (mock subprocess where needed) and run them.Chapter Summary
- Claude Code is a tool-calling AI assistant in your terminal. It reads files, writes code, runs commands, and interacts with Git — all through an explicit permission system.
- The permission system is not training wheels — it's a safety mechanism. Every action needs your approval (unless you explicitly auto-allow).
- You built a GitHub Profile Analyzer (not a hello world) and traced request flow through FastAPI's source code — two genuinely useful tasks.
- The tool exploration pattern is: map (Glob) → examine (Read) → search (Grep) → trace (Read again).
- Key commands:
/help,/clear,/compact,/model,/context,/usage(subscribers),/cost(API users). - Pipe mode (
claude -p) turns Claude into a scriptable UNIX tool for one-shot tasks. - When things go wrong: check Node.js version, API key, network, and npm permissions.
Next up: Chapter 2: CLAUDE.md & the Memory System. This is where Claude stops being a generic assistant and starts acting like a team member who knows your project's conventions. The difference is night and day.