第一章:安装与你的第一个真实项目
学习目标
- 在 Windows、macOS 或 Linux 上安装 Claude Code CLI 并验证安装成功
- 理解工具调用(Tool Calling)机制:为什么 Claude 使用工具而非生成文本,权限系统如何确保你始终掌控全局
- 构建一个 GitHub Profile Analyzer 作为你的第一个真实项目(不是 hello world)
- 用 Claude 追踪生产级代码库(FastAPI)中的请求处理流程
- 掌握关键命令:
/help、/clear、/compact、/usage、/cost、/model
附录链接:A05 工具调用内部机制 深入解析 Claude 如何选择使用哪个工具。A11 模型选择指南 详细介绍 Opus、Sonnet、Haiku 的区别。
核心概念
Claude Code 到底是什么?
跳过营销话术。Claude Code 是一个终端里的 AI,能读你的文件、写代码、跑命令、操作 Git。它通过一套工具调用系统工作 -- 不是什么黑魔法,不是自动补全,也不是"刚好看起来像代码的文本生成"。
实际使用起来是这样的:
┌───────────────────────────────────────────────────────────┐
│ Claude Code 循环 │
│ │
│ 1. 你输入提示 │
│ 2. Claude 决定使用哪个工具(Read、Write、Bash...) │
│ 3. Claude 展示它想做什么 │
│ 4. 你批准(y)、拒绝(n)或始终允许(a) │
│ 5. 工具执行,Claude 看到结果 │
│ 6. Claude 决定是否需要再调用一个工具 │
│ 7. 循环持续直到任务完成 │
│ │
│ 每一个操作都需要你先同意。 │
│ 没有意外。没有静默修改文件。 │
└───────────────────────────────────────────────────────────┘如果你用过 GitHub Copilot,可以把 Claude Code 理解为 Copilot 从 IDE 搬到终端的升级版。它不只是补全代码行 -- 它能阅读整个代码库、跑测试、创建分支、发 PR。核心架构区别在于:Copilot 预测编辑器中的下一个 token,而 Claude Code 推理应该采取什么行动,然后在执行前征求你的许可。
研究背景:这种"先思考再行动"的模式在 AI 研究文献中叫做 ReAct(Reasoning + Acting,推理 + 行动)。Anthropic 的工具调用实现建立在这个模式之上。详见 A04 Agent 架构。
工具调用:Claude 如何完成任务
Claude 不只是打印文字。每个有实质意义的操作都通过工具完成:
| 工具 | 做什么 | 实际例子 |
|---|---|---|
| Read | 读取文件内容 | 解析一个 500 行的配置文件找数据库 URL |
| Write | 创建新文件 | 从零生成一个迁移脚本 |
| Edit | 修改已有文件 | 把废弃的 API 调用替换成新版本 |
| Bash | 执行 shell 命令 | 跑 pytest、npm test、git status |
| Glob | 按模式查找文件 | 在 monorepo 里找到所有 *.test.ts |
| Grep | 搜索文件内容 | 找出所有调用 authenticate() 的地方 |
为什么用工具而不是直接生成文本? 三个原因:
- 基于事实(Grounding):当 Claude 读取你的实际文件时,它处理的是真实数据 -- 不是训练数据中虚构的版本。这大幅减少了错误。
- 可审计(Auditability):每次工具调用都是可见的。你能看到 Claude 读了什么文件、跑了什么命令、改了哪些文件。不是黑盒。
- 安全性(Safety):权限系统意味着 Claude 在没有你同意的情况下无法修改你的文件系统。纯文本生成模型做不到这种保证。
深入了解:工具选择过程使用 JSON Schema 定义 -- Claude 将你的请求与可用工具的签名进行匹配,选出最适合的工具。详见 A05 工具调用内部机制。
权限系统
默认情况下,Claude 做任何事之前都会先问你。实际的权限提示长这样:
╭──────────────────────────────────────────────────────────╮
│ Claude wants to run Bash │
│ │
│ rm -rf node_modules && npm install │
│ │
│ Allow? y(yes) / n(no) / a(always for this tool) │
╰──────────────────────────────────────────────────────────╯- y -- 这次允许
- n -- 拒绝这次调用
- a -- 本次会话内始终允许这类操作
这不是给新手的保护轮。 即使经验丰富的用户也会对某些权限保持审批。权限系统是 Claude Code 的主要安全机制 -- 防止失控命令、意外删除和非预期的副作用。你将在 第十章 权限与安全 学习精细权限配置。
五种权限模式(预览 -- 详见第十章):
| 模式 | 行为 | 适用场景 |
|---|---|---|
| Default | 所有操作都询问 | 学习阶段、不熟悉的代码库 |
| Trust read | 自动允许 Read/Glob/Grep,写操作需批准 | 日常开发 |
| Trust edit | 自动允许大多数编辑,Bash 需批准 | 信任的项目 |
| Auto | 自动允许匹配白名单的所有操作 | CI/CD、自动化工作流 |
| Full auto | 自动允许所有操作 | 仅用于沙箱环境 |
使用方式
| 方式 | 适用场景 | 平台 |
|---|---|---|
| Terminal CLI | 日常开发,完整功能 | Windows / macOS / Linux |
| VS Code 扩展 | IDE 集成,行内 diff | 跨平台 |
| JetBrains 插件 | IDE 集成 | 跨平台 |
| Desktop 应用 | 可视化 diff、定时任务 | macOS / Windows |
| Web 界面 | 通过 claude.ai/code 使用云端会话 | 浏览器 |
本教程以 Terminal CLI 为主线。其他方式在第十一章介绍。
Demo 1:构建 GitHub Profile Analyzer
不写 "hello world"。你的第一个项目要有实际用途。
目标
克隆一个公开的 GitHub profile 仓库,然后让 Claude 分析提交模式、常用语言,并生成一份总结。一个 Demo 同时学会工具调用、权限系统和多步骤工作流。
步骤
1. 安装 Claude Code
::: tabs @tab Windows (Git Bash / PowerShell)
# 确保 Node.js 已安装
node --version # 应该 >= 18
# 全局安装 Claude Code
npm install -g @anthropic-ai/claude-code
# 验证
claude --version@tab macOS / Linux
# 需要先装 Node.js
# macOS: brew install node
# Linux: 用你的包管理器(apt、dnf 等)
node --version # 应该 >= 18
# 全局安装 Claude Code
npm install -g @anthropic-ai/claude-code
# 验证
claude --version:::
预期输出:
$ claude --version
1.0.34 (Claude Code)2. 认证
# 方式 A:API key(按 token 计费)
export ANTHROPIC_API_KEY="sk-ant-..."
# 方式 B:Claude Pro/Max/Team 订阅
# 直接运行 claude,首次启动会引导你完成 OAuth 登录3. 选一个仓库来分析
mkdir -p ~/claude-demos/demo-01 && cd ~/claude-demos/demo-01
# 克隆一个知名的公开 profile 仓库:
git clone https://github.com/sindresorhus/sindresorhus.git profile
cd profile选任何公开的 GitHub profile 仓库。就是和用户名同名的那个仓库 -- 会渲染在 GitHub 个人主页上的。
4. 启动 Claude 开始分析
claude首次启动你会看到:
$ 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 >在提示符输入:
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 post接下来会发生什么 -- 实际的工具调用序列:
> [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 ← (本次会话自动允许 Read)
[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. 更进一步
还在同一个会话里:
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.这里开始有意思了。Claude 会在两个仓库之间来回操作,分别跑 git 命令,然后生成对比分析 -- 全部通过对话完成。
刚才发生了什么?
以下是 Claude 使用的工具调用序列,以及它为什么选择每个工具:
关键要点:
- 每个文件系统/shell 操作都通过工具调用,你可以看到并批准
- Claude 自然地串联多个工具 -- 不需要你写任何脚本
- 就这么个简单任务用了 4 种不同的工具、5 次调用
- Claude 每次都选对了工具:Read 读文件、Bash 跑 git 命令、Glob 做模式匹配
验证清单
- [ ]
claude --version输出了版本号 - [ ] 成功启动了交互式会话
- [ ] Claude 分析了至少一个仓库并给出了有用的输出
- [ ] 你批准了工具调用,理解了每个调用在做什么
- [ ] 你看到了权限提示,并尝试了
y和a两种响应
Demo 2:在 FastAPI 中追踪请求流程
来点真格的。我们要克隆 fastapi/fastapi(80k+ stars),让 Claude 追踪一个 HTTP 请求从 @app.get("/") 经过中间件到响应的完整流程。
这种任务自己做要花 2-3 小时读文档和源码。Claude 5 分钟搞定。
目标
通过让 Claude 追踪实际源码(带具体文件路径和行号),理解 FastAPI 的请求生命周期(Request Lifecycle)。
步骤
1. 克隆 FastAPI
mkdir -p ~/claude-demos/demo-02 && cd ~/claude-demos/demo-02
git clone --depth 1 https://github.com/fastapi/fastapi.git
cd fastapi2. 启动 Claude 开挖
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?Claude 会做的事:
> [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. 继续深入
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 会追踪进 fastapi/dependencies/,展示依赖解析器,解释它如何构建依赖图。你试试光靠读源码来做这件事。
4. 再来一个
Find the middleware stack. If I add a CORS middleware, where in the request lifecycle does it execute relative to my route handler?刚才发生了什么?
为什么这很重要:快速阅读陌生代码库是 Claude Code 的杀手级功能。你刚才 10 分钟做完的事,正常要花半天浏览源码文件、读文档、交叉查 StackOverflow。这对任何代码库、任何语言、任何规模都适用。
注意工具选择的模式:Claude 先用 Glob(勘察地形),然后 Read(检查关键文件),然后 Grep(查找具体实现),然后再 Read(追踪代码路径)。这是典型的探索模式:勘察 -> 检查 -> 搜索 -> 追踪。
验证清单
- [ ] 成功克隆了 FastAPI
- [ ] Claude 追踪了
@app.get()装饰器到它的实现 - [ ] Claude 解释了请求生命周期,并给出了具体文件路径和行号
- [ ] 你大致理解了 FastAPI 如何路由一个请求
常见问题排查
每个工具都有可能出错的地方。以下是你会遇到的常见问题和解决方法:
认证失败
$ claude
Error: No API key found. Set ANTHROPIC_API_KEY or run `claude login`.解决:要么 export ANTHROPIC_API_KEY="sk-ant-...",要么运行 claude login 通过浏览器认证(适用于 Pro/Max/Team 订阅)。
Node.js 版本太旧
$ npm install -g @anthropic-ai/claude-code
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npm解决:Claude Code 需要 Node.js 18 以上。升级 Node.js:
- macOS:
brew upgrade node或nvm install 18 - Windows:从 nodejs.org 下载或
nvm install 18 - Linux:
nvm install 18或用包管理器
网络超时
> Analyze this codebase
Error: Request timed out after 30s. Check your network connection.解决:通常是网络阻止了 API 调用。检查:
- VPN 或代理设置 -- 某些企业 VPN 会阻止 Anthropic 的 API 端点
- 防火墙规则 -- 确保
api.anthropic.com可达 - 重试 -- 暂时性网络问题时有发生
安装时权限被拒绝
$ npm install -g @anthropic-ai/claude-code
npm ERR! EACCES permission denied解决:不要用 sudo。而是修复 npm 的目录权限:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH # 添加到你的 .bashrc/.zshrc
npm install -g @anthropic-ai/claude-code深入探索
常用命令速查表
这些命令你会天天用。收藏这个表。
会话管理:
| 命令 | 作用 | 什么时候用 |
|---|---|---|
/help | 列出所有命令和快捷键 | 忘了什么东西的时候 |
/clear | 清空对话 | 完全换一个话题的时候 |
/compact | 压缩上下文,保留关键信息 | 上下文到 ~50% 的时候(第三章详讲) |
/model | 在 Opus / Sonnet / Haiku 之间切换 | 硬活用 Opus,简单查询用 Haiku |
/context | 显示 token 使用详情 | 决定是否要 compact 之前 |
计费和用量:
| 命令 | 适用人群 | 显示什么 |
|---|---|---|
/usage | Pro / Max / Team 订阅用户 | 当前计费周期的剩余额度 |
/cost | API key 用户 | 本次会话的 token 消耗和费用 |
/fast | 所有人 | 切换快速模式(同模型,更少润色) |
/login | 所有人 | 切换账号或重新认证 |
/context 输出示例:
> /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 tokens如果你是 Pro 或 Max 订阅用户,养成经常查看
/usage的习惯。如果你用的是 API key,/cost是你的好朋友。很多订阅用户不需要关心每个 token 的价格,但知道自己的额度情况总归是好事。
进阶命令预览(后续章节详讲):
| 命令 | 作用 | 章节 |
|---|---|---|
/memory | 查看/管理 Claude 自动保存的记忆 | Ch2 |
/sessions | 浏览和恢复历史会话 | Ch3 |
/rewind | 回退到之前的 checkpoint | Ch4 |
/review | 触发代码审查 | Ch4 |
/init | 为当前项目自动生成 CLAUDE.md | Ch2 |
/agents | 管理子 agent | Ch8 |
非交互式模式(管道模式)
这是 Claude Code 作为 UNIX 公民的用法:
# 一次性提问,不进入交互会话
claude -p "What does this project do?"
# 管道输入
cat error.log | claude -p "What's the root cause of these errors?"
# 一行命令搞定代码审查
git diff | claude -p "Review these changes. Focus on security issues."
# 生成 commit message
git diff --staged | claude -p "Write a conventional commit message for these changes"管道模式输出示例:
$ 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.管道模式对于脚本化特别强大。我们会在第四章 Git 工作流和第五章 Hooks进一步使用它。
模型选择
# 在会话中:
/model
# 从命令行指定:
claude --model claude-opus-4-7 # 最强大,适合复杂推理
claude --model claude-sonnet-4-6 # 均衡型,大多数工作的默认选择
claude --model claude-haiku-4-5 # 最快,适合简单查询| 模型 | 适用场景 | 速度 | 费用 | 上下文 |
|---|---|---|---|---|
| Opus 4.7 | 架构决策、复杂调试、多文件重构 | 较慢 | 较高 | 1M tokens |
| Sonnet 4.6 | 日常开发、代码审查、功能实现 | 快 | 中等 | 200k tokens |
| Haiku 4.5 | 快速提问、文件查找、简单生成 | 最快 | 最低 | 200k tokens |
经验法则:从 Sonnet 开始。需要深度推理(架构决策、复杂调试、需要很多步骤的任务)时切 Opus。只需要快速回答时切 Haiku。
深入了解:A11 模型选择指南 提供了基准测试、费用对比,以及生产团队使用的路由策略。
快捷键
| 快捷键 | 作用 |
|---|---|
Esc | 中断 Claude 当前生成 |
Ctrl+C | 退出 Claude Code |
Tab | 在提示中自动补全文件路径 |
Up / Down | 浏览提示历史 |
知识检测
练习:你的第一个多步骤构建
任务
在一个 Claude 会话中完成以下所有步骤:
- 让 Claude 创建一个 Python 脚本
repo_scanner.py,功能:- 接受一个本地 git 仓库路径作为参数
- 统计每个作者的提交数
- 列出最近修改的 5 个文件
- 以 Markdown 格式输出摘要
- 让 Claude 为它写测试(pytest)
- 让 Claude 跑测试
- 如果有失败,让 Claude 修复
- 用这个工具扫描 Demo 2 中的 FastAPI 仓库
成功标准
- [ ]
repo_scanner.py存在且可运行 - [ ] 测试文件存在,所有测试通过
- [ ] 对真实仓库运行扫描器得到了有意义的输出
- [ ] 整个过程在一个 Claude Code 会话中完成
- [ ] 你看到 Claude 使用了至少 3 种不同的工具(Write、Bash、Read)
提示
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.本章小结
- Claude Code 是终端里的工具调用 AI 助手。它读文件、写代码、跑命令、操作 Git -- 全部通过明确的权限系统控制。
- 权限系统不是给新手的保护轮 -- 它是安全机制。每个操作都需要你的同意(除非你明确自动允许)。
- 你构建了一个 GitHub Profile Analyzer(不是 hello world),还追踪了 FastAPI 源码中的请求流程 -- 两个真正有用的任务。
- 工具探索模式是:勘察(Glob)-> 检查(Read)-> 搜索(Grep)-> 追踪(再次 Read)。
- 关键命令:
/help、/clear、/compact、/model、/context、/usage(订阅用户)、/cost(API 用户)。 - 管道模式(
claude -p)把 Claude 变成可脚本化的 UNIX 工具,适合一次性任务。 - 出问题时:检查 Node.js 版本、API key、网络连接和 npm 权限。
下一章:第二章:CLAUDE.md 与记忆系统。这是 Claude 从通用助手变成了解你项目规范的团队成员的关键。差距是天壤之别。