Claude Skills

6 阅读15分钟

🚀 Claude Skills 使用教程

全面掌握Claude Skills的创建、使用和管理


目录


📚 什么是 Claude Skills

Claude Skills 是Claude Code平台的一个强大功能,允许用户创建自定义的技能(Skills)来扩展和定制Claude AI的功能。这些技能可以包含特定的指令、工具权限和工作流程,使Claude能够更好地适应您的特定需求。

主要特性

  • 自定义指令:为特定任务创建专门的指令集
  • 工具权限管理:精确控制技能可以使用的工具
  • 团队共享:项目技能可以在团队成员间共享
  • 版本控制:支持Git版本控制,便于追踪变更
  • API集成:可以通过API创建和管理技能
  • 多语言支持:支持Python、TypeScript等多种语言

使用场景

典型应用场景:

  • 代码审查:创建专门的代码审查技能,检查最佳实践和潜在问题
  • 文档处理:PDF处理、文档提取和分析
  • 数据分析:CSV分析、财务建模、数据可视化
  • API集成:外部API调用和集成
  • 工作流自动化:重复性任务的自动化
  • 团队协作:标准化的团队工作流程

🔧 技能类型

1. 个人技能(Personal Skills)

个人技能存储在用户主目录中(~/.claude/skills/),在所有项目中都可用。

适用场景:

  • 个人工作流程
  • 实验性功能
  • 跨项目使用的通用技能

2. 项目技能(Project Skills)

项目技能存储在项目目录中(.claude/skills/),只有项目成员可以使用。

适用场景:

  • 团队协作
  • 项目特定的工作流程
  • 需要版本控制的技能

3. 预构建技能(Pre-built Skills)

Anthropic提供的内置技能,如Excel处理、数据分析等。


👤 创建个人技能

步骤1:创建技能目录

首先为您的技能创建一个专用目录:

# 创建个人技能目录
mkdir -p ~/.claude/skills/my-skill-name

步骤2:创建 SKILL.md 文件

在目录中创建 SKILL.md 文件,这是技能的核心配置文件:

# ~/.claude/skills/my-skill/SKILL.md
---
name: code-reviewer
description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.
allowed-tools: Read, Grep, Glob
---

# 代码审查员

## 审查清单

1. 代码组织和结构
2. 错误处理
3. 性能考虑
4. 安全问题
5. 测试覆盖率

## 指令

1. 使用 Read 工具读取目标文件
2. 使用 Grep 工具搜索模式
3. 使用 Glob 工具查找相关文件
4. 提供详细的代码质量反馈

步骤3:验证技能安装

检查技能是否已正确安装:

# 列出所有个人技能
ls ~/.claude/skills/*/SKILL.md

# 查看特定技能内容
cat ~/.claude/skills/my-skill/SKILL.md

💡 提示: 个人技能在所有项目中都可用,非常适合创建您个人的常用工具和工作流程。


👥 创建项目技能

步骤1:创建项目技能目录

# 在项目根目录创建技能目录
mkdir -p .claude/skills/team-skill

步骤2:创建 SKILL.md 文件

# .claude/skills/team-skill/SKILL.md
---
name: pdf-processing
description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.
---

# PDF 处理工具

## 功能

- 文本提取:从 PDF 中提取文本内容
- 表单填写:自动填写 PDF 表单
- PDF 合并:合并多个 PDF 文件
- 页面操作:旋转、删除、重组页面

## 依赖包

此技能需要以下 Python 包:
- `pypdf`:PDF 处理核心库
- `pdfplumber`:高级 PDF 文本提取

## 安装依赖

```bash
pip install pypdf pdfplumber

使用示例

使用此技能处理 PDF 文件时,请提供:

  1. PDF 文件路径
  2. 需要执行的操作(提取/合并/填写)
  3. 输出要求(如有)

### 步骤3:提交到Git(团队共享)

```bash
# 添加技能文件到Git
git add .claude/skills/

# 提交更改
git commit -m "Add team Skill for PDF processing"

# 推送到远程仓库
git push

# 团队成员拉取更新
git pull

# 启动Claude,技能现已可用
claude

⚠️ 重要: 项目技能通过Git进行版本控制和共享。团队成员需要拉取最新更改才能使用新添加的技能。


📁 技能文件结构

基本结构

技能目录结构
my-skill/
├── SKILL.md          # 主要配置文件(必需)
├── FORMS.md          # 表单定义(可选)
├── REFERENCE.md      # 参考文档(可选)
└── scripts/          # 脚本目录(可选)
    ├── script1.py
    └── script2.js

SKILL.md 详解

SKILL.md 是技能的核心文件,包含YAML前置内容和Markdown说明。

YAML 前置内容
---
name: skill-name              # 技能名称
description: 技能描述         # 详细描述使用场景
allowed-tools: Read, Grep     # 允许使用的工具列表(可选)
---
字段类型说明必需
name字符串技能的名称标识符✅ 是
description字符串技能的详细描述和使用场景✅ 是
allowed-tools字符串列表技能可以使用的工具列表❌ 否
Markdown 内容

YAML前置内容之后是Markdown格式的详细说明,通常包括:

  • 📝 功能介绍:技能的主要功能
  • 📋 使用说明:如何使用该技能
  • 📦 依赖项:所需的包或工具
  • 💡 示例:使用示例和最佳实践
  • 检查清单:执行任务的步骤

🔐 工具权限管理

工具权限 允许您精确控制技能可以访问和使用哪些工具。这是一种安全机制,确保技能只能执行其设计范围内的操作。

支持的工具

常用的Claude Code工具:

Read Edit Write Grep Glob Bash WebFetch WebSearch

配置工具权限

在SKILL.md中配置工具权限:

---
name: safe-file-reader
description: Read files without making changes. Use when you need read-only file access.
allowed-tools: Read, Grep, Glob
---

# 安全文件阅读器

此技能提供只读文件访问权限。

## 指令
1. 使用 Read 查看文件内容
2. 使用 Grep 在文件内搜索
3. 使用 Glob 按模式查找文件

## 注意事项
-  此技能无法编辑文件
-  此技能无法执行Bash命令
-  此技能无法进行网络请求

工具权限示例对比

示例1:代码审查技能(有限权限)

只允许读取和搜索,禁止修改:

---
name: code-reviewer
description: Review code without making changes
allowed-tools: Read, Grep, Glob
---

# 代码审查
此技能只能读取和分析代码,无法修改文件。
示例2:文件管理器(全权限)

允许所有文件操作:

---
name: file-manager
description: Complete file management capabilities
allowed-tools: Read, Edit, Write, Grep, Glob, Bash
---

# 文件管理器
此技能可以执行完整的文件管理操作。
示例3:Web研究工具(网络权限)

允许网络操作和文件读取:

---
name: web-researcher
description: Research information from the web
allowed-tools: WebSearch, WebFetch, Read, Write, Grep
---

# 网络研究员
此技能可以从网络获取信息并保存到文件。

MCP 工具注释(高级)

在TypeScript实现中,您可以为工具添加注释以提供更多信息:

// 只读搜索工具
{
  name: "web_search",
  description: "Search the web for information",
  inputSchema: {
    type: "object",
    properties: {
      query: { type: "string" }
    },
    required: ["query"]
  },
  annotations: {
    title: "Web Search",
    readOnlyHint: true,
    openWorldHint: true
  }
}

// 破坏性文件删除工具
{
  name: "delete_file",
  description: "Delete a file from the filesystem",
  inputSchema: {
    type: "object",
    properties: {
      path: { type: "string" }
    },
    required: ["path"]
  },
  annotations: {
    title: "Delete File",
    readOnlyHint: false,
    destructiveHint: true,
    idempotentHint: true,
    openWorldHint: false
  }
}
注释属性类型说明
title字符串工具的显示名称
readOnlyHint布尔是否为只读操作
destructiveHint布尔是否为破坏性操作
idempotentHint布尔是否可重复执行
openWorldHint布尔是否与外部世界交互

🔌 使用 Claude API 管理 Skills

Claude API 允许您以编程方式创建、列出、和管理技能。这对于自动化工作流程和大规模部署非常有用。

列出所有技能

Python 示例
import anthropic

client = anthropic.Anthropic()

# 列出所有技能
skills = client.beta.skills.list(
    betas=["skills-2025-10-02"]
)

for skill in skills.data:
    print(f"{skill.id}: {skill.display_title} (来源: {skill.source})")

# 仅列出自定义技能
custom_skills = client.beta.skills.list(
    source="custom",
    betas=["skills-2025-10-02"]
)

for skill in custom_skills.data:
    print(f"{skill.id}: {skill.display_title}")
TypeScript 示例
const client = new Anthropic();

// 列出所有技能
const skills = await client.beta.skills.list({
  betas: ['skills-2025-10-02']
});

skills.data.forEach(skill => {
  console.log(`${skill.id}: ${skill.display_title} (来源: ${skill.source})`);
});

// 仅列出自定义技能
const customSkills = await client.beta.skills.list({
  source: 'custom',
  betas: ['skills-2025-10-02']
});

customSkills.data.forEach(skill => {
  console.log(`${skill.id}: ${skill.display_title}`);
});
cURL 示例
# 列出所有技能
curl "https://api.anthropic.com/v1/skills" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: skills-2025-10-02"

# 仅列出自定义技能
curl "https://api.anthropic.com/v1/skills?source=custom" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: skills-2025-10-02"

创建自定义技能

Python 示例
from anthropic.lib import files_from_dir

# 创建自定义DCF分析技能
dcf_skill = client.beta.skills.create(
    display_title="DCF Analysis",
    files=files_from_dir("/path/to/dcf_skill"),
    betas=["skills-2025-10-02"]
)

print(f"技能已创建: {dcf_skill.id}")

# 在消息中使用技能
response = client.beta.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=4096,
    betas=["code-execution-2025-08-25", "skills-2025-10-02"],
    container={
        "skills": [
            {"type": "anthropic", "skill_id": "xlsx", "version": "latest"},
            {"type": "custom", "skill_id": dcf_skill.id, "version": "latest"}
        ]
    },
    messages=[{
        "role": "user",
        "content": "Build a DCF valuation model for a SaaS company with the attached financials"
    }],
    tools=[{"type": "code_execution_20250825", "name": "code_execution"}]
)
cURL 示例
# 创建自定义DCF分析技能
DCF_SKILL=$(curl -X POST "https://api.anthropic.com/v1/skills" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: skills-2025-10-02" \
  -F "display_title=DCF Analysis" \
  -F "files[]=@dcf_skill/SKILL.md;filename=dcf_skill/SKILL.md")

DCF_SKILL_ID=$(echo "$DCF_SKILL" | jq -r '.id')

# 在消息中使用技能
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "anthropic-beta: code-execution-2025-08-25,skills-2025-10-02" \
  -H "content-type: application/json" \
  -d "{
    \"model\": \"claude-sonnet-4-5-20250929\",
    \"max_tokens\": 4096,
    \"container\": {
      \"skills\": [
        {
          \"type\": \"anthropic\",
          \"skill_id\": \"xlsx\",
          \"version\": \"latest\"
        },
        {
          \"type\": \"custom\",
          \"skill_id\": \"$DCF_SKILL_ID\",
          \"version\": \"latest\"
        }
      ]
    },
    \"messages\": [{
      \"role\": \"user\",
      \"content\": \"Build a DCF valuation model for a SaaS company\"
    }],
    \"tools\": [{
      \"type\": \"code_execution_20250825\",
      \"name\": \"code_execution\"
    }]
  }"

错误处理

try {
    const response = await client.beta.messages.create({
      model: 'claude-sonnet-4-5-20250929',
      max_tokens: 4096,
      betas: ['code-execution-2025-08-25', 'skills-2025-10-02'],
      container: {
        skills: [
          {type: 'custom', skill_id: 'skill_01AbCdEfGhIjKlMnOpQrStUv', version: 'latest'}
        ]
      },
      messages: [{role: 'user', content: 'Process data'}],
      tools: [{type: 'code_execution_20250825', name: 'code_execution'}]
    });
  } catch (error) {
    if (error instanceof Anthropic.BadRequestError && error.message.includes('skill')) {
      console.error(`技能错误: ${error.message}`);
      // 处理技能特定错误
    } else {
      throw error;
    }
  }

API 响应格式

{
  "data": [
    {
      "id": "sk_01abcdef1234567890",
      "display_title": "Financial Analysis",
      "source": "custom"
    },
    {
      "id": "sk_02fedcba0987654321",
      "display_title": "Web Search",
      "source": "anthropic"
    }
  ]
}
参数类型说明必需
betas数组API的beta版本标识符✅ 是
source字符串过滤技能类型: "custom" 或 "anthropic"❌ 否
display_title字符串技能的显示标题✅ 是
files文件列表技能相关的文件✅ 是

💼 实战示例

示例1:数据分析师技能

📊 CSV数据分析技能
# .claude/skills/data-analyst/SKILL.md
---
name: data-analyst
description: Analyze CSV files, generate insights, and create visualizations. Use for data exploration, statistical analysis, and reporting.
allowed-tools: Read, Grep, Bash, Write
---

# 数据分析师

## 功能

此技能可以帮助您:
- 加载和探索CSV数据
- 计算描述性统计信息
- 生成数据可视化
- 识别数据趋势和异常值
- 创建分析报告

## 依赖

```bash
pip install pandas matplotlib seaborn numpy

使用方法

  1. 提供CSV文件路径
  2. 指定分析类型(描述性统计/趋势分析/可视化)
  3. 技能将生成分析结果和图表

分析类型

  • 描述性统计: 均值、中位数、标准差、分位数
  • 趋势分析: 时间序列分析、相关性分析
  • 数据可视化: 直方图、散点图、热力图
  • 异常值检测: 识别和处理异常数据点

**使用示例**

用户: "请使用data-analyst技能分析这个销售数据文件"

Claude: 我将使用数据分析师技能来分析您的销售数据。

[技能将执行以下操作:]

  1. 读取CSV文件
  2. 计算关键统计指标
  3. 生成销售趋势可视化
  4. 提供数据洞察和建议

### 示例2:API集成技能

#### 🔌 GitHub集成技能

```yaml
# .claude/skills/github-integration/SKILL.md
---
name: github-integration
description: Create GitHub issues, pull requests, and manage repositories. Use for automated issue tracking and repository management.
allowed-tools: Write, Read, Grep, Bash
---

# GitHub 集成工具

## 功能

- 创建GitHub Issue
- 提交Pull Request
- 管理分支
- 同步代码

## 使用前准备

1. 配置GitHub Personal Access Token
2. 设置仓库权限

## 示例命令

```bash
# 创建Issue
github-create-issue --title "Bug fix needed" --body "Description"

# 创建PR
github-create-pr --title "Feature update" --body "Changes made"

安全注意事项

  • 妥善保管API令牌
  • 仅在可信环境中使用
  • 定期轮换访问令牌

**TypeScript 实现示例**

```typescript
// MCP工具实现GitHub集成
const server = new Server({
  name: "github-integration",
  version: "1.0.0"
}, {
  capabilities: {
    tools: {}
  }
});

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [{
      name: "github_create_issue",
      description: "Create a GitHub issue",
      inputSchema: {
        type: "object",
        properties: {
          title: { type: "string" },
          body: { type: "string" },
          labels: { type: "array", items: { type: "string" } }
        },
        required: ["title", "body"]
      }
    }]
  };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "github_create_issue") {
    const { title, body, labels } = request.params.arguments;

    // 调用GitHub API创建Issue
    const response = await fetch('https://api.github.com/repos/owner/repo/issues', {
      method: 'POST',
      headers: {
        'Authorization': `token ${GITHUB_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ title, body, labels })
    });

    return {
      content: [{
        type: "text",
        text: `Issue created successfully: ${response.url}`
      }]
    };
  }
});

示例3:系统操作技能

⚙️ 系统操作工具
# .claude/skills/system-ops/SKILL.md
---
name: system-ops
description: Execute shell commands and manage system operations. Use for automation, deployment, and system maintenance.
allowed-tools: Bash, Read, Write, Grep
---

# 系统操作工具

## 功能

- 执行Shell命令
- 文件系统管理
- 进程管理
- 系统监控

## 使用场景

- 自动化部署
- 日志分析
- 系统维护
- 批量文件操作

## 安全注意事项

⚠️ 此技能具有系统管理员权限,请谨慎使用
- 仅在受信任的环境中启用
- 避免执行破坏性操作
- 建议启用操作日志记录

## 示例操作

```bash
# 检查系统状态
system-check

# 部署应用
deploy-app --env production

# 分析日志
analyze-logs --file /var/log/app.log --pattern ERROR

**Python 实现示例**

```python
# Python MCP服务器实现
from anthropic_sdk_mcp import Server, types

app = Server("system-ops")

@app.list_tools()
async def list_tools() -> list[types.Tool]:
    return [
        types.Tool(
            name="execute_command",
            description="Run a shell command",
            inputSchema={
                "type": "object",
                "properties": {
                    "command": {"type": "string"},
                    "args": {"type": "array", "items": {"type": "string"}}
                },
                "required": ["command"]
            }
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
    if name == "execute_command":
        command = arguments["command"]
        args = arguments.get("args", [])

        # 执行命令
        import subprocess
        result = subprocess.run([command] + args,
                              capture_output=True,
                              text=True)

        return [types.TextContent(
            type="text",
            text=f"Exit code: {result.returncode}\nOutput: {result.stdout}\nError: {result.stderr}"
        )]

    raise ValueError(f"Tool not found: {name}")

if __name__ == "__main__":
    app.run()

示例4:动画GIF生成技能

🎨 Slack GIF 生成器
# .claude/skills/slack-gif-creator/SKILL.md
---
name: slack-gif-creator
description: Create animated GIFs for Slack messages with bounce and flash effects. Use for creating engaging visual feedback.
allowed-tools: Bash, Write
---

# Slack GIF 生成器

## 功能

- 创建带动画效果的GIF
- 支持多种缓动函数
- 帧合成和渲染
- 自定义动画参数

## 依赖

```bash
pip install pillow imageio numpy

使用示例

from gif_builder import GIFBuilder, create_gradient_background
from core.easing import interpolate

builder = GIFBuilder(480, 480, 20)

# 创建球体弹跳动画
for i in range(15):
    frame = create_gradient_background(480, 480, (240, 248, 255), (200, 230, 255))
    t = i / 14
    y = interpolate(0, 350, t, 'ease_in')
    draw_emoji(frame, '⚽', (220, int(y)), size=80)
    builder.add_frame(frame)

builder.save("bounce.gif")

缓动函数

  • ease_in: 加速运动
  • ease_out: 减速运动
  • bounce_out: 弹跳效果
  • elastic_out: 弹性效果

### 示例5:PDF处理技能

#### 📄 智能PDF处理

```yaml
# .claude/skills/pdf-processor/SKILL.md
---
name: pdf-processor
description: Extract text, fill forms, merge PDFs, and perform batch operations. Use for document automation and processing.
allowed-tools: Read, Write, Bash
---

# PDF 处理器

## 功能

### 文本提取
- 从PDF中提取纯文本
- 保留格式和布局信息
- 支持多语言OCR

### 表单处理
- 自动填写PDF表单
- 数据验证
- 批量表单处理

### PDF操作
- 合并多个PDF
- 页面旋转和删除
- 提取特定页面
- 添加水印

## 依赖

```bash
pip install pypdf pdfplumber PyPDF2

使用方法

  1. 指定输入PDF文件路径
  2. 选择操作类型
  3. 提供输出要求(如有)

示例操作

# 提取文本
extract_text --input file.pdf --output text.txt

# 合并PDF
merge-pdfs --inputs file1.pdf file2.pdf --output merged.pdf

# 填写表单
fill-form --input form.pdf --data data.json --output filled.pdf

高级功能

  • 批量处理: 同时处理多个PDF文件
  • 模板系统: 创建可重用的表单模板
  • 数据验证: 确保填写数据的准确性
  • 格式转换: PDF到其他格式的转换

---

## ✨ 最佳实践

### 1. 技能设计原则

#### 清晰明确的职责

每个技能应该有明确单一的职责,避免功能过于复杂。

**✅ 好的设计**

```yaml
---
name: csv-analyzer
description: Analyze CSV data and generate statistical reports
allowed-tools: Read, Write, Bash
---

# CSV 分析器
专注于CSV文件分析和报告生成。

❌ 避免的设计

---
name: data-everything
description: Handle all types of data processing, analysis, visualization, storage, and retrieval
allowed-tools: Read, Write, Bash, WebSearch, WebFetch
---

# 数据全能工具
功能过于宽泛,难以维护和测试。

2. 文档编写

  • ✅ 提供清晰的使用说明
  • ✅ 包含实际示例
  • ✅ 说明依赖和前置条件
  • ✅ 列出所有支持的参数
  • ✅ 提供故障排除指南

3. 安全性

⚠️ 安全建议

  • 仅授予技能必要的工具权限
  • 避免在技能中硬编码敏感信息
  • 使用环境变量存储API密钥
  • 定期审查和更新技能权限
  • 为破坏性操作添加确认机制

4. 版本管理

  • 使用Git跟踪技能变更
  • 编写清晰的提交信息
  • 为重大更改创建标签
  • 保持项目技能的同步

5. 测试和验证

  • 在多个环境中测试技能
  • 验证工具权限配置正确
  • 检查依赖项的兼容性
  • 测试错误处理机制
  • 收集用户反馈并改进

🔧 故障排除

常见问题

问题1:技能不可见

症状:创建了技能但在Claude中看不到

解决方案

# 检查技能文件是否存在
ls ~/.claude/skills/my-skill/SKILL.md    # 个人技能
ls .claude/skills/my-skill/SKILL.md      # 项目技能

# 检查文件权限
chmod +x ~/.claude/skills/my-skill/scripts/*.py

# 重新启动Claude
claude
问题2:权限被拒绝

症状:技能提示没有权限使用某个工具

解决方案

# 检查SKILL.md中的allowed-tools配置
cat ~/.claude/skills/my-skill/SKILL.md

# 确保工具名称正确且用逗号分隔
---
name: my-skill
allowed-tools: Read, Grep, Bash  # 注意逗号和空格
---
问题3:依赖项缺失

症状:技能运行时提示缺少Python包

解决方案

# 安装依赖
pip install -r requirements.txt

# 或者手动安装
pip install pillow imageio numpy

# 验证安装
pip list | grep -E "pillow|imageio|numpy"
问题4:团队成员无法使用项目技能

症状:其他团队成员看不到项目技能

解决方案

# 确保更改已提交并推送
git add .claude/skills/
git commit -m "Add team skill"
git push

# 团队成员拉取更新
git pull

# 验证技能文件存在
ls .claude/skills/team-skill/SKILL.md

调试技巧

  • 使用 claude --verbose 启用详细日志
  • 检查Claude的错误输出
  • 逐步测试技能功能
  • 使用简单的测试用例
  • 查看系统日志文件

🎓 总结

✅ 您已经学会了:

  • Claude Skills 的基本概念和类型
  • 如何创建个人技能和项目技能
  • 技能文件的结构和配置方法
  • 工具权限管理的最佳实践
  • 使用 Claude API 管理技能
  • 多个实战示例和应用场景
  • 安全性和故障排除技巧

下一步学习

资源链接

资源描述链接
官方文档Claude Skills 完整文档查看
API 参考Claude Skills API 详细说明查看
示例集合社区维护的技能示例查看
视频教程Claude Skills 视频教程查看

© 2025 Claude Skills 使用教程 | 基于 Claude Code 平台

本教程基于 Claude 官方文档和社区最佳实践编写