Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:25:55 +08:00
commit 42b20ade49
9 changed files with 2537 additions and 0 deletions

View File

@@ -0,0 +1,618 @@
# Platform-Specific Guidance for Claude Skills
Understanding the differences between Claude surfaces to create skills that work everywhere.
## Overview
Claude skills can run on three different surfaces:
1. **Claude.ai** - Web interface and mobile apps
2. **Claude API** - Programmatic access for developers
3. **Claude Code** - CLI tool for development workflows
Each platform has different capabilities, constraints, and runtime environments. This guide helps you create skills that work effectively across all platforms or target specific ones.
## Quick Comparison
| Feature | Claude.ai | Claude API | Claude Code |
|---------|-----------|------------|-------------|
| **Skill Scope** | User-specific | Workspace-wide | Project or user |
| **Network Access** | Variable (admin settings) | No (by default) | Yes (full access) |
| **File System** | Limited (uploads only) | Limited | Full access |
| **Package Installation** | No | No | Yes (with permissions) |
| **Bash Commands** | No | Limited (sandboxed) | Yes (full shell) |
| **Best For** | Personal productivity | Programmatic workflows | Development tasks |
## Claude.ai
### Overview
Web-based interface with mobile app support. Skills help individual users with their work.
### Characteristics
**Skill Scope**: User-specific only
- Each user uploads their own skills
- Skills are not shared across workspace
- No way to distribute org-wide skills
- Good for personal productivity
**Network Access**: Variable
- Depends on user settings
- Depends on admin/organization policies
- Can be restricted by IT
- Skills should handle network unavailability gracefully
**File System Access**: Upload-based
- Users upload files through the UI
- Skills can read uploaded files
- Skills can generate downloadable files
- No direct file system access
**Tool Availability**:
- ✅ Read (uploaded files)
- ✅ Write (generate downloads)
- ⚠️ WebFetch (if network allowed)
- ⚠️ WebSearch (if network allowed)
- ❌ Bash (no shell access)
- ❌ Git operations
### Best Practices for Claude.ai
#### Make Network Access Optional
```markdown
## Using the API (Optional)
If you have network access enabled, this skill can fetch live data.
Otherwise, you can upload data files directly.
```
#### Provide Upload Instructions
```markdown
## Setup
1. Download the template from [link]
2. Fill in your data
3. Upload the file to Claude
4. Use this skill to process it
```
#### Handle Missing Dependencies
```markdown
## Note
This skill works best with network access. If network is disabled,
you can still use the basic features by providing data manually.
```
#### Use Read/Write Effectively
- Generate files users can download
- Process uploaded CSV, JSON, Markdown
- Create reports, summaries, visualizations (as text/markdown)
### Example: Claude.ai-Friendly Skill
```yaml
---
name: meeting-notes-formatter
description: Format raw meeting notes into structured summaries with action items. Works with uploaded text files or pasted content.
tools: Read, Write
---
# Meeting Notes Formatter
Formats meeting notes into professional summaries.
## How to Use
**Option 1: Upload a file**
1. Save your meeting notes as a .txt or .md file
2. Upload to Claude
3. Ask me to format it: "Format the meeting notes"
**Option 2: Paste directly**
1. Copy your meeting notes
2. Paste into the chat
3. Ask me to format it
## What You'll Get
- Executive summary
- Key discussion points
- Action items with owners
- Decisions made
- Follow-up topics
No network access required!
```
## Claude API
### Overview
Programmatic access for developers to integrate Claude into applications and workflows.
### Characteristics
**Skill Scope**: Workspace-wide
- Skills are available to all workspace members
- Configured at the organization level
- Shared across all API calls in the workspace
- Centralized management
**Network Access**: None by default
- No outbound network requests
- No API calls to external services
- Skills must work offline
- Security-focused design
**Dependency Management**: Pre-configured only
- No dynamic package installation
- Dependencies must be pre-installed in the runtime
- Limited to standard library + pre-approved packages
- Skills cannot require new dependencies
**Execution Environment**: Sandboxed
- Controlled execution environment
- Limited file system access
- Security restrictions
- Predictable, reproducible behavior
**Tool Availability**:
- ✅ Read (from provided context)
- ✅ Write (to return data)
- ⚠️ Bash (sandboxed, limited commands)
- ❌ WebFetch (no network)
- ❌ WebSearch (no network)
- ❌ Package installation
### Best Practices for Claude API
#### Design for Offline Operation
```python
# ❌ Bad: Requires network
def fetch_user_data(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
# ✅ Good: Works with provided data
def process_user_data(user_data: dict) -> dict:
"""Process user data provided by the caller."""
return {
"summary": generate_summary(user_data),
"insights": extract_insights(user_data),
}
```
#### Use Only Standard Library
```python
# ✅ Good: Standard library only
import json
import re
from datetime import datetime
from pathlib import Path
from typing import Dict, List
# ❌ Bad: External dependency
import pandas as pd # Not available unless pre-installed
```
#### Document Data Requirements
```markdown
## API Integration
This skill requires the following data to be provided:
### Input Format
```json
{
"users": [...],
"events": [...],
"config": {...}
}
```
### Output Format
```json
{
"report": "...",
"metrics": {...},
"recommendations": [...]
}
```
```
#### Provide Clear Error Messages
```python
def validate_input(data: dict) -> tuple[bool, str]:
"""Validate input data structure."""
if "users" not in data:
return False, "Missing required field: 'users'"
if not isinstance(data["users"], list):
return False, "Field 'users' must be a list"
return True, ""
```
### Example: API-Optimized Skill
```yaml
---
name: data-transformer
description: Transform and validate JSON data structures. Requires data to be provided via API call. Works entirely offline with no external dependencies.
tools: Read, Write
model: haiku
---
# Data Transformer
Transforms JSON data according to specified rules.
## API Usage
```python
import anthropic
client = anthropic.Anthropic()
# Provide data in the API call
message = client.messages.create(
model="claude-3-sonnet-20240229",
messages=[{
"role": "user",
"content": f"Transform this data: {json.dumps(data)}"
}]
)
```
## Input Requirements
The skill expects JSON data in this format:
```json
{
"data": [...],
"rules": {...}
}
```
## Output
Returns transformed data:
```json
{
"transformed": [...],
"errors": [],
"stats": {...}
}
```
## No Dependencies
Uses only Python standard library - no external packages required.
```
## Claude Code
### Overview
CLI tool for development workflows with full system access.
### Characteristics
**Skill Scope**: Flexible
- Project-level: `.claude/skills/` (shared with team via git)
- User-level: `~/.claude/agents/` (personal)
- Plugin-level: `.claude-plugin/` (distributable)
**Network Access**: Full
- Unrestricted outbound requests
- Can call APIs
- Can fetch web pages
- Can download resources
**File System Access**: Full
- Read any accessible file
- Write to any writable location
- Execute commands
- Full git integration
**Package Installation**: Available
- Can install Python packages (pip)
- Can install npm packages
- Can use system package managers
- Can compile code
**Tool Availability**:
- ✅ All tools available
- ✅ Bash (full shell access)
- ✅ WebFetch
- ✅ WebSearch
- ✅ Git operations
- ✅ Read/Write/Edit
- ✅ Task (subagents)
### Best Practices for Claude Code
#### Leverage Full Capabilities
```yaml
---
name: api-tester
description: Test REST APIs with automatic request generation and validation. Use when developing or debugging API endpoints.
tools: Bash, Read, Write, WebFetch
---
# API Tester
Tests REST APIs with comprehensive validation.
## Features
- Automatic request generation
- Response validation
- Performance metrics
- Error handling tests
- OpenAPI spec generation
## Requirements
```bash
pip install requests pyyaml jsonschema
```
## Usage
Just tell me the API endpoint to test!
```
#### Use Project Configuration
```markdown
## Setup
Add to `.claude/settings.json`:
```json
{
"env": {
"API_KEY": "${YOUR_API_KEY}",
"API_URL": "https://api.example.com"
}
}
```
The skill will read these values automatically.
```
#### Integrate with Development Tools
```bash
# Run linters
black your_script.py
pylint your_script.py
# Run tests
pytest tests/
# Build project
npm run build
```
#### Create Complex Workflows
```markdown
## Workflow
1. Fetch latest data from API
2. Validate against schema
3. Transform and process
4. Update local files
5. Generate report
6. Commit changes to git
```
### Example: Claude Code-Optimized Skill
```yaml
---
name: github-issue-helper
description: Manage GitHub issues - create, update, search, and analyze issues using gh CLI. Use when working with GitHub repositories in development.
tools: Bash, Read, Write, Edit, Grep
---
# GitHub Issue Helper
Comprehensive GitHub issue management using gh CLI.
## Requirements
```bash
# Install GitHub CLI
brew install gh # macOS
# OR
apt install gh # Linux
# Authenticate
gh auth login
```
## Features
- **Create issues**: From templates or scratch
- **Search issues**: By label, state, author
- **Bulk operations**: Close, label, assign multiple issues
- **Analysis**: Generate reports, find patterns
- **Integration**: Link to commits, PRs, projects
## Commands
- "Create an issue for the bug in API endpoint"
- "Find all P0 issues assigned to me"
- "Close all issues labeled 'wontfix'"
- "Generate a weekly issue summary"
## Setup
No additional setup required if gh CLI is authenticated.
```
## Cross-Platform Skills
### Design Principles
To create skills that work across all platforms:
#### 1. Progressive Enhancement
Start with core functionality that works everywhere, add platform-specific features as available.
```markdown
## Core Features (All Platforms)
- Process uploaded/provided data
- Generate formatted output
- Validate inputs
## Enhanced Features (Claude Code Only)
- Fetch live data from APIs
- Update local files automatically
- Integrate with git workflow
```
#### 2. Graceful Degradation
Handle missing capabilities elegantly:
```markdown
## Setup
### Claude.ai / API
Upload your data file (CSV, JSON, or TXT)
### Claude Code
I can fetch data directly from your database or API.
Tell me the connection details.
```
#### 3. Platform Detection
Guide users based on their platform:
```markdown
## Platform Notes
**Claude.ai**: Upload files via the interface
**Claude API**: Provide data in the API request body
**Claude Code**: I can read files directly from your project
```
#### 4. Minimal Dependencies
Use standard library when possible:
```python
# ✅ Works everywhere
import json
from pathlib import Path
# ⚠️ Works in Claude Code only
import requests
import pandas
```
### Example: Universal Skill
```yaml
---
name: json-validator
description: Validate and format JSON data against schemas. Works with uploaded files, pasted data, or local files depending on platform.
tools: Read, Write
---
# JSON Validator
Validates JSON against schemas with detailed error reports.
## How to Use
**Claude.ai**:
1. Upload your JSON file
2. Upload your schema file (optional)
3. Ask: "Validate the JSON"
**Claude API**:
```python
message = client.messages.create(
messages=[{
"role": "user",
"content": f"Validate this JSON:\n{json_data}\n\nSchema:\n{schema}"
}]
)
```
**Claude Code**:
```
Validate JSON files in ./data/
```
## Features
- ✅ Schema validation (all platforms)
- ✅ Format checking (all platforms)
- ✅ Error highlighting (all platforms)
- ⚠️ Auto-fix suggestions (Claude Code only)
- ⚠️ Batch processing (Claude Code only)
No external dependencies required!
```
## Testing Across Platforms
### Test Checklist
- [ ] Test on Claude.ai (web interface)
- [ ] Test via Claude API (programmatic access)
- [ ] Test in Claude Code (CLI)
- [ ] Test with network disabled (API mode)
- [ ] Test with file uploads (Claude.ai mode)
- [ ] Test with local files (Claude Code mode)
- [ ] Verify error messages are clear on all platforms
- [ ] Check that platform-specific features degrade gracefully
### Platform-Specific Test Cases
**Claude.ai**:
- Upload various file formats
- Test with network restrictions
- Verify download generation works
- Test on mobile if applicable
**Claude API**:
- Test with no network access
- Verify offline operation
- Test with standard library only
- Check API response format
**Claude Code**:
- Test with project files
- Test bash commands
- Test package installation instructions
- Verify git integration
## Summary
### Choose Your Target
**Claude.ai**: Best for personal productivity skills that process documents
**Claude API**: Best for deterministic, offline data processing
**Claude Code**: Best for development workflows with full system access
### Design Patterns
**Single Platform**: Optimize for that platform's strengths
**Multi-Platform**: Use progressive enhancement and graceful degradation
**Universal**: Stick to core capabilities, document platform differences
### Key Takeaways
1. **Know your constraints**: Each platform has different capabilities
2. **Design accordingly**: Match skill design to platform capabilities
3. **Document clearly**: Tell users what works where
4. **Test thoroughly**: Verify on all target platforms
5. **Handle gracefully**: Degrade features when capabilities are missing
## Resources
- **Claude.ai**: https://claude.ai/skills
- **Claude API**: https://docs.anthropic.com/claude/docs/
- **Claude Code**: https://docs.claude.com/en/docs/claude-code/overview

View File

@@ -0,0 +1,656 @@
# Claude Skills Examples
Real-world examples of well-designed skills across different complexity levels and use cases.
## Table of Contents
1. [Simple Skills](#simple-skills) - Just SKILL.md, no scripts
2. [Skills with Scripts](#skills-with-scripts) - Including helper utilities
3. [Complex Skills](#complex-skills) - Full-featured with references
4. [Platform-Specific Skills](#platform-specific-skills) - Optimized for one platform
5. [Universal Skills](#universal-skills) - Work across all platforms
---
## Simple Skills
### Example 1: Commit Message Formatter
**Use Case**: Help developers write conventional commit messages
**Structure**:
```
commit-formatter/
└── SKILL.md
```
**SKILL.md**:
```markdown
---
name: commit-formatter
description: Format git commit messages following Conventional Commits. Use when writing commits or reviewing commit history for proper formatting.
---
# Commit Message Formatter
Helps create well-formatted git commit messages following the Conventional Commits specification.
## When to Use
- Writing new commit messages
- Reviewing existing commits for proper format
- Teaching team members commit conventions
- Generating changelogs
## Commit Format
```
<type>(<scope>): <subject>
<body>
<footer>
```
## Types
- **feat**: New feature for users
- **fix**: Bug fix
- **docs**: Documentation only changes
- **style**: Code style changes (formatting, semicolons)
- **refactor**: Code change that neither fixes a bug nor adds a feature
- **perf**: Performance improvement
- **test**: Adding or updating tests
- **chore**: Maintenance tasks (deps, configs)
- **ci**: CI/CD changes
## Subject Line Rules
- Use imperative mood ("add" not "added")
- No period at the end
- Keep under 50 characters
- Lowercase (except proper nouns)
## Body (Optional)
- Wrap at 72 characters
- Explain WHAT and WHY (not HOW)
- Separate from subject with blank line
## Footer (Optional)
- **Breaking changes**: `BREAKING CHANGE: <description>`
- **Issue references**: `Closes #123`, `Fixes #456`
- **Co-authors**: `Co-authored-by: Name <email>`
## Examples
### Simple Feature
```
feat(auth): add OAuth2 Google login
```
### Bug Fix with Body
```
fix(api): handle null user service response
The user service occasionally returns null when the user is not
found. This adds proper null checking and returns a 404 status.
```
### Breaking Change
```
feat(api)!: redesign authentication endpoints
BREAKING CHANGE: The /auth endpoint now requires POST instead of GET.
All clients must be updated to send POST requests with JSON body
containing username and password fields.
Migration guide: https://docs.example.com/v2-migration
Closes #456
```
### Multiple Issues
```
fix(ui): resolve button alignment in mobile view
Fixes several CSS issues affecting mobile users:
- Button text now wraps properly
- Icons align correctly with text
- Touch targets meet minimum 44px requirement
Fixes #789, #790, #791
```
## Interactive Mode
Just tell me what you changed, and I'll help format it:
**Example conversation**:
- You: "I added a new login page"
- Me: "Was this a new feature or a fix?"
- You: "New feature"
- Me: "What component/area does this affect?"
- You: "Authentication"
- Me: "Here's your commit message: `feat(auth): add login page`"
```
**Why This Works**:
- Clear, actionable instructions
- Concrete examples for different scenarios
- Covers edge cases (breaking changes, multiple issues)
- Action-oriented description triggers automatic use
- No dependencies or scripts needed
---
### Example 2: JSON Formatter
**Use Case**: Format and validate JSON data
**Structure**:
```
json-formatter/
└── SKILL.md
```
**SKILL.md**:
```markdown
---
name: json-formatter
description: Format, validate, and pretty-print JSON data. Use when working with JSON files, API responses, or config files that need formatting or validation.
---
# JSON Formatter
Format and validate JSON data with helpful error messages.
## When to Use
- Format messy JSON
- Validate JSON syntax
- Compare JSON structures
- Convert between compact and pretty formats
- Debug JSON parsing errors
## Features
### 1. Pretty Printing
Transform compact JSON into readable format:
**Input**:
```json
{"name":"John","age":30,"city":"NYC"}
```
**Output**:
```json
{
"name": "John",
"age": 30,
"city": "NYC"
}
```
### 2. Validation
Check for common JSON errors:
- Missing commas
- Trailing commas
- Unquoted keys
- Single quotes instead of double quotes
- Unescaped characters
### 3. Minification
Reduce JSON size for transmission:
**Input**:
```json
{
"users": [
{
"name": "John",
"age": 30
}
]
}
```
**Output**:
```json
{"users":[{"name":"John","age":30}]}
```
### 4. Structure Analysis
- Count objects, arrays, and primitives
- Find deeply nested paths
- Identify large values
- Detect duplicate keys
## Usage
Just paste or upload your JSON and tell me what you need:
- "Format this JSON"
- "Validate this JSON"
- "Minify this JSON"
- "What's wrong with this JSON?"
- "Compare these two JSON files"
## Common Fixes
### Trailing Comma
`{"name": "John", "age": 30,}`
`{"name": "John", "age": 30}`
### Single Quotes
`{'name': 'John'}`
`{"name": "John"}`
### Unquoted Keys
`{name: "John"}`
`{"name": "John"}`
### Missing Comma
`{"name": "John" "age": 30}`
`{"name": "John", "age": 30}`
## Tips
- Use JSON for configs (not YAML) when strict validation needed
- Keep nesting under 5 levels for readability
- Consider splitting large JSON files
- Use consistent key naming (camelCase or snake_case)
```
---
## Skills with Scripts
### Example 3: API Response Validator
**Use Case**: Validate API responses against schemas
**Structure**:
```
api-validator/
├── SKILL.md
├── scripts/
│ ├── __init__.py
│ ├── validator.py
│ └── schema_builder.py
└── README.md
```
**SKILL.md**:
```markdown
---
name: api-validator
description: Validate API responses against JSON schemas with detailed error reports. Use PROACTIVELY when testing or debugging REST APIs.
tools: Bash, Read, Write
model: sonnet
---
# API Response Validator
Comprehensive validation for API responses.
## Features
- Validate against JSON Schema
- Auto-generate schemas from examples
- Test status codes, headers, body
- Performance metrics
- Security checks
## Usage
### Validate a Response
```
Validate this API response:
{
"status": 200,
"body": {"user_id": 123, "name": "John"}
}
Against schema:
{
"type": "object",
"required": ["user_id", "name"],
"properties": {
"user_id": {"type": "integer"},
"name": {"type": "string"}
}
}
```
### Generate Schema
```
Generate a schema for this response:
{"user_id": 123, "name": "John", "email": "john@example.com"}
```
### Batch Validation
```
Validate all responses in ./tests/responses/
```
## Scripts
This skill includes Python scripts for deterministic validation:
- `validator.py`: Core validation logic
- `schema_builder.py`: Generate schemas from examples
Run manually:
```bash
python scripts/validator.py response.json schema.json
```
See README.md for detailed script documentation.
```
**scripts/validator.py**:
```python
#!/usr/bin/env python3
"""Validate JSON against JSON Schema."""
import argparse
import json
import sys
from pathlib import Path
from typing import Any, Dict, List, Tuple
def validate_json(data: Dict[str, Any], schema: Dict[str, Any]) -> Tuple[bool, List[str]]:
"""Validate JSON data against schema.
Returns:
Tuple of (is_valid, error_messages)
"""
errors = []
# Check required fields
if "required" in schema:
for field in schema["required"]:
if field not in data:
errors.append(f"Missing required field: {field}")
# Check field types
if "properties" in schema:
for field, field_schema in schema["properties"].items():
if field in data:
expected_type = field_schema.get("type")
actual_value = data[field]
if not check_type(actual_value, expected_type):
errors.append(
f"Field '{field}' has wrong type. "
f"Expected {expected_type}, got {type(actual_value).__name__}"
)
return len(errors) == 0, errors
def check_type(value: Any, expected_type: str) -> bool:
"""Check if value matches expected JSON type."""
type_map = {
"string": str,
"integer": int,
"number": (int, float),
"boolean": bool,
"array": list,
"object": dict,
"null": type(None),
}
expected_python_type = type_map.get(expected_type)
if expected_python_type is None:
return True # Unknown type, skip check
return isinstance(value, expected_python_type)
def main() -> int:
parser = argparse.ArgumentParser(description="Validate JSON against schema")
parser.add_argument("data_file", type=Path, help="JSON data file")
parser.add_argument("schema_file", type=Path, help="JSON schema file")
args = parser.parse_args()
# Load files
try:
data = json.loads(args.data_file.read_text())
schema = json.loads(args.schema_file.read_text())
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON - {e}", file=sys.stderr)
return 1
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return 1
# Validate
is_valid, errors = validate_json(data, schema)
if is_valid:
print("✅ Validation passed")
return 0
else:
print("❌ Validation failed:")
for error in errors:
print(f" - {error}")
return 1
if __name__ == "__main__":
sys.exit(main())
```
**Why This Works**:
- Combines AI guidance with deterministic validation
- Scripts provide precise, repeatable checks
- Clear examples show usage patterns
- Works across platforms (with network in Code, offline in API)
---
## Complex Skills
### Example 4: Database Migration Helper
**Use Case**: Validate and generate database migrations
**Structure**:
```
db-migrator/
├── SKILL.md
├── scripts/
│ ├── __init__.py
│ ├── validate_migration.py
│ ├── generate_rollback.py
│ └── analyze_schema.py
└── references/
├── sql-best-practices.md
├── migration-patterns.md
└── examples.md
```
**SKILL.md**:
```markdown
---
name: db-migrator
description: Create and validate database migrations with automatic rollback generation. Use PROACTIVELY when designing schema changes or creating migration files.
tools: Bash, Read, Write, Edit
model: sonnet
---
# Database Migration Helper
Comprehensive toolkit for database migrations.
## When to Use
- Creating new migrations
- Validating migration safety
- Generating rollback scripts
- Reviewing schema changes
- Planning database refactoring
## Features
### 1. Migration Validation
Checks for:
- Breaking changes (column removal, type changes)
- Performance issues (missing indexes, table locks)
- Data integrity risks (missing constraints)
- Naming conventions
- SQL syntax
### 2. Rollback Generation
Automatically generates rollback scripts for:
- Table creation → DROP TABLE
- Column addition → ALTER TABLE DROP COLUMN
- Index creation → DROP INDEX
- Data migrations → Inverse operations
### 3. Schema Analysis
- Compare schemas across environments
- Identify drift
- Suggest optimizations
- Generate documentation
## Quick Start
### Create a Migration
```
Create a migration to add an email column to the users table
```
I'll generate:
- Forward migration (add column)
- Rollback migration (remove column)
- Validation checks
- Index recommendations
### Validate Existing Migration
```
Validate this migration:
[paste your SQL]
```
I'll check for safety issues and suggest improvements.
### Generate Rollback
```
Generate rollback for:
[paste forward migration]
```
## Best Practices
For detailed migration patterns and SQL best practices:
```
Read .claude-plugin/references/sql-best-practices.md
```
## Scripts
### validate_migration.py
Validates SQL migrations for safety:
```bash
python scripts/validate_migration.py migration.sql
```
Checks:
- Syntax errors
- Breaking changes
- Performance issues
- Security risks
### generate_rollback.py
Creates rollback scripts:
```bash
python scripts/generate_rollback.py migration.sql > rollback.sql
```
### analyze_schema.py
Compares schema files:
```bash
python scripts/analyze_schema.py schema1.sql schema2.sql
```
## References
- **sql-best-practices.md**: SQL coding standards and patterns
- **migration-patterns.md**: Common migration scenarios with examples
- **examples.md**: Real-world migration examples
Load as needed for detailed guidance.
```
**Why This Works**:
- Combines AI reasoning with automated checks
- References provide deep expertise without token cost
- Scripts handle deterministic tasks
- Clear separation of concerns
- Works great in Claude Code with full tool access
---
## Summary
### Choosing Skill Complexity
**Simple** (SKILL.md only):
- Documentation formatting
- Writing assistance
- Simple validation
- Template generation
**With Scripts**:
- Data validation
- File processing
- Format conversion
- Code generation
**Complex** (Full featured):
- Multi-step workflows
- Technical domains (databases, APIs)
- Integration with external tools
- Comprehensive validation
### Key Takeaways
1. **Start simple**: Most skills don't need scripts
2. **Add scripts**: When you need deterministic, repeatable operations
3. **Use references**: For detailed specs that don't need to be in context
4. **Test thoroughly**: Ensure skills work as expected
5. **Document well**: Clear examples help users and Claude
### Templates
Use these examples as templates for your own skills:
- Copy the structure
- Adapt the content
- Validate with the validator
- Test thoroughly
- Share with the community!

View File

@@ -0,0 +1,456 @@
# Claude Skills Technical Specification
Complete technical requirements and validation rules for Claude skills.
## File Structure
### Required Files
**SKILL.md** - The main skill definition file
- Must be named exactly `SKILL.md` (case-sensitive)
- Must be UTF-8 encoded
- Must start with YAML frontmatter
- Must contain content after frontmatter
### Optional Components
**scripts/** - Helper scripts and utilities
- Python, JavaScript, or bash scripts
- Should include `__init__.py` for Python packages
- Scripts should have execute permissions (Unix)
- Must not execute arbitrary code (no eval/exec)
**references/** - Reference documentation
- Markdown files with detailed specifications
- API documentation
- Database schemas
- Templates and examples
- Loaded on-demand to minimize token usage
**README.md** - Skill-specific documentation
- Installation instructions
- Usage examples
- Platform-specific notes
## YAML Frontmatter Specification
### Format
```yaml
---
name: skill-name
description: Brief description of what this skill does
---
```
### Required Fields
#### name (string, required)
- **Type**: String
- **Required**: Yes
- **Format**: Lowercase letters, numbers, hyphens only
- **Pattern**: `^[a-z0-9-]+$`
- **Min length**: 1 character
- **Max length**: 64 characters
- **Restrictions**:
- Cannot contain "anthropic" (case-insensitive)
- Cannot contain "claude" (case-insensitive)
- Cannot contain XML tags (`<` or `>`)
- Must not start or end with hyphen
- No consecutive hyphens
**Examples**:
- ✅ Valid: `git-helper`, `api-tester`, `doc-writer-pro`
- ❌ Invalid: `GitHelper` (not lowercase), `api_tester` (underscore), `my-anthropic-skill` (contains "anthropic")
#### description (string, required)
- **Type**: String
- **Required**: Yes
- **Min length**: 1 character (after trimming whitespace)
- **Max length**: 1024 characters
- **Restrictions**:
- Cannot be only whitespace
- Cannot contain XML tags (regex: `<[^>]+>`)
- Should explain WHAT the skill does
- Should explain WHEN to use it
**Best Practices**:
- Use action-oriented language for auto-invocation
- Include trigger keywords
- Be specific about capabilities
- Mention platform requirements if relevant
**Examples**:
- ✅ Good: "Create and validate git commit messages following Conventional Commits. Use when writing commits or reviewing commit history."
- ✅ Good: "Analyze API responses and generate test cases. Use PROACTIVELY when designing or testing REST APIs."
- ❌ Poor: "Helps with git" (too vague, no trigger info)
- ❌ Poor: "A tool" (doesn't explain what or when)
### Optional Fields
#### tools (string or array, optional)
Specifies which tools this skill should have access to.
- **Type**: String (comma-separated) or Array
- **Default**: All tools (if omitted)
- **Valid tools**:
- `Bash` - Execute shell commands
- `Read` - Read files
- `Write` - Write new files
- `Edit` - Edit existing files
- `Glob` - Find files by pattern
- `Grep` - Search file contents
- `WebFetch` - Fetch web pages
- `WebSearch` - Search the web
- `Task` - Launch subagents
**Examples**:
```yaml
# String format
tools: Bash, Read, Write
# Array format
tools:
- Bash
- Read
- Write
```
**Use Cases**:
- Restrict to Read/Write for documentation-only skills
- Include Bash for scripts that need command execution
- Include WebFetch/WebSearch for research skills
#### model (string, optional)
Specifies which model to use for this skill.
- **Type**: String
- **Default**: Inherits from parent context
- **Valid values**:
- `sonnet` - Claude Sonnet (balanced)
- `opus` - Claude Opus (most capable)
- `haiku` - Claude Haiku (fastest, most efficient)
- `inherit` - Use parent context's model
**Examples**:
```yaml
# Use Haiku for fast, simple tasks
model: haiku
# Use Sonnet for complex reasoning
model: sonnet
```
## Content Requirements
### Body Structure
The content after frontmatter should be well-structured markdown:
#### Recommended Sections
1. **Overview/Introduction**
- Brief explanation of the skill
- Use cases
2. **When to Use This Skill**
- Specific scenarios
- Trigger conditions
- Context where skill is most helpful
3. **Instructions/Workflow**
- Step-by-step guidance
- Clear action items
- Decision points
4. **Examples**
- Concrete use cases
- Input/output examples
- Edge cases
5. **Best Practices** (optional)
- Tips for optimal use
- Common patterns
6. **Troubleshooting** (optional)
- Common issues
- Solutions
- Error handling
### Markdown Guidelines
- Use proper heading hierarchy (don't skip levels)
- Use code blocks with language tags
- Use lists for steps and options
- Use emphasis (bold/italic) sparingly for clarity
- Include links to external resources if helpful
### Token Efficiency
**Inactive State** (Just frontmatter loaded):
- Target: 30-50 tokens
- The name and description should be concise
**Active State** (Full SKILL.md loaded):
- Keep main instructions focused
- Move detailed specs to references/
- Use progressive disclosure
**References** (Loaded on-demand):
- No token limit
- Can be very detailed
- Include comprehensive examples
- Add API specs, schemas, etc.
## File Size Limits
- **SKILL.md**: Recommended max 50KB (will warn above this)
- **Scripts**: Reasonable size (< 1MB each)
- **References**: No strict limit, but keep focused
- **Total package**: Recommended < 10MB
## Security Requirements
### Path Safety
All file operations must:
- Validate paths to prevent traversal attacks
- Use pathlib.Path for cross-platform compatibility
- Resolve paths and check they're within expected directories
- Never accept arbitrary user paths without validation
**Example** (Python):
```python
from pathlib import Path
def safe_path(base: Path, user_input: str) -> Path:
resolved = (base / user_input).resolve()
if not resolved.is_relative_to(base):
raise ValueError(f"Path traversal detected: {user_input}")
return resolved
```
### Input Validation
- Validate all user inputs
- Use allowlists instead of denylists
- Sanitize before processing
- Check types, ranges, formats
- Provide clear error messages
### Code Execution
- **Never** use `eval()` or `exec()`
- **Never** execute arbitrary user code
- Be cautious with `pickle` - prefer JSON
- Validate file contents before processing
- Use subprocess carefully with fixed commands
### Credentials and Secrets
- Never include credentials in skill files
- Use environment variables
- Document required env vars in README
- Add secrets to .gitignore
- Use permission rules in .claude/settings.json
## Validation Checklist
Use this checklist to ensure compliance:
### Frontmatter
- [ ] File starts with `---`
- [ ] Valid YAML syntax
- [ ] Contains `name` field
- [ ] Contains `description` field
- [ ] Name is lowercase with hyphens only
- [ ] Name is 1-64 characters
- [ ] Name doesn't contain "anthropic" or "claude"
- [ ] Description is 1-1024 characters
- [ ] Description is non-empty (no whitespace-only)
- [ ] No XML tags in name or description
- [ ] Optional fields (tools, model) are valid if present
### Body Content
- [ ] Content exists after frontmatter
- [ ] Reasonable length (not too short)
- [ ] Includes "When to Use" section
- [ ] Includes instructions/steps
- [ ] Includes examples
- [ ] Uses proper markdown formatting
- [ ] Headings are hierarchical
### Directory Structure
- [ ] SKILL.md exists
- [ ] If scripts/ exists, contains relevant files
- [ ] If scripts/ has Python files, includes __init__.py
- [ ] Scripts have execute permissions (Unix)
- [ ] If references/ exists, contains markdown files
- [ ] No sensitive files (credentials, keys)
### Security
- [ ] No eval/exec in scripts
- [ ] Path operations are safe
- [ ] Inputs are validated
- [ ] No hardcoded credentials
- [ ] No path traversal vulnerabilities
### Quality
- [ ] Clear, actionable instructions
- [ ] Concrete examples provided
- [ ] Error handling documented
- [ ] Platform notes if needed
- [ ] Tested on target platforms
## Platform-Specific Requirements
### Claude.ai
- User-level skills only
- Upload via Skills UI
- Network access varies by settings
- No shell access to system
### Claude API
- Workspace-level skills
- No network access by default
- No dynamic package installation
- Integrated via API configuration
### Claude Code
- Project (.claude/skills/) or user level (~/.claude/agents/)
- Full network access
- Can execute bash commands
- Full file system access
## Versioning
While not required, consider versioning your skills:
**In manifest.json**:
```json
{
"version": "1.2.0",
"changelog": "Added support for X"
}
```
**Semantic Versioning Recommended**:
- Major: Breaking changes
- Minor: New features (backward compatible)
- Patch: Bug fixes
## Distribution Formats
### ZIP Package
```
skill-name.zip
├── SKILL.md
├── manifest.json (optional)
├── README.md (optional)
├── scripts/
│ └── *.py
└── references/
└── *.md
```
### Directory Structure
```
skill-name/
├── SKILL.md
├── manifest.json (optional)
├── README.md (optional)
├── scripts/
│ └── *.py
└── references/
└── *.md
```
### Plugin Format (.claude-plugin/)
```
.claude-plugin/
├── SKILL.md
├── scripts/
└── references/
```
## Manifest File (Optional)
When packaging, you can include a manifest.json:
```json
{
"name": "skill-name",
"description": "Brief description",
"version": "1.0.0",
"packaged_at": "2025-01-15T10:30:00Z",
"format": "claude-skill",
"format_version": "1.0",
"includes_scripts": true,
"includes_references": true,
"tools": "Bash, Read, Write",
"model": "sonnet"
}
```
## Common Validation Errors
### Error: "SKILL.md must start with YAML frontmatter"
**Cause**: File doesn't start with `---`
**Fix**: Add frontmatter at the beginning:
```yaml
---
name: skill-name
description: Description here
---
```
### Error: "Invalid YAML in frontmatter"
**Cause**: YAML syntax error
**Fix**: Check indentation, quotes, special characters
- Strings with `:` need quotes
- Multi-line strings need `|` or `>`
- Indentation must be consistent
### Error: "Skill name must be lowercase with hyphens only"
**Cause**: Name has uppercase, underscores, spaces, or special chars
**Fix**: Use only lowercase letters, numbers, and hyphens
### Error: "Description too long"
**Cause**: Description exceeds 1024 characters
**Fix**: Shorten description, move details to body
### Error: "Required field 'name' missing"
**Cause**: Frontmatter doesn't include name field
**Fix**: Add `name: skill-name` to frontmatter
## Testing Your Skill
1. **Validate**: Run the validator
```bash
python .claude-plugin/scripts/validate_skill.py path/to/skill/
```
2. **Manual Testing**: Place skill and try using it
- Test basic functionality
- Test edge cases
- Test error handling
- Test on target platforms
3. **Script Testing**: If your skill includes scripts
- Test scripts independently
- Verify inputs/outputs
- Check error messages
- Test on different platforms
4. **Integration Testing**: Use skill in real scenarios
- Invoke automatically
- Invoke explicitly
- Test with references
- Test tool permissions
## Further Resources
- **Claude Skills Documentation**: https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview
- **Skills Blog Post**: https://claude.com/blog/skills
- **Skills Cookbook**: https://github.com/anthropics/claude-cookbooks/tree/main/skills
- **This Project**: https://github.com/jgardner04/claude-skills-skill