Claude 概念完整指南
全面的参考指南,涵盖斜杠命令、子代理、记忆系统、MCP 协议和代理技能,包含表格、图表和实际示例。
目录
斜杠命令
概述
斜杠命令是以 Markdown 文件形式存储的用户调用快捷方式,Claude Code 可以执行这些快捷方式。它们帮助团队标准化常用提示词和工作流。
架构
文件结构
命令组织表
| 位置 | 范围 | 可用性 | 使用场景 | Git 追踪 |
|---|---|---|---|---|
.claude/commands/ | 项目专用 | 团队成员 | 团队工作流,共享规范 | ✅ 是 |
~/.claude/commands/ | 个人 | 单个用户 | 跨项目的个人快捷方式 | ❌ 否 |
| 子目录 | 命名空间 | 基于父级 | 按类别组织 | ✅ 是 |
功能与能力
| 功能 | 示例 | 是否支持 |
|---|---|---|
| Shell 脚本执行 | bash scripts/deploy.sh | ✅ 是 |
| 文件引用 | @path/to/file.js | ✅ 是 |
| Bash 集成 | $(git log --oneline) | ✅ 是 |
| 参数 | /pr --verbose | ✅ 是 |
| MCP 命令 | /mcp__github__list_prs | ✅ 是 |
实际示例
示例 1:代码优化命令
文件: .claude/commands/optimize.md
markdown
---
name: Code Optimization
description: Analyze code for performance issues and suggest optimizations
tags: performance, analysis
---
# 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
3. **Algorithm improvements** - suggest better algorithms or data structures
4. **Caching opportunities** - identify repeated computations
5. **Concurrency issues** - find race conditions or threading problems
Format your response with:
- Issue severity (Critical/High/Medium/Low)
- Location in code
- Explanation
- Recommended fix with code example用法:
bash
# 用户在 Claude Code 中输入
/optimize
# Claude 加载提示词并等待代码输入示例 2:Pull Request 辅助命令
文件: .claude/commands/pr.md
markdown
---
name: Prepare Pull Request
description: Clean up code, stage changes, and prepare a pull request
tags: git, workflow
---
# Pull Request Preparation Checklist
Before creating a PR, execute these steps:
1. Run linting: `prettier --write .`
2. Run tests: `npm test`
3. Review git diff: `git diff HEAD`
4. Stage changes: `git add .`
5. Create commit message following conventional commits:
- `fix:` for bug fixes
- `feat:` for new features
- `docs:` for documentation
- `refactor:` for code restructuring
- `test:` for test additions
- `chore:` for maintenance
6. Generate PR summary including:
- What changed
- Why it changed
- Testing performed
- Potential impacts用法:
bash
/pr
# Claude 执行检查清单并准备 PR示例 3:层级文档生成器
文件: .claude/commands/docs/generate-api-docs.md
markdown
---
name: Generate API Documentation
description: Create comprehensive API documentation from source code
tags: documentation, api
---
# API Documentation Generator
Generate API documentation by:
1. Scanning all files in `/src/api/`
2. Extracting function signatures and JSDoc comments
3. Organizing by endpoint/module
4. Creating markdown with examples
5. Including request/response schemas
6. Adding error documentation
Output format:
- Markdown file in `/docs/api.md`
- Include curl examples for all endpoints
- Add TypeScript types命令生命周期图
最佳实践
| 应该做 ✅ | 不应该做 ❌ |
|---|---|
| 使用清晰、面向动作的命名 | 为一次性任务创建命令 |
| 在描述中记录触发词 | 在命令中构建复杂逻辑 |
| 保持命令专注于单一任务 | 创建冗余命令 |
| 对项目命令进行版本控制 | 硬编码敏感信息 |
| 在子目录中组织 | 创建过长的命令列表 |
| 使用简单易读的提示词 | 使用缩写或神秘的措辞 |
子代理
概述
子代理是具有隔离上下文窗口和自定义系统提示词的专业 AI 助手。它们在保持清晰关注点分离的同时实现委派任务执行。
架构图
子代理生命周期
子代理配置表
| 配置项 | 类型 | 用途 | 示例 |
|---|---|---|---|
name | 字符串 | 代理标识符 | code-reviewer |
description | 字符串 | 用途与触发词 | Comprehensive code quality analysis |
tools | 列表/字符串 | 允许的能力 | read, grep, diff, lint_runner |
system_prompt | Markdown | 行为指令 | 自定义指南 |
工具访问层级
实际示例
示例 1:完整的子代理设置
文件: .claude/agents/code-reviewer.md
yaml
---
name: code-reviewer
description: Comprehensive code quality and maintainability analysis
tools: read, grep, diff, lint_runner
---
# Code Reviewer Agent
You are an expert code reviewer specializing in:
- Performance optimization
- Security vulnerabilities
- Code maintainability
- Testing coverage
- Design patterns
## Review Priorities (in order)
1. **Security Issues** - Authentication, authorization, data exposure
2. **Performance Problems** - O(n²) operations, memory leaks, inefficient queries
3. **Code Quality** - Readability, naming, documentation
4. **Test Coverage** - Missing tests, edge cases
5. **Design Patterns** - SOLID principles, architecture
## Review Output Format
For each issue:
- **Severity**: Critical / High / Medium / Low
- **Category**: Security / Performance / Quality / Testing / Design
- **Location**: File path and line number
- **Issue Description**: What's wrong and why
- **Suggested Fix**: Code example
- **Impact**: How this affects the system
## Example Review
### Issue: N+1 Query Problem
- **Severity**: High
- **Category**: Performance
- **Location**: src/user-service.ts:45
- **Issue**: Loop executes database query in each iteration
- **Fix**: Use JOIN or batch query文件: .claude/agents/test-engineer.md
yaml
---
name: test-engineer
description: Test strategy, coverage analysis, and automated testing
tools: read, write, bash, grep
---
# Test Engineer Agent
You are expert at:
- Writing comprehensive test suites
- Ensuring high code coverage (>80%)
- Testing edge cases and error scenarios
- Performance benchmarking
- Integration testing
## Testing Strategy
1. **Unit Tests** - Individual functions/methods
2. **Integration Tests** - Component interactions
3. **End-to-End Tests** - Complete workflows
4. **Edge Cases** - Boundary conditions
5. **Error Scenarios** - Failure handling
## Test Output Requirements
- Use Jest for JavaScript/TypeScript
- Include setup/teardown for each test
- Mock external dependencies
- Document test purpose
- Include performance assertions when relevant
## Coverage Requirements
- Minimum 80% code coverage
- 100% for critical paths
- Report missing coverage areas文件: .claude/agents/documentation-writer.md
yaml
---
name: documentation-writer
description: Technical documentation, API docs, and user guides
tools: read, write, grep
---
# Documentation Writer Agent
You create:
- API documentation with examples
- User guides and tutorials
- Architecture documentation
- Changelog entries
- Code comment improvements
## Documentation Standards
1. **Clarity** - Use simple, clear language
2. **Examples** - Include practical code examples
3. **Completeness** - Cover all parameters and returns
4. **Structure** - Use consistent formatting
5. **Accuracy** - Verify against actual code
## Documentation Sections
### For APIs
- Description
- Parameters (with types)
- Returns (with types)
- Throws (possible errors)
- Examples (curl, JavaScript, Python)
- Related endpoints
### For Features
- Overview
- Prerequisites
- Step-by-step instructions
- Expected outcomes
- Troubleshooting
- Related topics示例 2:实际的子代理委派
markdown
# 场景:构建支付功能
## 用户请求
"构建一个与 Stripe 集成的安全支付处理功能"
## 主代理流程
1. **计划阶段**
- 理解需求
- 确定所需任务
- 规划架构
2. **委派给代码审查员子代理**
- 任务:"审查支付处理实现的安全性"
- 上下文:认证、API 密钥、令牌处理
- 审查内容:SQL 注入、密钥暴露、HTTPS 强制
3. **委派给测试工程师子代理**
- 任务:"为支付流程创建全面测试"
- 上下文:成功场景、失败、边缘情况
- 创建测试:有效支付、拒绝卡、网络故障、Webhook
4. **委派给文档编写员子代理**
- 任务:"记录支付 API 端点"
- 上下文:请求/响应模式
- 产出:带 curl 示例的 API 文档、错误代码
5. **综合**
- 主代理收集所有输出
- 整合发现
- 向用户返回完整解决方案示例 3:工具权限范围
限制性设置 — 仅限特定命令
yaml
---
name: secure-reviewer
description: Security-focused code review with minimal permissions
tools: read, grep
---
# Secure Code Reviewer
Reviews code for security vulnerabilities only.
This agent:
- ✅ Reads files to analyze
- ✅ Searches for patterns
- ❌ Cannot execute code
- ❌ Cannot modify files
- ❌ Cannot run tests
This ensures the reviewer doesn't accidentally break anything.扩展设置 — 所有工具用于实现
yaml
---
name: implementation-agent
description: Full implementation capabilities for feature development
tools: read, write, bash, grep, edit, glob
---
# Implementation Agent
Builds features from specifications.
This agent:
- ✅ Reads specifications
- ✅ Writes new code files
- ✅ Runs build commands
- ✅ Searches codebase
- ✅ Edits existing files
- ✅ Finds files matching patterns
Full capabilities for independent feature development.子代理上下文管理
何时使用子代理
| 场景 | 使用子代理 | 原因 |
|---|---|---|
| 步骤众多的复杂功能 | ✅ 是 | 分离关注点,防止上下文污染 |
| 快速代码审查 | ❌ 否 | 不必要的开销 |
| 并行任务执行 | ✅ 是 | 每个子代理有自己的上下文 |
| 需要专业能力 | ✅ 是 | 自定义系统提示词 |
| 长时间运行的分析 | ✅ 是 | 防止主上下文耗尽 |
| 单一任务 | ❌ 否 | 不必要地增加延迟 |
代理团队
代理团队协调多个代理共同处理相关任务。与一次委派给一个子代理不同,代理团队允许主代理编排一组代理,这些代理可以协作、共享中间结果,朝着共同目标努力。这对于大规模任务非常有用,例如全栈功能开发,其中前端代理、后端代理和测试代理并行工作。
记忆系统
概述
记忆系统使 Claude 能够跨会话和对话保留上下文。它以两种形式存在:claude.ai 中的自动综合,以及 Claude Code 中基于文件系统的 CLAUDE.md。
记忆架构
Claude Code 中的记忆层级(7 层)
Claude Code 从 7 个层级加载记忆,按优先级从高到低排列:
记忆位置表
| 层级 | 位置 | 范围 | 优先级 | 共享 | 最适合 |
|---|---|---|---|---|---|
| 1. 托管策略 | 企业管理员 | 组织 | 最高 | 所有组织用户 | 合规、安全策略 |
| 2. 项目 | ./CLAUDE.md | 项目 | 高 | 团队(Git) | 团队规范、架构 |
| 3. 项目规则 | .claude/rules/*.md | 项目 | 高 | 团队(Git) | 模块化项目约定 |
| 4. 用户 | ~/.claude/CLAUDE.md | 个人 | 中 | 个人 | 个人偏好 |
| 5. 用户规则 | ~/.claude/rules/*.md | 个人 | 中 | 个人 | 个人规则模块 |
| 6. 本地 | .claude/local/CLAUDE.md | 本地 | 低 | 不共享 | 机器特定设置 |
| 7. 自动记忆 | 自动 | 会话 | 最低 | 个人 | 学习到的偏好、模式 |
自动记忆
自动记忆自动捕获在会话期间观察到的用户偏好和模式。Claude 从你的交互中学习并记住:
- 代码风格偏好
- 你经常做出的修正
- 框架和工具选择
- 沟通风格偏好
自动记忆在后台工作,无需手动配置。
记忆更新生命周期
实际示例
示例 1:项目记忆结构
文件: ./CLAUDE.md
markdown
# 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`示例 2:目录专用记忆
文件: ./src/api/CLAUDE.md
markdown
# API Module Standards
This file overrides root CLAUDE.md for everything in /src/api/
## API-Specific Standards
### Request Validation
- Use Zod for schema validation
- Always validate input
- Return 400 with validation errors
- Include field-level error details
### Authentication
- All endpoints require JWT token
- Token in Authorization header
- Token expires after 24 hours
- Implement refresh token mechanism
### Response Format
All responses must follow this structure:
```json
{
"success": true,
"data": { /* actual data */ },
"timestamp": "2025-11-06T10:30:00Z",
"version": "1.0"
}
```
### Error responses:
```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "User message",
"details": { /* field errors */ }
},
"timestamp": "2025-11-06T10:30:00Z"
}
```
### Pagination
- Use cursor-based pagination (not offset)
- Include `hasMore` boolean
- Limit max page size to 100
- Default page size: 20
### Rate Limiting
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints
- Return 429 when exceeded
- Include retry-after header
### Caching
- Use Redis for session caching
- Cache duration: 5 minutes default
- Invalidate on write operations
- Tag cache keys with resource type示例 3:个人记忆
文件: ~/.claude/CLAUDE.md
markdown
# 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示例 4:会话中更新记忆
会话交互:
markdown
用户:记住我更倾向于为所有新组件使用 React hooks
而不是 class 组件。
Claude:我将把这添加到你的记忆中。应该保存到哪个记忆文件?
1. 项目记忆(./CLAUDE.md)
2. 个人记忆(~/.claude/CLAUDE.md)
用户:项目记忆
Claude:✅ 记忆已保存!
添加到 ./CLAUDE.md:
---
### Component Development
- Use functional components with React Hooks
- Prefer hooks over class components
- Custom hooks for reusable logic
- Use useCallback for event handlers
- Use useMemo for expensive computationsClaude Web/Desktop 中的记忆
记忆综合时间线
记忆摘要示例:
markdown
## Claude 对用户的记忆
### 职业背景
- 拥有 8 年经验的高级全栈开发者
- 专注于 TypeScript/Node.js 后端和 React 前端
- 活跃的开源贡献者
- 对 AI 和机器学习感兴趣
### 项目背景
- 目前在构建电商平台
- 技术栈:Node.js、PostgreSQL、React 18、Docker
- 与 5 名开发者团队合作
- 使用 CI/CD 和蓝绿部署
### 沟通偏好
- 喜欢直接、简洁的解释
- 喜欢可视化图表和示例
- 欣赏代码片段
- 在注释中解释业务逻辑
### 当前目标
- 提升 API 性能
- 将测试覆盖率提高到 90%
- 实现缓存策略
- 记录架构记忆功能对比
| 功能 | Claude Web/Desktop | Claude Code(CLAUDE.md) |
|---|---|---|
| 自动综合 | ✅ 每 24 小时 | ❌ 手动 |
| 跨项目 | ✅ 共享 | ❌ 项目专用 |
| 团队访问 | ✅ 共享项目 | ✅ Git 追踪 |
| 可搜索 | ✅ 内置 | ✅ 通过 /memory |
| 可编辑 | ✅ 聊天中 | ✅ 直接编辑文件 |
| 导入/导出 | ✅ 是 | ✅ 复制/粘贴 |
| 持久化 | ✅ 24 小时以上 | ✅ 无限期 |
MCP 协议
概述
MCP(模型上下文协议)是 Claude 访问外部工具、API 和实时数据源的标准化方式。与记忆系统不同,MCP 协议提供对动态数据的实时访问。
MCP 架构
MCP 生态系统
MCP 设置流程
可用 MCP 服务器表
| MCP 服务器 | 用途 | 常用工具 | 认证 | 实时 |
|---|---|---|---|---|
| Filesystem | 文件操作 | read, write, delete | OS 权限 | ✅ 是 |
| GitHub | 仓库管理 | list_prs, create_issue, push | OAuth | ✅ 是 |
| Slack | 团队通信 | send_message, list_channels | Token | ✅ 是 |
| Database | SQL 查询 | query, insert, update | 凭据 | ✅ 是 |
| Google Docs | 文档访问 | read, write, share | OAuth | ✅ 是 |
| Asana | 项目管理 | create_task, update_status | API Key | ✅ 是 |
| Stripe | 支付数据 | list_charges, create_invoice | API Key | ✅ 是 |
| Memory | 持久记忆 | store, retrieve, delete | 本地 | ❌ 否 |
实际示例
示例 1:GitHub MCP 配置
文件: .mcp.json(项目范围)或 ~/.claude.json(用户范围)
json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}可用的 GitHub MCP 工具:
markdown
# GitHub MCP Tools
## Pull Request Management
- `list_prs` - List all PRs in repository
- `get_pr` - Get PR details including diff
- `create_pr` - Create new PR
- `update_pr` - Update PR description/title
- `merge_pr` - Merge PR to main branch
- `review_pr` - Add review comments
Example request:
```
/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
```
## Issue Management
- `list_issues` - List all issues
- `get_issue` - Get issue details
- `create_issue` - Create new issue
- `close_issue` - Close issue
- `add_comment` - Add comment to issue
## Repository Information
- `get_repo_info` - Repository details
- `list_files` - File tree structure
- `get_file_content` - Read file contents
- `search_code` - Search across codebase
## Commit Operations
- `list_commits` - Commit history
- `get_commit` - Specific commit details
- `create_commit` - Create new commit示例 2:数据库 MCP 设置
配置:
json
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["@modelcontextprotocol/server-database"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/mydb"
}
}
}
}使用示例:
markdown
用户:查找所有订单超过 10 笔的用户
Claude:我将查询你的数据库以找到相关信息。
# 使用 MCP 数据库工具:
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id
HAVING COUNT(o.id) > 10
ORDER BY order_count DESC;
# 结果:
- Alice:15 笔订单
- Bob:12 笔订单
- Charlie:11 笔订单示例 3:多 MCP 工作流
场景:日报生成
markdown
# 使用多个 MCP 的日报工作流
## 设置
1. GitHub MCP — 获取 PR 指标
2. Database MCP — 查询销售数据
3. Slack MCP — 发布报告
4. Filesystem MCP — 保存报告
## 工作流
### 步骤 1:获取 GitHub 数据
/mcp__github__list_prs completed:true last:7days
输出:
- 总 PR 数:42
- 平均合并时间:2.3 小时
- 审查周转时间:1.1 小时
### 步骤 2:查询数据库
SELECT COUNT(*) as sales, SUM(amount) as revenue
FROM orders
WHERE created_at > NOW() - INTERVAL '1 day'
输出:
- 销售:247
- 收入:$12,450
### 步骤 3:生成报告
将数据合并为 HTML 报告
### 步骤 4:保存到文件系统
将 report.html 写入 /reports/
### 步骤 5:发布到 Slack
将摘要发送到 #daily-reports 频道
最终输出:
✅ 报告已生成并发布
📊 本周合并了 47 个 PR
💰 日销售额 $12,450示例 4:Filesystem MCP 操作
配置:
json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
}
}
}可用操作:
| 操作 | 命令 | 用途 |
|---|---|---|
| 列出文件 | ls ~/projects | 显示目录内容 |
| 读取文件 | cat src/main.ts | 读取文件内容 |
| 写入文件 | create docs/api.md | 创建新文件 |
| 编辑文件 | edit src/app.ts | 修改文件 |
| 搜索 | grep "async function" | 在文件中搜索 |
| 删除 | rm old-file.js | 删除文件 |
MCP 与记忆系统:决策矩阵
请求/响应模式
代理技能
概述
代理技能是打包为文件夹的可复用、模型调用能力,包含指令、脚本和资源。Claude 自动检测并使用相关技能。
技能架构
技能加载流程
技能类型与位置表
| 类型 | 位置 | 范围 | 共享 | 同步 | 最适合 |
|---|---|---|---|---|---|
| 预置 | 内置 | 全局 | 所有用户 | 自动 | 文档创建 |
| 个人 | ~/.claude/skills/ | 个人 | 否 | 手动 | 个人自动化 |
| 项目 | .claude/skills/ | 团队 | 是 | Git | 团队规范 |
| 插件 | 通过插件安装 | 不定 | 视情况 | 自动 | 集成功能 |
预置技能
内置技能
Claude Code 现在包含 5 个开箱即用的内置技能:
| 技能 | 命令 | 用途 |
|---|---|---|
| Simplify | /simplify | 简化复杂代码或解释 |
| Batch | /batch | 对多个文件或条目执行批量操作 |
| Debug | /debug | 系统化调试问题并进行根因分析 |
| Loop | /loop | 按计时器安排周期性任务 |
| Claude API | /claude-api | 直接与 Anthropic API 交互 |
这些内置技能始终可用,无需安装或配置。
实际示例
示例 1:自定义代码审查技能
目录结构:
~/.claude/skills/code-review/
├── SKILL.md
├── templates/
│ ├── review-checklist.md
│ └── finding-template.md
└── scripts/
├── analyze-metrics.py
└── compare-complexity.py文件: ~/.claude/skills/code-review/SKILL.md
yaml
---
name: Code Review Specialist
description: Comprehensive code review with security, performance, and quality analysis
version: "1.0.0"
tags:
- code-review
- quality
- security
when_to_use: When users ask to review code, analyze code quality, or evaluate pull requests
effort: high
shell: bash
---
# Code Review Skill
This skill provides comprehensive code review capabilities focusing on:
1. **Security Analysis**
- Authentication/authorization issues
- Data exposure risks
- Injection vulnerabilities
- Cryptographic weaknesses
- Sensitive data logging
2. **Performance Review**
- Algorithm efficiency (Big O analysis)
- Memory optimization
- Database query optimization
- Caching opportunities
- Concurrency issues
3. **Code Quality**
- SOLID principles
- Design patterns
- Naming conventions
- Documentation
- Test coverage
4. **Maintainability**
- Code readability
- Function size (should be < 50 lines)
- Cyclomatic complexity
- Dependency management
- Type safety
## Review Template
For each piece of code reviewed, provide:
### Summary
- Overall quality assessment (1-5)
- Key findings count
- Recommended priority areas
### Critical Issues (if any)
- **Issue**: Clear description
- **Location**: File and line number
- **Impact**: Why this matters
- **Severity**: Critical/High/Medium
- **Fix**: Code example
### Findings by Category
#### Security (if issues found)
List security vulnerabilities with examples
#### Performance (if issues found)
List performance problems with complexity analysis
#### Quality (if issues found)
List code quality issues with refactoring suggestions
#### Maintainability (if issues found)
List maintainability problems with improvementsPython Script: analyze-metrics.py
python
#!/usr/bin/env python3
import re
import sys
def analyze_code_metrics(code):
"""Analyze code for common metrics."""
# Count functions
functions = len(re.findall(r'^def\s+\w+', code, re.MULTILINE))
# Count classes
classes = len(re.findall(r'^class\s+\w+', code, re.MULTILINE))
# Average line length
lines = code.split('\n')
avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0
# Estimate complexity
complexity = len(re.findall(r'\b(if|elif|else|for|while|and|or)\b', code))
return {
'functions': functions,
'classes': classes,
'avg_line_length': avg_length,
'complexity_score': complexity
}
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
code = f.read()
metrics = analyze_code_metrics(code)
for key, value in metrics.items():
print(f"{key}: {value:.2f}")Python Script: compare-complexity.py
python
#!/usr/bin/env python3
"""
Compare cyclomatic complexity of code before and after changes.
Helps identify if refactoring actually simplifies code structure.
"""
import re
import sys
from typing import Dict, Tuple
class ComplexityAnalyzer:
"""Analyze code complexity metrics."""
def __init__(self, code: str):
self.code = code
self.lines = code.split('\n')
def calculate_cyclomatic_complexity(self) -> int:
"""
Calculate cyclomatic complexity using McCabe's method.
Count decision points: if, elif, else, for, while, except, and, or
"""
complexity = 1 # Base complexity
# Count decision points
decision_patterns = [
r'\bif\b',
r'\belif\b',
r'\bfor\b',
r'\bwhile\b',
r'\bexcept\b',
r'\band\b(?!$)',
r'\bor\b(?!$)'
]
for pattern in decision_patterns:
matches = re.findall(pattern, self.code)
complexity += len(matches)
return complexity
def calculate_cognitive_complexity(self) -> int:
"""
Calculate cognitive complexity - how hard is it to understand?
Based on nesting depth and control flow.
"""
cognitive = 0
nesting_depth = 0
for line in self.lines:
# Track nesting depth
if re.search(r'^\s*(if|for|while|def|class|try)\b', line):
nesting_depth += 1
cognitive += nesting_depth
elif re.search(r'^\s*(elif|else|except|finally)\b', line):
cognitive += nesting_depth
# Reduce nesting when unindenting
if line and not line[0].isspace():
nesting_depth = 0
return cognitive
def calculate_maintainability_index(self) -> float:
"""
Maintainability Index ranges from 0-100.
> 85: Excellent
> 65: Good
> 50: Fair
< 50: Poor
"""
lines = len(self.lines)
cyclomatic = self.calculate_cyclomatic_complexity()
cognitive = self.calculate_cognitive_complexity()
# Simplified MI calculation
mi = 171 - 5.2 * (cyclomatic / lines) - 0.23 * (cognitive) - 16.2 * (lines / 1000)
return max(0, min(100, mi))
def get_complexity_report(self) -> Dict:
"""Generate comprehensive complexity report."""
return {
'cyclomatic_complexity': self.calculate_cyclomatic_complexity(),
'cognitive_complexity': self.calculate_cognitive_complexity(),
'maintainability_index': round(self.calculate_maintainability_index(), 2),
'lines_of_code': len(self.lines),
'avg_line_length': round(sum(len(l) for l in self.lines) / len(self.lines), 2) if self.lines else 0
}
def compare_files(before_file: str, after_file: str) -> None:
"""Compare complexity metrics between two code versions."""
with open(before_file, 'r') as f:
before_code = f.read()
with open(after_file, 'r') as f:
after_code = f.read()
before_analyzer = ComplexityAnalyzer(before_code)
after_analyzer = ComplexityAnalyzer(after_code)
before_metrics = before_analyzer.get_complexity_report()
after_metrics = after_analyzer.get_complexity_report()
print("=" * 60)
print("CODE COMPLEXITY COMPARISON")
print("=" * 60)
print("\nBEFORE:")
print(f" Cyclomatic Complexity: {before_metrics['cyclomatic_complexity']}")
print(f" Cognitive Complexity: {before_metrics['cognitive_complexity']}")
print(f" Maintainability Index: {before_metrics['maintainability_index']}")
print(f" Lines of Code: {before_metrics['lines_of_code']}")
print(f" Avg Line Length: {before_metrics['avg_line_length']}")
print("\nAFTER:")
print(f" Cyclomatic Complexity: {after_metrics['cyclomatic_complexity']}")
print(f" Cognitive Complexity: {after_metrics['cognitive_complexity']}")
print(f" Maintainability Index: {after_metrics['maintainability_index']}")
print(f" Lines of Code: {after_metrics['lines_of_code']}")
print(f" Avg Line Length: {after_metrics['avg_line_length']}")
print("\nCHANGES:")
cyclomatic_change = after_metrics['cyclomatic_complexity'] - before_metrics['cyclomatic_complexity']
cognitive_change = after_metrics['cognitive_complexity'] - before_metrics['cognitive_complexity']
mi_change = after_metrics['maintainability_index'] - before_metrics['maintainability_index']
loc_change = after_metrics['lines_of_code'] - before_metrics['lines_of_code']
print(f" Cyclomatic Complexity: {cyclomatic_change:+d}")
print(f" Cognitive Complexity: {cognitive_change:+d}")
print(f" Maintainability Index: {mi_change:+.2f}")
print(f" Lines of Code: {loc_change:+d}")
print("\nASSESSMENT:")
if mi_change > 0:
print(" ✅ Code is MORE maintainable")
elif mi_change < 0:
print(" ⚠️ Code is LESS maintainable")
else:
print(" ➡️ Maintainability unchanged")
if cyclomatic_change < 0:
print(" ✅ Complexity DECREASED")
elif cyclomatic_change > 0:
print(" ⚠️ Complexity INCREASED")
else:
print(" ➡️ Complexity unchanged")
print("=" * 60)
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: python compare-complexity.py <before_file> <after_file>")
sys.exit(1)
compare_files(sys.argv[1], sys.argv[2])Template: review-checklist.md
markdown
# Code Review Checklist
## Security Checklist
- [ ] No hardcoded credentials or secrets
- [ ] Input validation on all user inputs
- [ ] SQL injection prevention (parameterized queries)
- [ ] CSRF protection on state-changing operations
- [ ] XSS prevention with proper escaping
- [ ] Authentication checks on protected endpoints
- [ ] Authorization checks on resources
- [ ] Secure password hashing (bcrypt, argon2)
- [ ] No sensitive data in logs
- [ ] HTTPS enforced
## Performance Checklist
- [ ] No N+1 queries
- [ ] Appropriate use of indexes
- [ ] Caching implemented where beneficial
- [ ] No blocking operations on main thread
- [ ] Async/await used correctly
- [ ] Large datasets paginated
- [ ] Database connections pooled
- [ ] Regular expressions optimized
- [ ] No unnecessary object creation
- [ ] Memory leaks prevented
## Quality Checklist
- [ ] Functions < 50 lines
- [ ] Clear variable naming
- [ ] No duplicate code
- [ ] Proper error handling
- [ ] Comments explain WHY, not WHAT
- [ ] No console.logs in production
- [ ] Type checking (TypeScript/JSDoc)
- [ ] SOLID principles followed
- [ ] Design patterns applied correctly
- [ ] Self-documenting code
## Testing Checklist
- [ ] Unit tests written
- [ ] Edge cases covered
- [ ] Error scenarios tested
- [ ] Integration tests present
- [ ] Coverage > 80%
- [ ] No flaky tests
- [ ] Mock external dependencies
- [ ] Clear test namesTemplate: finding-template.md
markdown
# Code Review Finding Template
Use this template when documenting each issue found during code review.
---
## Issue: [TITLE]
### Severity
- [ ] Critical (blocks deployment)
- [ ] High (should fix before merge)
- [ ] Medium (should fix soon)
- [ ] Low (nice to have)
### Category
- [ ] Security
- [ ] Performance
- [ ] Code Quality
- [ ] Maintainability
- [ ] Testing
- [ ] Design Pattern
- [ ] Documentation
### Location
**File:** `src/components/UserCard.tsx`
**Lines:** 45-52
**Function/Method:** `renderUserDetails()`
### Issue Description
**What:** Describe what the issue is.
**Why it matters:** Explain the impact and why this needs to be fixed.
**Current behavior:** Show the problematic code or behavior.
**Expected behavior:** Describe what should happen instead.
### Code Example
#### Current (Problematic)
```typescript
// Shows the N+1 query problem
const users = fetchUsers();
users.forEach(user => {
const posts = fetchUserPosts(user.id); // Query per user!
renderUserPosts(posts);
});
```
#### Suggested Fix
```typescript
// Optimized with JOIN query
const usersWithPosts = fetchUsersWithPosts();
usersWithPosts.forEach(({ user, posts }) => {
renderUserPosts(posts);
});
```
### Impact Analysis
| Aspect | Impact | Severity |
|--------|--------|----------|
| Performance | 100+ queries for 20 users | High |
| User Experience | Slow page load | High |
| Scalability | Breaks at scale | Critical |
| Maintainability | Hard to debug | Medium |
### Related Issues
- Similar issue in `AdminUserList.tsx` line 120
- Related PR: #456
- Related issue: #789
### Additional Resources
- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem)
- [Database Join Documentation](https://docs.example.com/joins)
- [Performance Optimization Guide](./docs/performance.md)
### Reviewer Notes
- This is a common pattern in this codebase
- Consider adding this to the code style guide
- Might be worth creating a helper function
### Author Response (for feedback)
*To be filled by the code author:*
- [ ] Fix implemented in commit: `abc123`
- [ ] Fix status: Complete / In Progress / Needs Discussion
- [ ] Questions or concerns: (describe)
---
## Finding Statistics (for Reviewer)
When reviewing multiple findings, track:
- **Total Issues Found:** X
- **Critical:** X
- **High:** X
- **Medium:** X
- **Low:** X
**Recommendation:** ✅ Approve / ⚠️ Request Changes / 🔄 Needs Discussion
**Overall Code Quality:** 1-5 stars使用示例
markdown
用户:审查这段 React 组件代码
Claude:我将使用我的代码审查技能进行全面代码审查。
[加载 SKILL.md]
[对照检查清单分析代码]
[运行 Python 指标脚本]
[应用模板]
## 代码审查结果
### 摘要
质量评分:3.5/5
关键发现:7 项
优先改进区域:性能优化、错误处理
### 关键问题:1 个
**问题**:N+1 查询问题
**位置**:UserComponent.tsx,第 45-52 行
**影响**:20 个用户列表触发 100+ 次数据库查询
**严重性**:高
**修复**:
```javascript
// Before: N+1 queries
const users = fetchUsers();
users.forEach(user => fetchUserPosts(user.id)); // 20+ queries
// After: Single query with JOIN
const users = fetchUsersWithPosts(); // 1 query
```
### 性能发现
- 大列表缺少分页
- 建议:对列表项使用 React.memo()
- 数据库查询:可通过索引优化
### 质量发现
- 第 20 行的函数有 127 行(最大:50 行)
- 缺少错误边界
- Props 应有 TypeScript 类型示例 2:品牌声音技能
目录结构:
.claude/skills/brand-voice/
├── SKILL.md
├── brand-guidelines.md
├── tone-examples.md
└── templates/
├── email-template.txt
├── social-post-template.txt
└── blog-post-template.md文件: .claude/skills/brand-voice/SKILL.md
yaml
---
name: Brand Voice Consistency
description: Ensure all communication matches brand voice and tone guidelines
tags:
- brand
- writing
- consistency
when_to_use: When creating marketing copy, customer communications, or public-facing content
---
# Brand Voice Skill
## Overview
This skill ensures all communications maintain consistent brand voice, tone, and messaging.
## Brand Identity
### Mission
Help teams automate their development workflows with AI
### Values
- **Simplicity**: Make complex things simple
- **Reliability**: Rock-solid execution
- **Empowerment**: Enable human creativity
### Tone of Voice
- **Friendly but professional** - approachable without being casual
- **Clear and concise** - avoid jargon, explain technical concepts simply
- **Confident** - we know what we're doing
- **Empathetic** - understand user needs and pain points
## Writing Guidelines
### Do's ✅
- Use "you" when addressing readers
- Use active voice: "Claude generates reports" not "Reports are generated by Claude"
- Start with value proposition
- Use concrete examples
- Keep sentences under 20 words
- Use lists for clarity
- Include calls-to-action
### Don'ts ❌
- Don't use corporate jargon
- Don't patronize or oversimplify
- Don't use "we believe" or "we think"
- Don't use ALL CAPS except for emphasis
- Don't create walls of text
- Don't assume technical knowledge
## Vocabulary
### ✅ Preferred Terms
- Claude (not "the Claude AI")
- Code generation (not "auto-coding")
- Agent (not "bot")
- Streamline (not "revolutionize")
- Integrate (not "synergize")
### ❌ Avoid Terms
- "Cutting-edge" (overused)
- "Game-changer" (vague)
- "Leverage" (corporate-speak)
- "Utilize" (use "use")
- "Paradigm shift" (unclear)示例
✅ 好示例
"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and quality—saving your team hours every week."
为什么有效:清晰的价值主张,具体收益,面向行动
❌ 坏示例
"Claude leverages cutting-edge AI to provide comprehensive software development solutions."
为什么无效:模糊、充斥企业术语、无具体价值
Template: Email
Subject: [Clear, benefit-driven subject]
Hi [Name],
[Opening: What's the value for them]
[Body: How it works / What they'll get]
[Specific example or benefit]
[Call to action: Clear next step]
Best regards,
[Name]Template: Social Media
[Hook: Grab attention in first line]
[2-3 lines: Value or interesting fact]
[Call to action: Link, question, or engagement]
[Emoji: 1-2 max for visual interest]File: tone-examples.md
Exciting announcement:
"Save 8 hours per week on code reviews. Claude reviews your PRs automatically."
Empathetic support:
"We know deployments can be stressful. Claude handles testing so you don't have to worry."
Confident product feature:
"Claude doesn't just suggest code. It understands your architecture and maintains consistency."
Educational blog post:
"Let's explore how agents improve code review workflows. Here's what we learned..."示例 3:文档生成器技能
文件: .claude/skills/doc-generator/SKILL.md
yaml
---
name: API Documentation Generator
description: Generate comprehensive, accurate API documentation from source code
version: "1.0.0"
tags:
- documentation
- api
- automation
when_to_use: When creating or updating API documentation
---
# API Documentation Generator Skill
## Generates
- OpenAPI/Swagger specifications
- API endpoint documentation
- SDK usage examples
- Integration guides
- Error code references
- Authentication guides
## Documentation Structure
### For Each Endpoint
```markdown
## GET /api/v1/users/:id
### Description
Brief explanation of what this endpoint does
### Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| id | string | Yes | User ID |
### Response
**200 Success**
```json
{
"id": "usr_123",
"name": "John Doe",
"email": "john@example.com",
"created_at": "2025-01-15T10:30:00Z"
}
```
**404 Not Found**
```json
{
"error": "USER_NOT_FOUND",
"message": "User does not exist"
}
```
### Examples
**cURL**
```bash
curl -X GET "https://api.example.com/api/v1/users/usr_123" \
-H "Authorization: Bearer YOUR_TOKEN"
```
**JavaScript**
```javascript
const user = await fetch('/api/v1/users/usr_123', {
headers: { 'Authorization': 'Bearer token' }
}).then(r => r.json());
```
**Python**
```python
response = requests.get(
'https://api.example.com/api/v1/users/usr_123',
headers={'Authorization': 'Bearer token'}
)
user = response.json()
```
## Python Script: generate-docs.py
```python
#!/usr/bin/env python3
import ast
import json
from typing import Dict, List
class APIDocExtractor(ast.NodeVisitor):
"""Extract API documentation from Python source code."""
def __init__(self):
self.endpoints = []
def visit_FunctionDef(self, node):
"""Extract function documentation."""
if node.name.startswith('get_') or node.name.startswith('post_'):
doc = ast.get_docstring(node)
endpoint = {
'name': node.name,
'docstring': doc,
'params': [arg.arg for arg in node.args.args],
'returns': self._extract_return_type(node)
}
self.endpoints.append(endpoint)
self.generic_visit(node)
def _extract_return_type(self, node):
"""Extract return type from function annotation."""
if node.returns:
return ast.unparse(node.returns)
return "Any"
def generate_markdown_docs(endpoints: List[Dict]) -> str:
"""Generate markdown documentation from endpoints."""
docs = "# API Documentation\n\n"
for endpoint in endpoints:
docs += f"## {endpoint['name']}\n\n"
docs += f"{endpoint['docstring']}\n\n"
docs += f"**Parameters**: {', '.join(endpoint['params'])}\n\n"
docs += f"**Returns**: {endpoint['returns']}\n\n"
docs += "---\n\n"
return docs
if __name__ == '__main__':
import sys
with open(sys.argv[1], 'r') as f:
tree = ast.parse(f.read())
extractor = APIDocExtractor()
extractor.visit(tree)
markdown = generate_markdown_docs(extractor.endpoints)
print(markdown)技能发现与调用
技能与其他功能对比
Claude Code 插件
概述
Claude Code 插件是自定义功能的打包集合(斜杠命令、子代理、MCP 服务器和钩子),通过单个命令安装。它们是最高级别的扩展机制——将多个功能组合成连贯的可共享包。
架构
插件加载流程
插件类型与分发
| 类型 | 范围 | 共享 | 权威方 | 示例 |
|---|---|---|---|---|
| 官方 | 全局 | 所有用户 | Anthropic | PR Review、Security Guidance |
| 社区 | 公开 | 所有用户 | 社区 | DevOps、Data Science |
| 组织 | 内部 | 团队成员 | 公司 | 内部规范、工具 |
| 个人 | 个人 | 单个用户 | 开发者 | 自定义工作流 |
插件定义结构
yaml
---
name: plugin-name
version: "1.0.0"
description: "What this plugin does"
author: "Your Name"
license: MIT
# Plugin metadata
tags:
- category
- use-case
# Requirements
requires:
- claude-code: ">=1.0.0"
# Components bundled
components:
- type: commands
path: commands/
- type: agents
path: agents/
- type: mcp
path: mcp/
- type: hooks
path: hooks/
# Configuration
config:
auto_load: true
enabled_by_default: true
---插件结构
my-plugin/
├── .claude-plugin/
│ └── plugin.json
├── commands/
│ ├── task-1.md
│ ├── task-2.md
│ └── workflows/
├── agents/
│ ├── specialist-1.md
│ ├── specialist-2.md
│ └── configs/
├── skills/
│ ├── skill-1.md
│ └── skill-2.md
├── hooks/
│ └── hooks.json
├── .mcp.json
├── .lsp.json
├── settings.json
├── templates/
│ └── issue-template.md
├── scripts/
│ ├── helper-1.sh
│ └── helper-2.py
├── docs/
│ ├── README.md
│ └── USAGE.md
└── tests/
└── plugin.test.js实际示例
示例 1:PR Review 插件
文件: .claude-plugin/plugin.json
json
{
"name": "pr-review",
"version": "1.0.0",
"description": "Complete PR review workflow with security, testing, and docs",
"author": {
"name": "Anthropic"
},
"license": "MIT"
}文件: commands/review-pr.md
markdown
---
name: Review PR
description: Start comprehensive PR review with security and testing checks
---
# PR Review
This command initiates a complete pull request review including:
1. Security analysis
2. Test coverage verification
3. Documentation updates
4. Code quality checks
5. Performance impact assessment文件: agents/security-reviewer.md
yaml
---
name: security-reviewer
description: Security-focused code review
tools: read, grep, diff
---
# Security Reviewer
Specializes in finding security vulnerabilities:
- Authentication/authorization issues
- Data exposure
- Injection attacks
- Secure configuration安装:
bash
/plugin install pr-review
# 结果:
# ✅ 3 个斜杠命令已安装
# ✅ 3 个子代理已配置
# ✅ 2 个 MCP 服务器已连接
# ✅ 4 个钩子已注册
# ✅ 准备就绪!示例 2:DevOps 插件
组件:
devops-automation/
├── commands/
│ ├── deploy.md
│ ├── rollback.md
│ ├── status.md
│ └── incident.md
├── agents/
│ ├── deployment-specialist.md
│ ├── incident-commander.md
│ └── alert-analyzer.md
├── mcp/
│ ├── github-config.json
│ ├── kubernetes-config.json
│ └── prometheus-config.json
├── hooks/
│ ├── pre-deploy.js
│ ├── post-deploy.js
│ └── on-error.js
└── scripts/
├── deploy.sh
├── rollback.sh
└── health-check.sh示例 3:Documentation 插件
打包组件:
documentation/
├── commands/
│ ├── generate-api-docs.md
│ ├── generate-readme.md
│ ├── sync-docs.md
│ └── validate-docs.md
├── agents/
│ ├── api-documenter.md
│ ├── code-commentator.md
│ └── example-generator.md
├── mcp/
│ ├── github-docs-config.json
│ └── slack-announce-config.json
└── templates/
├── api-endpoint.md
├── function-docs.md
└── adr-template.md插件市场
插件安装与生命周期
插件功能对比
| 功能 | 斜杠命令 | 技能 | 子代理 | 插件 |
|---|---|---|---|---|
| 安装 | 手动复制 | 手动复制 | 手动配置 | 一条命令 |
| 设置时间 | 5 分钟 | 10 分钟 | 15 分钟 | 2 分钟 |
| 打包 | 单文件 | 单文件 | 单文件 | 多文件 |
| 版本控制 | 手动 | 手动 | 手动 | 自动 |
| 团队共享 | 复制文件 | 复制文件 | 复制文件 | 安装 ID |
| 更新 | 手动 | 手动 | 手动 | 自动可用 |
| 依赖项 | 无 | 无 | 无 | 可能有 |
| 市场 | 否 | 否 | 否 | 是 |
| 分发 | 仓库 | 仓库 | 仓库 | 市场 |
插件使用场景
| 使用场景 | 建议 | 原因 |
|---|---|---|
| 团队入职 | ✅ 使用插件 | 即时设置,所有配置 |
| 框架设置 | ✅ 使用插件 | 打包框架特定命令 |
| 企业规范 | ✅ 使用插件 | 集中分发,版本控制 |
| 快速任务自动化 | ❌ 使用命令 | 过于复杂 |
| 单域专业能力 | ❌ 使用技能 | 太重,改用技能 |
| 专业分析 | ❌ 使用子代理 | 手动创建或使用技能 |
| 实时数据访问 | ❌ 使用 MCP** | 独立使用,不要打包 |
何时创建插件
发布插件
发布步骤:
- 创建包含所有组件的插件结构
- 编写
.claude-plugin/plugin.json清单 - 创建带文档的
README.md - 通过
/plugin install ./my-plugin本地测试 - 提交到插件市场
- 审核并批准
- 在市场上发布
- 用户可以通过一条命令安装
提交示例:
markdown
# PR Review Plugin
## Description
Complete PR review workflow with security, testing, and documentation checks.
## What's Included
- 3 slash commands for different review types
- 3 specialized subagents
- GitHub and CodeQL MCP integration
- Automated security scanning hooks
## Installation
```bash
/plugin install pr-review
```
## Features
✅ Security analysis
✅ Test coverage checking
✅ Documentation verification
✅ Code quality assessment
✅ Performance impact analysis
## Usage
```bash
/review-pr
/check-security
/check-tests
```
## Requirements
- Claude Code 1.0+
- GitHub access
- CodeQL (optional)插件与手动配置对比
手动设置(2 小时以上):
- 逐一安装斜杠命令
- 单独创建子代理
- 分别配置 MCP
- 手动设置钩子
- 记录所有内容
- 与团队共享(希望他们配置正确)
使用插件(2 分钟):
bash
/plugin install pr-review
# ✅ 所有内容已安装并配置
# ✅ 立即可用
# ✅ 团队可以复现完全相同的设置对比与集成
功能对比矩阵
| 功能 | 调用方式 | 持久化 | 范围 | 使用场景 |
|---|---|---|---|---|
| 斜杠命令 | 手动(/cmd) | 仅会话内 | 单条命令 | 快速快捷方式 |
| 子代理 | 自动委派 | 隔离上下文 | 专项任务 | 任务分发 |
| 记忆系统 | 自动加载 | 跨会话 | 用户/团队上下文 | 长期学习 |
| MCP 协议 | 自动查询 | 外部实时 | 实时数据访问 | 动态信息 |
| 技能 | 自动调用 | 基于文件系统 | 可复用专业能力 | 自动化工作流 |
交互时间线
实际集成示例:客户支持自动化
架构
请求流程
markdown
## 客户支持请求流程
### 1. 收到邮件
"上传文件时出现 500 错误。这阻碍了我的工作!"
### 2. 记忆系统查找
- 加载带支持规范的 CLAUDE.md
- 检查客户历史:VIP 客户,本月第 3 次事件
### 3. MCP 查询
- GitHub MCP:列出未关闭问题(找到相关 bug 报告)
- Database MCP:检查系统状态(无已知故障)
- Slack MCP:检查工程团队是否知晓
### 4. 技能检测与加载
- 请求匹配「技术支持」技能
- 从技能中加载支持响应模板
### 5. 子代理委派
- 路由到技术支持子代理
- 提供上下文:客户历史、错误详情、已知问题
- 子代理可访问:read、bash、grep 工具
### 6. 子代理处理
技术支持子代理:
- 在代码库中搜索文件上传 500 错误
- 在提交 8f4a2c 中找到最近的更改
- 创建临时解决方案文档
### 7. 技能执行
响应生成器技能:
- 使用品牌声音指南
- 以移情的方式格式化响应
- 包含临时解决方案步骤
- 链接到相关文档
### 8. MCP 输出
- 在 #support Slack 频道发布更新
- 标记工程团队
- 在 Jira MCP 中更新工单
### 9. 响应
客户收到:
- 移情的确认
- 原因说明
- 即时临时解决方案
- 永久修复时间线
- 相关问题链接完整功能编排
何时使用各功能
选择决策树
汇总表
| 方面 | 斜杠命令 | 子代理 | 记忆系统 | MCP | 技能 | 插件 |
|---|---|---|---|---|---|---|
| 设置难度 | 简单 | 中等 | 简单 | 中等 | 中等 | 简单 |
| 学习曲线 | 低 | 中 | 低 | 中 | 中 | 低 |
| 团队收益 | 高 | 高 | 中 | 高 | 高 | 非常高 |
| 自动化程度 | 低 | 高 | 中 | 高 | 高 | 非常高 |
| 上下文管理 | 单会话 | 隔离 | 持久 | 实时 | 持久 | 所有功能 |
| 维护负担 | 低 | 中 | 低 | 中 | 中 | 低 |
| 可扩展性 | 好 | 优秀 | 好 | 优秀 | 优秀 | 优秀 |
| 可共享性 | 一般 | 一般 | 好 | 好 | 好 | 优秀 |
| 版本控制 | 手动 | 手动 | 手动 | 手动 | 手动 | 自动 |
| 安装 | 手动复制 | 手动配置 | N/A | 手动配置 | 手动复制 | 一条命令 |
快速入门指南
第 1 周:从简单开始
- 为常见任务创建 2-3 个斜杠命令
- 在设置中启用记忆系统
- 在 CLAUDE.md 中记录团队规范
第 2 周:添加实时访问
- 设置 1 个 MCP(GitHub 或数据库)
- 使用
/mcp进行配置 - 在工作流中查询实时数据
第 3 周:分发工作
- 为特定角色创建第一个子代理
- 使用
/agents命令 - 用简单任务测试委派
第 4 周:自动化一切
- 为重复自动化创建第一个技能
- 使用技能市场或自行构建
- 将所有功能组合为完整工作流
持续进行
- 每月审查和更新记忆系统
- 随着模式出现添加新技能
- 优化 MCP 查询
- 改进子代理提示词
钩子
概述
钩子是事件驱动的 shell 命令,在响应 Claude Code 事件时自动执行。它们实现自动化、验证和自定义工作流,无需手动干预。
钩子事件
Claude Code 支持跨四种钩子类型(command、http、prompt、agent)的 25 个钩子事件:
| 钩子事件 | 触发时机 | 使用场景 |
|---|---|---|
| SessionStart | 会话开始/恢复/清除/压缩 | 环境设置,初始化 |
| InstructionsLoaded | 加载 CLAUDE.md 或规则文件 | 验证、转换、增强 |
| UserPromptSubmit | 用户提交提示词 | 输入验证,提示词过滤 |
| PreToolUse | 任何工具运行前 | 验证,审批门控,日志记录 |
| PermissionRequest | 显示权限对话框 | 自动批准/拒绝流程 |
| PostToolUse | 工具成功后 | 自动格式化,通知,清理 |
| PostToolUseFailure | 工具执行失败 | 错误处理,日志记录 |
| Notification | 发送通知 | 告警,外部集成 |
| SubagentStart | 生成子代理 | 上下文注入,初始化 |
| SubagentStop | 子代理完成 | 结果验证,日志记录 |
| Stop | Claude 完成响应 | 摘要生成,清理任务 |
| StopFailure | API 错误结束轮次 | 错误恢复,日志记录 |
| TeammateIdle | 代理团队成员空闲 | 工作分配,协调 |
| TaskCompleted | 任务标记为完成 | 任务后处理 |
| TaskCreated | 通过 TaskCreate 创建任务 | 任务跟踪,日志记录 |
| ConfigChange | 配置文件更改 | 验证,传播 |
| CwdChanged | 工作目录更改 | 目录特定设置 |
| FileChanged | 被监视文件更改 | 文件监控,重建触发 |
| PreCompact | 上下文压缩前 | 状态保存 |
| PostCompact | 压缩完成后 | 压缩后操作 |
| WorktreeCreate | 创建工作树 | 环境设置,依赖安装 |
| WorktreeRemove | 删除工作树 | 清理,资源释放 |
| Elicitation | MCP 服务器请求用户输入 | 输入验证 |
| ElicitationResult | 用户响应 elicitation | 响应处理 |
| SessionEnd | 会话终止 | 清理,最终日志记录 |
常用钩子
钩子在 ~/.claude/settings.json(用户级)或 .claude/settings.json(项目级)中配置:
json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "prettier --write $CLAUDE_FILE_PATH"
}
]
}
],
"PreToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "eslint $CLAUDE_FILE_PATH"
}
]
}
]
}
}钩子环境变量
$CLAUDE_FILE_PATH— 被编辑/写入文件的路径$CLAUDE_TOOL_NAME— 使用的工具名称$CLAUDE_SESSION_ID— 当前会话标识符$CLAUDE_PROJECT_DIR— 项目目录路径
最佳实践
✅ 应该:
- 保持钩子快速(< 1 秒)
- 使用钩子进行验证和自动化
- 优雅地处理错误
- 使用绝对路径
❌ 不应该:
- 让钩子具有交互性
- 用钩子处理长时运行的任务
- 硬编码凭据
参见:06-hooks/ 获取详细示例
检查点与回退
概述
检查点允许你保存对话状态并回退到之前的时间点,从而实现安全实验和探索多种方案。
核心概念
| 概念 | 描述 |
|---|---|
| 检查点 | 对话状态的快照,包括消息、文件和上下文 |
| 回退 | 返回到之前的检查点,放弃后续更改 |
| 分支点 | 从该检查点探索多种方案 |
访问检查点
每次用户提示都会自动创建检查点。要回退:
bash
# 按两次 Esc 打开检查点浏览器
Esc + Esc
# 或使用 /rewind 命令
/rewind选择检查点后,你可以从以下五个选项中选择:
- 恢复代码和对话 — 将两者都恢复到该时间点
- 恢复对话 — 回退消息,保留当前代码
- 恢复代码 — 恢复文件,保留对话
- 从此处摘要 — 将对话压缩为摘要
- 取消 — 取消操作
使用场景
| 场景 | 工作流 |
|---|---|
| 探索方案 | 保存 → 尝试方案 A → 保存 → 回退 → 尝试方案 B → 对比 |
| 安全重构 | 保存 → 重构 → 测试 → 如果失败:回退 |
| A/B 测试 | 保存 → 设计 A → 保存 → 回退 → 设计 B → 对比 |
| 错误恢复 | 发现问题 → 回退到上一个良好状态 |
配置
json
{
"autoCheckpoint": true
}参见:08-checkpoints/ 获取详细示例
高级功能
计划模式
在编码前创建详细的实现计划。
激活:
bash
/plan Implement user authentication system收益:
- 带时间估算的清晰路线图
- 风险评估
- 系统化任务分解
- 审查和修改的机会
扩展思考
对复杂问题进行深度推理。
激活:
- 在会话中通过
Alt+T(macOS 上为Option+T)切换 - 以编程方式设置
MAX_THINKING_TOKENS环境变量
bash
# 通过环境变量启用扩展思考
export MAX_THINKING_TOKENS=50000
claude -p "Should we use microservices or monolith?"收益:
- 深入分析权衡
- 更好的架构决策
- 考虑边缘情况
- 系统化评估
后台任务
无需阻塞对话即可运行长时间操作。
用法:
bash
用户:在后台运行测试
Claude:已启动任务 bg-1234
/task list # 显示所有任务
/task status bg-1234 # 检查进度
/task show bg-1234 # 查看输出
/task cancel bg-1234 # 取消任务权限模式
控制 Claude 可以执行的操作。
| 模式 | 描述 | 使用场景 |
|---|---|---|
| default | 标准权限,对敏感操作提示确认 | 常规开发 |
| acceptEdits | 自动接受文件编辑无需确认 | 受信任的编辑工作流 |
| plan | 仅分析和计划,不修改文件 | 代码审查,架构规划 |
| auto | 自动批准安全操作,仅对风险操作提示 | 平衡自主性与安全性 |
| dontAsk | 无确认提示执行所有操作 | 有经验的用户,自动化 |
| bypassPermissions | 完全不受限访问,无安全检查 | CI/CD 流水线,受信任脚本 |
用法:
bash
claude --permission-mode plan # 只读分析
claude --permission-mode acceptEdits # 自动接受编辑
claude --permission-mode auto # 自动批准安全操作
claude --permission-mode dontAsk # 无确认提示无头模式(打印模式)
使用 -p(打印)标志在无需交互输入的情况下运行 Claude Code,用于自动化和 CI/CD。
用法:
bash
# 运行特定任务
claude -p "Run all tests"
# 通过管道传入进行分析
cat error.log | claude -p "explain this error"
# CI/CD 集成(GitHub Actions)
- name: AI Code Review
run: claude -p "Review PR changes and report issues"
# 用于脚本的 JSON 输出
claude -p --output-format json "list all functions in src/"定时任务
使用 /loop 命令按重复计划运行任务。
用法:
bash
/loop every 30m "Run tests and report failures"
/loop every 2h "Check for dependency updates"
/loop every 1d "Generate daily summary of code changes"定时任务在后台运行,完成时报告结果。它们适用于持续监控、定期检查和自动维护工作流。
Chrome 集成
Claude Code 可以与 Chrome 浏览器集成,用于网络自动化任务。这使得可以在开发工作流中直接导航网页、填写表单、截图和从网站提取数据。
会话管理
管理多个工作会话。
命令:
bash
/resume # 恢复上一次对话
/rename "Feature" # 命名当前会话
/fork # 派生到新会话
claude -c # 继续最近的对话
claude -r "Feature" # 按名称/ID 恢复会话交互功能
键盘快捷键:
Ctrl + R— 搜索命令历史Tab— 自动补全↑ / ↓— 命令历史Ctrl + L— 清屏
多行输入:
bash
用户:\
> 长而复杂的提示词
> 跨多行
> \end配置
完整配置示例:
json
{
"planning": {
"autoEnter": true,
"requireApproval": true
},
"extendedThinking": {
"enabled": true,
"showThinkingProcess": true
},
"backgroundTasks": {
"enabled": true,
"maxConcurrentTasks": 5
},
"permissions": {
"mode": "default"
}
}参见:09-advanced-features/ 获取全面指南
资源
最后更新:2026 年 3 月适用于 Claude Haiku 4.5、Sonnet 4.6 和 Opus 4.6现包含:钩子、检查点、计划模式、扩展思考、后台任务、权限模式(6 种)、无头模式、会话管理、自动记忆、代理团队、定时任务、Chrome 集成、Channels、语音输入和内置技能