蓝色天空.知识 · 实践 · 创造
我的收藏
Claude Code 教程目录 42章
Claude Code / LEARN BY DOING

Claude Code 插件参考手册

对照 Anthropic 官方文档,系统梳理 Claude Code 插件标准目录结构、plugin.json 清单字段、hooks.json 生命周期钩子、Skills 技能规范及 MCP/LSP 集成配置。

学完这一章,你能够

  • 掌握 Claude Code 插件包的标准化目录布局,能够正确放置清单、技能、子代理、钩子与 MCP/LSP 配置。
  • 熟悉 `.claude-plugin/plugin.json` 核心字段与语义化版本校验规范,及 `userConfig` 安装交互配置。
  • 理解 `hooks/hooks.json` 的生命周期事件匹配、全局/项目/插件三层作用域叠加顺序,以及 `skills/` 与旧版 `.claude/commands/` 的演进关系。

插件标准目录结构总览

Claude Code 插件是一个自包含目录包,把技能(Skills)、专属子代理(Agents)、事件钩子(Hooks)、MCP 工具服务与 LSP 语言服务打包成单一可安装、可启停的分发单元,便于团队跨仓库复用工程工作流。

text
my-plugin/
├── .claude-plugin/
│   └── plugin.json       # 插件清单(元数据、版本与安装配置项)
├── skills/
│   └── <skill-name>/
│       └── SKILL.md      # 任务技能指令与资源目录
├── agents/
│   └── <agent-name>.md   # 专属子代理角色与提示定义
├── hooks/
│   └── hooks.json        # 生命周期事件钩子配置
├── .mcp.json             # 随插件提供的 MCP 服务端配置
└── .lsp.json             # 语言服务器(LSP)代码智能配置

插件清单(.claude-plugin/plugin.json)字段参考

若插件完全遵循标准约定目录,清单文件在轻量场景下可省略;但需要声明元数据、语义化版本、市场展示名或安装期用户参数(`userConfig`)时,必须在 `.claude-plugin/plugin.json` 中显式配置。

字段名类型必填性说明
namestring推荐必填插件唯一机器标识符(小写字母、数字与连字符)
displayNamestring可选展示在界面与插件市场中的可读名称
versionstring推荐必填遵循 SemVer 规范的版本号(如 "1.2.0")
descriptionstring推荐必填简明描述插件提供的核心能力与适用场景
userConfigobject可选安装或启用插件时提示用户填写的配置项定义(类型、说明、默认值)

生命周期钩子(hooks.json)与 Skills 规范

Hooks 允许在工具执行前(`PreToolUse`)、执行后(`PostToolUse`)、会话停止(`Stop`)等生命周期节点自动触发本地脚本或检查器(例如编辑代码后自动运行格式化/静态检查)。Hook 可同时存在于全局用户设置(`~/.claude/settings.json`)、仓库项目设置(`.claude/settings.json`)与已启用插件(`hooks/hooks.json`)三层作用域。

概念位置核心机制与推荐实践
Hooks(事件钩子)hooks/hooks.json按事件名 + matcher.tool 过滤,在工具调用前后确定性执行检查脚本
Skills(现代技能)skills/<name>/SKILL.md支持斜杠显式触发与上下文自动匹配,可携带多文件脚本与参考资料,为现代推荐标准
Commands(旧版命令).claude/commands/*.md历史单文件文本替换命令;向后兼容,但新插件建议统一迁移至 skills/ 目录
MCP / LSP 集成.mcp.json / .lsp.json声明随插件启停的外部工具服务与代码诊断服务,避免全局环境污染

说明:本参考手册由用户授权结合 Anthropic 官方插件文档独立整理;真实插件安装、市场发布与 Hook 宿主执行需在安装 Claude Code CLI 的环境中实测确认。

可运行验证实验与边界检查

含完整源码 · 129 行
展开查看收起
python
"""Offline verification lab for Claude Code Ch 32 (plugin-ref): Plugin layout, manifest, hooks & skills."""
import json
import re
from pathlib import Path
from tempfile import TemporaryDirectory

RUNTIME = "CPython 3.12.14 offline Claude Code plugin reference verifier"

VALID_HOOK_EVENTS = {"PreToolUse", "PostToolUse", "Notification", "Stop", "SubagentStop", "UserPromptSubmit"}
SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$")


def validate_plugin_dir(root: Path) -> dict:
    manifest_path = root / ".claude-plugin" / "plugin.json"
    errors = []
    manifest = {}
    if manifest_path.is_file():
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        for req in ("name", "version", "description"):
            if not manifest.get(req):
                errors.append(f"missing:{req}")
        if manifest.get("version") and not SEMVER_RE.match(manifest["version"]):
            errors.append("invalid_semver")
    skills = sorted(p.parent.name for p in (root / "skills").glob("*/SKILL.md")) if (root / "skills").is_dir() else []
    agents = sorted(p.stem for p in (root / "agents").glob("*.md")) if (root / "agents").is_dir() else []
    has_hooks = (root / "hooks" / "hooks.json").is_file()
    has_mcp = (root / ".mcp.json").is_file()
    return {
        "name": manifest.get("name"),
        "version": manifest.get("version"),
        "skills": skills,
        "agents": agents,
        "has_hooks": has_hooks,
        "has_mcp": has_mcp,
        "errors": errors,
    }


def dispatch_hooks(hooks_cfg: dict, event: str, tool_name: str) -> list[str]:
    assert event in VALID_HOOK_EVENTS
    triggered = []
    for entry in hooks_cfg.get(event, []):
        matcher = entry.get("matcher", {})
        expected_tool = matcher.get("tool")
        if expected_tool in (None, "*", tool_name):
            triggered.append(entry["handler"]["command"])
    return triggered


def merge_hook_scopes(global_hooks: list[str], project_hooks: list[str], plugin_hooks: list[str]) -> list[str]:
    return [*global_hooks, *project_hooks, *plugin_hooks]


def main() -> None:
    cases = []

    # Case 1: Standard plugin directory anatomy & plugin.json validation
    with TemporaryDirectory(prefix="claude-plugin-lab-") as td:
        root = Path(td) / "deploy-tools"
        (root / ".claude-plugin").mkdir(parents=True)
        (root / "skills" / "release-check").mkdir(parents=True)
        (root / "agents").mkdir(parents=True)
        (root / "hooks").mkdir(parents=True)
        (root / ".claude-plugin" / "plugin.json").write_text(
            json.dumps(
                {
                    "name": "deploy-tools",
                    "displayName": "Deployment Tools",
                    "version": "1.2.0",
                    "description": "Automated pre-release checks and deployment workflow",
                    "userConfig": {"targetEnvironment": {"type": "string", "default": "staging"}},
                },
                ensure_ascii=False,
            ),
            encoding="utf-8",
        )
        (root / "skills" / "release-check" / "SKILL.md").write_text("---\nname: release-check\n---\n# Check\n", encoding="utf-8")
        (root / "agents" / "auditor.md").write_text("# Auditor Agent\n", encoding="utf-8")
        (root / "hooks" / "hooks.json").write_text('{"PostToolUse": []}', encoding="utf-8")
        (root / ".mcp.json").write_text('{"mcpServers": {}}', encoding="utf-8")

        res1 = validate_plugin_dir(root)
        exp1 = {
            "name": "deploy-tools",
            "version": "1.2.0",
            "skills": ["release-check"],
            "agents": ["auditor"],
            "has_hooks": True,
            "has_mcp": True,
            "errors": [],
        }
        cases.append({"name": "plugin_layout_and_manifest", "expected": exp1, "actual": res1, "passed": res1 == exp1})

    # Case 2: Lifecycle hook matcher dispatch
    hooks_cfg = {
        "PreToolUse": [{"matcher": {"tool": "Bash"}, "handler": {"type": "shell", "command": "guard-bash"}}],
        "PostToolUse": [
            {"matcher": {"tool": "Edit"}, "handler": {"type": "shell", "command": "run-prettier"}},
            {"matcher": {"tool": "*"}, "handler": {"type": "shell", "command": "audit-log"}},
        ],
    }
    act2 = {
        "pre_bash": dispatch_hooks(hooks_cfg, "PreToolUse", "Bash"),
        "pre_read": dispatch_hooks(hooks_cfg, "PreToolUse", "Read"),
        "post_edit": dispatch_hooks(hooks_cfg, "PostToolUse", "Edit"),
    }
    exp2 = {"pre_bash": ["guard-bash"], "pre_read": [], "post_edit": ["run-prettier", "audit-log"]}
    cases.append({"name": "hook_event_matcher_dispatch", "expected": exp2, "actual": act2, "passed": act2 == exp2})

    # Case 3: Multi-scope hook resolution order (global -> project -> plugin)
    merged = merge_hook_scopes(["global:audit"], ["project:lint"], ["plugin:deploy-check"])
    exp3 = ["global:audit", "project:lint", "plugin:deploy-check"]
    cases.append({"name": "hook_scope_layering", "expected": exp3, "actual": merged, "passed": merged == exp3})

    # Case 4: Invalid semver & missing fields detection
    with TemporaryDirectory(prefix="claude-plugin-bad-") as td:
        bad = Path(td) / "broken"
        (bad / ".claude-plugin").mkdir(parents=True)
        (bad / ".claude-plugin" / "plugin.json").write_text('{"name": "broken", "version": "v1"}', encoding="utf-8")
        res4 = validate_plugin_dir(bad)
        exp4 = ["missing:description", "invalid_semver"]
        cases.append({"name": "invalid_manifest_rejection", "expected": exp4, "actual": res4["errors"], "passed": res4["errors"] == exp4})

    print(json.dumps({"runtime": RUNTIME, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()

预期结果与验证边界:离线运行 4 项验证用例:标准插件目录结构与 plugin.json 校验、PreToolUse/PostToolUse 钩子匹配分发、全局/项目/插件三层作用域叠加顺序及非法 SemVer/缺字段拒绝,全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

下载本章实验包 (mbskycom202612a3140.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Claude Code

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3140.zip

下载课程关联工程包:Claude Code

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip

常见错误与边界检查

  • 把 `plugin.json` 直接放在插件根目录而不是 `.claude-plugin/` 下:标准清单路径为 `.claude-plugin/plugin.json`,放错目录会导致元数据与 `userConfig` 不生效。
  • 在 `PostToolUse` 钩子中使用耗时极长或带交互阻塞的脚本:钩子在工具调用链路内同步运行,应保持快速、非交互、确定性返回退出码。
  • 在插件内硬编码个人凭据或 API Key:使用 `userConfig` 或环境变量注入配置,切勿将敏感令牌打包进插件仓库。

技术规范与官方资料

练习与参考解答

为一个代码质量插件编写 `hooks/hooks.json` 片段:每当 `Edit` 工具执行完成后(`PostToolUse`),自动执行 `npm run lint`。

查看参考解答

在 `hooks/hooks.json` 中配置 `{"PostToolUse": [{"matcher": {"tool": "Edit"}, "handler": {"type": "shell", "command": "npm run lint"}}]}`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习