Claude Code Agent Skills 完全指南
Agent Skills 是模块化功能,通过包含指令、脚本和资源的组织文件夹来扩展 Claude 的功能。它们使团队能够专业知识包装成可发现、可重用的组件。
概念对比
Agent Skills 与斜杠命令在根本方式上有所不同。斜杠命令由用户调用,您明确调用它们,而 Agent Skills 由模型调用,Claude 根据请求上下文和技能描述自主触发它们。
这种区别使得 Skills 更加智能和自动化,能够在适当的时候主动提供帮助,而不需要用户明确了解它们的存在。
核心优势
扩展能力方面,Skills 为 Claude 添加了特定的工作流程和专业知识。团队协作方面,Skills 可以通过 git 在团队之间共享。减少重复性方面,Skills 消除了常见任务的重复提示需求。组合性方面,Skills 可以组合多个技能来完成复杂工作流程。可发现性方面,Claude 会自动找到并使用相关技能。
技能类型
个人技能
个人技能位于 ~/.claude/skills/ 目录,在所有项目中都可用。个人技能适用于个人工作流程、实验性能力和个人生产力工具。这种类型允许开发者根据自己的需求和偏好定制功能。
项目技能
项目技能位于项目内的 .claude/skills/ 目录,通过 git 与团队共享。项目技能最适合团队工作流程、项目特定专业知识和标准化流程。这种类型确保团队成员使用一致的工具和方法。
插件技能
插件技能与 Claude Code 插件捆绑在一起,并在安装时自动可用。这种类型为第三方开发者提供了分发功能的标准方式。
技能创建方法
每个技能都需要一个带有 YAML 前置元数据的 SKILL.md 文件。前置元数据包含技能的名称和描述,这些信息对于技能的发现和使用至关重要。
描述字段对于发现至关重要。它决定了 Claude 何时激活您的技能。好的描述包括技能的功能、使用时机、特定触发器或用例。
例如,“Extract text and tables from PDF files when the user asks to read or analyze PDF content” 是一个良好的描述,而 “Helps with documents” 则过于模糊。同样,“Generate TypeScript types from JSON schemas, activated when user wants to create types from JSON or OpenAPI specs” 比简单的 “Works with types” 更有效。
支持文件结构
技能可以包含 SKILL.md 之外的可选文件。典型的技能目录结构包括参考文档、示例文件、辅助脚本和模板文件。Claude 会渐进式加载这些文件,高效管理上下文。
技能目录可以包含参考文档、示例文件夹、脚本文件夹和模板文件夹。这种结构使技能能够提供完整的解决方案,而不仅仅是基本功能。
工具访问限制
使用前置元数据中的 allowed-tools 来限制 Claude 在技能内的能力。这种限制对于只读工作流程、安全敏感操作和防止意外修改非常有用,因为它限制了 Claude 只能使用指定的工具,而不需要权限请求。
实际应用示例
PDF 文本提取器技能
---
name: PDF Text Extractor
description: Extract text and tables from PDF files when user asks to read or analyze PDF content
allowed-tools: Read, Bash(pdftotext:*)
---
# PDF Text Extraction Skill
When the user provides a PDF file or asks to analyze PDF content:
1. Use `pdftotext` to extract text content
2. Format the output for readability
3. If tables are present, attempt to preserve structure
4. Provide a summary of the extracted content
## Prerequisites
Ensure `pdftotext` is installed on the system.
## Usage Examples
- "Extract text from report.pdf"
- "What does this PDF say?"
- "Analyze the tables in data.pdf"
## Implementation
```bash
# Check if pdftotext is available
which pdftotext
# Extract text from PDF
pdftotext -layout -nopgbrk input.pdf output.txt
# For table preservation
pdftotext -layout -enc UTF-8 input.pdf output.txt
### 只读分析器技能
```yaml
---
name: Read-Only Analyzer
description: Analyze code structure without making changes
allowed-tools: Read, Grep, Glob, Bash(ls:*)
---
# Read-Only Code Analyzer
This skill provides comprehensive code analysis capabilities without modifying any files.
## Analysis Capabilities
### Code Structure Analysis
```bash
# List directory structure
ls -la src/
# Find all TypeScript files
find . -name "*.ts" -type f
# Analyze import patterns
grep -r "import.*from" src/ --include="*.ts"
Dependency Mapping
# Check package.json dependencies
cat package.json | jq '.dependencies'
# Find unused imports
grep -r "import" src/ --include="*.ts" | cut -d':' -f1 | sort | uniq
Code Quality Metrics
# Count lines of code
find src/ -name "*.ts" -exec wc -l {} + | tail -1
# Find large files
find . -name "*.ts" -exec du -h {} + | sort -rh | head -10
### Git 工作流技能
```yaml
---
name: Git Workflow Helper
description: Streamline Git operations with conventional commits and branch management
allowed-tools: Read, Write, Bash, Grep
---
# Git Workflow Automation
## Conventional Commit Generator
```bash
# Analyze staged changes
git diff --cached --name-only
# Generate commit message based on changes
git status --porcelain
Branch Management
# Create feature branch with naming convention
git checkout -b feature/user-authentication
# Sync with main branch
git fetch origin
git rebase origin/main
Commit Message Template
# Format: type(scope): description
feat(auth): add JWT token validation
fix(api): resolve user creation timeout issue
docs(readme): update installation instructions
数据库迁移技能
---
name: Database Migration Assistant
description: Handle database schema migrations with safety checks and rollback support
allowed-tools: Read, Write, Bash, Grep
---
# Database Migration Helper
## Migration Template
```sql
-- migrations/001_create_users_table.sql
BEGIN;
-- Create users table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create indexes
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
COMMIT;
Rollback Script
-- rollbacks/001_create_users_table.sql
BEGIN;
-- Drop indexes
DROP INDEX IF EXISTS idx_users_email;
DROP INDEX IF EXISTS idx_users_username;
-- Drop table
DROP TABLE IF EXISTS users;
COMMIT;
Migration Execution
# Check current migration status
npm run migrate:status
# Run pending migrations
npm run migrate:up
# Rollback last migration
npm run migrate:down
# Create new migration
npm run migrate:create add_user_roles
API 测试技能
---
name: API Testing Assistant
description: Generate and execute API tests with comprehensive coverage
allowed-tools: Read, Write, Bash, Grep
---
# API Testing Framework
## Test Template
```javascript
// tests/api/users.test.js
const request = require('supertest');
const app = require('../../app');
describe('Users API', () => {
describe('GET /api/users', () => {
it('should return all users', async () => {
const response = await request(app)
.get('/api/users')
.expect(200);
expect(response.body).toHaveProperty('data');
expect(Array.isArray(response.body.data)).toBe(true);
});
it('should handle pagination', async () => {
const response = await request(app)
.get('/api/users?page=1&limit=10')
.expect(200);
expect(response.body.data.length).toBeLessThanOrEqual(10);
});
});
describe('POST /api/users', () => {
it('should create a new user', async () => {
const userData = {
username: 'testuser',
email: 'test@example.com'
};
const response = await request(app)
.post('/api/users')
.send(userData)
.expect(201);
expect(response.body).toMatchObject(userData);
});
it('should validate required fields', async () => {
const response = await request(app)
.post('/api/users')
.send({})
.expect(400);
expect(response.body).toHaveProperty('errors');
});
});
});
Test Execution
# Run all API tests
npm test -- tests/api/
# Run specific test file
npm test -- tests/api/users.test.js
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
代码生成技能
---
name: Code Generator Pro
description: Generate boilerplate code with consistent patterns and best practices
allowed-tools: Read, Write, Grep, Glob
---
# Code Generation Templates
## React Component Template
```jsx
// src/components/UserCard/UserCard.jsx
import React from 'react';
import PropTypes from 'prop-types';
import styles from './UserCard.module.css';
const UserCard = ({ user, onEdit, onDelete }) => {
const handleEdit = () => {
onEdit(user.id);
};
const handleDelete = () => {
onDelete(user.id);
};
return (
<div className={styles.card}>
<div className={styles.header}>
<h3>{user.username}</h3>
<p>{user.email}</p>
</div>
<div className={styles.actions}>
<button
onClick={handleEdit}
className={styles.editButton}
>
Edit
</button>
<button
onClick={handleDelete}
className={styles.deleteButton}
>
Delete
</button>
</div>
</div>
);
};
UserCard.propTypes = {
user: PropTypes.shape({
id: PropTypes.number.isRequired,
username: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
}).isRequired,
onEdit: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
};
export default UserCard;
CSS Module Template
/* src/components/UserCard/UserCard.module.css */
.card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
margin-bottom: 16px;
background-color: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
margin-bottom: 12px;
}
.header h3 {
margin: 0 0 8px 0;
color: #333;
}
.header p {
margin: 0;
color: #666;
font-size: 14px;
}
.actions {
display: flex;
gap: 8px;
}
.editButton,
.deleteButton {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.editButton {
background-color: #007bff;
color: white;
}
.editButton:hover {
background-color: #0056b3;
}
.deleteButton {
background-color: #dc3545;
color: white;
}
.deleteButton:hover {
background-color: #c82333;
}
Express Route Template
// routes/users.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const { validateUser } = require('../middleware/validation');
// GET /api/users - Get all users
router.get('/', userController.getAllUsers);
// GET /api/users/:id - Get user by ID
router.get('/:id', userController.getUserById);
// POST /api/users - Create new user
router.post('/', validateUser, userController.createUser);
// PUT /api/users/:id - Update user
router.put('/:id', validateUser, userController.updateUser);
// DELETE /api/users/:id - Delete user
router.delete('/:id', userController.deleteUser);
module.exports = router;
最佳实践指南
保持技能专注
良好的技能设计遵循一个技能对应一个功能的原则。PDF 文本提取、数据库迁移助手都是专注的技能示例。而文档助手(过于模糊)或开发者工具(过于宽泛)则是不良的设计。
编写具体描述
在描述中包含具体的触发器和用例。好的描述应该明确说明技能的功能和激活条件。例如,“Generate conventional git commit messages with emojis when user asks to commit changes” 是好的描述,而 “Create conventional git commits (feat, fix, docs) with descriptive emojis. Activated when user says ‘commit’, ‘create commit’, or ‘commit these changes’” 则更好。
实践建议
创建技能时应该考虑具体的使用场景和目标用户。描述应该清晰明确,包含足够的上下文信息以便 Claude 正确识别和使用技能。技能的功能应该保持专注,避免过于宽泛或模糊的设计。
定期审查和更新技能,确保它们随着项目需求和技术发展保持相关性。通过团队协作和版本控制,技能可以不断改进和优化。
技能管理策略
有效的技能管理包括版本控制、文档维护和质量保证。通过 git 管理技能文件,确保团队成员使用一致的版本。为每个技能提供清晰的文档说明,包括使用方法、前提条件和示例。
建立技能审查流程,确保新技能的质量和一致性。通过用户反馈和性能监控,持续改进技能的功能和可用性。
通过掌握 Agent Skills 的创建和管理,开发团队可以构建强大的知识库和工作流程自动化系统,显著提高开发效率和协作质量。