Làm chủ Claude Code trong một tuần (Phần 6): Skills
Đây là phần thứ sáu trong series "Làm chủ Claude Code trong một tuần". Trong bài này, chúng ta sẽ tìm hiểu Skills — khả năng tái sử dụng được tự động kích hoạt.
Skills là gì?
Skills là reusable capabilities — tập hợp instructions, scripts, và templates được tự động kích hoạt khi Claude phát hiện context phù hợp. Không giống Slash Commands (manual trigger), Skills được invoke dựa trên nội dung conversation.
┌────────────────────────────────────────────────────────────────┐
│ SKILLS │
├────────────────────────────────────────────────────────────────┤
│ │
│ User: "Review this code for security issues" │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────┐ │
│ │ Claude detects: "code review" + "security" │
│ └────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────┐ │
│ │ Auto-invokes: security-review skill │ │
│ │ │ │
│ │ ~/.claude/skills/security-review/ │ │
│ │ ├── SKILL.md (instructions) │ │
│ │ ├── scripts/scan.sh │ │
│ │ └── templates/report.md │ │
│ └────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Comprehensive security review executed │
│ │
└────────────────────────────────────────────────────────────────┘
Skills vs Slash Commands
| Aspect | Skills | Slash Commands |
|---|---|---|
| Trigger | Auto-invoked | Manual (/cmd) |
| Persistence | Filesystem | Session |
| Complexity | Can include scripts, templates | Markdown only |
| Scope | Automated workflows | Quick shortcuts |
| Structure | Folder with SKILL.md | Single .md file |
Cấu trúc Skill
skill-name/
├── SKILL.md # Main instructions (required)
├── scripts/ # Helper scripts (optional)
│ ├── analyze.sh
│ └── report.py
├── templates/ # Output templates (optional)
│ ├── summary.md
│ └── report.json
└── examples/ # Example files (optional)
└── sample-output.md
SKILL.md Structure
---
name: skill-name
description: Brief description for Claude to match
triggers:
- "trigger phrase 1"
- "trigger phrase 2"
---
# Skill Name
## Purpose
What this skill does.
## When to Use
Conditions that should trigger this skill.
## Instructions
Step-by-step instructions for Claude.
## Scripts Available
- `scripts/analyze.sh`: Description
- `scripts/report.py`: Description
## Templates
- `templates/summary.md`: For final summary
- `templates/report.json`: For structured output
## Output Format
Expected output structure.
Cài đặt Skills
Vị trí lưu trữ
Personal (global):
~/.claude/skills/
Project-specific:
.claude/skills/
Từ claude-howto
# Copy tất cả skills
cp -r claude-howto/03-skills/* ~/.claude/skills/
# Hoặc copy skill cụ thể
cp -r claude-howto/03-skills/code-review ~/.claude/skills/
Ví dụ Skills
1. Code Review Skill
Location: ~/.claude/skills/code-review/
SKILL.md:
---
name: code-review
description: Comprehensive code review with best practices
triggers:
- "review this code"
- "code review"
- "check this code"
- "review PR"
---
# Code Review Skill
## Purpose
Perform comprehensive code review covering quality, security,
performance, and maintainability.
## When to Use
- When user asks for code review
- When reviewing pull requests
- When checking code quality
## Instructions
### 1. Initial Analysis
- Identify the programming language
- Understand the code's purpose
- Note the architecture/patterns used
### 2. Quality Check
Run through checklist:
- [ ] Clean code principles followed
- [ ] Proper naming conventions
- [ ] Single responsibility principle
- [ ] DRY (Don't Repeat Yourself)
- [ ] Error handling present
### 3. Security Review
Check for:
- SQL injection vulnerabilities
- XSS vulnerabilities
- Authentication/Authorization issues
- Sensitive data exposure
- Input validation
### 4. Performance Analysis
Look for:
- N+1 query problems
- Unnecessary loops
- Memory leaks
- Caching opportunities
- Algorithm efficiency
### 5. Generate Report
Use template: `templates/review-report.md`
## Scripts Available
### `scripts/complexity.sh`
Calculate cyclomatic complexity:
```bash
./scripts/complexity.sh <file>
scripts/security-scan.sh
Run basic security checks:
./scripts/security-scan.sh <directory>
Output Format
Use templates/review-report.md format:
Code Review Report
Summary
[Overall assessment]
Issues Found
Critical
- [Issue with file:line reference]
Major
- [Issue with file:line reference]
Minor
- [Issue with file:line reference]
Recommendations
- [Recommendation]
- [Recommendation]
Positive Aspects
- [What's done well]
**templates/review-report.md**:
```markdown
# Code Review Report
**Reviewed**: {{file_path}}
**Date**: {{date}}
**Reviewer**: Claude Code
## Summary
{{summary}}
## Metrics
| Metric | Value | Status |
|--------|-------|--------|
| Complexity | {{complexity}} | {{complexity_status}} |
| Test Coverage | {{coverage}} | {{coverage_status}} |
| Code Smells | {{smells_count}} | {{smells_status}} |
## Issues Found
### 🔴 Critical ({{critical_count}})
{{#critical_issues}}
- **{{file}}:{{line}}** - {{description}}
```{{language}}
{{code_snippet}}
Fix: {{fix_suggestion}} {{/critical_issues}}
🟠 Major ({{major_count}})
{{#major_issues}}
- {{file}}:{{line}} - {{description}} {{/major_issues}}
🟡 Minor ({{minor_count}})
{{#minor_issues}}
- {{file}}:{{line}} - {{description}} {{/minor_issues}}
Recommendations
{{#recommendations}}
- {{.}} {{/recommendations}}
Positive Aspects
{{#positives}}
- {{.}} {{/positives}}
**scripts/complexity.sh**:
```bash
#!/bin/bash
# Calculate cyclomatic complexity
FILE=$1
if [ -z "$FILE" ]; then
echo "Usage: complexity.sh <file>"
exit 1
fi
# Count decision points
COMPLEXITY=$(grep -cE "(if|else|elif|for|while|case|catch|&&|\|\|)" "$FILE")
echo "Cyclomatic Complexity: $((COMPLEXITY + 1))"
if [ $COMPLEXITY -gt 10 ]; then
echo "Status: HIGH - Consider refactoring"
elif [ $COMPLEXITY -gt 5 ]; then
echo "Status: MEDIUM - Acceptable"
else
echo "Status: LOW - Good"
fi
2. Documentation Generator Skill
Location: ~/.claude/skills/doc-generator/
SKILL.md:
---
name: doc-generator
description: Generate technical documentation automatically
triggers:
- "generate docs"
- "document this"
- "create documentation"
- "write docs"
---
# Documentation Generator Skill
## Purpose
Automatically generate comprehensive technical documentation.
## When to Use
- When user asks for documentation
- When documenting APIs
- When creating README files
## Instructions
### 1. Analyze Code
- Identify public interfaces
- Extract function signatures
- Find existing comments/docstrings
### 2. Determine Doc Type
- API Documentation
- README
- Architecture Doc
- User Guide
- Code Comments
### 3. Generate Documentation
#### For API Documentation:
- Endpoint path and method
- Parameters (path, query, body)
- Request/Response examples
- Error codes
#### For README:
- Project description
- Installation steps
- Usage examples
- Configuration options
- Contributing guidelines
#### For Code Files:
- File purpose
- Class/function descriptions
- Parameter documentation
- Return value documentation
- Usage examples
### 4. Format Output
Use appropriate template from `templates/`
## Templates
### `templates/api-doc.md`
For REST API documentation
### `templates/readme.md`
For project README
### `templates/class-doc.md`
For class documentation
## Scripts
### `scripts/extract-api.py`
Extract API routes from code:
```bash
python scripts/extract-api.py <source_dir>
Output Quality Rules
- Include working examples
- Use consistent formatting
- Link related documentation
- Add table of contents for long docs
### 3. Brand Voice Skill
**Location**: `~/.claude/skills/brand-voice/`
**SKILL.md**:
```markdown
---
name: brand-voice
description: Ensure content matches brand voice guidelines
triggers:
- "write in brand voice"
- "brand guidelines"
- "marketing copy"
- "content review for brand"
---
# Brand Voice Skill
## Purpose
Review and generate content that matches brand voice guidelines.
## When to Use
- Writing marketing copy
- Creating user-facing messages
- Reviewing content for brand consistency
## Instructions
### 1. Load Brand Guidelines
Check for brand guidelines in:
1. `CLAUDE.md` (Brand Voice section)
2. `.claude/brand-voice.md`
3. `docs/brand-guidelines.md`
### 2. Analyze Content
- Tone: Formal vs Casual
- Voice: Active vs Passive
- Vocabulary: Technical level
- Personality: Brand attributes
### 3. Review/Generate
#### For Review:
- Highlight inconsistencies
- Suggest alternatives
- Score brand alignment
#### For Generation:
- Apply brand voice rules
- Use approved vocabulary
- Match tone guidelines
## Default Brand Voice (if not specified)
### Tone
- Professional but friendly
- Clear and concise
- Helpful and supportive
### Vocabulary
- Use simple language
- Avoid jargon unless necessary
- Be inclusive
### Personality
- Knowledgeable
- Trustworthy
- Approachable
## Output Format
### For Review:
Brand Voice Analysis
Overall Score: X/10
Issues Found:
- Line X: "phrase" → Should be "alternative" (Reason)
Positive Matches:
- Line Y: Good use of brand voice
Recommendations:
- [Suggestion]
### For Generation:
Content written in brand voice with notes explaining choices.
Tạo Skill của riêng bạn
Step 1: Create folder structure
mkdir -p ~/.claude/skills/my-skill/{scripts,templates,examples}
touch ~/.claude/skills/my-skill/SKILL.md
Step 2: Define SKILL.md
---
name: my-skill
description: What this skill does
triggers:
- "trigger phrase"
---
# My Skill
## Purpose
What this skill accomplishes.
## When to Use
Conditions for triggering.
## Instructions
Step-by-step guide.
## Output Format
Expected output structure.
Step 3: Add scripts (optional)
# scripts/helper.sh
#!/bin/bash
# Helper script
echo "Running helper..."
Step 4: Add templates (optional)
# templates/output.md
# {{title}}
## Summary
{{summary}}
## Details
{{details}}
Step 5: Test
Ask Claude something that should trigger your skill:
User: "Please generate docs" # Should trigger doc-generator
User: "Review this code" # Should trigger code-review
Skills từ Community
Claude-howto cung cấp collection skills tại luongnv89/skills:
Available Skills
| Skill | Description |
|---|---|
code-review |
Comprehensive code review |
doc-generator |
Documentation generation |
brand-voice |
Brand voice consistency |
test-generator |
Generate test cases |
refactor-helper |
Refactoring assistance |
security-scan |
Security vulnerability check |
Install từ collection
# Clone skills repository
git clone https://github.com/luongnv89/skills.git
# Install specific skill
cp -r skills/code-review ~/.claude/skills/
# Install all skills
cp -r skills/* ~/.claude/skills/
Best Practices
1. Clear Triggers
# ❌ Bad - Too generic
triggers:
- "help"
- "do something"
# ✅ Good - Specific
triggers:
- "review code for security"
- "security audit"
- "check vulnerabilities"
2. Detailed Instructions
# ❌ Bad - Vague
## Instructions
Review the code.
# ✅ Good - Detailed
## Instructions
### 1. Initial Analysis
- Identify programming language
- Note architecture patterns
- List dependencies
### 2. Security Check
For each category:
- [ ] SQL Injection: Check for parameterized queries
- [ ] XSS: Check for output encoding
- [ ] Auth: Check for proper authentication
3. Useful Scripts
Keep scripts focused and reusable:
#!/bin/bash
# ✅ Good - Single purpose, reusable
# scripts/count-lines.sh
FILE=$1
if [ -z "$FILE" ]; then
echo "Usage: count-lines.sh <file>"
exit 1
fi
wc -l < "$FILE"
4. Template Placeholders
Use clear placeholders:
# ✅ Good templates
## Summary
{{summary}}
## Findings
{{#findings}}
- **{{severity}}**: {{description}}
{{/findings}}
5. Examples
Include example output:
## Example Output
### Input
```php
function getUser($id) {
return DB::query("SELECT * FROM users WHERE id = $id");
}
Output
Security Issue Found:
- Line 2: SQL Injection vulnerability
- Fix: Use parameterized query
## Debugging Skills
### Skill không được trigger
1. **Check triggers**: Đảm bảo trigger phrases match user input
2. **Check location**: Skill phải ở `~/.claude/skills/` hoặc `.claude/skills/`
3. **Check SKILL.md**: Có YAML frontmatter đúng format
### Script không chạy
1. **Check permissions**: `chmod +x scripts/*.sh`
2. **Check shebang**: `#!/bin/bash` ở đầu file
3. **Check path**: Reference đúng relative path
### Test skill manually
User: "I want to trigger my code-review skill. Please review this code for security issues."
## Tổng kết
Skills là powerful automation tool:
- ✅ Auto-invoked based on context
- ✅ Include scripts và templates
- ✅ Reusable across projects
- ✅ Shareable với team
## Tiếp theo
Trong phần tiếp theo, chúng ta sẽ tìm hiểu **Hooks** — event-driven automation cho Claude Code.
## Tài liệu tham khảo
- [Skills - claude-howto](https://github.com/luongnv89/claude-howto/tree/main/03-skills)
- [Skills Collection](https://github.com/luongnv89/skills)
---
**Series này được dịch và mở rộng từ [claude-howto](https://github.com/luongnv89/claude-howto/) — MIT License.**