学习目标:掌握Claude Code Skill的核心文件格式SKILL.md,理解全部YAML frontmatter字段的语义和用法,学会编写高质量指令的五大设计原则,并通过一个完整的代码审查Skill实战项目,打通从规范理解到可发布Skill的全流程。
适用人群:已具备Claude Code基本使用经验,希望构建高质量、可复用、可分发自定义Skill的开发者和团队负责人。
SKILL.md是Claude Code Skill的核心载体——一个纯文本Markdown文件,通过YAML frontmatter声明元数据,通过Markdown正文定义行为指令。它不依赖任何API、SDK或编译步骤,本质上就是结构化的自然语言程序。
Claude Code在启动时会扫描特定目录下的SKILL.md文件,将其内容加载到上下文窗口中,作为Claude行为的持久化知识层。这意味着Skill的效果完全取决于文件内容的精确度。
Skill文件有三个存放层级,对应不同的作用域:
~/.claude/skills/ ← 全局级:所有项目可用
├── code-review/
│ └── SKILL.md
└── security-scan/
└── SKILL.md
your-project/.claude/skills/ ← 项目级:仅当前项目
├── api-style/
│ └── SKILL.md
└── db-migration/
└── SKILL.md
your-project/.claude/commands/ ← 自定义命令(旧格式,仍兼容)
├── deploy.md
└── test-all.md
加载优先级:项目级 > 全局级。当两个层级的Skill名称冲突时,项目级覆盖全局级。
一个最小的SKILL.md只需要两个字段:
---
name: hello-reviewer
description: A simple code review skill that checks for common issues.
---
# Hello Reviewer
When reviewing code, always check for:
1. Missing error handling
2. Unused imports
3. Hardcoded secrets
但生产级Skill需要充分利用全部字段。下面逐一拆解。
当前SKILL.md规范定义了15个YAML frontmatter字段。按功能分为四组:
| 分组 | 字段 | 必填 | 类型 | 作用 |
|---|---|---|---|---|
| 身份 | name |
是 | string | Skill唯一标识符 |
description |
是 | string | 向Agent说明何时激活 | |
version |
否 | string | 语义化版本号 | |
| 行为控制 | instructions |
否 | string | 指令正文(也可写在Markdown body中) |
disable-model-invocation |
否 | boolean | 是否禁止模型自主调用 | |
auto-activate |
否 | boolean | 是否自动检测激活 | |
| 工具权限 | tools |
否 | list | 允许使用的工具列表 |
allowed-tools |
否 | list | 工具白名单(与tools互补) | |
blocked-tools |
否 | list | 工具黑名单 | |
| 输入输出 | variables |
否 | object | 模板变量定义 |
input |
否 | object | 输入参数schema | |
output |
否 | object | 输出格式定义 | |
| 生命周期 | hooks |
否 | object | 前后置钩子 |
dependencies |
否 | list | 依赖的其他Skill或MCP服务器 | |
metadata |
否 | object | 自定义扩展元数据 |
name(必填)Skill的唯一标识符,必须与所在文件夹名称完全一致。这是Claude Code查找和加载Skill的依据。
# 如果文件路径是 .claude/skills/api-reviewer/SKILL.md
name: api-reviewer # ✓ 正确:与文件夹名一致
name: api_reviewer # ✗ 错误:下划线不匹配
name: API-Reviewer # ✗ 错误:大小写不匹配
命名规范:
- 使用kebab-case(短横线分隔)
- 长度3-40个字符
- 只允许小写字母、数字和短横线
- 避免使用claude、anthropic等保留前缀
description(必填)这不是给人看的描述,而是给Agent看的路由指令。Agent根据description字段判断当前任务是否应该激活此Skill。因此description需要精确描述Skill的触发条件和适用场景。
# ✗ 差的描述:太模糊
description: A helpful tool for developers.
# ✓ 好的描述:精确的触发条件
description: >
Use when reviewing Python REST API code for security vulnerabilities.
Triggers on files matching routes/*.py, views/*.py, or api/*.py.
Activates for tasks mentioning "API review", "security audit", or "endpoint check".
description的最佳实践: - 包含何时使用(When to use) - 包含适用文件模式(File patterns) - 包含触发关键词(Trigger keywords) - 控制在2-4行以内
version遵循语义化版本规范(SemVer),用于插件市场版本管理和依赖解析:
version: 1.2.0
auto-activate控制Skill是否被自动检测并激活。默认为true。
# 只有用户明确 /skill-name 时才激活
auto-activate: false
适用场景: - 重量级Skill(消耗大量上下文) - 专用Skill(只在特定情况下需要) - 调试中的Skill
disable-model-invocation禁止模型在后台自动调用此Skill。与auto-activate不同,这个字段完全阻止Skill被执行,除非用户通过斜杠命令显式触发。
disable-model-invocation: true
典型用途:将Skill作为参考文档而非可执行指令。
tools / allowed-tools / blocked-tools这三个字段形成完整的工具权限矩阵:
# 模式一:白名单——只允许指定工具
allowed-tools:
- Read
- Grep
- Glob
# 模式二:黑名单——禁止指定工具
blocked-tools:
- Bash # 禁止执行shell命令
- Write # 禁止写入文件(只读模式)
# 模式三:混合——允许大部分但排除危险操作
tools:
- Read
- Grep
- Glob
- Edit
blocked-tools:
- Bash
可用工具列表:
| 工具 | 用途 | 风险等级 |
|---|---|---|
| Read | 读取文件 | 低 |
| Glob | 文件搜索 | 低 |
| Grep | 内容搜索 | 低 |
| Edit | 编辑文件 | 中 |
| Write | 创建文件 | 中 |
| Bash | Shell命令 | 高 |
| Task | 子Agent | 中 |
| WebSearch | 网络搜索 | 低 |
variables定义模板变量,使Skill可以参数化复用。使用{{variable_name}}语法在正文中引用:
variables:
framework:
description: Target framework name
default: react
type: string
style-guide:
description: URL to the team style guide
type: string
required: false
max-complexity:
description: Maximum cyclomatic complexity allowed
default: 10
type: integer
在Markdown正文中引用:
# {{framework}} Code Review
Review all code against the style guide at {{style-guide}}.
Flag any function with cyclomatic complexity > {{max-complexity}}.
变量类型支持:string、integer、boolean、enum、list。
input / output定义结构化的输入参数schema和输出格式,为Skill之间的组合调用提供类型安全:
input:
type: object
properties:
file_path:
type: string
description: Path to the file to review
severity_threshold:
type: enum
values: [low, medium, high, critical]
default: medium
output:
type: object
properties:
issues:
type: list
description: List of found issues
summary:
type: string
description: Brief review summary
score:
type: integer
description: Code quality score (0-100)
hooks定义Skill执行前后的钩子函数,用于数据准备和结果处理:
hooks:
pre-invoke:
- name: validate-project
description: Ensure the project has the required structure
post-invoke:
- name: cleanup-temp-files
description: Remove temporary files created during skill execution
dependencies声明Skill运行所需的外部依赖:
dependencies:
skills:
- name: security-scanner
version: ">=1.0.0"
- name: test-runner
mcp-servers:
- name: filesystem
- name: github
metadata自定义扩展字段,不参与Skill执行逻辑,但可用于插件市场展示和分类:
metadata:
author: your-team
tags: [security, code-review, python]
license: MIT
repository: https://github.com/your-org/claude-skills
min-claude-version: 1.0.25
拥有完整的YAML字段知识只是基础。Skill的效果90%取决于正文中的指令质量。以下是从分析数百个社区Skill中提炼出的五大设计原则。
差指令告诉Claude"做什么",好指令告诉Claude"在什么条件下做什么、在什么条件下不做"。
<!-- ✗ 模糊指令 -->
Review the code and find issues.
<!-- ✓ 锚定指令 -->
## Activation Conditions
Activate this skill ONLY when:
- User explicitly asks for a code review, OR
- The file being edited is in src/api/ directory
DO NOT activate when:
- User is writing tests
- User is making documentation changes
## Review Scope
For each file under review, check:
1. **Error handling**: Every async function must have try/catch
2. **Input validation**: All external inputs must be validated with zod schemas
3. **SQL injection**: Parameterized queries only in database calls
将指令分为三个层级:必做(MUST)、应该(SHOULD)、可选(MAY)。这避免了指令全部被当作同等重要而导致的优先级混乱。
## Review Rules
### MUST (Block on violation)
- [SECURITY] No hardcoded secrets or API keys
- [SECURITY] All user inputs sanitized before database operations
- [CRASH] No unhandled promise rejections in async code
### SHOULD (Warn but don't block)
- [STYLE] Consistent naming conventions per file
- [PERF] Avoid N+1 database queries in loops
- [MAINT] Functions should not exceed 50 lines
### MAY (Suggest as improvement)
- [DX] Consider extracting repeated logic into utility functions
- [TEST] Missing test coverage for edge cases
大语言模型对示例的理解远超抽象描述。每个关键行为都应该附带完整的输入输出示例。
## Output Format
When reporting issues, use this exact format:
### Example Output
⚠️ SECURITY [HIGH] src/api/users.ts:42
Issue: SQL injection via string concatenation
Code: query('SELECT * FROM users WHERE id = ' + userId)
Fix: query('SELECT * FROM users WHERE id = $1', [userId])
ℹ️ STYLE [LOW] src/api/users.ts:78
Issue: Function name doesn't match convention
Code: function getUserData()
Fix: function fetchUser() (use 'fetch' for API calls)
告诉Claude不该做什么,和告诉它该做什么同样重要。否定约束可以防止常见的"过度热情"问题。
## Constraints (DO NOT)
- DO NOT modify files outside the review scope
- DO NOT add new dependencies without explicit approval
- DO NOT rewrite working code to match personal style preferences
- DO NOT suggest changes that would break existing tests
- DO NOT output more than 20 issues per file (prioritize by severity)
将所有可变参数集中到YAML variables中,使指令正文保持稳定和通用。
variables:
severity-threshold:
type: enum
values: [info, warn, error, critical]
default: warn
description: Minimum severity level to report
max-issues-per-file:
type: integer
default: 20
description: Maximum number of issues to report per file
ignore-patterns:
type: list
default: ["*.test.ts", "*.spec.ts", "**/generated/**"]
description: File patterns to exclude from review
## Configuration
- Report severity: {{severity-threshold}} and above
- Max issues per file: {{max-issues-per-file}}
- Skip files matching: {{ignore-patterns}}
现在将上述全部知识应用到一个完整的实战项目中。我们将构建一个api-security-reviewer Skill,用于审查REST API端点的安全漏洞。
~/.claude/skills/api-security-reviewer/
├── SKILL.md # 主文件
└── references/
└── owasp-top10.md # 参考资料(可选)
---
name: api-security-reviewer
description: >
Activate when reviewing API endpoint code for security vulnerabilities.
Triggers on files in routes/, controllers/, api/, endpoints/ directories.
Keywords: "security review", "API audit", "vulnerability scan", "pen test".
version: 1.0.0
auto-activate: true
allowed-tools:
- Read
- Grep
- Glob
- Edit
blocked-tools:
- Bash
variables:
language:
description: Primary programming language of the API
type: enum
values: [typescript, python, go, java]
default: typescript
framework:
description: Web framework being used
type: string
default: express
severity-floor:
description: Minimum severity level to report
type: enum
values: [info, low, medium, high, critical]
default: medium
report-format:
description: Output format for findings
type: enum
values: [table, markdown, json]
default: markdown
metadata:
author: security-team
tags: [security, api, owasp, review]
license: MIT
---
# API Security Reviewer
## Activation Conditions
Activate this skill ONLY when:
- User explicitly requests a security review of API code
- User is editing files in routes/, controllers/, api/, or endpoints/ directories
- User mentions "security", "vulnerability", "OWASP", or "penetration test"
DO NOT activate when:
- User is writing frontend code
- User is modifying configuration files (docker-compose, CI/CD)
- User is working on documentation
## Review Checklist
### MUST Check (Block on finding)
1. **Injection (OWASP A03)**: All database queries use parameterized statements
2. **Authentication (OWASP A07)**: Every endpoint validates auth token before processing
3. **Access Control (OWASP A01)**: Role-based checks present for sensitive operations
4. **Input Validation**: Request body/params validated with schema (zod/joi/pydantic)
### SHOULD Check (Warn on finding)
5. **Rate Limiting**: Endpoints have appropriate rate limiting configured
6. **CORS**: Cross-origin headers are restrictive, not using wildcard `*`
7. **Error Handling**: Error responses don't leak stack traces or internal details
8. **Logging**: Security-relevant events are logged (auth failures, access denied)
### MAY Check (Suggest if time permits)
9. **HTTPS Enforcement**: API only accessible over HTTPS
10. **Response Headers**: Security headers present (X-Content-Type-Options, etc.)
## Language-Specific Rules
{{#if (eq language "typescript")}}
- Check for `any` type casts in request handlers
- Verify `express.json()` has size limits: `express.json({ limit: '10kb' })`
- Ensure `helmet` middleware is configured
{{/if}}
{{#if (eq language "python")}}
- Verify SQLAlchemy uses `text()` with parameters, not f-strings
- Check Flask/Django decorators for `@login_required` or `@permission_required`
- Ensure `CORS` configuration is restrictive
{{/if}}
{{#if (eq language "go")}}
- Check `sql.Query` uses `$1, $2` placeholders, not `fmt.Sprintf`
- Verify `jwt` token validation middleware is applied
- Ensure `http.Error` doesn't expose internal details
{{/if}}
## Output Format
{{#if (eq report-format "markdown")}}
### Example Output
File: src/api/users.ts
Reviewed: 2026-05-22
Framework: {{framework}}
| # | Severity | Category | Line | Issue | Status |
|---|---|---|---|---|---|
| 1 | 🔴 CRITICAL | Injection | 42 | Raw SQL query via string concat | MUST FIX |
| 2 | 🟡 HIGH | Auth | 15 | Missing auth middleware | MUST FIX |
| 3 | 🟠 MEDIUM | Validation | 78 | No request body schema | SHOULD FIX |
| 4 | 🔵 LOW | CORS | 3 | Wildcard CORS header | SUGGESTED |
{{/if}}
## Constraints (DO NOT)
- DO NOT modify production configuration files
- DO NOT add new npm/pip packages (only suggest)
- DO NOT write fixes automatically — present findings and let user decide
- DO NOT report issues below severity level: {{severity-floor}}
- DO NOT skip endpoints marked with `@skip-security-review` comment
## Severity Definitions
- **CRITICAL**: Exploitable remotely, no authentication required
- **HIGH**: Exploitable with valid user credentials
- **MEDIUM**: Requires specific conditions or internal access
- **LOW**: Best practice violation, limited attack surface
- **INFO**: Informational, no direct security impact
将Skill安装到项目中:
# 创建目录结构
mkdir -p your-project/.claude/skills/api-security-reviewer
# 将上面的SKILL.md内容写入文件
# 方式一:直接复制
cp SKILL.md your-project/.claude/skills/api-security-reviewer/
# 方式二:通过curl从远程仓库安装
mkdir -p your-project/.claude/skills
curl -sL https://example.com/skills/api-security-reviewer.tar.gz | tar xz -C your-project/.claude/skills/
验证Skill是否被加载:
# 在Claude Code中执行
claude
# 使用斜杠命令触发
/api-security-reviewer
# 或者让Claude自动检测
# 打开一个routes/目录下的文件,输入 "review this API endpoint for security issues"
当你编辑src/api/users.ts并请求安全审查时,Skill会:
Q: Skill没有被自动激活?
检查以下几点:
1. description是否包含当前文件的路径模式
2. auto-activate是否设为true(默认值)
3. 文件夹名与name字段是否完全一致
4. SKILL.md是否在正确的目录层级
Q: Skill没有使用限制的工具?
allowed-tools和blocked-tools只是建议性约束,在当前版本中Claude会尽量遵守但不是强制的。如果需要严格限制,配合Claude Code的--allowedTools参数使用。
Q: 变量默认值如何覆盖?
通过对话中直接指定:
/api-security-reviewer language=python severity-floor=high
graph TB
A[Skill测试金字塔] --> B[Layer 1: 加载验证]
A --> C[Layer 2: 触发测试]
A --> D[Layer 3: 行为验证]
B --> B1[SKILL.md语法检查]
B --> B2[文件夹名与name字段一致]
B --> B3[YAML字段完整性]
C --> C1[关键词触发测试]
C --> C2[文件路径触发测试]
C --> C3[显式命令触发测试]
D --> D1[输出格式合规性]
D --> D2[工具权限遵守]
D --> D3[否定约束验证]
第一层:加载验证
# 检查Skill是否被Claude Code识别
claude --list-skills
# 手动验证YAML语法
python3 -c "
import yaml, sys
with open('.claude/skills/api-security-reviewer/SKILL.md') as f:
content = f.read()
parts = content.split('---')
if len(parts) < 3:
sys.exit('Missing YAML frontmatter')
frontmatter = yaml.safe_load(parts[1])
assert 'name' in frontmatter, 'Missing name field'
assert 'description' in frontmatter, 'Missing description field'
print('✓ YAML frontmatter valid')
print(f' name: {frontmatter[\"name\"]}')
print(f' description: {frontmatter[\"description\"][:50]}...')
"
第二层:触发测试
准备一个测试用例文件,然后验证Skill是否能被正确激活:
# 创建测试用例
cat > /tmp/test-api-route.ts << 'EOF'
import express from 'express';
const router = express.Router();
// This endpoint has intentional security issues for testing
router.post('/users', async (req, res) => {
const { name, email } = req.body;
const result = await db.query(
`SELECT * FROM users WHERE email = '${email}'`
);
res.json(result);
});
EOF
# 在Claude Code中测试
claude
> Review /tmp/test-api-route.ts for security issues
# 预期:api-security-reviewer Skill被自动激活
第三层:行为验证
验证Skill的输出是否符合预期: - 是否按严重性排序 - 是否使用了正确的输出格式 - 是否遵守了否定约束(如不自动修复) - 是否检查了所有MUST级别的规则
| 反模式 | 表现 | 修复 |
|---|---|---|
| 描述过长 | description超过5行 | 精简为2-3行,聚焦触发条件 |
| 指令过宽 | "Review all code" | 限定到具体文件类型和目录 |
| 缺少示例 | 只有抽象规则 | 每个关键行为附带输入/输出对 |
| 无否定约束 | Claude过度修改代码 | 添加DO NOT清单 |
| 变量硬编码 | 框架名写在正文里 | 提取到variables中 |
graph LR
A[Skill开发完成] --> B{分发方式}
B --> C[npm包]
B --> D[Git仓库]
B --> E[插件市场]
C --> F[npm publish]
C --> G[团队npm install]
D --> H[Git submodule]
D --> I[install脚本]
E --> J[Plugin Marketplace]
E --> K[一键安装]
适用于需要在多个项目间共享Skill的团队:
// package.json
{
"name": "@your-org/claude-skill-security",
"version": "1.0.0",
"files": [".claude/skills/**/SKILL.md"],
"keywords": ["claude-code", "skill", "security"],
"scripts": {
"postinstall": "node scripts/install-skills.js"
}
}
// scripts/install-skills.js
const fs = require('fs');
const path = require('path');
const source = path.join(__dirname, '..', '.claude', 'skills');
const target = path.join(process.cwd(), '.claude', 'skills');
if (!fs.existsSync(target)) {
fs.mkdirSync(target, { recursive: true });
}
fs.cpSync(source, target, { recursive: true });
console.log('✓ Skills installed to .claude/skills/');
安装:
npm install @your-org/claude-skill-security
适用于私有团队,无需发布到npm:
# 方式A:Git Submodule
git submodule add https://github.com/your-org/claude-skills.git .claude/skills-shared
ln -s .claude/skills-shared/api-security-reviewer .claude/skills/api-security-reviewer
# 方式B:curl一键安装
mkdir -p .claude/skills
curl -sL https://raw.githubusercontent.com/your-org/claude-skills/main/install.sh | bash
Anthropic在2026年推出了官方插件市场,支持一键安装和版本管理:
# 发布到市场
claude plugin publish --skill api-security-reviewer
# 从市场安装
claude plugin install api-security-reviewer
# 搜索市场
claude plugin search "security review"
插件市场的Skill需要满足额外要求:
- 必须包含version字段
- 必须包含metadata.license
- 必须通过安全审核
- 必须有完整的description和示例
flowchart TD
A[需求分析] --> B[确定触发条件]
B --> C[编写YAML frontmatter]
C --> D[编写指令正文]
D --> E[本地测试]
E --> F{测试通过?}
F -->|否| G[调试修复]
G --> D
F -->|是| H[团队Review]
H --> I{Review通过?}
I -->|否| J[根据反馈修改]
J --> D
I -->|是| K[选择分发方式]
K --> L[npm / Git / 市场]
L --> M[版本管理与迭代]
style A fill:#4A90D9,color:#fff
style E fill:#F5A623,color:#fff
style K fill:#7ED321,color:#fff
style M fill:#BD10E0,color:#fff
需求分析阶段:明确三个问题—— 1. 这个Skill解决什么问题? 2. 什么时候需要触发? 3. 需要哪些工具权限?
本地测试阶段:至少覆盖三种场景—— 1. 正向触发(应该激活时是否激活) 2. 反向触发(不应该激活时是否沉默) 3. 边界条件(空输入、超长输入、无效参数)
版本管理:遵循SemVer—— - PATCH(1.0.x):修Bug、优化指令措辞 - MINOR(1.x.0):新增检查规则、新增变量 - MAJOR(x.0.0):改变输出格式、删除检查规则
一个Skill可以依赖另一个Skill,形成链式调用:
# .claude/skills/full-audit/SKILL.md
dependencies:
skills:
- name: api-security-reviewer
version: ">=1.0.0"
- name: performance-analyzer
## Execution Flow
1. Run `api-security-reviewer` first
2. Collect security findings
3. Run `performance-analyzer` next
4. Merge results into unified audit report
利用变量实现条件化指令分支:
variables:
environment:
type: enum
values: [development, staging, production]
default: development
{{#if (eq environment "production")}}
## Production-Specific Rules
- ALL endpoints must have authentication
- ALL database queries must use connection pooling
- ALL responses must have security headers
{{else}}
## Development Relaxations
- Authentication may be optional for health check endpoints
- Detailed error messages are acceptable
{{/if}}
Skill内容会被加载到上下文窗口中,因此控制Skill大小至关重要:
| 字段/段落 | 建议长度 | 原因 |
|---|---|---|
| description | ≤200字符 | 避免触发判断延迟 |
| MUST规则 | ≤10条 | 过多规则降低遵守率 |
| 每条规则描述 | ≤2行 | 简洁才有执行力 |
| 示例 | 1-2个 | 过多示例浪费上下文 |
| 总SKILL.md | ≤3KB | 超过3KB考虑拆分 |
在企业环境中,建议建立Skill治理流程:
.claude/skills/
├── _registry.md # Skill注册表(谁维护、最后更新时间)
├── api-security/
│ └── SKILL.md
├── code-style/
│ └── SKILL.md
└── test-coverage/
└── SKILL.md
_registry.md示例:
# Team Skill Registry
| Skill | Owner | Last Updated | Status | Version |
|-------|-------|-------------|--------|---------|
| api-security | @security-team | 2026-05-20 | Active | 1.2.0 |
| code-style | @frontend-team | 2026-05-15 | Active | 2.0.1 |
| test-coverage | @qa-team | 2026-05-10 | Beta | 0.3.0 |
| 维度 | 评估 |
|---|---|
| 适用训练营 | AI工具进阶营、DevSecOps训练营、团队效能提升营 |
| 教学时长 | 3-4小时(含实战) |
| 难度等级 | 中级(需先完成Claude Code入门) |
| 实操占比 | 60%(第五章实战为核心环节) |
| 前置课程 | Claude Code基础操作、Markdown/YAML基础 |
| 后续课程 | MCP服务器开发、多Agent编排、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 等场景全覆盖。
