ARTICLE · 1521041
Claude Code还能这样改:从零写出你的第一个插件
本文编译转载自 Anthropic Claude.dev 开发者博客,原文标题《Getting started with Claude Code mods》。
你以为 Claude Code 是一个可以调设置、改权限的命令行工具?它已经是一个可以编程的平台了。
区别在哪:调设置是选官方给的选项,编程是你自己造选项。Mods 让你能拦截 Claude Code 的每一个行为,工具调用、文件编辑、界面渲染,观察它、改写它,甚至直接拒绝它。你不需要 fork 源码,不需要等官方支持某个功能,写一个几十行的小模块就能改变它的运行方式。
这篇教程从一个空文件夹开始,带你搭建第一个 Mod,Token Weather,一个绘制在提示符上方的上下文窗口实时预报,大约 80 行代码。然后介绍两个进阶 Mod,Blast Radius 和 Replay Theater,展示这个 API 还能做什么。
图 A:Token Weather、Blast Radius 和 Replay Theater,在终端会话中依次出现
图 B:Token Weather 的色带随上下文窗口填充:18% 时 Clear,67% 时 Showers,81% 时 Storm
Mods 如何工作
一个 Mod 就是一个 Claude Code 插件,核心是一个 JavaScript 或 TypeScript 模块。你可以把它理解成一个"中间人":它站在你和 Claude Code 之间,能看到每一次操作,可以选择放行、修改或者拦下。
具体来说,一个 Mod 的文件夹里有三样东西:
一个 .claude-plugin/plugin.json清单文件,告诉 Claude Code 这是一个插件hooks/hooks.json,声明模块入口 一个模块文件,导出 register(on, options)函数,在其中用on(event, matcher?, hook)添加 hook
每个 hook 都有相同的结构:
on("tool.call", { tool: "Bash" }, async ($, e, next) => { // $ 是 mods API:ui, session, state, store, fs, process, clock, http, tool, command, model ... // e 是本次事件的输入,纯数据 // next 把 e 交给其他插件,然后交给 Claude Code 自身的行为 return next(e); });Hooks 形成一条链,就像一条流水线上的质检站。你的 hook 先运行,next(e) 把事件交给下一个插件的 hook,在流水线末端 Claude Code 做它本来会做的事。一个 hook 可以做三件事之一:
| 观察 | ||
| 重写 | ||
| 应答 |
这些事件涵盖工具调用、提交时的提示、轮次开始和结束、会话开始和结束、斜杠命令,以及 ui.render(界面绘制时的每一部分)。模块在自己的沙箱中运行(沙箱就是一种隔离环境,模块不能直接访问操作系统),没有 DOM 也没有 Node,所以它之外的一切都通过 $ 这个 API 来访问。
三种动作是 Mods 的核心能力。那它和已有的 settings hooks 有什么区别?settings hook 为每个事件运行一个 shell 命令,通过 stdin/stdout 传递 JSON。一个 Mod 加载一次并留在会话中,可以保持状态,绘制随事件更新的 UI,并回调 Claude Code:打开窗格、运行进程、注册斜杠命令或注册模型可调用的工具。
Claude Code 自己也用它们。 前面说了 Mods 能做什么,但最有力的证据来自 Claude Code 自身:AGENTS.md 支持和对话旁边的 /diff 窗格,这些官方功能就是用 Mods 构建的。它们的源代码及测试在公开的 anthropics/claude-code 仓库的 mods/ 目录下。原来这么大的功能,也就是这么几十行代码。
前提条件
截至原文发布时,需要 Claude Code 2.1.287 或更高版本。Mods 默认开启,无需额外操作。API 可能在不同版本之间变化。每次 Claude Code 加载一个 Mod,它都会为你的构建把类型声明写入该 Mod 的 .claude-plugin/types/ 文件夹,这些就是你版本的权威依据。
捷径:让 Claude 帮你写
你可以跳过下面的五个步骤。Claude Code 知道如何编写 Mod,所以你可以描述你想要的那个,然后让它来完成。用 claude 启动一个会话,粘贴下面的提示词:
Make me a Claude Code mod called token-weather: a live forecast of my context window, shown in the band above the prompt. What it should show, on one line: - A weather icon and word for how full the context window is: under 25% ☀ Clear (yellow), 25–49% ☁ Cloudy (cyan), 50–74% ☂ Showers (blue), 75–89% ☇ Storm (magenta), 90% and up ↯ Compact soon (red). - The percentage used, then the tokens used out of the window, like "134.4k / 200k". - A small chart of the last 12 turns, drawn with ▁▂▃▄▅▆▇█. - How much the last turn added, like "▲ +98.3k last turn". It should update after every turn.Claude 会询问一次是否为该会话开启热重载。允许后,当 Claude 的回合结束时,色带就会出现在提示符上方。从那时起,每次更改都会就地重新加载,你可以不断要求调整("让 Storm 从 70% 开始""在末尾加上美元成本"),并观察色带变化。该 Mod 仅在此会话中加载,文件夹稍后会被清理,想保留的话复制出来按第 5 步的方式安装即可。
注意,提示词只描述了你想要看到的内容,不需要了解 API 就能编写一个。修改"它应该显示什么"那几行,它就是你的 Mod。
如果你想先看看它是如何组合起来的,或者想检查 Claude 写了什么,请继续阅读。
五步搭建 Token Weather
Token Weather 在每一轮之后读取上下文窗口的占用情况,并在提示符上方绘制一行:天气图标、百分比、已用 token 数占窗口的比例、最近几轮的小图表,以及上一轮新增了多少。
第 1 步:创建文件夹
检查你的 Claude Code 版本是否足够新:
claude --version # 2.1.287 or later创建以下目录结构:
token-weather/ ├── .claude-plugin/ │ ├── plugin.json │ └── types/ (Claude Code 加载 mod 时自动写入) ├── hooks/ │ ├── hooks.json │ └── token-weather.mjs ├── types/ │ └── index.d.ts (第 3 步添加) └── tests/ └── token-weather.test.ts (第 5 步添加).claude-plugin/plugin.json 是标准的插件清单:
{ "name": "token-weather", "version": "0.1.0", "description": "A live forecast of the context window, drawn above the prompt.", "author": { "name": "You" } }hooks/hooks.json 指向该模块。一个 Mod 恰好有一个:
{ "modules": ["./token-weather.mjs"] }第 2 步:画点东西
骨架搭好了,但这个 Mod 什么都不做。先画一行字试试。
提示符正上方的那条色带是一个名为 AbovePrompt 的组件。Claude Code 本身不会在那里绘制任何内容,所以它是一个很好的首个目标。挂钩它的 ui.render 事件并返回一棵元素树:
// hooks/token-weather.mjs export function register(on) { on("ui.render", { component: "AbovePrompt" }, ($, e, next) => { const { Box, Text } = $.ui.resolve(e); return Box({ paddingX: 1, children: [ Text({ color: "yellow", bold: true, children: "☀ Clear skies" }) ], }); }); }$.ui.resolve(e) 返回正在绘制的表面所对应的构造函数,因为 Claude Code 绘制的每个表面支持的元素集略有不同。JSX 也可以使用,以 h 作为工厂函数。
在加载了插件的情况下启动一个会话:
claude --plugin-dir ./token-weather"☀ Clear skies" 会出现在提示符上方。保持会话打开,文件夹会被监视,每次保存都会就地重新加载模块,无需重启。这种快速反馈循环正是编写 Mod 的乐趣所在。
第 3 步:读取真实数字并保存在 $.state 中
色带能显示了,但只是静态文字。下一步是读取真实的 token 计数,让色带动起来。
$.session.usage() 返回与状态栏相同的数字。context.tokens 是上一个响应所依据的输入,context.window 是模型的窗口,context.percent 是前者与后者之比。该调用是免费的:只有当你请求 breakdown 时才会发送 token 计数请求。
在会话开始时以及每一轮之后读取一次:
on("session.start", async ($, e, next) => { const result = await next(e); await takeReading($); return result; }); on("turn.complete", async ($, e, next) => { const result = await next(e); if (!e.agentId) { await takeReading($); // 只记录主循环轮次,不记录子代理 } return result; });两个钩子都先调用 next(e),然后再观察。两者都不会改变实际发生的行为。
读数保存在哪里。 模块级的 let readings = [] 看起来是显而易见的选择,但热重载是一次全新的加载:register 会再次运行,session.start 会再次触发,模块变量也会从头开始。把历史记录放在 $.state 里。它会在整个会话期间把命名值保存在宿主中,并且能在重载后存活。
// 由宿主持有,所以历史记录能在热重载后存活 const readings = { plugin: "token-weather", key: "readings" }; async function takeReading($) { const { context } = await $.session.usage(); if (!context?.window) return; const tokens = context.tokens ?? 0; const percent = context.percent ?? Math.round((tokens / context.window) * 100); const { value: history = [] } = await $.state.get(readings); await $.state.set(readings, [...history, { tokens, window: context.window, percent }].slice(-HISTORY)); }状态值在插件的类型契约中声明,这是一个 manifest 指向的小型 .d.ts 文件。添加 types/index.d.ts:
export type TokenWeatherReading = { tokens: number; window: number; percent: number }; declare module "claude-code" { interface PluginState { "token-weather": { readings: TokenWeatherReading[] }; } }然后把 "types": "./types/index.d.ts" 添加到 plugin.json。如果你跳过这一步,claude plugin validate 会用一个指明修复方法的错误阻止你:token-weather.readings is not declared: the manifest's types contract must name it in interface PluginState { … }。
作为回报,你可以免费获得重绘。在渲染钩子运行时创建的 $.state.get 会订阅该绘制,因此之后的每一次 $.state.set 都会重绘色带。你永远不需要调用 $.ui.invalidate。
第 4 步:绘制预报
百分比能读了,但还差最后一步:把数字变成一条带颜色、带图表的完整色带。以下是整个模块:
// Token Weather:上下文窗口的实时预报,绘制在提示符上方 const HISTORY = 12; const BARS = "▁▂▃▄▅▆▇█"; const FORECAST = [ { upTo: 25, icon: "☀", word: "Clear", color: "yellow" }, { upTo: 50, icon: "☁", word: "Cloudy", color: "cyan" }, { upTo: 75, icon: "☂", word: "Showers", color: "blue" }, { upTo: 90, icon: "☇", word: "Storm", color: "magenta" }, { upTo: Infinity, icon: "↯", word: "Compact soon", color: "red" }, ]; const readings = { plugin: "token-weather", key: "readings" }; export function register(on) { on("session.start", async ($, e, next) => { const result = await next(e); await takeReading($); return result; }); on("turn.complete", async ($, e, next) => { const result = await next(e); if (!e.agentId) { await takeReading($); } return result; }); on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => { const { value: history = [] } = await $.state.get(readings); if (e.props.hasSurvey || history.length === 0) { return next(e); } const { Box, Text } = $.ui.resolve(e); return band(Box, Text, history, e.props.bodyColumns); }); } async function takeReading($) { const { context } = await $.session.usage(); if (!context?.window) return; const tokens = context.tokens ?? 0; const percent = context.percent ?? Math.round((tokens / context.window) * 100); const { value: history = [] } = await $.state.get(readings); await $.state.set(readings, [...history, { tokens, window: context.window, percent }].slice(-HISTORY)); } function band(Box, Text, history, columns) { const now = history[history.length - 1]; const f = FORECAST.find((b) => now.percent < b.upTo); const parts = [ Text({ color: f.color, bold: true, children: `${f.icon} ${f.word}` }), Text({ children: ` ${now.percent}% of context` }), Text({ dimColor: true, children: ` ${short(now.tokens)} / ${short(now.window)}` }), ]; if (columns >= 60) { parts.push(Text({ dimColor: true, children: " last turns " })); parts.push(Text({ color: f.color, children: sparkline(history) })); if (history.length > 1) { parts.push(Text({ dimColor: true, children: trend(history) })); } } return Box({ flexDirection: "row", paddingX: 1, children: parts }); } function sparkline(history) { const top = Math.max(...history.map((r) => r.tokens), 1); return history.map((r) => BARS[Math.floor((r.tokens / top) * (BARS.length - 1))]).join(""); } function trend(history) { const delta = history[history.length - 1].tokens - history[history.length - 2].tokens; if (delta === 0) return " steady"; return delta > 0 ? ` ▲ +${short(delta)} last turn` : ` ▼ ${short(-delta)} last turn`; } function short(n) { if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`; if (n >= 1_000) return `${+(n / 1_000).toFixed(1)}k`; return String(n); }三个细节值得复制到你自己的 Mod 中:
- 组件的 props 在
e.props上。hasSurvey告诉你某个 survey 想要这条色带,因此钩子用 next(e)让位给它。bodyColumns是色带的实际宽度,当有窗格停靠在对话记录旁边时,它比终端更窄。只有e.component、e.surface、e.requestId和e.viewport位于e的顶层。 - 没有可绘制内容时就 pass。
返回 next(e)会把色带还给 Claude Code 和其他 Mod。 - 使用单宽符号,而不是 emoji。
☀ ☁ ☂ ☇ ↯ 在每种终端字体中都能对齐。
保存文件后,正在运行的会话会立即采用它。在几轮读取大文件之后,色带会从 Clear 变为 Showers 再变为 Storm。
图 C:完整终端会话中三轮的 Token Weather:先是 18%,然后 67%,再到 200k 窗口的 81%
第 5 步:验证和测试
claude plugin validate 会以 Claude Code 的方式读取 manifest 和模块源码,并报告模块挂钩和调用了什么:
$ claude plugin validate ./token-weather > types ./types/index.d.ts declares state: token-weather.readings > ./token-weather.mjs hooks: session.start, turn.complete, ui.render{component=AbovePrompt} > ./token-weather.mjs calls: $.session.usage (via takeReading), $.state.get, $.state.set (via takeReading), $.ui.resolve > ./token-weather.mjs state writes: token-weather.readings > ./token-weather.mjs state reads: token-weather.readings √ Validation passedclaude plugin test 会针对真实的 Claude Code 运行时运行插件的 *.test.ts 文件。测试用 on 注册的钩子会在链中该 Mod 之后运行,并 stub 掉 Claude Code 会给出的回答,因此你可以精确控制 $.session.usage() 返回什么:
// tests/token-weather.test.ts import { describe, expect, test } from "claude-code/testing"; describe("token-weather", () => { test("the band follows the context window", async ($, on) => { let tokens = 36_100; on("session.start", ($, e) => ({ cwd: e.cwd })); on("session.usage", () => ({ value: { startedAt: 0, rateLimits: [], context: { tokens, window: 200_000, percent: Math.round(tokens / 2_000) } }, })); on("turn.complete", () => ({ text: "" })); await $.session.start({ surface: "terminal", isInteractive: true, cwd: "/work" } as any); const ui = await $.ui.mount({ plugin: "token-weather", surface: "terminal", component: "AbovePrompt", props: { hasSurvey: false, isWorking: false, maxRows: 10, bodyColumns: 120 }, } as any); expect(await ui.find({ type: "Text", text: /Clear/ })).toBeDefined(); tokens = 134_400; await $.turn.complete({ reason: "answer", answer: "ok", durationMs: 1 } as any); expect(await ui.find({ type: "Text", text: /Showers/ })).toBeDefined(); expect(await ui.find({ type: "Text", text: /67% of context/ })).toBeDefined(); expect(await ui.find({ type: "Text", text: /▲ \+98\.3k last turn/ })).toBeDefined(); await ui.unmount(); }); });$ claude plugin test ./token-weather (pass) token-weather > the band follows the context window 1 pass 0 fail该测试还会检查第 3 步中的重绘行为。色带会在 turn.complete 之后更新,而 Mod 从未请求重绘。
分享你的 Mod
Mod 就是一个插件,所以你像分享任何其他插件一样分享它。把 Mod 放进一个带有 marketplace 文件的 GitHub 仓库,该仓库就成了你的 marketplace。任何人都可以从它安装,你也可以通过普通的 push 来更新它。
安装需要三条斜杠命令:
/plugin marketplace add your-org/my-mods /plugin install token-weather@my-mods /reload-plugins重载后 Mod 就会启动。如果它没有出现,请重启 Claude Code。
Mod 是在你机器上的 Claude Code 内运行的代码,拥有与 Claude Code 相同的访问权限,并且它由其发布者编写,而非 Anthropic。所以安装 Mod 要像安装软件包一样:先阅读仓库,只从你信任的人那里安装。在你运行命令之前,什么都不会被安装。
Claude 目录未来将接受包含 Mod 的插件,届时你可以在 claude.ai/directory/manage 提交你的插件,这样人们无需你提供链接就能找到它。
两个进阶 Mod
Token Weather 只负责观察和绘制。下面两个 Mod 会介入事件、打开窗格并接收输入。
先回顾三种动作的设计含义。观察是旁听,不改任何东西,只是记录和展示,Token Weather 就是这一类。重写是介入,改掉 Claude Code 看到的内容,比如把一条危险命令替换成更安全的版本。应答是替代,直接拒绝并给出自己的答案,不让事件继续传递。三种动作覆盖了你能对一个事件做的所有事:看、改、拦。
Blast Radius:在危险命令运行前,先看看它会改动什么
当 Claude 用 rm -rf、git reset --hard、git clean、强制推送或数据库迁移调用 Bash 时,Blast Radius 会拦住这次调用。它会算出这条命令会触及什么,并打开一个带有 Proceed 和 Cancel 的面板。按 2,Claude 会收到带原因的拒绝。按 1,命令就按原样运行。
图 D:Blast Radius 拦住 rm -rf build,列出它将要删除的 9 个文件(1.1 MB)。Cancel 拒绝它;第二次尝试时,Proceed 运行它
它使用三个钩子:Bash 上的 tool.call,以及 Pane 和 AbovePrompt 上的 ui.render。其核心是上表中的"应答"动作:
on("tool.call", { tool: "Bash" }, async ($, e, next) => { const risk = classify(String(e.command ?? "")); if (risk === null) return next(e); // 非危险命令,正常运行 const report = await measure($, risk, await $.session.cwd()); held = { command: e.command, risk, report, decision: null }; const opened = await $.ui.open({ id: "blast-radius", title: "Blast Radius", focus: true }); if (!opened.isPlaced) held.where = "band"; // 太窄放不下面板:画在提示符上方 while (held.decision === null && !next.signal.aborted) { await $.process.run(["sleep", "0.25"]); // $ 调用内的等待时间不计入钩子时限 } if (held.decision === "proceed") return next(e); // 放行 return { deny: `Blast Radius held this command: the user pressed Cancel. It would have: ${report.summary}.` }; });它教会我们:
- 用
$.process.run做试运行。报告来自工具自身的命令: git status --porcelain、git clean -n、git log HEAD..origin/main、showmigrations。参数以 argv 数组传入,路径中没有任何内容会被当作 shell 代码执行。 - 挂起一次调用。
钩子每次派发有 10 秒自己的时间,但在 $调用内等待的时间不计入。循环等待短暂的sleep进程,直到某个按钮的onPress设定决定,并在next.signal中止(你按了 Esc)时放弃。 - 带热键的按钮。
Button({ label: "Proceed", hotkey: "1", onPress })可通过点击、Tab 加 Enter 或数字键工作。 - 降级到色带。
当终端足够宽时,它会在记录旁边停靠一个面板。当 $.ui.open回答isPlaced: false时,同一份报告会绘制在提示符上方。
图 E:在 120 列时,Blast Radius 将 git reset --hard 的报告绘制在提示符上方的色带中
它是安全网,不是权限系统。它读取命令文本,所以 $(…)、别名和调用 rm 的脚本都能绕过它。要硬性阻止,请使用权限规则。
Replay Theater:逐步回放上一轮的编辑
当一轮运行时,Replay Theater 会记录每一次 Edit 和 Write 调用:文件,以及修改前后的文本。当这一轮结束时,提示符上方会出现一条提示。按 r(或输入 /replay),一个面板会一次一个 diff 地走过这些编辑,并带有一条编号步骤条和 Prev、Next 和 Close 按钮。
图 F:Replay Theater:跨 3 个文件进行 5 次编辑重命名后的提示,然后是面板中的第 1 到第 5 步
它从不阻止或更改编辑,只是观察:
on("tool.call", async ($, e, next) => { if (EDIT_TOOLS.has(e.tool)) state.pending.push(...(await stepsFor($, e))); // 旧/新文本 → diff return next(e); // 编辑原样运行 }); on("turn.start", ($, e, next) => { if (!e.agentId) state.pending = []; return next(e); }); on("turn.complete", async ($, e, next) => { const r = await next(e); if (!e.agentId && state.pending.length) state.replay = state.pending; // 每轮一次回放 return r; }); on("session.start", async ($, e, next) => { const r = await next(e); await $.command.register({ name: "replay", description: "Step through the last turn's file edits" }); return r; }); on("command.run", { command: "replay" }, async ($, e) => ({ text: (await openReplay($)) ? "Replaying" : "No edits" }));它教会我们:
- 配对事件。
turn.start和 turn.complete将编辑括起来,使每轮成为一次回放,而e.agentId将子代理轮次排除在分组之外。 - 注册斜杠命令。
在 session.start中执行$.command.register,然后在command.run上应答它。 - 读取文件。
对于 Write, $.fs.read会在写入落地前获取旧内容,因此 diff 是真实的。 - 放置是界面的职责。
在全屏模式下,面板停靠在右侧。在 80 列时,它内联打开在提示符上方。无论哪种方式,Mod 都绘制同一棵树。
图 G:80 列下的 Replay Theater,内联绘制在提示符上方
四个值得保留的习惯
前两个习惯是写代码时的,帮你少踩坑。
善用 Claude Code 为你编写的类型。 每次加载你的 Mod 时,Claude Code 都会将你的构建声明写入 Mod 的 .claude-plugin/types/ 文件夹,因此你的编辑器和 tsc -p 无需额外步骤即可工作。它们是每个事件、$ 上的每个方法以及每个元素 props 的参考。
从 e.props 读取 props。hasSurvey、bodyColumns 以及其他内容都在那里,而不是在 e 本身上。
后两个习惯是运行时的,帮你排查问题。
为热重载做好规划。 每次保存都会再次运行 register 和 session.start,因此请将数据放在 $.state 中,而不是模块变量中。
当绘图不显示时,查看日志。 运行 claude --debug,查找一行提示某个 hook 返回了无法通过验证的树。
你能 Mod 什么
回到开头那个判断:Mods 把 Claude Code 从一个可配置的工具变成了一个可编程的平台。
这意味着什么?意味着你可以问自己一个问题:在 Claude Code 的每一次操作中,有没有一个环节你想要不同的行为?
每次它要删文件时,你想先看影响范围?写一个 Mod。 每轮对话结束后,你想知道花了多少钱?写一个 Mod。 每次它编辑代码,你想在侧边窗格里逐步回放?写一个 Mod。 你团队有特定的代码规范,想让 Claude 每次提交前自动检查?写一个 Mod。
想看官方怎么写 Mod?它们的源代码在 anthropics/claude-code 仓库的 mods/ 目录下,包括完整的实现和测试。
来源:Anthropic Claude.dev 开发者博客,原文标题《Getting started with Claude Code mods》















































































