Claude Code mods 入门教程:从零构建 Token Weather 上下文窗口预报插件
Getting started with Claude Code mods
这篇 Claude Code 官方开发者教程介绍 mods,即以 hooks 形式运行在插件内的 JavaScript 或 TypeScript 模块,可以观察、重写或拒绝事件,甚至绘制自定义 UI,需 Claude Code 2.1.287 或更高版本。
教程从空文件夹完整构建一个 mods 插件,并给出事件链、状态保持和热重载等可直接复用的实践要点。
Claude Code 已经允许你对它的行为做很多调整:设置、权限规则、斜杠命令、技能和状态栏。Mods 则更进一步。Mods 可以重写或替换 Claude Code 的行为,甚至可以绘制自定义 UI。在底层,mods 就是 hooks,它们打包在插件里。每一个都是一个小的 JavaScript 或 TypeScript 模块,在你的会话中运行,实时看到每一个事件。
这让 mods 成为一种让 Claude Code 适应你工作方式的方法。你可以添加一个你随时查看的读数,在你感到紧张的指令前放一个守卫,或者为你喜欢的变更阅读方式构建一个审查视图。
本指南从空文件夹开始构建一个 mod,Token Weather,一个绘制在提示符上方的上下文窗口实时预报。它大约 80 行。然后它会介绍两个更大的 mod,Blast Radius 和 Replay Theater,展示 API 还能做什么。

Claude Code 2.1.287 或更高版本。 Mods 默认开启,所以无需打开任何东西。API 可能在不同版本之间变化。每次 Claude Code 加载一个 mod,它都会为你的构建把类型声明写入该 mod 的 .claude-plugin/types/ 文件夹,这些就是你版本的权威依据。
MOD 如何工作
一个 mod 是一个 Claude Code 插件,其行为存在于一个 JavaScript 或 TypeScript 模块中:
- 该文件夹是一个普通插件,带有一个
.claude-plugin/plugin.json清单。 hooks/hooks.json在modules下命名一个模块。- 该模块导出
register(on, options)。在其中,on(event, matcher?, hook)添加一个 hook。
每个 hook 都有相同的形状:
CODEJavaScript
on("tool.call", { tool: "Bash" }, async ($, e, next) => { // $ the mods API: ui, session, state, store, fs, process, clock, http, tool, command, model, ... // e this event's input, as plain data // next passes e to the other plugins and then to Claude Code's own behavior return next(e); });
Hooks 形成一条链,就像中间件。你的运行,next(e) 把事件交给下一个插件,在底部 Claude Code 做它本来会做的事。一个 hook 可以做三件事之一:
Hooks 形成一条链
一个事件穿过你的 hook,然后其他插件,然后 Claude Code
| 动作 | 方式 | 示例 |
|---|---|---|
| 观察 | const r = await next(e); /* look */ return r | 记录每一次文件编辑。每轮之后取一个读数。 |
| 重写 | return next({ ...e, command: safer }) | 改变链中其余部分看到的内容。 |
| 应答 | return { deny: "…" } 而不调用 next | 拒绝一个工具调用。自己提供一个命令或工具。 |
这些事件涵盖工具调用、提交时的提示、轮次的开始和结束、会话的开始和结束、斜杠命令,以及 ui.render:界面绘制时的每一个部分。该模块在自己的沙箱中运行,没有 DOM 也没有 Node,所以它之外的一切都通过 $。
这与设置 hooks 有何不同。 设置 hook 为每个事件运行一个 shell 命令,并通过 stdin 和 stdout 传递 JSON。一个 mod 加载一次并留在会话中。它可以保持状态,绘制随事件更新的 UI,并回调 Claude Code:打开一个窗格、运行一个进程、注册一个斜杠命令,或注册一个模型可以调用的工具。
Claude Code 自己也使用它们。 Claude Code 的一些自身功能就是作为 mods 构建的,包括 AGENTS.md 支持和对话旁边的 /diff 窗格。它们的源代码及测试在公开的 anthropics/claude-code 仓库中的 mods/ 下,所以你可以阅读团队是如何构建它们的。
构建你的第一个 MOD:TOKEN WEATHER
Token Weather 会在每一轮之后读取上下文窗口的占用情况,并在提示符上方绘制一行:一个天气图标、百分比、已用 token 数占窗口的比例、最近几轮的小图表,以及上一轮新增了多少。
| 已用 | 预测 |
|---|---|
| 低于 25% | ☀ 晴朗 |
| 25–49% | ☁ 多云 |
| 50–74% | ☂ 阵雨 |
| 75–89% | ☇ 风暴 |
| 90% 及以上 | ↯ 即将压缩 |
下面是一个真实会话中的效果。每一轮都会读取更多文件,色带从 ☀ 晴朗逐渐变为 ☂ 阵雨,再到 ☇ 风暴:
捷径:让 Claude 来构建
你可以跳过这六个步骤。Claude Code 知道如何编写 mod,所以你可以描述你想要的那个,然后让它来完成。用 claude 启动一个会话,并粘贴下面的提示词:
CODEText
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 的回合结束时,色带就会出现在提示符上方。从那时起,每次更改都会就地重新加载,因此你可以不断要求调整(“让风暴从 70% 开始”、“在末尾加上美元成本”),并观察色带的变化。该 mod 仅在此会话中加载,其文件夹稍后会被清理,所以如果想保留它,请把文件夹复制出来,然后像任何插件一样安装它(第 6 步)。
注意,提示词只描述了你想要看到的内容。你不需要了解 API 就能编写一个。Claude Code 内置的 mod 编写指南涵盖了具体做法:在哪里保存状态以便在重新加载后仍然存在、如何用 claude plugin validate 检查插件,以及要挂钩哪些事件。修改“它应该显示什么”那几行,它就是你的 mod,而不是我们的。
如果你更想先看看它是如何组合起来的,或者想检查 Claude 写了什么,请继续阅读。
第 1 步:创建文件夹
检查你的 Claude Code 版本是否足够新:
CODEShell
claude --version # 2.1.287 or later
创建以下目录结构:
CODEText
token-weather/
├── .claude-plugin/
│ ├── plugin.json
│ └── types/ (written by Claude Code when it loads the mod)
├── hooks/
│ ├── hooks.json
│ └── token-weather.mjs
├── types/
│ └── index.d.ts (added in step 3)
└── tests/
└── token-weather.test.ts (added in step 5).claude-plugin/plugin.json 是标准的插件清单:
CODEJSON
{ "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 恰好有一个:
CODEJSON
{ "modules": ["./token-weather.mjs"] }
第 2 步:画点东西
提示符正上方的那条色带是一个名为 AbovePrompt 的组件。Claude Code 本身不会在那里绘制任何内容,所以它是一个很好的首个目标。挂钩它的 ui.render 事件并返回一棵元素树:
CODEJavaScript
// 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 作为工厂函数。
在加载了插件的情况下启动一个会话:
CODEShell
claude --plugin-dir ./token-weather“☀ 晴空”会出现在提示符上方。保持会话打开。该文件夹会被监视,因此每次保存都会就地重新加载模块,无需重启。这种快速反馈循环正是编写 mod 的乐趣所在。
提示:一旦你了解了它的形态,就可以像捷径那样向 Claude 描述下一个 mod。它会将插件写入一个在同一会话中热重载的文件夹。
第 3 步:读取真实数字并将它们保存在 $.state 中
$.session.usage() 返回与状态栏相同的数字。context.tokens 是上一个响应所依据的输入,context.window 是模型的窗口,context.percent 是前者与后者之比。该调用是免费的:只有当你请求 breakdown 时,它才会发送 token 计数请求。
在会话开始时以及每一轮之后读取一次:
CODEJavaScript
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($); // main-loop turns only, not subagents } return result; });
两个钩子都先调用 next(e),然后再进行观察。两者都不会改变实际发生的行为。
读数保存在哪里。模块级的 let readings = [] 看起来是显而易见的选择,但热重载是一次全新的加载:register 会再次运行,session.start 会再次触发,模块变量也会从头开始。把历史记录放在 $.state 里。它会在整个会话期间把命名值保存在宿主中,并且它们能在重载后存活。
CODEJavaScript
// Held by the host, so the history survives a hot reload of this file. 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:
CODETypeScript
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 步:绘制预报
以下是整个模块:
CODEJavaScript
// Token Weather: a live forecast of the context window, above the prompt. 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" }, ]; // Held by the host, so the history survives a hot reload of this file. 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($); // main-loop turns only, not subagents } 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,正如本节开头的录屏所示。
第 5 步:验证和测试
claude plugin validate 会以 Claude Code 的方式读取 manifest 和模块源码,并报告模块挂钩和调用了什么:
CODEText
$ 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() 返回什么:
CODETypeScript
// 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) => { // Hooks registered here run after the mod and stub what Claude Code would answer. 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(); }); });
CODEText
$ claude plugin test ./token-weather
(pass) token-weather > the band follows the context window
1 pass
0 fail该测试还会检查第 3 步中的重绘行为。条带会在 turn.complete 之后更新,而 mod 从未请求重绘。
mod 就是一个插件,所以它的发布方式相同。把它放进一个 marketplace,这可以简单到只是一个包含 .claude-plugin/marketplace.json 的文件夹:
CODEJSON
{ "name": "my-mods", "owner": { "name": "You" }, "plugins": [{ "name": "token-weather", "source": "./token-weather" }] }
CODEShell
claude plugin marketplace add ./my-mods
claude plugin install token-weather@my-mods --scope user分享你的 MOD
mod 是一个 Claude Code 插件,因此你像分享任何其他插件一样分享它,没有什么新东西要学。把 mod 放进一个带有 marketplace 文件的 GitHub 仓库,该仓库就成了你的 marketplace。任何人都可以从它安装,你也可以通过普通的 push 来更新它。
在 Claude Code 中安装需要三条命令:
CODEText
/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 会介入事件、打开窗格并接收输入。
Blast Radius:在危险命令运行前,先看看它会改动什么
当 Claude 用 rm -rf、git reset --hard、git clean、强制推送或数据库迁移调用 Bash 时,Blast Radius 会拦住这次调用。它会算出这条命令会触及什么,并打开一个带有 Proceed 和 Cancel 的面板。按 2,Claude 会收到带原因的拒绝。按 1,命令就按原样运行。
它使用三个钩子:Bash 上的 tool.call,以及 Pane 和 AbovePrompt 上的 ui.render。其核心是上表中的“answer”动作:
代码JavaScript
on("tool.call", { tool: "Bash" }, async ($, e, next) => { const risk = classify(String(e.command ?? "")); if (risk === null) return next(e); // everything else runs as normal const report = await measure($, risk, await $.session.cwd()); // git status, git clean -n, du, ... 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"; // too narrow for a pane: draw above the prompt while (held.decision === null && !next.signal.aborted) { await $.process.run(["sleep", "0.25"]); // time inside $ calls doesn't count against the hook's time limit } if (held.decision === "proceed") return next(e); // let it run 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时,同一份报告会绘制在提示符上方:

它是安全网,不是权限系统。它读取命令文本,所以 $(…)、别名和调用 rm 的脚本都能绕过它。要硬性阻止,请使用权限规则。
Replay Theater:逐步回放上一轮的编辑
当一轮运行时,Replay Theater 会记录每一次 Edit 和 Write 调用:文件,以及修改前后的文本。当这一轮结束时,提示符上方会出现一条提示。按 r(或输入 /replay),一个面板会一次一个 diff 地走过这些编辑,并带有一条编号步骤条和 Prev、Next 和 Close 按钮。
它从不阻止或更改编辑。它只是观察:
代码JavaScript
on("tool.call", async ($, e, next) => { if (EDIT_TOOLS.has(e.tool)) state.pending.push(...(await stepsFor($, e))); // old/new text → diff return next(e); // the edit runs untouched }); 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; // one replay per turn 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 都绘制同一棵树。

四个值得保留的习惯
- 善用 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 各自源于一个问题:我的上下文有多满?、这条命令即将删除什么?,以及Claude 刚刚改了什么?你的问题会不一样,而这正是重点。可以从这些想法入手:
- 来自
$.session.usage()的成本或速率限制计量器,作为状态行与$.ui.status一起显示 - 一个
prompt.submithook,将你团队的约定添加到每个提示中 - 一个窗格,列出 Claude 本次会话读取过的文件,作为它所见内容的实时地图
- 一个专注计时器,在长时间回合结束时通过
$.ui.toast发送 toast 通知 - 一个针对你的技术栈调优的
tool.call守卫,例如生产环境的 kubectl 上下文或terraform apply
做了一个你现在每天都用的 mod?把它发到 X 或 LinkedIn 上,附上它运行时的 GIF 或截图,让其他开发者看到可能性。把插件放到市场里(分享你的 mod)并附上链接,这样任何喜欢它的人都能用三条命令安装它。
来源:Anthropic:Claude.dev 开发者博客 · claude.dev