插件是 Claude Code 扩展包,可包含 Skills(模型调用的能力)、Agents(专用子 Agent)、Hooks(事件处理器)和 MCP 服务器。通过 plugins 选项以编程方式加载本地插件目录。
核心机制
加载方式:在 query() 的 options.plugins 中传入本地路径数组,type 字段目前只支持 "local"。
插件目录结构:
my-plugin/
├── .claude-plugin/
│ └── plugin.json # 必须:插件清单
├── skills/ # 推荐:Agent Skills
│ └── my-skill/
│ └── SKILL.md
├── commands/ # 旧格式(向后兼容)
├── agents/ # 自定义 Agent
├── hooks/
│ └── hooks.json
└── .mcp.json # MCP 服务器定义
验证加载:插件加载成功后出现在 SystemMessage(subtype="init") 的 plugins 字段中,可用命令在 slash_commands 字段中。
Skills 命名空间:插件 Skills 使用 plugin-name:skill-name 格式,避免与项目 Skills 冲突。
关键细节
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
plugins=[
{"type": "local", "path": "./my-plugin"},
{"type": "local", "path": "/absolute/path/to/another-plugin"},
]
),
):
if isinstance(message, SystemMessage) and message.subtype == "init":
print("Plugins:", message.data.get("plugins"))
print("Commands:", message.data.get("slash_commands"))调用插件 Skill:
async for message in query(
prompt="/my-plugin:greet", # 使用命名空间格式
options=ClaudeAgentOptions(plugins=[{"type": "local", "path": "./my-plugin"}]),
):
...路径解析:相对路径从当前工作目录解析,建议使用绝对路径确保可靠性。
从 marketplace 安装的插件:CLI 安装的插件在 ~/.claude/plugins/,可通过绝对路径在 SDK 中使用。
与其他概念的关联
- skills - 插件提供的 Skills 使用方式
- slash-commands - 插件提供的自定义命令
- subagents - 插件提供的自定义 Agent
- hooks - 插件提供的 Hooks
实践要点
- 插件路径必须指向包含
.claude-plugin/plugin.json的目录 commands/是旧格式,新插件应使用skills/目录(两者向后兼容)- 开发阶段可用相对路径快速迭代,生产环境建议绝对路径
- 多个插件可同时加载,Skills 通过命名空间隔离避免冲突