Claude Code How to–如何组合CC各种工具

从github项目中学习如果组合官方提供的各种工具–不定版本尽量新版本

官方文档描述了各种功能,但没有告诉你如何将它们组合起来使用。你知道斜杠命令的存在,但却不知道如何将它们与Hooks、Memory和Subagent串联起来,形成一个真正能节省数小时的工作流,该文章提供先对部件认知然后给组合提供一些思路

1. 背景

前面文章已经学习了如何安装claude colder,如何安装Skills,MCP,Command,Agent,settings等,但是都是独立的模块进行的了解,该如何整合起来形成自己的工作流才是最重要的事情

这里依据luongnv89/claude-howto仓库进行第二步的学习

维度 官方文档(Official Docs) 本指南(This Guide)
格式 参考型文档 使用 Mermaid 图的可视化教程
深度 功能说明 底层工作原理解析
示例 基础代码片段 可直接用于生产的模板
结构 按功能组织 渐进式学习路径(从入门到进阶)
入门方式 自主学习 带时间预估的引导式路线
自我评估 交互式测验,定位知识缺口并生成个性化路径

该仓库主要是下面几个部分:

  • 覆盖 Claude Code 所有功能的 10 个教程模块——从斜杠命令到自定义智能体团队
  • 可直接复制粘贴的配置——斜杠命令、CLAUDE.md 模板、hook 脚本、MCP 配置、子智能体定义以及完整插件包
  • 使用 Mermaid 图展示每个功能的内部工作原理,让你不仅知道“怎么用”,还理解“为什么这样设计”
  • 内置自我评估——可以在 Claude Code 中直接运行 /self-assessment/lesson-quiz hooks 来识别知识盲区

主要是介绍了10个模块和上手容易程度

顺序 模块 等级
1 Slash Commands(斜杠命令) Beginner(初级)
2 Memory(记忆) Beginner+(初级+)
3 Checkpoints(检查点) Intermediate(中级)
4 CLI Basics(命令行基础) Beginner+(初级+)
5 Skills(技能) Intermediate(中级)
6 Hooks(钩子) Intermediate(中级)
7 MCP Intermediate+(中级+)
8 Subagents(子智能体) Intermediate+(中级+)
9 Advanced Features(高级功能) Advanced(高级)
10 Plugins(插件) Advanced(高级)

不同版本的claude code会发生变化,有可能大版本之后会有大的逻辑变化,所以要紧跟版本

2. Claude Code How To

将项目从github克隆下来之后,挨个进行复制,前面的claude code learn已经介绍了不同工具安装的目录路径,这里将不同的文件夹拷贝到目标文件夹即可

# 1. Clone the guide,克隆当前的仓库
git clone https://github.com/luongnv89/claude-howto.git
cd claude-howto

# 2. Copy your first slash command,启动第一个命令
mkdir -p /path/to/your-project/.claude/commands
cp 01-slash-commands/optimize.md /path/to/your-project/.claude/commands/

# 3. Try it — in Claude Code, type: 尝试第一个命令
# /optimize

# 4. Ready for more? Set up project memory: 设置项目记忆
cp 02-memory/project-CLAUDE.md /path/to/your-project/CLAUDE.md

# 5. Install a skill: skill的安装
cp -r 03-skills/code-review-specialist ~/.claude/skills/

更新会随着版本来,所以有的方式会发生变化,有的会淘汰,这个是需要注意的

3 Commands学习

斜杠命令就像你个人访问 AI 助手的快捷方式,可以把slash command想象成你在手机上设置的快捷方式图标,点击一下就能直接打开特定的功能,而不需要每次都输入完整的指令。而slash command可以看作是存储提示的markdown文件,里面包含了你想要AI执行的任务的详细说明和示例。通过使用斜杠命令,你可以快速调用这些预设的提示,节省时间并提高效率

3.1 基础结构

  1. slash command结构

当你使用/commands的时候,其实底层触发的是下面的逻辑

┌─────────────────┐
 User Input      
 /command-name   
└──────────┬──────┘
            Triggers
           
┌─────────────────────────┐
 Search                  
 .claude/commands/       
└──────────┬──────────────┘
            Finds
           
┌─────────────────────────┐
 command-name.md         
└──────────┬──────────────┘
            Loads
           
┌─────────────────────────┐
 Markdown Content        
└──────────┬──────────────┘
            Executes
           
┌─────────────────────────┐
 Claude Processes Prompt 
└──────────┬──────────────┘
            Returns
           
┌─────────────────────────┐
 Result in Context       
└─────────────────────────┘

现在command用户体验层面基本合并skills了,但底层概念没有完全合并,Command本质上只是markdown文档,但是Skills增加了比如Tool权限控制,有更好的参数处理,能够与Hook配合等

cc command hook

  1. 新版命令分类
类型 来源 定义方式 示例 是否推荐 备注
Built-in Commands Claude Code 内置 系统提供 /help, /clear, /model ✅ 必须 不可修改
Skills(新标准) 用户定义 .claude/skills/*.md /optimize, /pr, /refactor ⭐⭐⭐⭐⭐ 推荐 替代旧 custom commands
Plugin Commands 插件系统 插件注册 /frontend-design:frontend-design ⭐⭐⭐ 依赖插件生态
MCP Prompts MCP Server MCP tools / prompts /mcp__github__list_prs ⭐⭐⭐⭐ 面向工具/API
Legacy Commands(旧) .claude/commands/ Markdown 文件 /build, /test ⚠️ 兼容但不推荐 已被 Skills 取代

不同的类型有了自己的命名规则,方便分类和管理

类型 命名格式
Skill command /skill-name
Plugin command /plugin:command
MCP command /mcp__server__tool
Built-in /help

自定义斜杠命令已合并到技能中。.claude/commands/ 目录下的文件仍然有效,但现在推荐使用技能目录 (.claude/skills/), 两者都会创建 /commands-name 快捷方式。

  1. 命令示例

[1] Claude Code内置命令

Claude Code内置命令都是绑定在claude code安装过程中的,不像自定义的命令需要手动安装到指定目录下

分类 Slash Command 别名 功能说明
帮助与元信息 /help - 查看帮助信息
/feedback /bug/share 提交反馈或问题
/powerup - 查看增强功能
/release-notes - 查看版本更新日志
/exit - 退出 Claude Code
会话与对话 /clear - 清空当前会话
/resume - 恢复历史会话
/rename - 重命名会话
/branch - 创建会话分支
/rewind /checkpoint 回退到历史检查点
/fork - 分叉当前对话
/copy - 复制当前会话
/export - 导出会话内容
/recap - 生成会话总结
/btw - 后台继续执行任务
/background - 后台运行任务
/stop - 停止当前任务
上下文与规划 /context - 查看上下文状态
/compact - 压缩上下文
/focus - 设置关注范围
/plan - 生成执行计划
/goal - 管理目标
/tasks - 查看任务列表
模型与推理强度 /model - 切换模型
/effort - 调整推理强度
/fast - 快速模式
/advisor - 顾问模式
项目初始化与配置 /init - 初始化项目
/config /settings 配置 Claude Code
/memory - 管理记忆
/permissions - 权限管理
/hooks - 配置 Hooks
/mcp - MCP 管理
/agents - Agent 管理
/skills - Skills 管理
/plugin - 插件管理
/workflows - 工作流管理
/statusline - 状态栏设置
/keybindings - 快捷键配置
/theme - 主题设置
/color - 配色设置
/scroll-speed - 滚动速度设置
/vim - Vim 模式配置
/terminal-setup - 终端环境配置
/ide - IDE 集成配置
/sandbox - 沙箱配置
/add-dir - 添加工作目录
/cd - 切换目录
/reload-skills - 重新加载 Skills
/reload-plugins - 重新加载插件
/privacy-settings - 隐私设置
注记

不同的版本会有不同的命令迭代更新,核心是知道有什么命令,在需要的时候调用即可,有的命令是针对桌面版的Claude Code

[2] Code Quality Command (/optimize)

Command现在并入了skills中,当前学习还是放置在commands文件夹中

# 1. 克隆仓库
git clone https://github.com/luongnv89/claude-howto.git
cd claude-howto

# 2. 创建项目文件夹或者直接复制到个人目录下的.claude
mkdir -p /path/to/your-project/.claude/commands

# 3. 复制命令文件
cp 01-slash-commands/optimize.md /path/to/your-project/.claude/commands/

下面是Optimization的markdown文件内容:

---
description: Analyze code for performance issues and suggest optimizations
---

# Code Optimization

Review the provided code for the following issues in order of priority:

1. **Performance bottlenecks** - identify O(n²) operations, inefficient loops
2. **Memory leaks** - find unreleased resources, circular references
  • 已经不需要name字段了,文件名就是命令名
  • description字段是可选的,但建议添加,方便在命令列表中快速了解

Claude Code中输入/optimize,就会触发这个命令,Claude会根据markdown文件中的提示分析代码并给出优化建议。

 /optimize 是一个代码性能优化分析技能。它会扫描代码并按优先级检
  查以下问题:

  1. 性能瓶颈 — O(n²) 操作、低效循环
  2. 内存泄漏 — 未释放的资源、循环引用
  3. 算法改进 — 更优的算法或数据结构建议
  4. 缓存机会 — 重复计算的可缓存点
  5. 并发问题 — 竞态条件、线程安全问题

  每个发现会标注严重程度(Critical/High/Medium/Low)、代码位置、
  解释和修复建议。

  用法: 对当前工作目录中的代码运行分析。你可以在后面指定要分析
  的文件或代码范围,比如 /optimize src/utils.ts。

  需要我对当前项目跑一次优化分析吗?

[3] Bundled Skills

Claude Code中有几个命令是以Skills的形式打包然后以/command命令调用,方便直接使用,后续介绍Skills的时候会详细介绍

技能命令 用途说明
/batch <instruction> 使用 Worktree 编排和执行大规模并行代码修改任务。
/claude-api 加载当前项目所使用编程语言对应的 Claude API 参考文档。
/debug [description] 启用调试日志,并可附带调试说明。
/loop [interval] <prompt> 按指定时间间隔重复执行同一个 Prompt。
/code-review [effort] 对当前 Diff 进行代码审查,重点查找正确性和潜在 Bug。可指定审查强度(如 lowmediumhigh)。在 v2.1.146 中曾吸收 /simplify 功能,但后来重新拆分。
/simplify 执行仅针对代码清理和优化的审查,包括代码复用、简化、效率提升和结构优化,并自动应用修改;不会主动查找 Bug。如需 Bug 检查,应使用 /code-review。曾在 v2.1.152 中作为 /code-review --fix 的别名,v2.1.154 后恢复为独立命令。

3.2 常规流程

  1. 初次进入仓库(First session in a repo)
  • /init: 生成一个基础的 CLAUDE.md 初始化文件(项目说明与规范)
  • /memory: 用来优化和完善项目记忆(让 Claude 更懂你的项目)
  • /mcp: 配置 MCP 服务器(外部系统连接,如 GitHub、数据库等)
  • /agents:设置子代理(subagents),用于任务拆分和协作
  • /permissions:配置权限规则(哪些操作需要确认,哪些可以自动执行)
  1. 任务进行中(During a task)
  • /plan: 进入计划模式,在执行大改动前先制定方案
  • /model: 调整模型能力/推理强度(更强或更快)
  • /effort:调整思考与执行的“投入程度”
  • /context:查看上下文窗口使用情况(是否接近上限)
  • /compact:压缩历史对话,减少 token 占用
  • /btw: 插入一个“顺带一提”的内容,不污染主对话结构
  1. 并行执行工作
  • /agents:打开代理管理器,分配子任务给多个 agent
  • /batch:使用 Worktree 执行大规模并行任务
  • /tasks: 查看当前后台正在运行的任务
  • /background:将整个会话转为后台运行(类似守护进程)
  1. 提交前
  • /diff:查看代码变更内容
  • /code-review: 对代码做检查(bug、风格、优化),支持自动修复 –fix
  • /review:对 GitHub PR 做只读代码审查
  • /security-review:深入的安全审查
  1. 会话之间
  • /clear:清空当前会话,开始新任务(保留项目记忆)
  • /resume:恢复之前的对话
  • /branch: 从某个历史点分支出新对话
  1. 出现问题
  • /rewind: 回滚代码或对话到某个检查点
  • /doctor:检查安装或运行环境问题
  • /debug:启用调试日志,并附带调试说明
  • /feedback:提交 bug 报告,并附带当前会话上下文

4 Memory学习

记忆功能使 Claude 能够在会话和对话之间保留上下文。它以两种形式存在:claude.ai 中的自动合成,以及 Claude Code 中基于文件系统的 CLAUDE.md 文件。

在 Claude.ai(网页端 Claude)中,Claude 会自动从你和它的长期对话里提炼出一些有价值的信息,形成 Memory,而不是让你手动维护一个文件

Claude Code中的记忆系统提供了永久的上下文保存,可以多重的会话.不像临时的上下文窗口,记忆文件有优势:

  • 能够在team中分享项目标准
  • 存储个人开发偏好
  • 保持项目规则和设置
  • 导入额外文档
  • 项目的版本控制
Command 作用(Purpose) 用法(Usage) 适用场景(When to Use)
/init 初始化项目记忆,创建或更新 CLAUDE.md /init 新项目开始时;首次创建项目记忆
/memory 编辑和管理记忆文件 /memory 大规模修改、整理、查看项目记忆
# 前缀 快速添加单行记忆(已废弃) 已移除 现在使用 /memory 或直接对话告诉 Claude
@path/to/file 导入外部文件内容作为上下文 @README.md
@docs/api.md
引用已有文档、规范、设计说明

这里先给一个整体的关系图

                    项目知识管理

                           │
         ┌─────────────────┼─────────────────┐
         │                 │                 │
         ▼                 ▼                 ▼

      /init            /memory          @file

   创建记忆库        编辑记忆库       导入临时上下文

         │                 │                 │
         └──────────┬──────┘                 │
                    ▼                        │

                CLAUDE.md                    │
              (长期项目记忆)                  

                    ▲                        │
                    └───────────────┬────────┘
                                    ▼

                             Claude 回答问题

4.1 /init命令

/init在Claude Code是设置项目记忆的最快方式,它会初始化一个包含项目基础文档的CLAUDE.md文件

在claude code中输入/init

  • 在您的项目中创建一个新的 CLAUDE.md 文件,可以位于项目中的CLAUDE.md,也可以在用户层面的./claude/CLAUDE.md,或者两者都创建
  • 制定项目规范和准则
  • 为跨会话的上下文持久性奠定基础
  • 为项目标准提供模板

增强交互模式(Enhanced interactive mode):设置环境变量 CLAUDE_CODE_NEW_INIT=1 后,Claude Code 的 /init 命令会启用新的多阶段交互流程,引导你一步一步完成项目初始化

./CLAUDE.md和./.claude/CLAUDE.md现在属于平级状态

bashzsh中设置:

export CLAUDE_CODE_NEW_INIT=1

4.2 /memory命令

#快捷键已经弃用,之前还没了解过现在已经弃用了,发展太快学的太慢不知道是好还是坏了..

Claude Code中输入/memory,Claude会提示你选择要编辑的文件,然后确认后会跳转到编辑器去编辑文件,确认即可

cc memory

注记

AI Agent现在能做很多,包括你可以直接让AI去修改memory,比如告诉它下面的信息请记住,本项目始终使用 TypeScript 严格模式。 另请注意:优先使用 async/await 而非 Promise 链。

什么时候使用/memory?

  • 审查现有内存内容
  • 做大量项目标准的更新
  • 重新组织结构
  • 添加详细的文档或者指南
  • 随着项目的演进,维护和更新内存

4.3 @/path/file功能

这是 Claude Code 中一个很实用的功能,允许你在 CLAUDE.md 里引用其他文件内容,避免把所有内容都堆到一个大文件里

比如在CLAUDE.md文件中可以这么写

# Project Documentation
See @README.md for project overview
See @package.json for available npm commands
See @docs/architecture.md for system design

# Import from home directory using absolute path
@~/.claude/my-project-instructions.md

有点类似Ghostty中的设置文件,可以引用别的位置的文件来补充设置,放置一个文件内容过多导致的信息爆炸

  • 相对路径和绝对路径都是可以的
  • 文件深度最大是5层,相当于5个子文件夹
  • 首次从外部位置导入数据时,会触发安全审批对话框。
  • 在 Markdown 代码 span 或代码块中,导入指令不会被执行
  • 通过引用现有文档,有助于避免重复工作。

4.4 记忆架构和层级管理

cc memory architecture

Claude Code 使用多层级Memory系统。Memory文件会在 Claude Code 启动时自动加载,级别较高的文件优先级更高

  1. Claude Code 企业级集中管理(Managed Policy) 的功能,类似公司 IT 管理员统一下发配置和规则,让所有开发者使用 Claude Code 时自动遵守相同的规范
系统级CLAUDE.md
系统 路径
macOS /Library/Application Support/ClaudeCode/CLAUDE.md
Linux / WSL /etc/claude-code/CLAUDE.md
Windows C:\Program Files\ClaudeCode\CLAUDE.md
  1. Managed Drop-ins 以前只能写有一个巨大的CLAUDE.md从v2.1.83 开始新增,可以拆分多个文件,大型组织经常有很多的团队,如安全团队,开发规范团队,AI平台团队,所有人都修改同一个CLAUDE.md会造成冲突
Managed CLAUDE.md
└── 同目录下的 managed-settings.d/

01-security.md
02-compliance.md
03-devops.md
04-python.md
05-web.md
注记

managed-settings.d这种写法来自Unix/Linux设计了灵感,.d表示directory(目录)

  1. Project Memory–团队共享上下文(版本控制)

./.claude/CLAUDE.md or ./CLAUDE.md (in repository root)

提示

这里的./非常容易让人误解,文档里的./CLAUDE.md并不是当前Shell工作目录,而是指Repository Root(git仓库根目录)

/etc/claude-code/CLAUDE.md     (系统级)

项目根目录 CLAUDE.md            (项目级)

.claude/CLAUDE.md             (本项目附加规则)

memory
  1. 项目规则 - 模块化、主题特定的项目说明
  • .claude/rules/*.md:把项目规则拆成多个主题文件,按需组织和维护
  • 项目里的 CLAUDE.md:写一个总规则文件
my-project/

├── CLAUDE.md
└── .claude/
└──     rules/
├──     python.md
├──     testing.md
├──     git.md
├──     architecture.md
└──     security.md

以前是把规则按主题一起塞入到CLAUDE.md,文件越来越大,越来越难维护,现在加入rules/*.md之后,团队协作项目,每个关键流程都是一个单独的文件,方便维护和更新

特性 .claude/rules/*.md Managed Drop-ins
作用范围 当前项目 整台机器 / 整个组织
位置 项目目录内 系统目录
管理者 项目开发者 IT管理员 / 企业管理员
是否提交 Git 通常是 通常不是
是否随项目传播
优先级 较低 较高
目标 项目规范 企业强制策略
  1. 个人记忆 - 个人偏好(所有项目)

~/.claude/CLAUDE.md (in user home directory)

  1. User-Level Rules - Personal rules (all projects)

~/.claude/rules/*.md

  1. 本地项目记忆(Local Project Memory)

专门解决:同一个项目里,团队共享规则和我个人习惯不一样怎么办

./CLAUDE.local.md

  1. Auto Memory - Claude’s automatic notes and learnings

Claude 在使用过程中自动积累的项目记忆

注记

Claude Code 对于memory搜索是有顺序的

cc memory order

4.5 使用 claudeMdExcludes 排除 CLAUDE.md 文件

在大型单体仓库中,某些 CLAUDE.md 文件可能与您当前工作无关。claudeMdExcludes 设置允许您跳过特定的 CLAUDE.md 文件,使其不被加载到上下文中

// In ~/.claude/settings.json or .claude/settings.json
{
  "claudeMdExcludes": [
    "packages/legacy-app/CLAUDE.md",
    "vendors/**/CLAUDE.md"
  ]
}

或者直接让AI去写入到文件中去

  1. Setting 文件的层级

Claude Code 设置(包括 autoMemoryDirectory、claudeMdExcludes 和其他配置)是根据五级层次结构解析的,级别越高优先级越高:

Level Location Scope 说明
1 (Highest) Managed policy (system-level) Organization-wide enforcement 组织级强制策略(最高优先级,无法被覆盖)
2 managed-settings.d/ (v2.1.83+) Modular policy drop-ins 模块化策略片段,按文件名字母顺序合并
3 .claude/settings.local.json Local overrides 本地覆盖配置(通常被 git ignore)
4 .claude/settings.json Project-level 项目级配置(会提交到 git 仓库)
5 (Lowest) ~/.claude/settings.json User preferences 用户全局偏好设置(最低优先级)

在claude code输入/config同样会修改当前用户下的setting.json文件,选择之后都会保存

注记

优先级不等于覆盖等级,个人local设计覆盖project是为了防止个人的设置与团队的设置冲突

cc config

  1. 本地缓存文件清理
{
  "cleanupPeriodDays": 14
}

Claude Code 启动时,会删除 14 天前的本地历史文件,会清理下面的目录

目录 用途
~/.claude/checkpoints/ Checkpoint 历史快照
~/.claude/tasks/ Task 执行记录
~/.claude/shell-snapshots/ Shell 命令快照
~/.claude/backups/ Claude 自动备份文件

对于用户和项目推荐的CLAUDE.md写法和结构,更加合理的管控项目和个人偏好

your-project/
├── .claude/
│   ├── CLAUDE.md
│   └── rules/
│       ├── code-style.md
│       ├── testing.md
│       ├── security.md
│       └── api/                  # Subdirectories supported
│           ├── conventions.md
│           └── validation.md

~/.claude/
├── CLAUDE.md
└── rules/                        # User-level rules (all projects)
    ├── personal-style.md
    └── preferred-patterns.md
  • ~/.claude中放长期不变的个人习惯
  • your-project/.claude中放项目级别的规则
  • 这两个是可以共存的,但是~/.claude下面的会覆盖项目里面的
  1. 在Rules中指定文件

Path-Specific Rules with YAML Frontmatter 的作用是: > 让某条规则只对特定目录、文件类型或路径生效,而不是整个项目都生效

不使用特定路径的话,Rules会应用到整个项目,使用YAML Frontmatter会指定文件

---
paths: src/api/**/*.ts
---

# API Development Rules

- All API endpoints must include input validation
- Use Zod for schema validation
- Document all parameters and response types
- Include error handling for all operations

还可以使用全局模式:

  • **/*.ts - All TypeScript files
  • src/**/* - All files under src/
  • src/**/*.{ts,tsx} - Multiple extensions
  • {src,lib}/**/*.ts, tests/**/*.test.ts - Multiple patterns
重要

.claude/rules/ 的两个组织能力增强功能:子目录递归 + 符号链接(symlink)复用规则

  • Subdirectories(子目录)
  • Symlinks(符号链接): 允许你在多个项目之间共享同一份规则文件

cc memory cycle

4.6 Auto Memory

自动记忆库是一个持久目录,Claude 会在项目运行过程中自动记录学习成果、模式和见解。与您手动编写和维护的 CLAUDE.md 文件不同,自动记忆库由 Claude 在运行过程中自动生成。

  • 自动记忆库中的内容会根据项目需求自动更新,无需手动干预。
  • 自动记忆库的位置在~/.claude/projects/<project>/memory/
  • 入口点: MEMORY.md 是自动内存目录中的主文件
  • 会话启动时,MEMORY.md 文件的前 200 行(或前 25KB,以先到者为准)会被加载到上下文中。主题文件是按需加载的,而不是在启动时加载的。

cc memory

注记

常见的目录结构:

~/.claude/projects/<project>/memory/
├── MEMORY.md              # Entrypoint (first 200 lines / 25KB loaded at startup)
├── debugging.md           # Topic file (loaded on demand)
├── api-conventions.md     # Topic file (loaded on demand)
└── testing-patterns.md    # Topic file (loaded on demand)

自动记忆功能需要 Claude Code v2.1.59 或更高版本

默认情况下,自动内存存储在 ~/.claude/projects/<项目>/memory/ 目录中。您可以使用 autoMemoryDirectory 设置(自 v2.1.74 版本起可用)更改此位置

// In ~/.claude/settings.json or .claude/settings.local.json (user/local settings only)
{
  "autoMemoryDirectory": "/path/to/custom/memory/directory"
}

[2] Worktree and Repository Sharing

同一个 Git 仓库中的所有工作树和子目录共享同一个自动内存目录。这意味着在不同的工作树之间切换,或者在同一个仓库的不同子目录中工作,都会读写同一个内存文件。

subagents有自己独立的memory 上下文,在子代理定义中使用内存前置信息字段来指定要加载的内存范围

memory: user      # Load user-level memory only
memory: project   # Load project-level memory only
memory: local     # Load local memory only

[3] Additional Directories with --add-dir

--add-dir 标志允许 Claude Code 从当前工作目录之外的其他目录加载 CLAUDE.md 文件。这对于单体仓库或多项目架构非常有用,因为在这些情况下,其他目录的上下文信息也很重要。

有两种方法来允许claude code读取子目录

  • 临时生效,在终端直接写CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude,只对这一次claude启动生效
  • export CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1写在.bashrc或者.zshrc中,永久生效

同样的控制是否启动自动记忆也是这样子的

# Disable auto memory for a session
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude

# Force auto memory on explicitly
CLAUDE_CODE_DISABLE_AUTO_MEMORY=0 claude

4.7 实际例子

[1] 个人偏好定位等,写在~/.claude/CLAUDE.md中,可以用来参考:

# My Development Preferences

## About Me
- **Experience Level**: 8 years full-stack development
- **Preferred Languages**: TypeScript, Python
- **Communication Style**: Direct, with examples
- **Learning Style**: Visual diagrams with code

## Code Preferences

### Error Handling
I prefer explicit error handling with try-catch blocks and meaningful error messages.
Avoid generic errors. Always log errors for debugging.

### Comments
Use comments for WHY, not WHAT. Code should be self-documenting.
Comments should explain business logic or non-obvious decisions.

### Testing
I prefer TDD (test-driven development).
Write tests first, then implementation.
Focus on behavior, not implementation details.

### Architecture
I prefer modular, loosely-coupled design.
Use dependency injection for testability.
Separate concerns (Controllers, Services, Repositories).

## Debugging Preferences
- Use console.log with prefix: `[DEBUG]`
- Include context: function name, relevant variables
- Use stack traces when available
- Always include timestamps in logs

## Communication
- Explain complex concepts with diagrams
- Show concrete examples before explaining theory
- Include before/after code snippets
- Summarize key points at the end

## Project Organization
I organize my projects as:

   project/
   ├── src/
   │   ├── api/
   │   ├── services/
   │   ├── models/
   │   └── utils/
   ├── tests/
   ├── docs/
   └── docker/

## Tooling
- **IDE**: VS Code with vim keybindings
- **Terminal**: Zsh with Oh-My-Zsh
- **Format**: Prettier (100 char line length)
- **Linter**: ESLint with airbnb config
- **Test Framework**: Jest with React Testing Library

[2] 个人项目下的./CLAUDE.md文件

# Project Configuration

## Project Overview
- **Name**: E-commerce Platform
- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker
- **Team Size**: 5 developers
- **Deadline**: Q4 2025

## Architecture
@docs/architecture.md
@docs/api-standards.md
@docs/database-schema.md

## Development Standards

### Code Style
- Use Prettier for formatting
- Use ESLint with airbnb config
- Maximum line length: 100 characters
- Use 2-space indentation

### Naming Conventions
- **Files**: kebab-case (user-controller.js)
- **Classes**: PascalCase (UserService)
- **Functions/Variables**: camelCase (getUserById)
- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)
- **Database Tables**: snake_case (user_accounts)

### Git Workflow
- Branch names: `feature/description` or `fix/description`
- Commit messages: Follow conventional commits
- PR required before merge
- All CI/CD checks must pass
- Minimum 1 approval required

### Testing Requirements
- Minimum 80% code coverage
- All critical paths must have tests
- Use Jest for unit tests
- Use Cypress for E2E tests
- Test filenames: `*.test.ts` or `*.spec.ts`

### API Standards
- RESTful endpoints only
- JSON request/response
- Use HTTP status codes correctly
- Version API endpoints: `/api/v1/`
- Document all endpoints with examples

### Database
- Use migrations for schema changes
- Never hardcode credentials
- Use connection pooling
- Enable query logging in development
- Regular backups required

### Deployment
- Docker-based deployment
- Kubernetes orchestration
- Blue-green deployment strategy
- Automatic rollback on failure
- Database migrations run before deploy

## Common Commands

| Command | Purpose |
|---------|---------|
| `npm run dev` | Start development server |
| `npm test` | Run test suite |
| `npm run lint` | Check code style |
| `npm run build` | Build for production |
| `npm run migrate` | Run database migrations |

## Team Contacts
- Tech Lead: Sarah Chen (@sarah.chen)
- Product Manager: Mike Johnson (@mike.j)
- DevOps: Alex Kim (@alex.k)

## Known Issues & Workarounds
- PostgreSQL connection pooling limited to 20 during peak hours
- Workaround: Implement query queuing
- Safari 14 compatibility issues with async generators
- Workaround: Use Babel transpiler

## Related Projects
- Analytics Dashboard: `/projects/analytics`
- Mobile App: `/projects/mobile`
- Admin Panel: `/projects/admin`

5. Agent Skills

Agent 技能是可重用的、基于文件系统的功能,可以扩展 Claude 的功能。他们将特定领域的专业知识、工作流程和最佳实践打包成可发现的组件,Claude 会在相关时自动使用这些组件。

Agent 技能是模块化功能,可以将常规的agent转变为领域专家,与提示词工程(针对一次性任务的对话指令)不同,skills按需加载,无需在多次对话中重复提供相同的指导

  • 定制化Claude: 特定任务定制化能力
  • 减少重复:自动交叉使用
  • 组合能力:结合各种技能构建复杂的工作流程
  • 扩展工作流程:在多个项目和团队中重用技能
注记

Agent skills现在已经成为一个被行业采用的开发标准(Open Standed),是由Anthropic提出并开源的,已经被claude code,cusor,github copilot,opencode共同使用,Claude Code 在标准基础上增加了调用控制、子代理执行和动态上下文注入等功能。

自定义的slash commands已经被合并到.claude/commands/,commands依然是可以用的,现在推荐使用skills

5.1 Skill工作原理–渐进式揭露

该功能利用渐进式披露架构——Claude 会根据需要分阶段加载信息,而不是预先获取上下文。这既能实现高效的上下文管理,又能保持无限的可扩展性

agent skill

Level 加载时机 Token 开销 内容
Level 1:元数据(Metadata) 始终加载(启动时) 每个 Skill 约 100 Tokens YAML Frontmatter 中的 namedescription
Level 2:指令(Instructions) Skill 被触发时 小于 5k Tokens SKILL.md 主体内容,包括操作说明和使用指导
Level 3+:资源(Resources) 按需加载 理论上无限制 Skill 附带的资源文件,通过 Bash 直接执行,无需将文件内容加载到上下文中

cc skills

类型(Type) 位置(Location) 作用范围(Scope) 是否共享(Shared) 最适用场景(Best For)
Enterprise(企业级) Managed settings(集中管理设置) 所有组织用户 组织级标准与规范
Personal(个人级) ~/.claude/skills/<skill-name>/SKILL.md 个人用户 个人工作流
Project(项目级) .claude/skills/<skill-name>/SKILL.md 项目团队 是(通过 Git 共享) 团队标准与规范
Plugin(插件级) <plugin>/skills/<skill-name>/SKILL.md 插件启用范围内 取决于插件 随插件打包分发的技能

当skill名称相同时,会有不同的层级触发,enterprise > personal > project.插件的skill比较特殊,是使用plugin-name:skill-name,所以不会冲突

5.2 Skills自动发现机制

嵌套目录: 当您处理子目录中的文件时,Claude Code 会自动从嵌套的 .claude/skills/ 目录中发现技能.例如你在一个项目里project/A,claude code将在project/A/.claude/skills寻找.

从 v2.1.178 版本开始,当嵌套的 .claude/skills/ 目录中出现技能名称冲突时,将以距离当前工作目录最近的目录命名——包级技能会覆盖仓库根目录下同名技能。

--add-dir目录: 当你使用--add-dir参数时,Claude Code 会从指定的目录中发现技能。例如,--add-dir /path/to/dir 将从 /path/to/dir/.claude/skills/ 中发现技能。会立即生效,而不用重新启动claude code

Reloading skills:/reload-skills命令(在版本2.1.152)之后提供了,能够不退出claude code直接扫描当前所有技能目录. 在Hook中使用SessionStart 钩子可以通过返回 reloadSkills: true 来触发相同的重新扫描

预算说明: 技能描述(1 级元数据)限制为上下文窗口的 1%(备用:8,000 个字符),如果安装了多个技能,技能描述可能会被缩短。所有技能名称都会保留,但描述会根据文本长度进行精简.在终端使用SLASH_COMMAND_TOOL_CHAR_BUDGET更改预算

5.3 自定义Skills

  1. 基础文件结构
my-skill/
├── SKILL.md           # Main instructions (required)
├── template.md        # Template for Claude to fill in
├── examples/
│   └── sample.md      # Example output showing expected format
└── scripts/
    └── validate.sh    # Script Claude can execute
  1. SKILL.md格式
---
name: your-skill-name
description: Brief description of what this Skill does and when to use it
---

# Your Skill Name

## Instructions
Provide clear, step-by-step guidance for Claude.

## Examples
Show concrete examples of using this Skill.
  • namedescription 是必须的元数据字段,它们会显示在技能列表中。
  • name:仅限小写字母,数字和连字符(最大64字符),不能包含“anthropic”或“claude”
  • description:描述技能的作用和适用场景(最大1024字符),主要是为了让claude能知道怎么激活skill
注记

64 个字符(64 characters) 指的是总共 64 个字符,不是 64 个单词

内容类型 64字符大约能写多少
英文单词 10~15 个单词
中文 64 个汉字
中英混合 视具体情况而定
代码 1~3 行短代码
  1. Skills可选的YAML字段
---
name: my-skill
description: What this skill does and when to use it
argument-hint: "[filename] [format]"        # Hint for autocomplete
disable-model-invocation: true              # Only user can invoke
user-invocable: false                       # Hide from slash menu
allowed-tools: Read, Grep, Glob             # Restrict tool access
disallowed-tools: Write, Edit               # Remove specific tools while active (v2.1.152)
model: opus                                 # Specific model to use
effort: high                                # Effort level override (low, medium, high, xhigh, max)
context: fork                               # Run in isolated subagent
agent: Explore                              # Which agent type (with context: fork)
shell: bash                                 # Shell for commands: bash (default) or powershell
hooks:                                      # Skill-scoped hooks
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate.sh"
paths: "src/api/**/*.ts"               # Glob patterns limiting when skill activates
---
字段(Field) 中文说明
name Skill 名称。只能包含小写字母(a-z)、数字(0-9)和连字符(-),最长 64 个字符。名称中不能包含 “anthropic”“claude”
description Skill 的功能描述以及使用场景说明(最长 1024 个字符)。这是 Claude 判断是否自动调用该 Skill 的核心依据,对自动匹配(Auto Invocation)非常重要
argument-hint / 命令自动补全菜单中显示的参数提示。例如:"[filename] [format]"
disable-model-invocation 是否禁止 Claude 自动调用 Skill。
true = 仅允许用户通过 /skill-name 手动调用;Claude 永远不会自动调用。
false(默认)= Claude 可根据上下文自动调用
user-invocable 是否允许用户通过 / 菜单直接调用。
false = 在 / 菜单中隐藏,仅允许 Claude 自动调用。
true = 用户可以在 / 菜单中看到并手动调用。
allowed-tools Skill 运行期间允许使用的工具白名单(逗号分隔)。这些工具可直接使用,无需额外权限确认。
disallowed-tools Skill 运行期间禁止使用的工具黑名单(逗号分隔)。用于从当前可用工具集中移除指定工具,与 allowed-tools 配合使用。新增于 v2.1.152
model Skill 激活时使用的模型覆盖设置。例如:opussonnet
effort Skill 激活时使用的推理强度(Effort)覆盖设置。可选值:lowmediumhighxhighmax。可用级别取决于模型。例如 Opus 4.8 默认是 high,Opus 4.7 默认是 xhigh
context Skill 运行上下文。设置为 fork 时,Skill 会在独立的 Subagent(子代理)上下文中运行,并拥有独立的上下文窗口(Context Window)。
agent context: fork 时指定使用的 Subagent 类型。例如:ExplorePlangeneral-purpose 等。
shell Skill 执行 !命令 替换或脚本时使用的 Shell。可选:bash(默认)或 powershell
hooks 仅作用于当前 Skill 生命周期的 Hook(钩子)配置,格式与全局 Hooks 相同。
paths 限制 Skill 自动激活范围的文件路径匹配规则(Glob Pattern)。可以是逗号分隔字符串,也可以是 YAML 列表。格式与 Path-Specific Rules 相同。只有匹配这些路径时,Skill 才会自动触发。
  1. Skill内容类型
类型 作用 类比
Reference Content 提供知识、规范、约定 像一本参考手册
Task Content 提供操作步骤、执行流程 像一份SOP(标准操作流程)
  • Reference Content:参考内容,用于提供知识、规范、约定。这些内容通常不会频繁变动,且在 Skill 的生命周期内保持不变。例如,API 文档、代码规范、项目文档等。
  • Task Content:任务内容,用于提供操作步骤、执行流程。这些内容可能需要根据上下文或用户输入进行调整,且在 Skill 的生命周期内可能会发生变化。例如,代码生成、文档编写、数据提取等。

[1] Reference Content

添加claude用于当前工作的知识——惯例、模式、风格指南、领域知识。

---
name: api-conventions
description: API design patterns for this codebase
---

When writing API endpoints:
- Use RESTful naming conventions
- Return consistent error formats
- Include request validation

[2] 任务内容

针对特定操作的分步说明。通常直接使用 /skill-name 命令调用

---
name: deploy
description: Deploy the application to production
context: fork
disable-model-invocation: true
---

Deploy the application:
1. Run the test suite
2. Build the application
3. Push to the deployment target
  1. 控制skill调用

默认情况下,用户和claude都可以使用任何技能。两个前置元数据字段控制着三种技能使用模式:

Frontmatter 配置 用户可调用(You can invoke) Claude 可自动调用(Claude can invoke)
(默认) ✅ 是 ✅ 是
disable-model-invocation: true ✅ 是 ❌ 否
user-invocable: false ❌ 否 ✅ 是

对于无法作为命令执行的背景知识,请使用 user-invocable: false。例如,遗留系统上下文技能可以解释旧系统的工作原理——这对 Claude 很有用,但对用户来说没有实际意义

  1. 字符串替换

Skill 支持动态变量(Dynamic Values),这些变量会在 Skill 内容发送给 Claude 之前先被解析(替换成实际值)

SKILL.md 原始内容

变量解析(Resolve)

生成最终内容

发送给 Claude
变量 / 语法 中文说明 示例
$ARGUMENTS 获取调用 Skill 时传入的全部参数(原样拼接)。 /report sales.xlsx pdf$ARGUMENTS = sales.xlsx pdf
$ARGUMENTS[N] 获取指定位置的参数(从 0 开始计数)。 $ARGUMENTS[0] = sales.xlsx
$ARGUMENTS[1] = pdf
$N $ARGUMENTS[N] 的简写形式。 $0 = sales.xlsx
$1 = pdf
${CLAUDE_SESSION_ID} 当前 Claude 会话(Session)的唯一 ID。可用于日志记录、缓存目录、临时文件命名等。 session_abc123...
${CLAUDE_SKILL_DIR} 当前 Skill 所在目录(包含 SKILL.md 的目录)。便于引用同目录下的脚本、模板和资源文件。 /project/.claude/skills/api-review
${CLAUDE_EFFORT} 当前 Skill 运行时的推理强度(Effort Level)。可用于根据推理等级动态调整行为。支持:lowmediumhighxhighmax。新增于 v2.1.120+。 highmax
!`command` 动态上下文注入(Dynamic Context Injection)。执行 Shell 命令,并将命令输出直接插入到 Skill 内容中。 !`git branch --show-current`main

举个例子

用户执行/analyze data.csv pdf summary,

变量
$ARGUMENTS data.csv pdf summary
$0 data.csv
$1 pdf
$2 summary

${CLAUDE_SKILL_DIR} 示例:

.claude/
└── skills/
    └── api-review/
        ├── SKILL.md
        ├── standards.md
        └── review.sh

在skill中写Read:${CLAUDE_SKILL_DIR}/standards.md,会解析出来绝对路径

实际的例子:

---
name: fix-issue
description: Fix a GitHub issue
---

Fix GitHub issue $ARGUMENTS following our coding standards.
1. Read the issue description
2. Implement the fix
3. Write tests
4. Create a commit

当运行/fix-issue 123,参数就会$ARGUMENTS替换成123

5.4 在subagents中运行skills

添加context: fork以在隔离的子代理上下文中运行技能。技能内容由一个具有独立上下文窗口的专用子代理负责处理,从而保持主要对话的简洁性

当 Skill 使用 context: fork 创建 Subagent 时,可以选择什么类型的 Agent 来执行任务。

context: fork
agent: Explore

不要在 Main Agent 中执行
而是创建一个 Explore 类型的 Subagent 来执行
Agent Type 中文含义 最适合的场景
Explore 探索型 Agent 只读研究、代码库分析、信息收集
Plan 规划型 Agent 制定实施方案、设计路线图
general-purpose 通用型 Agent 需要多种工具和综合能力的任务
Custom agents 自定义 Agent 用户或团队配置的专用 Agent
注记

如果你要使用真正的 Custom Agent,通常需要先定义 Agent 文件

如果你要在skill中使用自定义的agent,就需要自己定义好agent

常规的Skills文档可以包含下面的部分,包括templates, examples, scripts, reference documents

my-skill/
├── SKILL.md              # Main instructions (required, keep under 500 lines)
├── templates/            # Templates for Claude to fill in
│   └── output-format.md
├── examples/             # Example outputs showing expected format
│   └── sample-output.md
├── references/           # Domain knowledge and specifications
│   └── api-spec.md
└── scripts/              # Scripts Claude can execute
    └── validate.sh
  • 保证SKILL.md低于500行 -使用相对路径从 SKILL.md 引用其他文件(例如,[API 参考](references/api-spec.md)

5.5 Claude code内置Skills

每次claude code更新都可能变动和内置skills,这里先介绍当前版本内置的skills

Claude Code 内置 Skills / Commands(中文说明)

Skill / Command 中文说明 用途
/batch <instruction> 批量并行代码修改工具 使用 git worktree 在整个代码库中并行执行大规模修改(适合重构、迁移、批量修复)
/claude-api Claude API/SDK 文档加载器 加载 Anthropic API / SDK 参考文档;当检测到 anthropic@anthropic-ai/sdk 时会自动触发
/debug [description] 调试当前会话 读取调试日志,帮助定位当前会话中的问题或异常行为
/fewer-permission-prompts 权限优化建议工具 分析历史操作记录,生成一个更少权限弹窗的 allowlist(偏只读工具优先)
/loop [interval] <prompt> 循环执行任务 按时间间隔重复执行某个 prompt,例如每 5 分钟检查一次部署状态
/run (v2.1.145+) 运行项目应用 启动当前项目并观察运行效果;会优先使用 project skill,否则使用内置项目识别规则
/run-skill-generator (v2.1.145+) 生成项目运行 Skill 自动学习当前项目结构,生成用于 /run/verify 的项目专用 Skill
/code-review [effort] 代码审查工具 对当前 diff 做系统性代码审查,可指定审查强度(low/medium/high 等),支持 --comment 直接在 PR 中写评论
/verify (v2.1.145+) 运行验证工具 构建 + 运行 + 实际观察应用行为,用于验证修复是否真正生效(比单元测试更完整)

6. Subagents

Subagents主要用来在claude code中被委托处理任务

  • 创建具有独立上下文窗口的隔离式 AI 助手
  • 为专业知识提供定制化系统提示
  • 强制执行工具访问控制以限制其功能
  • 防止复杂任务中上下文的污染
  • 支持并行执行多个专门任务

每个子agent都独立运行,从零开始,只接收完成任务所需的特定上下文,然后将结果返回给主代理进行综合

使用/agents命令能够创建,查看,编辑和管理子agent

cc agent command

6.1 Agent文件位置

Claude 在加载同名 Subagent 时,会按照以下优先级顺序查找和覆盖,数字越小优先级越高:

优先级 类型 (Type) 位置 (Location) 作用范围 (Scope) 说明
1(最高) CLI-defined 通过 --agents 参数传入的 JSON 当前会话(Session Only) 仅对本次 Claude 运行有效,会覆盖所有其他来源的同名 Agent。适合临时测试或动态生成 Agent。
2 Project Subagents .claude/agents/ 当前项目(Current Project) 项目专属 Agent,仅在当前仓库或项目中生效。通常提交到 Git,与团队共享。
3 User Subagents ~/.claude/agents/ 所有项目(All Projects) 用户级 Agent,对该用户的所有 Claude 项目生效。适合个人常用助手。
4(最低) Plugin Agents 插件提供的 agents/ 目录 通过插件加载 来自 Claude 插件(Plugin)的 Agent。如果其他位置存在同名 Agent,会被更高优先级覆盖。

同样的如果名字重复,高优先级的处于优先地位;如果同一位置的agent重复,越早定义的处于优先地位

6.2 设置

  1. 文件格式

子agent在 YAML 前置元数据中定义,后面跟着 Markdown 格式的系统提示

---
name: your-sub-agent-name
description: Description of when this subagent should be invoked
tools: tool1, tool2, tool3  # Optional - inherits all tools if omitted
disallowedTools: tool4  # Optional - explicitly disallowed tools
model: sonnet  # Optional - sonnet, opus, haiku, or inherit
permissionMode: default  # Optional - permission mode
maxTurns: 20  # Optional - limit agentic turns
skills: skill1, skill2  # Optional - skills to preload into context
mcpServers: server1  # Optional - MCP servers to make available
memory: user  # Optional - persistent memory scope (user, project, local)
background: false  # Optional - run as background task
effort: high  # Optional - reasoning effort (low, medium, high, max)
isolation: worktree  # Optional - git worktree isolation
initialPrompt: "Start by analyzing the codebase"  # Optional - auto-submitted first turn
hooks:  # Optional - component-scoped hooks
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/security-check.sh"
---

Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach
to solving problems.
字段 (Field) 必需 说明 示例
name ✅ 是 Agent 唯一标识符,只能使用小写字母和连字符(-)。 python-expert
description ✅ 是 Agent 功能描述。建议包含 “use PROACTIVELY”,让 Claude 更倾向于自动调用该 Agent。 Python code expert. Use PROACTIVELY for code review.
tools ❌ 否 限制 Agent 可使用的工具。省略时继承主会话所有工具。支持 Agent(agent_name) 语法限制可调用的子 Agent。 Read,Edit,Bash
disallowedTools ❌ 否 明确禁止使用的工具,即使主会话拥有这些工具。 Bash
model ❌ 否 指定 Agent 使用的模型。可选 haikusonnetopus、完整模型 ID 或 inherit。默认继承配置。 sonnet
permissionMode ❌ 否 Agent 的权限模式。控制是否自动接受修改、跳过权限确认等。 dontAsk
maxTurns ❌ 否 Agent 最多允许进行的自主推理轮数(Agentic Turns)。达到后自动停止。 10
skills ❌ 否 启动时预加载的 Skills。会把 Skill 内容直接注入 Agent 上下文。 python,testing
mcpServers ❌ 否 指定 Agent 可访问的 MCP(Model Context Protocol)服务器。 filesystem,github
hooks ❌ 否 为该 Agent 配置专属 Hook。可在工具调用前后或结束时执行逻辑。 PreToolUse,PostToolUse
memory ❌ 否 指定 Agent 使用的记忆范围。 project
background ❌ 否 设置为 true 时,该 Agent 默认作为后台任务运行。 true
effort ❌ 否 推理深度等级。可选:lowmediumhighmax high
isolation ❌ 否 设置为 worktree 时,为 Agent 创建独立 Git Worktree,避免影响主工作区。 worktree
initialPrompt ❌ 否 当该 Agent 作为主 Agent 运行时,自动提交的第一条提示词。 "Analyze the repository structure"
  1. CLI-based 设置

自定义单会话的子代理,通过 --agents 参数传入 JSON 格式定义,常见的格式有

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

然后使用claude --agents xxx.json

6.2 内置的subagents

新版本的Claude code包含了一些内置的subagent

Agent Model Purpose
general-purpose Inherits 复杂、多步骤任务处理(规划 + 执行 + 综合分析)
Plan Inherits Plan mode 专用,用于研究、拆解任务并生成执行计划
Explore Haiku 代码库探索(只读),支持快速 / 中等 / 深度三种探索模式
statusline-setup Sonnet 配置 Claude Code 的 status line(状态栏)
Claude Code Guide Haiku 解答 Claude Code 功能、用法相关问题

Inherits 指默认继承主会话配置的模型,不同的subagent有不同的Tools调用,为了完成不同的目的

6.3 文件直接管理agents

1 .创建agents

比如在当前项目的中创建agents,直接创建md文档即可

# Create a project subagent
mkdir -p .claude/agents
cat > .claude/agents/test-runner.md << 'EOF'
---
name: test-runner
description: Use proactively to run tests and fix failures
---

You are a test automation expert. When you see code changes, proactively
run the appropriate tests. If tests fail, analyze the failures and fix
them while preserving the original test intent.
EOF

# Create a user subagent (available in all projects)
mkdir -p ~/.claude/agents
  1. 使用Subagents

自动委托

  • 在请求中描述的任务
  • 子代理配置中的描述字段
  • 当前情况和可用工具

为了鼓励积极使用,请在description里面使用use PROACTIVELY或者必须使用

---
name: code-reviewer
description: Expert code review specialist. Use PROACTIVELY after writing or modifying code.
---
  1. 显式调用

可以明确指定某个子代理

> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error

Claude 现在找 agent 的时候“更聪明了”,不会因为大小写或分隔符不同而找错 agent

  1. @-Mention调用

使用@前缀去准确调用subagent,从而绕过系统的“自动选择 agent 的规则”

> @"code-reviewer (agent)" review the auth module
  1. 会话范围Agent

使用特定代理作为主代理运行整个会话,相当于使用某个agent启动claude

# Via CLI flag
claude --agent code-reviewer

# Via settings.json
{
  "agent": "code-reviewer"
}

cc learn agent

这里的code-reviewerecc项目中的subagent,它默认调用了,不用太纠结后续介绍

  1. 交互式Agents界面

新版本中使用claude agents会进行交互界面,而不是单纯的列出来agents

  1. 多个subagent切换

可以同一句话中分配不同的agents

> First use the code-analyzer subagent to find performance issues,
  then use the optimizer subagent to fix them

6.4 Subagents 细节设定

  1. Memory文件

memory字段为subagents提供了一个跨对话持久存在的目录。这使得subagents能够随着时间的推移积累知识,存储笔记、发现和上下文信息,这些信息在会话之间得以保留

Scope Directory Use Case
user ~/.claude/agent-memory/<name>/ Personal notes and preferences across all projects
project .claude/agent-memory/<name>/ Project-specific knowledge shared with the team
local .claude/agent-memory-local/<name>/ Local project knowledge not committed to version control
  • 内存目录中的 MEMORY.md 文件的前 200 行会自动加载到子代理的系统提示符中
  • subagent会自动启用读取、写入和编辑工具,以便管理其内存文件
  • 子代理可以根据需要在其内存目录中创建其他文件。
---
name: researcher
memory: user
---

You are a research assistant. Use your memory directory to store findings,
track progress across sessions, and build up knowledge over time.

Check your MEMORY.md file at the start of each session to recall previous context.

cc memory agent

  1. Background Subagents

subagent 可以在后台运行,让主对话可以用于其他任务。

---
name: long-runner
background: true
description: Performs long-running analysis tasks in the background
---
  • Ctrl+B:背后运行当前正在运行的子代理任务
  • Ctrl+F:消灭所有后台代理(按两次确认)

设置环境变量以完全禁用后台任务支持,同样也是在bash中运行export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

  1. worktree isolation

为不同任务、Agent 或功能分支创建独立的 Git Worktree,使它们拥有各自隔离的文件系统工作目录,避免互相影响

---
name: feature-builder
isolation: worktree
description: Implements features in an isolated git worktree
tools: Read, Write, Edit, Bash, Grep, Glob
---

worktree cc

  • 子代理在其独立的 Git 工作树中运行,位于单独的分支上
  • 如果子代理不做任何更改,工作树将自动清理
  1. Forked Subagents

分叉的subagents(context: fork)在分叉的一刻继承父代理的完整对话上下文,而不是干净的状态.这种方式是为了不丢失当前的会话

设置CLAUDE_CODE_FORK_SUBAGENT=1能够确保forking

---
name: alternative-explorer
description: Explore an alternative implementation path while preserving parent context
context: fork
tools: Read, Edit, Bash, Grep, Glob
---

You are a forked subagent. You inherit the parent's full conversation and
may explore an alternative approach. Return your findings and the parent
will decide whether to adopt them.
  1. Restrict Spawnable Subagents

你可以在 tools 字段中使用 Agent(agent_type) 语法,来控制某个子代理允许创建(spawn)哪些其他子代理。这相当于为代理委派(delegation)建立一个白名单(allowlist)机制。

---
name: coordinator
description: Coordinates work between specialized agents
tools: Agent(worker, researcher), Read, Bash
---

You are a coordinator agent. You can delegate work to the "worker" and
"researcher" subagents only. Use Read and Bash for your own exploration.

在这个例子中,coordinatorsubagent仅仅能够生成workerresearcher两个子代理,它无法生成任何其他子代理,即使这些子代理在其他地方已定义

6.5 Agent Teams

Agent Teams团队协调多个 Claude Code 实例共同完成复杂任务。不像subagents,team各自独立工作,并有自己单独的上下文窗口,能够通过mailbox系统分享信息

注记

传统的Claude Code Agent大多数情况是

   Main
  /  |  \
 A   B   C

而mailbox system是相互沟通的

A ←→ B ↑ ↓ C ←→ D

方面(Aspect) Subagents(子代理) Agent Teams(代理团队)
委派模型(Delegation Model) 父 Agent 将子任务委派给 Subagent,并等待结果返回 Team Lead(团队负责人)协调工作,队友 Agent 独立执行任务
上下文(Context) 每个子任务获得全新的上下文,完成后将结果提炼并返回给父 Agent 每个队友 Agent 维护自己的持久上下文窗口(Persistent Context Window)
协调方式(Coordination) 由父 Agent 管理,可串行或并行执行 共享任务列表(Shared Task List),自动管理任务依赖关系
通信方式(Communication) 结果只能返回给父 Agent,不支持 Agent 间直接通信 队友 Agent 可通过共享邮箱(Mailbox)直接互相发送消息
会话恢复(Session Resumption) 支持恢复会话 不支持恢复使用进程内队友(In-Process Teammates)的会话
适用场景(Best For) 聚焦、边界明确的独立子任务 需要 Agent 间协作沟通和大规模并行执行的复杂工作
  1. 设置Agent Teams

临时或者永久的修改环境变量来启动Agent Teams

export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

或者在settings.json中

{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  }
}
  1. 开启team

在claude code中输入

User: Build the authentication module. Use a team — one teammate for the API endpoints,
      one for the database schema, and one for the test suite.

Claude 会自动创建团队、分配任务并协调工作。

  1. 显示模式

控制团队活动的显示模式

模式 参数 说明
Auto(自动) --teammate-mode auto 根据当前终端环境自动选择最合适的显示模式
In-process(默认) --teammate-mode in-process 在当前终端内联显示 Teammate 的输出
Split-panes(分屏) --teammate-mode tmux 为每个 Teammate 打开独立的 tmux 或 iTerm2 窗格

claude --teammate-mode tmux

同样的也可以在setting.json中进行设置,team的设置在~/.claude/teams/{team-name}/config.json

{
  "teammateMode": "tmux"
}

注意:分屏模式需要 tmux 或 iTerm2。VS Code 终端、Windows Terminal 或 Ghostty 不支持此功能

  1. 架构

claude code team

  • 团队负责人:Claude Code 的主要会话,负责创建团队、分配任务和协调工作
  • 共享任务列表:具有自动依赖关系跟踪功能的同步任务列表
  • 邮箱:一个供团队成员沟通状态和协调的代理间消息系统
  • Teammates: 独立的 Claude Code 实例,每个实例都有自己的上下文窗口
  1. 在任务开始前使用/plan进行计划
  2. Agent Teams使用Hook events
  1. Team 适合的Hook
TeammateIdle
项目 内容
Event TeammateIdle
Fires When A teammate finishes its current task and has no pending work
中文 某个 Teammate 完成当前任务后,暂时无事可做
TaskCompleted
项目 内容
Event TaskCompleted
Fires When A task in the shared task list is marked complete
中文 共享任务列表中的某项任务被标记完成
提示

使用Agent Team需要注意的点:

  • 团队规模:为达到最佳协调效果,团队人数应保持在 3-5 人之间。
  • 任务规模:将工作分解成每个耗时 5-15 分钟的小任务——既要足够小以便并行处理,又要足够大以确保工作的意义。
  • 避免文件冲突:将不同的文件或目录分配给不同的团队成员,以防止合并冲突。
  • 先从简单的开始:第一个团队使用流程内模式;熟悉之后再切换到分屏模式
  • 清晰的任务描述:提供具体、可操作的任务描述,以便团队成员能够独立完成工作

6.6 实际操作

  1. 系统提示词练习
  1. 明确角色
You are an expert code reviewer specializing in [specific areas]
  1. 明确优先事项
Review priorities (in order):
1. Security Issues
2. Performance Problems
3. Code Quality
  1. 指定输出格式
For each issue provide: Severity, Category, Location, Description, Fix, Impact
  1. 包含行动步骤
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
  1. 工具使用策略
  • 限制性起始:一开始只使用必要的工具
  • 仅在需要时扩展:根据需求添加工具
  • 尽可能使用只读模式:对分析代理使用 Read/Grep 命令。
  • 沙盒执行:限制 Bash 命令为特定模式

7. MCP(Model Context Protocol)

MCP(模型上下文协议)是 Claude 访问外部工具、API 和实时数据源的标准化方式。与memory不同,MCP 提供对动态数据的实时访问。

  • 实时访问外部服务
  • 实时数据同步
  • 可扩展架构
  • 安全认证
  • 基于工具的交互

MCP 是一套标准协议,用来规定 AI 如何发现工具、调用工具,以及工具如何返回结果。

7.1 MCP架构和生态

架构

claude code mcp

MCP 生态

claude code mcp02

  • 文件系统
  • Github
  • Database数据库
  • Slack
  • Google文档

MCP Server本质就是一个“给 AI 用的工具 API 服务”,它可以运行在任何地方.可以在本地MCP Server,也可以在远程服务器上运行MCP Server.

7.2 MCP安装方法(注册)

Claude Code 支持多种 MCP 服务器连接的传输协议:

  1. HTTP 传输(推荐)
# Basic HTTP connection
claude mcp add --transport http notion https://mcp.notion.com/mcp

# HTTP with authentication header
claude mcp add --transport http secure-api https://api.example.com/mcp --header "Authorization: Bearer your-token"

这一步相当于把MCP Server注册到Claude Code中,Claude Code会保存MCP Server的配置信息,比如github提供了token,那么Claude Code就会保存这个token,这样Claude Code就可以使用这个token来访问github提供的github MCP Server.

部分 含义
claude mcp add 添加一个 MCP Server
--transport http 使用 HTTP 方式连接
secure-api 给这个 MCP Server 起的名字
https://api.example.com/mcp MCP Server 地址
--header 额外添加 HTTP 请求头
Authorization: Bearer your-token 身份认证 Token

Header 是由于很多 MCP Server 需要身份认证,所以需要添加 Header 信息

而Claude Code实际会保存:

{
  "mcpServers": {
    "secure-api": {
      "transport": "http",
      "url": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer your-token"
      }
    }
  }
}

本质上MCP是:需要远端/本地启动一个 GitHub MCP Server,然后在 Claude Code 里注册它。claude mcp add 做的不是“运行服务”,而是:注册一个“如何启动 MCP server 的方式”

  1. 在bash终端中输入这个命令claude mcp add --transport http github https://api.githubcopilot.com/mcp;你也可以在终端输入claude mcp list查看是否在claude中添加成功

  2. 在github中create新的Token,Settings → Developer settings → Personal access tokens,加入描述,名称等创建即可

mcp github

注记

GitHub 现在更推荐 Fine-grained Personal Access Token,因为它可以只允许访问某几个 Repository,可以只给 Read 或 Read/Write和比 Classic Token 更安全

当选择给claude code可以操作哪个仓库之后,进行权限的选择:

github mcp

创建好之后记得保存好Tokengithub_pat_xxxxxx

  1. claude code终端中输入/mcp进行MCP设定github token

github mcp

选择github认证,有的GitHub Copilot MCP 不支持 Dynamic Client Registration,所以认证直接失败。Claude 官方文档也说明了:对于不支持 DCR 的 MCP Server,需要使用预先配置好的 OAuth Client,或者其他认证方式,而不是自动注册

github mcp

GitHub 官方 Remote MCP 推荐的是使用 GitHub Personal Access Token (PAT) 放到 Authorization Header 中,而不是直接依赖 OAuth 登录

  1. 先取消刚刚添加的配置 claude mcp remove github
  2. 再添加配置 claude mcp add --transport http github https://api.githubcopilot.com/mcp --header "Authorization: Bearer github_pat_xxxx"
部分 含义
Authorization HTTP 请求头名称,表示认证信息
Bearer 认证方式,表示后面跟着的是一个 Bearer Token
YOUR_GITHUB_PAT 你的 GitHub Personal Access Token,需要替换成真实的 Token
提示

最方便的就是食用AI 直接告诉它,你要安装什么MCP,安装的Token是什么,上面的方式主要是为了了解MCP注册的底层

  1. Stdio Transport(Local)

在 MCP 中,Stdio(Standard Input/Output)Transport 是最常见的本地通信方式;换种说法就是如果 AI(客户端)要和一个“本地 MCP Server”通信,最常用的一种方式是——通过标准输入/输出流(stdin/stdout)来传数据

方式 stdio HTTP
是否需要端口 ❌ 不需要 ✅ 需要
是否网络通信 ❌ 本地进程 ✅ 网络/本地
启动方式 子进程 独立服务
常见场景 本地 MCP server 远程 MCP server
# Local Node.js server
claude mcp add --transport stdio myserver -- npx @myorg/mcp-server

# With environment variables
claude mcp add --transport stdio myserver --env KEY=value -- npx server
部分 含义
claude mcp add 添加一个 MCP Server
–transport stdio 使用 stdin/stdout 通信
myserver 给这个 Server 起的名字
后面开始是真正启动 Server 的命令
npx @myorg/mcp-server 启动 MCP Server
–env KEY=value 启动 Server 时传递的环境变量

上面的命令等价于: Claude Code:以后要用 myserver,就帮我启动这个进程:npx @myorg/mcp-server; 启动 MCP server 进程时顺便设置环境变量 KEY=value

这里使用本地安装github,需要注意名称问题,防止与http冲突

claude mcp add --transport stdio github-local --env GITHUB_TOKEN=github_xxxxx -- npx @modelcontextprotocol/server-github

Claude 启动 stdio MCP Server 时,会自动注入一个环境变量: CLAUDE_PROJECT_DIR=/Users/wu/project/my-app 这个值就是当前项目根目录的绝对路径

调用本地文件的情况:

{
  "mcpServers": {
    "repo-tools": {
      "type": "stdio",
      "command": "node",
      "args": ["${CLAUDE_PROJECT_DIR}/.claude/mcp/repo-tools.js"],
      "env": {
        "REPO_ROOT": "${CLAUDE_PROJECT_DIR}"
      }
    }
  }
}

Claude 启动一个名叫 repo-tools 的本地 MCP Server,执行项目目录下 .claude/mcp/repo-tools.js 文件,并把当前项目根目录通过环境变量 REPO_ROOT 传给它。

这样写的话,无论你换了哪台电脑,哪个环境都能准确的找到项目

项目 npx / 本地 Stdio HTTP
需要 Node.js
需要启动进程
运行在本机
运行在服务器
延迟 较低 网络延迟
部署难度 简单 较复杂
多人共享 不方便 非常方便
适合 个人工具 企业服务
  1. SSE Transport

服务器发送事件 (Server-Sent Events) 传输方式已被弃用,取而代之的是 HTTP 传输方式,但仍然受支持

claude mcp add --transport sse legacy-server https://example.com/sse
  1. Windows特殊情况

“Windows-Specific Note” 一般出现在 MCP / Node / CLI 工具文档里,它的意思很简单: > 只针对 Windows 系统的特殊情况或额外注意事项

claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package
  1. OAuth 2.0 Authentication

MCP Server 通过 OAuth 2.0 机制,让 Claude(或 MCP Client)安全地“登录并授权”外部服务(GitHub / Google / Notion 等),而不需要直接提供账号密码或长期 API key

# Connect to an OAuth-enabled MCP server (interactive flow)
claude mcp add --transport http my-service https://my-service.example.com/mcp

# Pre-configure OAuth credentials for non-interactive setup
claude mcp add --transport http my-service https://my-service.example.com/mcp \
  --client-id "your-client-id" \
  --client-secret "your-client-secret" \
  --callback-port 8080

整体流程

① 用户运行 /mcp
② Claude 发现需要 OAuth
③ 打开浏览器登录
④ 用户授权
⑤ MCP 接收 callback + 换 token
⑥ token 安全存储 + 后续自动使用
功能 描述
Interactive OAuth(交互式 OAuth) 使用 /mcp 命令触发基于浏览器的 OAuth 授权流程。
Pre-configured OAuth Clients(预配置 OAuth 客户端) 内置常见服务的 OAuth 客户端配置,例如 :contentReferenceoaicite:0、:contentReferenceoaicite:1 等(v2.1.30+)。
Pre-configured Credentials(预配置凭据) 支持通过 --client-id--client-secret--callback-port 参数自动完成 OAuth 客户端配置。
Token Storage(令牌存储) OAuth Token 会安全地存储在操作系统的 Keychain(密钥链)或凭据管理器中。
Step-up Authentication(权限升级认证) 支持在执行高权限或敏感操作时触发额外身份验证。
Discovery Caching(发现信息缓存) OAuth Discovery Metadata(发现元数据)会被缓存,以提高后续连接和认证速度。
Metadata Override(元数据覆盖) 可在 .mcp.json 中通过 oauth.authServerMetadataUrl 指定 OAuth 元数据地址,覆盖默认的 OAuth Metadata Discovery 机制。
  1. Claude.ai MCP Connectors

在 Claude.ai 账户中配置的 MCP 服务器会自动在 Claude Code 中可用。这意味着您通过 Claude.ai Web 界面设置的任何 MCP 连接都无需​​额外配置即可访问

项目 Claude.ai MCP Connectors Claude Code MCP
本质 Claude.ai 里的「连接器」功能 Claude Code 里的 MCP 功能
面向用户 普通用户、企业用户 开发者
配置位置 Claude.ai 网页设置页 本地 .mcp.jsonclaude mcp add
MCP Server 类型 主要是远程 MCP(Remote MCP) 本地 MCP + 远程 MCP
使用方式 点按钮连接 命令行配置
运行环境 Claude Web、Mobile Claude Code CLI
典型场景 Notion、Slack、Google Drive GitHub、数据库、本地脚本、终端工具
权限 Claude.ai 管理 本机完全控制
技术门槛

Claude.ai MCP Connectors 是 MCP 的一种产品化形态

7.3 MCP 设置流程

MCP setting

/MCP命令
在会话中输入 /mcp 可以列出已连接的服务器、触发 OAuth 流程并检查连接状态

MCP setting

  1. MCP Tool Search

当 MCP 工具描述超过上下文窗口的 10% 时,Claude Code 会自动启用工具搜索,以便高效地选择合适的工具,而不会使模型上下文过于庞大

设置值 含义 工作方式 适用场景
ENABLE_TOOL_SEARCH=auto(默认) 自动启用 Tool Search 当工具描述占用上下文超过默认阈值(通常为约 10%)时自动开启 大多数用户,推荐使用
ENABLE_TOOL_SEARCH=auto:<N> 自定义自动启用阈值 当达到指定阈值 N 时自动开启 Tool Search(具体含义取决于版本实现) 需要精细控制工具检索行为
ENABLE_TOOL_SEARCH=true 始终启用 Tool Search 每次先检索相关工具,再将匹配工具发送给模型 工具数量很多(数十到数百个 MCP Tools)
ENABLE_TOOL_SEARCH=false 禁用 Tool Search 每次都将所有工具定义完整发送给模型 工具数量较少,希望模型始终看到全部工具

从 Claude Code v2.1.121 开始,可以在某个 MCP Server 的配置中添加:

  1. 自动load开启
{
  "mcpServers": {
    "notion": {
      "command": "npx",
      "args": ["@notionhq/notion-mcp"],
      "alwaysLoad": true
    }
  }
}
注记

不进行Tool Search,而是加在所有的MCP Server工具,这个是针对某些工具几乎每轮都可以用到

这个 MCP Server 不参与 Tool Search,启动后其所有工具始终加载到 Claude 上下文中,每轮对话都可直接调用

  1. 动态工具更新

当同一个 MCP 服务器在多个作用域(本地、项目、用户)中定义时,本地配置优先。这样,您就可以使用本地自定义设置覆盖项目级或用户级的 MCP 设置,而不会发生冲突。

类型 作用 Claude Code 中表现
Tools 执行动作 AI 自动调用
Resources 提供数据 AI 读取资源
Prompts 预定义提示模板 Slash Command(斜杠命令)

例如

GitHub MCP

Tools:
  create_pr
  list_issues

Resources:
  repository_info

Prompts:
  review
  explain_pr

MCP 服务器可以公开提示符,这些提示符在 Claude 代码中显示为斜杠命令。

  1. MCP 资源通过 @ 提及

以使用 @提及语法在提示中直接引用 MCP 资源。

@server-name:protocol://resource/path

Claude 就可以获取 MCP 资源内容并将其作为对话上下文的一部分内联包含

7.4 MCP Scopes和常规管理

  1. MCP层级

MCP 配置可以存储在不同的范围内,并具有不同的共享级别:

Scope(范围) 存储位置 含义 共享范围 是否需要审批
Local(默认) ~/.claude.json(在项目路径下) 仅对当前用户 + 当前项目生效(旧版本叫 project scope) 只有你自己 ❌ 不需要
Project .mcp.json(项目仓库文件) 写入 Git 仓库,团队共享配置 所有项目成员 ✅ 需要(首次使用时)
User ~/.claude.json 全局用户级配置,所有项目都可用(旧版本叫 global scope) 只有你自己 ❌ 不需要

.mcp.json中常见的配置项

{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.github.com/mcp"
    }
  }
}
  1. MCP设置管理
# 添加HTTP-base的server
claude mcp add --transport http github https://api.github.com/mcp

# 添加本地local stdio server
claude mcp add --transport stdio database -- npx @company/db-server

# 列出MCP 服务器列表
claude mcp list

# 查看mcp server的详细信息
claude mcp get github

# 移除mcp server
claude mcp remove github

# Authenticate an MCP server from the CLI (v2.1.186+)
claude mcp login github

# Sign out of an MCP server (v2.1.186+)
claude mcp logout github

# Import from Claude Desktop
claude mcp add-from-claude-desktop

claude mcp login claude mcp logout /mcp菜单中 OAuth 流程的非交互式版本——无需打开菜单即可进行身份验证或注销。在登录命令中添加–no-browser` 参数,即可通过 SSH 或在无头会话中完成 OAuth 认证(它会将流程重定向到标准输入)

  1. 常规的MCP
MCP Server 主要用途 常见工具(Tools) 认证方式 是否支持实时操作
Filesystem(文件系统) 文件和目录操作 readwritedelete 操作系统文件权限 ✅ 是
GitHub 仓库与代码管理 list_prscreate_issuepush OAuth / Personal Access Token(PAT) ✅ 是
Slack 团队沟通与消息管理 send_messagelist_channels Access Token ✅ 是
Database(数据库) SQL 数据库操作 queryinsertupdate 数据库账号密码或凭据 ✅ 是
Google Docs 文档读取与协作 readwriteshare OAuth ✅ 是
Asana 项目与任务管理 create_taskupdate_status API Key 或 OAuth ✅ 是
Stripe 支付与账单管理 list_chargescreate_invoice API Key ✅ 是
Memory 持久化记忆管理 storeretrievedelete 本地存储 ❌ 否(非实时外部服务)
  • 主要用途(Purpose):MCP Server 所连接的外部系统或服务
  • 常见工具(Common Tools):该 MCP Server 通常暴露给 AI 调用的工具(Tool)示例
  • 认证方式(Auth):连接对应服务时所采用的身份验证方式
  • 是否支持实时操作(Real-time)
    • :能够实时访问或修改外部服务的数据
    • :主要操作本地数据或持久化存储,不直接与在线服务实时交互

7.5 练习例子

  1. GitHub MCP Configuratio项目本地配置

在project中创建.mcp.json,把下面内容写入

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

在之前~/.zshrc!/.bashrc中加入export GITHUB_TOKEN="github_pat_xxxxx",这样就可以在项目本地使用github mcp

github mcp

claude code 输入/mcp,查看当前MCP Server,找到github mcp,就可以看到tools可食用的内容,在当前版本(v2.1.181)中,是在command中输入命令,例如create_pull_request相当于create_pr,在旧版本中是输入

/mcp__github__get_pr 456

# Returns:
Title: Add dark mode support
Author: @alice
Description: Implements dark theme using CSS variables
Status: OPEN
Reviewers: @bob, @charlie

github mcp command

Claude Code(以及很多支持 MCP 配置的程序) 的一种环境变量展开(Environment Variable Expansion)功能

配置文件里不用写死内容,而是在程序启动时自动从操作系统的环境变量中读取,可以理解成一种变量替换

注记

假设配置是

{
  "command": "${MCP_BIN_PATH}"
}

程序启动时会去系统里面找MCP_BIN_PATH,如果环境变量是Linux/macOS中有export MCP_BIN_PATH=npx

  1. 第一种写法 ${VAR}
${VAR}
Uses environment variable,
error if not set

就是系统中参数必须存在,如果不存在就会报错

  1. 第二种写法 ${VAR:-default}
{
  "mcpServers": {
    "api-server": {
      "type": "http",
      "url": "${API_BASE_URL:-https://api.example.com}/mcp",
      "headers": {
        "Authorization": "Bearer ${API_KEY}",
        "X-Custom-Header": "${CUSTOM_HEADER:-default-value}"
      }
    },
    "local-server": {
      "command": "${MCP_BIN_PATH:-npx}",
      "args": ["${MCP_PACKAGE:-@company/mcp-server}"],
      "env": {
        "DB_URL": "${DATABASE_URL:-postgresql://localhost/dev}"
      }
    }
  }
}
  1. Database MCP Setup
{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-database"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/mydb"
      }
    }
  }
}

数据库MCP的使用和连接

  你的 Claude Code
        |
        | npx 运行

  server-postgres (桥接器)  ← 需要 Node.js
        |
        | 通过 DATABASE_URL 连接

  PostgreSQL 数据库  ← 远程就不用装,本地玩就得装
  1. 多重MCP 工作流程
# Daily Report Workflow using Multiple MCPs

## Setup
1. GitHub MCP - fetch PR metrics
2. Database MCP - query sales data
3. Slack MCP - post report
4. Filesystem MCP - save report

## Workflow

### Step 1: Fetch GitHub Data
/mcp__github__list_prs completed:true last:7days

Output:
- Total PRs: 42
- Average merge time: 2.3 hours
- Review turnaround: 1.1 hours

### Step 2: Query Database
SELECT COUNT(*) as sales, SUM(amount) as revenue
FROM orders
WHERE created_at > NOW() - INTERVAL '1 day'

Output:
- Sales: 247
- Revenue: $12,450

### Step 3: Generate Report
Combine data into HTML report

### Step 4: Save to Filesystem
Write report.html to /reports/

### Step 5: Post to Slack
Send summary to #daily-reports channel

Final Output:
✅ Report generated and posted
📊 47 PRs merged this week
💰 $12,450 in daily sales

github mcp database

7.6 MCP 高级应用

  1. Claude Code作为MCP Server

Claude Code 本身可以作为其他应用程序的 MCP 服务器。这使得外部工具、编辑器和自动化系统能够通过标准的 MCP 协议利用 Claude 的功能。

# Start Claude Code as an MCP server on stdio
claude mcp serve

其他应用程序可以像连接任何基于标准 I/O 的 MCP 服务器一样连接到此服务器。例如,要将 Claude Code 添加为另一个 Claude Code 实例中的 MCP 服务器

claude mcp add --transport stdio claude-agent -- claude mcp serve
  1. 托管 MCP 配置(企业版)

对于企业部署,IT 管理员可以通过 managed-mcp.json 配置文件强制执行 MCP 服务器策略。该文件提供对组织范围内允许或阻止哪些 MCP 服务器的完全控制

位置:

  • macOS: /Library/Application Support/ClaudeCode/managed-mcp.json
  • Linux: ~/.config/ClaudeCode/managed-mcp.json
  • Windows: %APPDATA%\ClaudeCode\managed-mcp.json

在设置中,可以启用或禁用 MCP 服务器,并指定哪些用户或组可以访问它们。

{
  "allowedMcpServers": [
    {
      "serverName": "github",
      "serverUrl": "https://api.github.com/mcp"
    },
    {
      "serverName": "company-internal",
      "serverCommand": "company-mcp-server"
    }
  ],
  "deniedMcpServers": [
    {
      "serverName": "untrusted-*"
    },
    {
      "serverUrl": "http://*"
    }
  ]
}
  1. Plugin-Provided MCP Servers

插件可以捆绑自己的 MCP 服务器,使其在插件安装时自动可用。插件提供的 MCP 服务器可以通过两种方式定义。

  • Standalone .mcp.json – Place a .mcp.json file in the plugin root directory
  • Inline in plugin.json – Define MCP servers directly within the plugin manifest

使用 ${CLAUDE_PLUGIN_ROOT} 变量来引用相对于插件安装目录的路径

{
  "mcpServers": {
    "plugin-tools": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp-server.js"],
      "env": {
        "CONFIG_PATH": "${CLAUDE_PLUGIN_ROOT}/config.json"
      }
    }
  }
}
  1. Subagent-Scoped MCP

MCP 服务器可以通过 mcpServers: 键在代理的 frontmatter 中直接定义,从而将其作用域限定于特定的子代理,而不是整个项目。当某个代理需要访问工作流中其他代理不需要的特定 MCP 服务器时,此功能非常有用。

---
mcpServers:
  my-tool:
    type: http
    url: https://my-tool.example.com/mcp
---

You are an agent with access to my-tool for specialized operations.
  1. MCP输出限制

Claude Code 对 MCP 工具返回的数据(tool output)做了“长度限制 + 防爆内存机制”。

阈值类型 数值 行为说明
警告阈值 10,000 tokens 当输出超过 10,000 tokens 时,会提示结果过大(仅警告,不截断)
默认最大限制 25,000 tokens 超过此限制后,输出内容会被截断,超出部分不会进入上下文
磁盘持久化阈值 50,000 characters 当工具结果超过 50,000 字符时,会被持久化到磁盘(而非直接进入内存/上下文)
# Increase the max output to 50,000 tokens
export MAX_MCP_OUTPUT_TOKENS=50000

7.7 利用代码执行解决MCP上下文臃肿问题

随着 MCP 应用规模的扩大,连接到数十台服务器以及数百甚至数千个工具带来了一个重大挑战:上下文膨胀。这可以说是 MCP 大规模应用面临的最大问题,而 Anthropic 的工程团队提出了一种巧妙的解决方案——使用代码执行而非直接调用工具

注记

Anthropic 提出的方案是:

  • 不要让模型直接处理数据
  • 让模型写代码,让代码去调用 MCP

传统方式

Model → MCP tool → 返回大数据 → 再进 context → 再调用另一个 tool

新方式(Code Execution)

code execution

组件 类比
Claude model 项目经理
Sandbox 实验室
MCP tools 外部供应商
Code execution 实验室里的操作员
Context window 会议记录

MCP sandbox 本质是一个“受控执行环境(container/VM/WASM)”,让模型只负责写代码和决策,所有工具调用与数据处理都在隔离环境中执行,从而避免 context overflow 并提升安全性与效率。