Claude Skills 完整工作原理深度解析
由coder创建,最终由coder 被浏览 10 用户
📋 目录
🏗️ 核心架构:Meta-Tool 系统
关键概念
Skills 是一个 基于提示词的元工具(Meta-Tool)系统,而不是传统的函数调用机制。
架构对比
传统工具(如 Read, Bash, Write):
User → Claude → [选择工具] → [执行动作] → [返回结果]
特点:直接执行,立即返回结果
Skills 系统(元工具):
User → Claude → [扫描 Skill 元数据] → [决定加载] → [注入指令到上下文] → [修改执行环境] → [执行任务]
特点:通过提示词注入改变 Claude 的行为
核心组件
// 系统提示词中的 Skill 工具定义(简化版)
{
"name": "Skill",
"type": "meta_tool",
"description": "Load and activate specialized skills for domain-specific tasks",
"parameters": {
"skill_name": "string",
"user_arguments": "string (optional)"
}
}
关键设计原则
1. 声明式系统
- Claude 通过文本描述决定是否使用 Skill
- 没有算法匹配,完全基于 LLM 推理
- 使用语义相似度而非关键词匹配
2. 双消息模式
用户消息 1(可见): "[Skill activated: pdf-processing]"
用户消息 2(隐藏): 完整的 SKILL.md 指令内容
这两个消息都作为 "user" 角色发送到 API
但只有消息 1 显示在 UI 中
3. 上下文修改
# Skill 激活时可以修改的执行环境参数
{
"allowed_tools": ["Read", "Bash", "Grep"], # 限制可用工具
"model": "claude-sonnet-4", # 切换模型
"thinking_tokens": 5000, # 思维链 token 限制
"timeout": 300 # 执行超时
}
🔄 完整生命周期
Phase 0: Claude Code 启动时
# 1. 扫描 Skill 目录
~/.claude/skills/ # 用户全局 Skills
.claude/skills/ # 项目级别 Skills
# 2. 解析所有 SKILL.md 的 YAML frontmatter
for skill_dir in skill_directories:
parse_frontmatter(skill_dir / "SKILL.md")
extract_metadata: {
name: "pdf-processing",
description: "Extract text and tables from PDF files...",
version: "1.0.0",
allowed_tools: ["Bash", "Read"]
}
# 3. 构建 Skill 索引(内存中)
skill_index = {
"pdf-processing": {
"path": "~/.claude/skills/pdf-processing",
"metadata": {...},
"loaded": False
},
"excel-analysis": {...},
...
}
Phase 1: 系统提示词注入
# Claude Code 的系统提示词结构(简化)
system_prompt = f"""
You are Claude Code, an AI assistant for software development.
Working directory: /home/user/project
Available tools:
- Read: Read file contents
- Bash: Execute shell commands
- Write: Write files
... (其他20多个工具)
Available Skills:
{generate_skill_metadata_list()}
When a user request matches a skill description, use the Skill tool to load it.
"""
def generate_skill_metadata_list():
"""
生成 Skill 元数据列表
每个 Skill 约 30-50 tokens
"""
output = "Skills:\n"
for skill in skill_index.values():
output += f"- name: {skill.name}\n"
output += f" description: {skill.description}\n"
return output
# 示例输出
"""
Skills:
- name: pdf-processing
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
- name: excel-analysis
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when working with Excel files or analyzing tabular data.
- name: makecoder-api
description: Interact with makeCoder platform APIs for model deployment, API calls, and resource management. Use when user asks about makeCoder services, model APIs, or platform features.
- name: makecoder-agent
description: Create and manage intelligent agents on makeCoder platform. Use when user wants to build agents, configure workflows, or integrate tools.
- name: makecoder-knowledge
description: Build and query knowledge bases on makeCoder platform. Use when user needs document Q&A, knowledge management, or RAG applications.
...
"""
Token 消耗(启动时):
基础系统提示词: ~2,000 tokens
10个 Skills 元数据: ~400 tokens (40 tokens/skill)
用户消息: 500 tokens
对话历史: 3,000 tokens
─────────────────────────────
总共占用: ~5,900 tokens
可用于响应: 194,100 tokens (200K 上下文窗口)
Phase 2: Skill 匹配决策
# 当用户发送消息时
user_message = "帮我在 makeCoder 上创建一个智能客服 Agent"
# Claude 的内部推理过程(简化)
"""
<thinking>
用户需要在 makeCoder 平台上创建智能客服 Agent。
扫描可用的 Skills:
- pdf-processing: "Extract text and tables from PDF files..."
→ 匹配度:低 ✗
- excel-analysis: "Analyze Excel spreadsheets..."
→ 匹配度:低 ✗
- makecoder-api: "Interact with makeCoder platform APIs..."
→ 匹配度:中 ~
- makecoder-agent: "Create and manage intelligent agents on makeCoder platform..."
→ 匹配度:高 ✓
- makecoder-knowledge: "Build and query knowledge bases..."
→ 匹配度:中 ~
决定:应该使用 makecoder-agent Skill
</thinking>
我需要使用 makecoder-agent skill 来帮你创建智能客服 Agent。
<tool_use>
<tool_name>Skill</tool_name>
<parameters>
<skill_name>makecoder-agent</skill_name>
<user_arguments>create customer service agent</user_arguments>
</parameters>
</tool_use>
"""
Phase 3: Skill 加载
# Claude Code Agent 收到工具调用请求
def handle_skill_tool(skill_name, user_arguments):
"""
处理 Skill 工具调用
"""
# 1. 验证 Skill 存在
if skill_name not in skill_index:
return {"error": "Skill not found"}
skill = skill_index[skill_name]
# 2. 读取完整的 SKILL.md
skill_path = Path(skill["path"]) / "SKILL.md"
skill_content = read_file(skill_path)
# 3. 解析 SKILL.md
frontmatter, instructions = parse_skill_markdown(skill_content)
# 4. 准备上下文注入
# 这是关键步骤!
context_injection = prepare_context_injection(
skill_name=skill_name,
instructions=instructions,
base_dir=skill["path"],
user_arguments=user_arguments,
allowed_tools=frontmatter.get("allowed_tools")
)
return context_injection
def prepare_context_injection(skill_name, instructions, base_dir, user_arguments, allowed_tools):
"""
准备要注入到对话中的内容
"""
# 消息 1:用户可见的元数据
visible_message = {
"role": "user",
"content": f"[Skill activated: {skill_name}]",
"metadata": {
"skill": skill_name,
"visible": True
}
}
# 消息 2:隐藏的完整指令
# 注意:这个消息有特殊标记 isMeta: true
hidden_message = {
"role": "user",
"content": format_skill_instructions(
instructions=instructions,
base_dir=base_dir,
user_arguments=user_arguments
),
"metadata": {
"skill": skill_name,
"visible": False,
"isMeta": True # 标记为元提示
}
}
# 执行环境修改
context_modifications = {
"allowed_tools": allowed_tools or None,
"base_directory": base_dir
}
return {
"messages": [visible_message, hidden_message],
"context_mods": context_modifications
}
def format_skill_instructions(instructions, base_dir, user_arguments):
"""
格式化 Skill 指令
"""
return f"""
# Skill: makeCoder Agent Development
Base directory: {base_dir}
User arguments: {user_arguments}
{instructions}
## Available resources in this skill:
- reference.md - makeCoder agent API documentation
- examples/ - Agent configuration examples
- templates/ - Agent template files
- scripts/deploy_agent.py - Agent deployment script
Remember: You can reference these files when needed, but they won't be loaded until you explicitly read them.
"""
Phase 4: 对话历史更新
# 对话历史在 Skill 加载后的状态
conversation_history = [
{
"role": "user",
"content": "帮我在 makeCoder 上创建一个智能客服 Agent"
},
{
"role": "assistant",
"content": "我需要使用 makecoder-agent skill...",
"tool_calls": [{"name": "Skill", "params": {...}}]
},
{
"role": "user",
"content": "[Skill activated: makecoder-agent]",
"metadata": {"visible": True}
},
{
"role": "user",
"content": """
# Skill: makeCoder Agent Development
Base directory: ~/.claude/skills/makecoder-agent
...
""",
"metadata": {"visible": False, "isMeta": True}
}
]
Token 消耗(Skill 加载后):
之前的对话: ~5,900 tokens
加载的 SKILL.md: ~2,000 tokens
─────────────────────────────
新的总占用: ~7,900 tokens
可用于响应: 192,100 tokens
Phase 5: Skill 内部工作
# Claude 现在在 Skill 上下文中工作
# 它可以:
# 1. 访问 Skill 的其他资源文件
response = """
让我先查看一下 makeCoder Agent 的配置模板和示例。
<tool_use>
<tool_name>Read</tool_name>
<parameters>
<file_path>~/.claude/skills/makecoder-agent/examples/customer_service.md</file_path>
</parameters>
</tool_use>
"""
# 2. 执行 Skill 提供的脚本
response = """
<tool_use>
<tool_name>Bash</tool_name>
<parameters>
<command>python ~/.claude/skills/makecoder-agent/scripts/create_agent.py --type customer-service --name "智能客服"</command>
</parameters>
</tool_use>
"""
# 注意:脚本的代码本身不会加载到上下文
# 只有脚本的输出结果会返回
# 这是 Skills 的关键优势!
# 3. 遵循 Skill 的指令进行工作
# Skill 可能指定了特定的工作流程
"""
Per the skill instructions:
1. Review agent requirements
2. Select appropriate template
3. Configure agent settings
4. Deploy to makeCoder platform
5. Test and validate
"""
🎯 渐进式披露机制
三层架构
┌─────────────────────────────────────────────────────────┐
│ Layer 1: Metadata (Always Loaded) │
│ - name, description │
│ - Token cost: ~40 per skill │
│ - Purpose: Skill discovery │
└─────────────────────────────────────────────────────────┘
↓ (Only if matched)
┌─────────────────────────────────────────────────────────┐
│ Layer 2: Core Instructions (Loaded on activation) │
│ - SKILL.md content │
│ - Token cost: ~500-2000 │
│ - Purpose: Workflow guidance │
└─────────────────────────────────────────────────────────┘
↓ (Only if needed)
┌─────────────────────────────────────────────────────────┐
│ Layer 3: Reference Materials (Loaded on demand) │
│ - reference.md, examples/, scripts/ │
│ - Token cost: Variable (0-10000+) │
│ - Purpose: Detailed documentation │
└─────────────────────────────────────────────────────────┘
实际例子:makeCoder 平台开发
场景:用户想在 makeCoder 上部署一个 LLM 应用
# === Layer 1: 启动时 ===
# Claude 加载所有 Skill 的元数据
skills_metadata = """
- makecoder-api: Interact with makeCoder platform APIs...
- makecoder-agent: Create and manage intelligent agents...
- makecoder-knowledge: Build and query knowledge bases...
- makecoder-model: Deploy and manage LLM models...
"""
# Token 消耗: 4 × 40 = 160 tokens
# === User Query ===
user: "我想在 makeCoder 上部署一个 GPT-4 应用"
# === Layer 2: 匹配后加载 ===
# Claude 判断需要 makecoder-model skill
# 加载 SKILL.md 的核心指令
makecoder_model_instructions = """
# makeCoder Model Deployment
## When to Use
Use this skill when user wants to deploy, manage, or configure LLM models on makeCoder platform.
## Core Workflow
1. Check platform requirements
2. Select model configuration
3. Set up API endpoints
4. Configure rate limits and quotas
5. Test deployment
## Available Tools
- scripts/deploy_model.py
- reference.md (complete API docs)
- examples/ (deployment templates)
"""
# Token 消耗: ~1,000 tokens
# 总 token: 160 + 1,000 = 1,160
# === Layer 3: 按需加载 ===
# 如果用户问:"具体的 API 参数是什么?"
# Claude 才会读取 reference.md
<tool_use>
<tool_name>Read</tool_name>
<parameters>
<file_path>~/.claude/skills/makecoder-model/reference.md</file_path>
</parameters>
</tool_use>
# reference.md 内容(假设 5000 tokens)
# Token 消耗: 1,160 + 5,000 = 6,160
# 如果用户不问细节,这 5000 tokens 永远不会加载!
为什么这很重要?
传统方式(全部加载):
启动时加载所有文档
makeCoder API docs: 3,000 tokens
makeCoder Agent docs: 4,000 tokens
makeCoder Knowledge: 3,500 tokens
makeCoder Model docs: 5,000 tokens
总计: 15,500 tokens
可用上下文: 184,500 tokens
Skills 方式(渐进式):
启动时只加载元数据
所有 skills 元数据: 400 tokens
用户查询匹配后加载核心: 1,000 tokens
按需加载详细文档: 5,000 tokens (仅在需要时)
总计(最坏情况): 6,400 tokens
节省: ~9,100 tokens (58% 节省!)
📡 API 请求结构
标准对话流程
# === 初始请求 ===
POST /v1/messages
{
"model": "claude-sonnet-4",
"max_tokens": 4096,
"system": """
You are Claude Code...
Available Skills:
- makecoder-api: Interact with makeCoder platform...
- makecoder-agent: Create and manage agents...
""",
"messages": [
{"role": "user", "content": "帮我用 makeCoder API 查询可用模型列表"}
]
}
# === Claude 响应(决定使用 Skill) ===
{
"content": [
{"type": "text", "text": "我需要使用 makecoder-api skill..."},
{
"type": "tool_use",
"name": "Skill",
"input": {
"skill_name": "makecoder-api",
"user_arguments": "list available models"
}
}
]
}
# === Agent 注入 Skill 内容 ===
# 构建新的消息列表
POST /v1/messages
{
"model": "claude-sonnet-4",
"max_tokens": 4096,
"system": "...(same)...",
"messages": [
{"role": "user", "content": "帮我用 makeCoder API 查询可用模型列表"},
{
"role": "assistant",
"content": [
{"type": "text", "text": "我需要使用 makecoder-api skill..."},
{"type": "tool_use", "name": "Skill", "input": {...}}
]
},
# --- Skill 注入的两条消息 ---
{
"role": "user",
"content": "[Skill activated: makecoder-api]"
# 用户可见
},
{
"role": "user",
"content": """
# Skill: makeCoder API Integration
## Overview
This skill helps you interact with makeCoder platform APIs...
## Available Operations
- List models: GET /api/v1/models
- Deploy model: POST /api/v1/models/deploy
- Query status: GET /api/v1/models/{id}/status
## Authentication
Use environment variable MAKECODER_API_KEY
## Example Scripts
See examples/list_models.py
"""
# 隐藏,但 Claude 能看到
}
]
}
# === Claude 在 Skill 上下文中工作 ===
{
"content": [
{"type": "text", "text": "让我查看可用的 API 脚本..."},
{
"type": "tool_use",
"name": "Read",
"input": {"file_path": "~/.claude/skills/makecoder-api/examples/list_models.py"}
}
]
}
跨 Skill 切换
# === 场景:用户先查询模型,后创建 Agent ===
# 第一轮对话
messages = [
{"role": "user", "content": "帮我查询 makeCoder 上有哪些模型"},
{"role": "assistant", "content": [...], "tool_calls": [Skill: makecoder-api]},
{"role": "user", "content": "[Skill activated: makecoder-api]"},
{"role": "user", "content": "# Skill: makeCoder API...", "metadata": {"isMeta": True}},
{"role": "assistant", "content": "找到了以下模型:\n- GPT-4\n- Claude-3-Sonnet\n- ..."}
]
# makecoder-api skill 的指令现在在上下文中
# Context size: 6,000 tokens
# 用户新请求
{"role": "user", "content": "好的,现在帮我创建一个基于 GPT-4 的客服 Agent"}
# Claude 判断需要新的 skill
{"role": "assistant", "content": [...], "tool_calls": [Skill: makecoder-agent]}
# 新的 Skill 注入
messages.extend([
{"role": "user", "content": "[Skill activated: makecoder-agent]"},
{"role": "user", "content": "# Skill: makeCoder Agent...", "metadata": {"isMeta": True}}
])
# 现在上下文中有两个 Skill 的指令!
# Context size: 6,000 + 2,000 = 8,000 tokens
# Claude 可以同时参考两个 Skill 的知识
"""
根据 makecoder-api skill,GPT-4 在平台上是可用的。
现在我将使用 makecoder-agent skill 的工作流来创建 Agent...
"""
🔧 实际执行流程
完整例子:在 makeCoder 上创建知识库应用
# === 用户请求 ===
user_query = """
我想在 makeCoder 上创建一个基于公司文档的问答系统。
我有 100 多个 PDF 文档需要导入。
"""
# === Step 1: Claude 分析需求 ===
"""
<thinking>
用户需要:
1. 在 makeCoder 平台操作
2. 创建知识库
3. 导入大量 PDF 文档
4. 搭建问答系统
匹配的 Skills:
- makecoder-knowledge ✓ (知识库创建)
- pdf-processing ✓ (PDF 处理)
- makecoder-agent ~ (可能需要,用于问答界面)
优先加载 makecoder-knowledge
</thinking>
"""
# === Step 2: 加载主 Skill ===
# 触发 Skill 工具
tool_call = {
"name": "Skill",
"input": {
"skill_name": "makecoder-knowledge",
"user_arguments": "create knowledge base from PDF documents"
}
}
# 注入 Skill 内容
skill_content = """
# Skill: makeCoder Knowledge Base
## Core Capabilities
1. Create and manage knowledge bases
2. Upload and process documents (PDF, Word, Markdown)
3. Configure RAG settings
4. Query knowledge base
## Workflow for Document Q&A
1. Create knowledge base via API
2. Upload documents (batch or single)
3. Wait for processing completion
4. Configure retrieval parameters
5. Test queries
## Important Notes
- Large PDFs (>20MB) should be split
- Processing time: ~1min per 100 pages
- Supported formats: PDF, DOCX, TXT, MD
- Max documents per KB: 1000
## Available Tools
- scripts/create_kb.py: Create knowledge base
- scripts/upload_docs.py: Batch upload
- scripts/query_kb.py: Test queries
- reference.md: Complete API documentation
"""
# === Step 3: Claude 开始执行工作流 ===
# 3.1 读取示例脚本
<tool_use>
<tool_name>Read</tool_name>
<parameters>
<file_path>~/.claude/skills/makecoder-knowledge/examples/batch_pdf_upload.md</file_path>
</parameters>
</tool_use>
# 3.2 创建知识库
<tool_use>
<tool_name>Bash</tool_name>
<parameters>
<command>
python ~/.claude/skills/makecoder-knowledge/scripts/create_kb.py \
--name "公司文档问答" \
--description "基于公司 PDF 文档的智能问答系统" \
--model gpt-4
</command>
</parameters>
</tool_use>
# 输出: Knowledge Base created: kb_abc123
# 3.3 批量上传文档
<tool_use>
<tool_name>Bash</tool_name>
<parameters>
<command>
python ~/.claude/skills/makecoder-knowledge/scripts/upload_docs.py \
--kb-id kb_abc123 \
--folder ./company_docs \
--batch-size 10
</command>
</parameters>
</tool_use>
# 输出: Uploaded 100 documents. Processing...
# 3.4 判断是否需要额外 Skill
"""
<thinking>
用户可能需要一个问答界面。
应该建议使用 makecoder-agent 创建对话应用。
</thinking>
"""
# 3.5 提出下一步建议
response = """
已成功创建知识库并上传了 100 个文档!
知识库 ID: kb_abc123
文档数量: 100
状态: 处理中(预计 3-5 分钟完成)
接下来你可以:
1. 创建一个智能问答 Agent(推荐)
2. 直接通过 API 调用查询
3. 在 makeCoder 控制台测试
需要我帮你创建智能问答 Agent 吗?
"""
# === Step 4: 用户确认创建 Agent ===
user: "是的,帮我创建 Agent"
# === Step 5: 加载新 Skill ===
# 触发 makecoder-agent skill
tool_call = {
"name": "Skill",
"input": {
"skill_name": "makecoder-agent",
"user_arguments": "create Q&A agent using knowledge base kb_abc123"
}
}
# === Step 6: 在新 Skill 上下文中工作 ===
# 现在 Claude 可以同时参考:
# - makecoder-knowledge skill (知识库操作)
# - makecoder-agent skill (Agent 创建)
<tool_use>
<tool_name>Bash</tool_name>
<parameters>
<command>
python ~/.claude/skills/makecoder-agent/scripts/create_agent.py \
--type qa \
--name "公司文档助手" \
--knowledge-base kb_abc123 \
--model gpt-4
</command>
</parameters>
</tool_use>
# === 最终输出 ===
response = """
完成!你的智能问答系统已经创建成功:
📚 知识库: kb_abc123
- 文档数: 100
- 状态: 已就绪
- 模型: GPT-4
🤖 智能助手: agent_xyz789
- 名称: 公司文档助手
- 类型: 知识库问答
- 访问链接: https://makecoder.com/agent/xyz789
你现在可以:
- 在网页端测试对话
- 通过 API 集成到你的应用
- 分享给团队成员使用
"""
Token 消耗分析
阶段 1 - 启动:
系统提示词: 2,000
Skill 元数据: 400
用户查询: 100
小计: 2,500 tokens
阶段 2 - 加载 makecoder-knowledge:
Skill 指令: 1,500
小计: 4,000 tokens
阶段 3 - 读取示例:
batch_pdf_upload.md: 800
小计: 4,800 tokens
阶段 4 - 工具执行:
(脚本输出,不占用输入 token)
阶段 5 - 加载 makecoder-agent:
Skill 指令: 1,200
小计: 6,000 tokens
总计输入 tokens: ~6,000
剩余上下文: 194,000 tokens
💻 技术实现细节
Skill 文件结构
makecoder-api/
├── SKILL.md # 必需:主指令文件
│ ├── YAML frontmatter # 元数据
│ └── Markdown content # 指令
├── reference.md # 可选:完整 API 文档
├── examples/ # 可选:示例
│ ├── list_models.py
│ ├── deploy_model.py
│ └── query_status.md
├── scripts/ # 可选:辅助脚本
│ ├── api_client.py
│ └── deploy.sh
└── templates/ # 可选:配置模板
├── model_config.json
└── deployment.yaml
SKILL.md 示例(makeCoder)
---
name: makecoder-api
version: "1.0.0"
description: "Interact with makeCoder platform APIs for model deployment, API calls, and resource management. Use when user asks about makeCoder services, model APIs, or platform features."
allowed_tools:
- Read
- Bash
- Grep
author: "makeCoder Team"
tags:
- api
- platform
- deployment
---
# makeCoder API Integration Skill
## When to Use This Skill
Trigger this skill when the user mentions:
- makeCoder platform operations
- Model deployment or management
- API integration
- Resource quotas or limits
- Platform status queries
## Core Capabilities
### 1. Model Management
- List available models
- Deploy new models
- Update model configurations
- Check deployment status
- Manage API keys
### 2. Resource Operations
- Query quota limits
- Monitor usage statistics
- Manage billing information
### 3. API Integration
- Generate API endpoints
- Configure authentication
- Test API calls
## Workflow Guidelines
### Deploying a Model
1. Check platform requirements (reference.md)
2. Validate user's quota
3. Prepare deployment config
4. Submit deployment request
5. Monitor deployment status
6. Test deployed endpoint
### Querying Resources
1. Authenticate with API key
2. Make appropriate API call
3. Parse and format response
4. Handle errors gracefully
## Available Resources
### Scripts
- `scripts/api_client.py`: Python client for makeCoder API
- `scripts/deploy_model.sh`: Automated model deployment
- `scripts/check_quota.py`: Query resource limits
### Documentation
- `reference.md`: Complete API reference (5000+ tokens)
- `examples/`: Working code examples
### Templates
- `templates/model_config.json`: Model configuration template
- `templates/deployment.yaml`: Deployment specification
## Best Practices
1. **Always verify quota before deployment**
- Check available resources
- Estimate required resources
- Warn user if insufficient
2. **Use authentication securely**
- Never expose API keys in output
- Use environment variables
- Validate key format
3. **Handle errors gracefully**
- Parse error responses
- Provide actionable suggestions
- Log failures for debugging
4. **Optimize API calls**
- Use batch operations when possible
- Cache frequently accessed data
- Respect rate limits
## Common Patterns
### Pattern 1: Quick Model List
```python
# Don't load reference.md for simple queries
# Use cached knowledge or execute script directly
python scripts/list_models.py
Pattern 2: Complex Configuration
# Load reference.md only when needed
Read reference.md → section on advanced config
# Then apply configuration
Pattern 3: Multi-step Deployment
# Use workflow approach
1. Check quota
2. Validate config
3. Deploy
4. Test
5. Report status
Error Handling
Common Errors
QUOTA_EXCEEDED: User needs to upgrade planINVALID_CONFIG: Check model parametersAUTH_FAILED: Verify API keyRATE_LIMIT: Wait and retry
Recovery Strategies
- Automatic retry for transient errors
- Clear error messages for user errors
- Suggestions for resolution
Notes
- All scripts require MAKECODER_API_KEY environment variable
- Reference documentation is large (~5000 tokens) - load only when needed
- Examples are self-contained and can run independently
- Platform API rate limit: 100 requests/minute
### SKILL.md 解析
```python
import yaml
from pathlib import Path
def parse_skill_file(skill_path):
"""
解析 SKILL.md 文件
"""
content = Path(skill_path).read_text()
# 分离 frontmatter 和 content
if content.startswith('---'):
parts = content.split('---', 2)
if len(parts) >= 3:
frontmatter_text = parts[1]
markdown_content = parts[2].strip()
else:
raise ValueError("Invalid SKILL.md format")
else:
raise ValueError("SKILL.md must start with YAML frontmatter")
# 解析 YAML
metadata = yaml.safe_load(frontmatter_text)
# 验证必需字段
required_fields = ['name', 'description']
for field in required_fields:
if field not in metadata:
raise ValueError(f"Missing required field: {field}")
return {
'metadata': metadata,
'instructions': markdown_content,
'path': skill_path
}
# 示例
skill = parse_skill_file("~/.claude/skills/makecoder-api/SKILL.md")
# {
# 'metadata': {
# 'name': 'makecoder-api',
# 'description': '...',
# 'version': '1.0.0',
# 'allowed_tools': ['Bash', 'Read']
# },
# 'instructions': '# makeCoder API Integration Skill\n\n## Overview...',
# 'path': '...'
# }
allowed-tools 实现
def apply_tool_restrictions(skill_metadata, available_tools):
"""
根据 Skill 的 allowed-tools 限制可用工具
"""
allowed = skill_metadata.get('allowed_tools')
if allowed is None:
# 没有限制,返回所有工具
return available_tools
# 过滤工具列表
restricted_tools = [
tool for tool in available_tools
if tool['name'] in allowed
]
# 特殊情况:通配符
if 'Bash(*)' in allowed:
# 允许所有 bash 命令
bash_tool = next(t for t in restricted_tools if t['name'] == 'Bash')
bash_tool['restrictions'] = None
elif 'Bash(python:*)' in allowed:
# 只允许 python 命令
bash_tool = next(t for t in restricted_tools if t['name'] == 'Bash')
bash_tool['restrictions'] = {'allowed_commands': ['python', 'python3']}
return restricted_tools
# 示例
skill_metadata = {
'allowed_tools': ['Read', 'Grep', 'Bash(python:*)']
}
restricted = apply_tool_restrictions(skill_metadata, all_tools)
# Claude 只能使用 Read, Grep, 和 python 命令
版本管理
# SKILL.md 中的版本控制
"""
---
name: makecoder-api
description: ...
version: "2.1.0"
---
# makeCoder API Integration
## Version History
- v2.1.0 (2025-01-15): Added support for batch model deployment
- v2.0.0 (2024-12-01): Updated API to v2, breaking changes in authentication
- v1.0.0 (2024-10-01): Initial release
## Breaking Changes in v2.0
- API endpoints now use `/v2/` prefix
- Authentication requires Bearer token instead of API key header
- Response format changed to JSON:API spec
"""
# 可以在 Skill 中检查版本兼容性
"""
## Version Check
If you encounter authentication errors, check if you're using v2 API endpoints.
For v1.x compatibility, see legacy_examples.md.
"""
Skill 间通信
# makecoder-agent Skill 可以引用 makecoder-api 的功能
"""
---
name: makecoder-agent
description: Create and manage intelligent agents on makeCoder platform
depends_on:
- makecoder-api # 依赖 API skill
- makecoder-knowledge # 依赖知识库 skill
---
# makeCoder Agent Development Skill
## Dependencies
This skill builds on:
- makecoder-api: For model deployment and API operations
- makecoder-knowledge: For integrating knowledge bases
## Workflow
1. Use makecoder-api to check available models
2. Use makecoder-knowledge to create/link knowledge base (if needed)
3. Create agent configuration
4. Deploy agent
5. Test and validate
"""
# Claude 可以自动加载依赖的 Skills
# 如果它判断需要的话
性能优化技巧
# 1. 使用缓存标记
{
"role": "user",
"content": "Long SKILL.md content...",
"cache_control": {"type": "ephemeral"}
}
# Anthropic 会缓存这个消息
# 后续请求如果包含相同内容,不会重新计费
# 2. 分层文档
"""
SKILL.md # 500 tokens - 总是加载
├── quick_ref.md # 200 tokens - 频繁访问
├── api_overview.md # 1000 tokens - 偶尔访问
└── full_api_ref.md # 5000 tokens - 很少访问
"""
# 3. 脚本化处理
# 不要写:
"Read makeCoder API docs and list all available models"
# 而是写:
"""
Run: python scripts/list_models.py
This returns model list without loading all docs
"""
# 4. 索引文件
# index.json
{
"models": {
"llm": ["gpt-4", "claude-3-sonnet", "gemini-pro"],
"embedding": ["text-embedding-ada-002", "bge-large"],
"image": ["dall-e-3", "stable-diffusion-xl"]
},
"endpoints": {
"deployment": "/api/v1/models/deploy",
"status": "/api/v1/models/{id}/status",
"list": "/api/v1/models"
}
}
# Claude 可以快速查找而不需要读取所有文档
📊 与其他机制的对比
Skills vs Traditional Tools
| 特性 | Traditional Tools | Skills |
|---|---|---|
| 执行方式 | 直接函数调用 | 提示词注入 |
| 状态 | 无状态 | 有状态(指令留在上下文) |
| 扩展性 | 需要修改代码 | 添加文件即可 |
| Token 消耗 | 工具描述(固定) | 元数据 + 按需加载 |
| 适用场景 | 离散操作 | 复杂工作流 |
Skills vs MCP
| 特性 | Skills | MCP |
|---|---|---|
| 主要用途 | 传授知识和流程 | 连接外部系统 |
| 数据来源 | 本地文件 | 远程 API/数据库 |
| 安装 | 文件夹 | 服务器进程 |
| 触发方式 | 模型判断 | 模型选择工具 |
| 最佳实践 | 程序性知识 | 数据访问 |
Skills vs Projects (claude.ai)
| 特性 | Skills | Projects |
|---|---|---|
| 平台 | 所有 Claude 产品 | claude.ai 专属 |
| 内容类型 | 指令 + 代码 | 文档 + 对话 |
| 激活方式 | 自动(基于描述) | 手动选择项目 |
| 持久性 | 永久可用 | 项目内有效 |
| 共享 | 通过文件/Git | 团队功能 |
🎓 最佳实践总结
1. 写好 description
# ❌ 不好
description: "makeCoder module"
# ✅ 好
description: "Interact with makeCoder platform APIs for model deployment, resource management, and API integration. Use when user asks about makeCoder services, deploying models, checking quotas, or platform operations."
2. 结构化指令
# ❌ 不好
Just help with makeCoder platform.
# ✅ 好
# makeCoder Platform Integration
## When to Use
Trigger this skill when user mentions:
- Model deployment on makeCoder
- API integration
- Resource management
- Platform configuration
## Core Capabilities
1. Model deployment
2. API integration
3. Resource monitoring
4. Configuration management
## Workflow
1. Authenticate with API key
2. Verify user permissions
3. Execute requested operation
4. Validate results
5. Provide clear feedback
## Available Tools
- scripts/deploy.py
- scripts/query.py
- reference.md (full API docs)
3. 渐进披露
SKILL.md → 核心工作流(500-1000 字)
├── quick_ref.md → 快速参考(200 字)
├── examples/ → 使用示例
├── reference/ → 完整文档
└── scripts/ → 辅助工具
4. 实际测试
# 测试 Skill 触发
echo "帮我在 makeCoder 上部署一个 GPT-4 模型" | claude
# 检查是否加载正确的 Skill
# 查看日志:~/.claude/logs/
# 迭代改进 description
# 根据实际使用调整触发条件
🔍 调试技巧
查看加载的 Skills
# Claude Code 启动时会显示
✔ Found 6 Skills
• makecoder-api
• makecoder-agent
• makecoder-knowledge
• makecoder-model
• pdf-processing
• excel-analysis
# 查看 Skill 详情
cat ~/.claude/skills/makecoder-api/SKILL.md | head -20
检查 Skill 是否被触发
# 在对话中,Claude 会显示
# [Skill activated: makecoder-api]
# 或者查看详细日志
tail -f ~/.claude/logs/main.log | grep "Skill"
测试 Skill 指令
# 直接用 claude --prompt 测试
claude --prompt "$(cat ~/.claude/skills/makecoder-api/SKILL.md)"
# 或者在交互模式中
/skill makecoder-api
📝 总结
Claude Skills 的核心创新:
- 元工具架构:通过提示词注入而非函数调用
- 渐进式披露:三层加载机制,按需消耗 token
- 文件系统导航:像查阅文档一样使用 Skills
- 脚本化优势:执行代码但只返回结果
- 上下文修改:动态改变工具权限和执行环境
对于 makeCoder 平台:
- ✅ 完美适配平台 API 文档(模型、Agent、知识库等)
- ✅ 使用示例可无限扩展(通过本地文件或 MCP)
- ✅ 多个功能模块可组合使用
- ✅ 团队可通过 Git 共享 Skills
- ✅ 持续迭代优化,无需修改核心代码
🚀 makeCoder 专属优势
为什么 Skills 特别适合 makeCoder?
-
API 文档丰富
- 模型部署 API
- Agent 管理 API
- 知识库操作 API
- 资源监控 API
通过 Skills,可以将所有 API 文档分层组织,按需加载!
-
多模块协作
- 用户可能需要:部署模型 → 创建知识库 → 搭建 Agent
- Skills 支持多个 skill 组合工作
- 每个模块独立维护,易于更新
-
实战示例库
- makeCoder 有大量实战案例
- 通过 examples/ 目录组织
- 用户需要时才加载,节省 token
-
持续更新
- makeCoder 平台持续迭代
- 只需更新对应的 SKILL.md
- 无需重新训练模型或修改系统提示词
-
社区共享
- 团队可以共享 makeCoder Skills
- 通过 Git 版本管理
- 降低新成员学习成本
这就是为什么 Skills 是 makeCoder 用户的最佳开发伴侣!
📚 推荐阅读
本文档基于 Claude Skills 技术深度分析,使用 makeCoder 作为实战平台示例。 如有技术问题或改进建议,欢迎反馈!