本教程面向希望自定义Claude Code工作流的开发者,系统讲解如何从零创建一个功能完整的Skill。你将学会Skill的文件结构、YAML Frontmatter全部15个字段的用法、动态上下文注入、子Agent执行、权限控制,以及打包发布到Plugin市场的完整流程。学完后,你可以将团队常用的代码审查、部署、文档生成等工作流封装为可复用的Skill。
适用人群:已安装Claude Code、有基本命令行操作经验的开发者。
学习目标: - 理解Skill的架构和加载机制 - 掌握SKILL.md的编写规范 - 能独立创建带动态注入和子Agent的高级Skill - 了解Skill的测试、调试和分发方法
Skill的本质是一个文件夹,核心是SKILL.md文件。Claude Code通过扫描特定目录发现并加载Skill。
my-skill/
├── SKILL.md # 主指令文件(必需)
├── template.md # 模板文件(可选)
├── examples/
│ └── sample.md # 示例输出(可选)
├── references/
│ └── api-spec.md # 参考文档(可选)
└── scripts/
└── helper.py # 辅助脚本(可选)
Skill的作用域由存放位置决定,这是理解Skill系统的第一步:
| 位置 | 路径 | 生效范围 |
|---|---|---|
| 企业级 | 托管设置 | 组织全部用户 |
| 个人级 | ~/.claude/skills/<skill-name>/SKILL.md |
你的所有项目 |
| 项目级 | .claude/skills/<skill-name>/SKILL.md |
仅当前项目 |
| 插件级 | <plugin>/skills/<skill-name>/SKILL.md |
插件启用处 |
优先级规则:同名Skill,企业级覆盖个人级,个人级覆盖项目级。插件Skill使用plugin-name:skill-name命名空间,不会产生冲突。
flowchart TD
A[Claude Code启动] --> B[扫描Skill目录]
B --> C[加载元数据<br>description字段]
C --> D{用户消息匹配<br>Skill描述?}
D -->|是| E[加载完整SKILL.md内容]
D -->|否| F[仅保留元数据在上下文中]
E --> G[执行Skill指令]
G --> H{有!`cmd`注入?}
H -->|是| I[运行Shell命令<br>替换输出到正文]
H -->|否| J[直接发送给Claude]
I --> J
F --> K[等待下次匹配]
style A fill:#2563eb,color:#fff
style D fill:#f59e0b,color:#fff
style E fill:#10b981,color:#fff
关键理解点:Skill的元数据(description)始终在上下文中,但完整的SKILL.md正文只在触发时才加载。这意味着你可以在Skill中放置大量参考材料而不影响日常上下文开销。
我们从最简单的Skill开始——一个自动总结Git变更并标记风险的工具。
mkdir -p ~/.claude/skills/summarize-changes
cat > ~/.claude/skills/summarize-changes/SKILL.md << 'SKILL_EOF'
---
description: Summarizes uncommitted changes and flags anything risky. Use when the user asks what changed, wants a commit message, or asks to review their diff.
---
## Current changes
!`git diff HEAD`
## Instructions
Summarize the changes above in two or three bullet points, then list any risks you notice such as missing error handling, hardcoded values, or tests that need updating. If the diff is empty, say there are no uncommitted changes.
SKILL_EOF
启动Claude Code并测试两种触发方式:
# 进入任意Git项目
cd ~/my-project
claude
方式一:自然语言触发
> What did I change?
Claude会自动匹配到这个Skill的description,加载并执行。
方式二:直接命令调用
> /summarize-changes
注意到!git diff HEAD``这一行了吗?这是Skill最强大的特性之一:
!command`` 语法在Skill发送给Claude之前执行Shell命令多行命令使用代码块语法:
## Environment
```!
node --version
npm --version
git status --short
```
SKILL.md的YAML Frontmatter有15个可配置字段,每个控制Skill行为的不同方面。
---
# === 基础字段 ===
name: my-skill # 显示名称,kebab-case,最长64字符
description: What & when to use # 触发依据,最长1024字符(最重要的字段)
when_to_use: Extra trigger info # 补充触发上下文,追加到description
# === 交互控制 ===
argument-hint: "[issue-number]" # 自动补全提示
arguments: issue branch # 命名位置参数
disable-model-invocation: true # 禁止Claude自动触发
user-invocable: false # 从/菜单隐藏
# === 执行控制 ===
allowed-tools: Read Grep Bash # 预授权工具列表
model: claude-sonnet-4-6 # 覆盖会话模型
effort: high # 覆盖思考预算
context: fork # 在子Agent中运行
agent: Explore # 子Agent类型
# === 高级特性 ===
hooks: # 生命周期钩子
paths: "*.ts,*.tsx" # 文件路径匹配自动激活
shell: powershell # Shell类型(Windows)
---
description是Claude决定何时触发Skill的依据。写好description遵循"三要素公式":
做什么(What) + 何时用(When) + 产出什么(Output)
反面教材:
# 太模糊 —— 无法判断触发时机
description: Helps with git stuff
# 太技术化 —— 描述实现而非用途
description: Queries /api/v2/sprint endpoint with OAuth2
# 太宽泛 —— 会过度触发
description: Assists with any development task
正面示范:
# 精准触发:领域 + 场景 + 产出
description: >
Reviews pull requests for security vulnerabilities using OWASP Top 10.
Use when reviewing PRs that touch authentication, authorization, or
data handling code. Checks for SQL injection, XSS, and CSRF patterns.
两个关键字段组合出四种调用模式:
| disable-model-invocation | user-invocable | 效果 | 适用场景 |
|---|---|---|---|
| false(默认) | true(默认) | 双方都可调用 | 通用工具 |
| true | true | 仅用户手动/name |
部署、发布 |
| false | false | 仅Claude自动调用 | 背景知识库 |
| true | false | 无人可调用(无意义) | — |
实战示例——部署Skill必须手动触发:
---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
allowed-tools: Bash(git add *) Bash(git commit *) Bash(npm run build *)
---
Deploy $ARGUMENTS to production:
1. Run the test suite
2. Build the application
3. Push to the deployment target
4. Verify the deployment succeeded
Skill支持三种参数占位符:
---
name: fix-issue
description: Fix a GitHub issue by number
arguments: issue_branch
---
| 占位符 | 说明 | 示例 |
|---|---|---|
$ARGUMENTS |
全部参数 | /fix-issue 123 fix-login → 123 fix-login |
$0, $1, $2 |
按位置索引 | $0 → 123, $1 → fix-login |
$issue_branch |
命名参数(映射arguments字段) | $issue_branch → 123 |
命名参数示例:
---
name: migrate-component
description: Migrate a component from one framework to another
arguments: component from_framework to_framework
---
Migrate the $component component from $from_framework to $to_framework.
Preserve all existing behavior and tests.
调用:/migrate-component SearchBar React Vue
除了用户参数,还有系统变量:
| 变量 | 说明 |
|---|---|
${CLAUDE_SESSION_ID} |
当前会话ID |
${CLAUDE_EFFORT} |
当前思考级别 |
${CLAUDE_SKILL_DIR} |
Skill所在目录的绝对路径 |
${CLAUDE_SKILL_DIR}在引用捆绑脚本时特别有用:
Run the analysis script:
```bash
python3 ${CLAUDE_SKILL_DIR}/scripts/analyze.py $ARGUMENTS
---
## 第四步:构建高级Skill——子Agent与隔离执行
当Skill需要大量探索性工作或长时间运行的任务时,使用`context: fork`在隔离的子Agent中执行。
### 4.1 工作原理
```mermaid
sequenceDiagram
participant U as 用户
participant M as 主Agent
participant S as 子Agent(Explore)
U->>M: /deep-research "认证流程"
M->>M: 检测context: fork
M->>S: 创建隔离上下文<br>SKILL.md内容作为Prompt
Note over S: 无会话历史<br>仅CLAUDE.md + Skill内容
S->>S: 使用Explore工具集<br>Glob/Grep/Read
S->>M: 返回研究结果摘要
M->>U: 展示研究结果
---
name: deep-research
description: >
Research a codebase topic thoroughly with file references.
Use when understanding architecture, tracing data flow,
or investigating unfamiliar code patterns.
context: fork
agent: Explore
allowed-tools: Bash(grep *) Bash(find *)
---
Research "$ARGUMENTS" thoroughly:
1. Use Glob to find relevant files matching the topic
2. Use Grep to search for key terms and patterns
3. Read the most relevant files to understand the implementation
4. Create a structured report with:
- Summary of findings (2-3 paragraphs)
- Key files involved (with paths and line numbers)
- Architecture diagram in Mermaid syntax
- Open questions or areas needing further investigation
Format the output as Markdown with clear sections.
| Agent类型 | 工具集 | 适用场景 |
|---|---|---|
Explore |
Glob, Grep, Read(只读) | 代码探索、架构调研 |
Plan |
全部(只读) | 设计实施方案 |
general-purpose |
全部 | 通用任务 |
注意:Explore和Plan类型的子Agent不会加载CLAUDE.md和git status,保持上下文精简。如果Skill中的指令是"参考性知识"而非"可执行任务",子Agent会因为没有明确任务而空转返回。
我们将创建一个完整的、生产级别的PR审查Skill,涵盖前面所有知识点。
mkdir -p ~/.claude/skills/pr-review/{scripts,references}
cat > ~/.claude/skills/pr-review/SKILL.md << 'SKILL_EOF'
---
name: pr-review
description: >
Performs comprehensive code review on a pull request.
Use when reviewing PRs, checking code quality, identifying bugs,
or when the user says "review this PR" or "check my changes".
Covers security, performance, readability, and test coverage.
argument-hint: "[PR-number]"
allowed-tools: Bash(gh *) Read Grep Glob
disable-model-invocation: false
when_to_use: >
Triggers on: review PR, check code, code review, look at my changes,
review this pull request, any mention of PR review.
---
# PR Code Review
## PR Context
```!
gh pr view ${PR_NUMBER:-HEAD} --json title,body,author,files,additions,deletions
```! gh pr diff ${PR_NUMBER:-HEAD}
## Changed Files
```!
gh pr diff ${PR_NUMBER:-HEAD} --name-only
Perform a systematic review across these dimensions:
Produce a structured review:
[2-3 sentence overview of the changes]
[Must fix before merging]
- File: path/to/file.ts:L42
- Issue: Description
- Fix: Specific recommendation
[Should address] - Same format as above
[Nice to have improvements]
[Are the changes adequately tested?]
APPROVE / REQUEST CHANGES / COMMENT
gh command fails: Ask the user to install GitHub CLI or check authentication### 5.3 添加参考文档
```bash
cat > ~/.claude/skills/pr-review/references/owasp-checklist.md << 'REF_EOF'
# OWASP Top 10 Quick Reference
| # | Risk | What to Check |
|---|------|---------------|
| A01 | Broken Access Control | Missing auth checks, IDOR, CORS misconfig |
| A02 | Cryptographic Failures | Hardcoded secrets, weak hashing, plaintext storage |
| A03 | Injection | Unparameterized SQL, eval(), template injection |
| A04 | Insecure Design | Missing rate limiting, no input validation |
| A05 | Security Misconfiguration | Default credentials, verbose errors, unused features |
| A06 | Vulnerable Components | Outdated dependencies with known CVEs |
| A07 | Auth Failures | Weak password policies, missing MFA, session fixation |
| A08 | Data Integrity Failures | Untrusted deserialization, unsigned updates |
| A09 | Logging Failures | Missing audit logs, sensitive data in logs |
| A10 | SSRF | Unvalidated URLs, internal service access |
For detailed checklist, refer to [reference.md](reference.md).
REF_EOF
# 在项目目录中
claude
# 方式一:自然语言
> review my latest PR
# 方式二:指定PR号
> /pr-review 42
# 方式三:Claude自动识别场景
> I just opened a PR, can you check it?
Claude会按照SKILL.md中定义的格式输出结构化审查结果:
### Summary
This PR adds JWT-based authentication to the user API endpoints,
including login, logout, and token refresh flows. The implementation
covers 3 new routes with corresponding middleware.
### Critical Issues 🔴
- **File**: `src/auth/middleware.ts:L28`
- **Issue**: Token secret is read from env but has no fallback validation
- **Fix**: Add startup check: `if (!process.env.JWT_SECRET) throw new Error(...)`
### Warnings 🟡
- **File**: `src/auth/routes.ts:L67`
- **Issue**: refreshTokens array is in-memory, lost on restart
- **Fix**: Use Redis or database for token storage
### Suggestions 🟢
- Consider adding rate limiting to /login endpoint
- Token expiry could be configurable via environment variable
### Verdict
**REQUEST CHANGES** — 1 critical issue must be addressed.
理解Skill在会话中的生命周期对于编写高质量Skill至关重要。
一旦Skill被触发,其完整SKILL.md内容会作为单条消息进入对话,并在会话剩余时间内保持。Claude Code不会在后续轮次重新读取文件。
这意味着: - 将需要在整个任务中持续的指令写成"持续性指令"而非"一次性步骤" - Skill内容是常驻token开销,保持简洁
当对话接近上下文窗口限制时,Claude Code执行自动压缩:
flowchart LR
A[会话接近<br>上下文上限] --> B[压缩摘要]
B --> C[重新附加<br>最近触发的Skill]
C --> D{Token预算}
D -->|每个Skill<br>前5000 tokens| E[保留]
D -->|总计<br>25000 tokens| F[从最新Skill<br>开始填充]
F --> G[超出预算的<br>旧Skill被丢弃]
style A fill:#ef4444,color:#fff
style D fill:#f59e0b,color:#fff
style G fill:#ef4444,color:#fff
实用建议: - 保持SKILL.md正文在500行以内 - 关键指令放在文件顶部 - 如果Skill在压缩后停止影响行为,重新调用一次即可恢复
所有Skill的描述(description + when_to_use)共享一个上下文预算,为模型上下文窗口的1%。当预算溢出时:
/doctor检查预算状态调优方法:
// .claude/settings.json
{
"skillOverrides": {
"legacy-context": "name-only", // 仅显示名称,释放描述预算
"deprecated-skill": "off" // 完全隐藏
}
}
| 问题 | 原因 | 解决方案 |
|---|---|---|
| Skill未被触发 | description缺少关键词 | 添加用户可能说的自然语言 |
| Skill过度触发 | description过于宽泛 | 缩小范围,明确触发场景 |
| 描述被截断 | 超出1536字符或预算溢出 | 将核心用途放在开头,精简文本 |
| 动态注入失败 | !后跟了非空白字符 |
确保!在行首或紧跟空白 |
| 子Agent空转 | 内容是参考知识而非任务 | 在正文中包含明确的可执行步骤 |
# 检查Skill是否被发现
claude
> What skills are available?
# 诊断配置问题
> /doctor
# 查看特定Skill的完整内容(验证渲染结果)
# 直接读取文件确认frontmatter格式
flowchart TD
A[编写SKILL.md] --> B[手动测试<br>/skill-name]
B --> C{行为符合预期?}
C -->|是| D[多场景测试]
C -->|否| E[分析问题]
E --> F{触发问题?}
F -->|未触发| G[优化description<br>添加when_to_use]
F -->|过度触发| H[缩小description范围<br>或加disable-model-invocation]
F -->|输出质量差| I[细化指令<br>添加示例和checklist]
G --> B
H --> B
I --> B
D --> J{覆盖足够?}
J -->|是| K[发布]
J -->|否| L[补充边界用例]
L --> B
style A fill:#2563eb,color:#fff
style K fill:#10b981,color:#fff
将.claude/skills/提交到Git仓库,团队自动获得:
git add .claude/skills/
git commit -m "Add code review and deploy skills"
创建一个Plugin包来分发Skill:
# 1. 创建Plugin仓库结构
my-plugin/
├── SKILL.md # Plugin描述(可选)
├── skills/
│ ├── pr-review/
│ │ └── SKILL.md
│ └── deploy/
│ └── SKILL.md
└── package.json # Plugin元数据
# 2. 注册为Plugin市场
claude
> /plugin marketplace add your-org/your-plugin-repo
# 3. 或直接安装
> /plugin install plugin-name@marketplace-name
通过托管设置(Managed Settings)向组织全体推送Skill,适用于安全审查、代码规范等统一标准场景。
Skill可以捆绑脚本生成可视化HTML,这是超越纯文本输出的强大模式。
mkdir -p ~/.claude/skills/codebase-visualizer/scripts
SKILL.md:
---
name: codebase-visualizer
description: >
Generate an interactive collapsible tree visualization of your codebase.
Use when exploring a new repo, understanding project structure,
or identifying large files.
allowed-tools: Bash(python3 *)
---
# Codebase Visualizer
Generate an interactive HTML tree view of the project.
## Usage
```bash
python3 ${CLAUDE_SKILL_DIR}/scripts/visualize.py .
This creates codebase-map.html and opens it in the browser.
将Python脚本放在`scripts/visualize.py`中,使用`${CLAUDE_SKILL_DIR}`确保路径正确。
---
## 第十步:权限控制与安全实践
### 10.1 Skill访问控制
三种方式限制Claude调用Skill:
```bash
# 方式一:在Skill中设置
disable-model-invocation: true
# 方式二:通过权限规则
# .claude/settings.json
{
"permissions": {
"allow": ["Skill(commit)", "Skill(review-pr *)"],
"deny": ["Skill(deploy *)"]
}
}
# 方式三:完全禁止Skill工具
# /permissions deny Skill
allowed-tools让Skill预授权工具使用,但需注意:
allowed-tools,避免过度授权disable-model-invocation: trueflowchart TD
subgraph 创建阶段
A[确定Skill用途] --> B[选择存放位置<br>个人/项目/插件]
B --> C[创建目录和SKILL.md]
C --> D[编写description<br>三要素公式]
D --> E[编写指令正文<br>具体可操作]
end
subgraph 增强阶段
E --> F{需要动态数据?}
F -->|是| G[添加!`cmd`注入]
F -->|否| H{需要隔离执行?}
G --> H
H -->|是| I[设置context: fork]
H -->|否| J{需要捆绑资源?}
I --> J
J -->|是| K[添加scripts/references/]
J -->|否| L[配置allowed-tools]
K --> L
end
subgraph 测试阶段
L --> M[手动调用测试]
M --> N{触发正确?}
N -->|未触发| O[优化description]
N -->|过度触发| P[添加disable-model-invocation]
N -->|质量不佳| Q[细化指令和示例]
O --> M
P --> M
Q --> M
end
subgraph 发布阶段
N -->|通过| R{分发方式}
R -->|团队| S[提交到Git仓库]
R -->|社区| T[创建Plugin]
R -->|企业| U[托管设置分发]
end
style A fill:#2563eb,color:#fff
style M fill:#f59e0b,color:#fff
style R fill:#10b981,color:#fff
以下是经过验证的通用SKILL.md模板,适合大多数场景:
---
name: your-skill-name
description: >
[做什么 — 一句话描述核心功能].
Use when [何时用 — 列出2-3个触发场景].
[产出 — 说明输出格式或效果].
when_to_use: >
Triggers on: [关键词1], [关键词2], [自然语言触发示例].
argument-hint: "[参数提示]"
allowed-tools: [工具列表]
disable-model-invocation: false
---
# [Skill名称]
## Context
[当前状态或动态注入的数据]
!`relevant-command-here`
## Instructions
[具体、可操作的步骤列表]
1. Step one — use the [Tool] to [action]
2. Step two — check [specific criteria]
3. Step three — generate [output format]
## Output Format
[期望的输出结构]
## Error Handling
- If [error condition]: [fallback action]
- If [missing data]: [ask user or skip]
## Guidelines
- [规则1]
- [规则2]
- [注意事项]
# 差
Review the code and suggest improvements.
# 好
Use the Read tool to load each changed file. Check against these criteria:
- No hardcoded secrets (API keys, passwords, tokens)
- All public functions have error handling
- SQL queries use parameterized statements
For each issue: file path, line number, severity, fix recommendation.
SKILL.md正文建议控制在500行以内。将详细参考材料拆分到references/子目录,在正文中用链接引用。
自动压缩时每个Skill只保留前5000 tokens。将最关键的指令放在文件开头。
disable-model-invocation: true| 维度 | 评估 |
|---|---|
| 适合训练营类型 | 企业内部AI工具培训、开发者效率提升营、DevOps自动化工坊 |
| 预计教学时长 | 4-6小时(含动手练习) |
| 学员基础要求 | 基本命令行操作、YAML语法、Git使用经验 |
| 实操占比 | 70%(每步都有可运行代码) |
| 建议分组 | 2-3人小组,各自创建不同类型的Skill后互相演示 |
[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。
