Skills 基本结构:编写和检查 SKILL.md
将发现用的描述与执行说明分开放置,用真实 YAML 解析核对必填项和可选字段。
学完这一章,你能够
- 将发现用的描述与执行说明分开放置,用真实 YAML 解析核对必填项和可选字段。
从最小技能目录开始
建一个 sales-summary 目录,把 SKILL.md 放在目录内。文件开头是用两行三连字符界定的 YAML frontmatter,下方的 Markdown 正文写操作顺序和可验证结果。公开格式要求 name 和 description。
Skill 是工作说明。宿主可先读取名称与说明,任务需要时再加载完整内容。正文可以按使用条件、处理步骤与示例组织。技能入口是否有 / 命令及何时读取由产品实现,不能由标头字段推断。
用名称标识技能
name 为 1 至 64 个字符。可用 a-z、0-9 与单个连字符分隔词段。开头和结尾不能是连字符,连续两个连字符也不允许。父目录名必须大小写完全一致。
sales-summary 与 export-ledger 都是可辨识的命名。动词短语可以表明目的,也可用团队约定。名称里的版本片段若满足语法且和目录一致,仍可通过格式校验。把常变版本写到 metadata 往往更便于保持入口稳定。
为描述写清功能与触发条件
description 为非空字符串,最多 1024 字符。在描述中写任务、所需输入和适用场景,例如接到季度结算请求时,按照已批准的 CSV 汇总净额。多行值可用 YAML 的折叠或保留换行写法,限制作用于解析后的字符串。
描述过泛时,多个技能的用途难区分。PDF 抽取可明确文本、表格或填写表单,扫描件要单独确认 OCR 条件。HTML 邮件转换可在描述中写出输入 Markdown 和适用的邮件模板。
按需要添加正文与工作材料
正文说明主要规则,参考资料放 references/,执行程序放 scripts/,模板或图像放 assets/。宿主读取补充资料和允许运行脚本时仍受各自能力和权限约束。在正文用相对路径指向实际文件。
对示例中的 PDF 工作可分别写文本抽取、表单填写和扫描件处理,给每个分支标出所需依赖与文件结果。本章实际校验技能结构,PDF 解析、OCR 和表单写入运行待后续验证。
YAML 必填信息
| 字段 | 必填 | 语义 |
| name | 是 | 标识技能,需与父目录一致,调用界面由宿主提供。 |
| description | 是 | 说明作用和何时使用,内容限制 1 至 1024 字符。 |
对照名称与约束
| 合法形式 | 反例或风格差异 | 判断依据 |
| render-report | RenderReport | 大写字母超出允许字符。 |
| audit-ledger | audit_ledger | 下划线不可以做分隔符,目录还须同名。 |
| stage-audit | stage-audit-v2 | 二者语法都成立。版本可保存在 metadata 以保持目录稳定。 |
描述的可辨识性
| 用途 | 表达 | 触发条件 |
| 代码扫描 | 说明扫描 Python 查询构造并列出修复位置。 | 需要审查 SQL 拼接时。 |
| 生成邮件模板 | 说明将 Markdown 转成给定版式的 HTML。 | 需要生成有指定模板的邮件草稿时。 |
规范字段与约束
| 字段 | 必需 | 作用 |
| name | 是 | 1 至 64 个字符,校验词段格式并与目录名比对。 |
| description | 是 | 1 至 1024 字符的非空说明,包含用途和场景。 |
| license | 否 | 写许可证标识或指向随目录提供的许可证文件。 |
| compatibility | 否 | 说明宿主、系统包或网络需求,最长 500 字符。 |
| metadata | 否 | 附加键值信息,例如作者或版本,建议键值都用字符串。 |
| allowed-tools | 否 | 实验性字段,用空格列预先允许的工具。宿主支持和权限行为需单独验。 |
校验目录、YAML 和必填项
展开查看收起
"""Validate the workshop Skill structure and inspect its optional files."""
import argparse
import json
from pathlib import Path
import re
from tempfile import TemporaryDirectory
import yaml
OPTIONAL_DIRECTORIES = ("assets", "references", "scripts")
OPTIONAL_FIELDS = ("allowed-tools", "compatibility", "license", "metadata")
SKILL_NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
def check(folder):
errors = []
file = folder / "SKILL.md"
if not file.is_file():
return {"valid": False, "errors": ["SKILL.md is missing"]}
first, opening, rest = file.read_text(encoding="utf-8").partition("\n")
if first != "---" or not opening:
return {"valid": False, "errors": ["opening YAML delimiter is missing"]}
lines = rest.splitlines()
if "---" not in lines:
return {"valid": False, "errors": ["closing YAML delimiter is missing"]}
stop = lines.index("---")
try:
fields = yaml.safe_load("\n".join(lines[:stop]))
except yaml.YAMLError:
return {"valid": False, "errors": ["invalid YAML"]}
if not isinstance(fields, dict):
return {"valid": False, "errors": ["frontmatter must be a mapping"]}
name = fields.get("name")
if not isinstance(name, str) or not (1 <= len(name) <= 64 and SKILL_NAME.fullmatch(name)):
errors.append("name must have 1–64 lowercase ASCII letters, numbers and single hyphen separators")
elif name != folder.name:
errors.append("name must match the directory")
description = fields.get("description")
if not isinstance(description, str) or not (description.strip() and len(description) <= 1024):
errors.append("description must be nonblank and at most 1024 characters")
if "compatibility" in fields:
compatible = fields["compatibility"]
if not isinstance(compatible, str) or not (1 <= len(compatible.strip()) and len(compatible) <= 500):
errors.append("compatibility must be a nonblank string of at most 500 characters")
if "metadata" in fields:
metadata = fields["metadata"]
if not isinstance(metadata, dict) or any(not isinstance(key, str) or not isinstance(value, str)
for key, value in metadata.items()):
errors.append("metadata must map strings to strings")
for field in ("allowed-tools", "license"):
if field in fields and not isinstance(fields[field], str):
errors.append(f"{field} must be a string")
return {"valid": not errors, "errors": errors,
"optional_fields": [field for field in OPTIONAL_FIELDS if field in fields],
"directories": [name for name in OPTIONAL_DIRECTORIES if (folder / name).is_dir()]}
def exercise():
source = Path(__file__).parent / "skills" / "sales-summary"
with TemporaryDirectory(prefix="mbsky-skill-structure-") as directory:
root = Path(directory)
def verify(folder_name, header):
folder = root / folder_name
folder.mkdir(exist_ok=True)
file = folder / "SKILL.md"
file.write_text(f"---\n{header}\n---\n\n# Review an inventory sample\n", encoding="utf8")
return check(folder)
required = [check(source)["valid"]]
for content in (
"name: minimum", "name: minimum\ndescription: ' '",
"name: minimum\ndescription: " + "x" * 1024,
"name: minimum\ndescription: " + "x" * 1025,
"name: [broken",
):
required.append(verify("minimum", content)["valid"])
names = [verify(folder, f"name: {name}\ndescription: Audit a local inventory.")["valid"]
for folder, name in [("a", "a"), ("b" * 64, "b" * 64), ("c" * 65, "c" * 65),
("RenderReport", "RenderReport"), ("audit_ledger", "audit_ledger"),
("leading", "-leading"), ("trailing", "trailing-"),
("double--gap", "double--gap"), ("parent", "another"),
("stage-audit-v2", "stage-audit-v2")]]
for name in OPTIONAL_DIRECTORIES:
(root / "full-inspection" / name).mkdir(parents=True)
header = ("name: full-inspection\ndescription: |\n Confirm approved inventory inputs\n"
" before reconciling totals.\nlicense: MIT\nmetadata:\n version: '2'\n"
"allowed-tools: Read\ncompatibility: ")
optional = verify("full-inspection", header + "local audit runner")
too_long = verify("full-inspection", header + "x" * 501)["valid"]
return {"required": required, "names": names, "yaml_version": yaml.__version__,
"optional": {"valid": optional["valid"], "too_long": too_long,
"fields": optional["optional_fields"], "directories": optional["directories"]}}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("folder", type=Path, nargs="?")
parser.add_argument("--exercise", action="store_true")
args = parser.parse_args()
if not args.exercise and args.folder is None:
parser.error("supply the skill directory or --exercise")
print(json.dumps(exercise() if args.exercise else check(args.folder), ensure_ascii=False))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
运行本地实验
解压后按 README 运行当前章节对应的脚本,并查看真实输出。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
父目录必须与 name 完全匹配,且名称只能使用小写英文字母、数字和分隔用的连字符。