Claude Code mods let you run TypeScript middleware on tool calls, prompts and rendering. Here's how they work, with real code and the gotchas.
Claude Code now lets you run your own TypeScript inside it, sitting in front of its internal events: tool calls, prompts, rendering. That means the small annoyances you've been working around (no view of your context window, Claude touching files it shouldn't, client emails showing up on screen while you're sharing it) can be fixed in about thirty lines, not with a feature request.
These are called mods. I've spent some time with them, and the mental model is simpler than the docs make it look. If you've written Express or ASP.NET Core middleware, you already know 80% of it. The other 20% is where people will get burned, so that's where most of this post goes.
There's no new packaging format to learn. A mod is a normal Claude Code plugin: a folder with .claude-plugin/plugin.json and a hooks/hooks.json. The difference is that hooks.json has a modules key pointing at a JavaScript or TypeScript file, and that file is the mod.
env-guard/
├── .claude-plugin/
│ └── plugin.json
└── hooks/
├── hooks.json
└── register.ts
// .claude-plugin/plugin.json
{ "name": "env-guard", "version": "0.1.0", "description": "Stops Claude from editing .env files" }
// hooks/hooks.json
{ "modules": ["./register.ts"] }
Because it's a plugin, sharing works the way plugins already do. Put it in a marketplace repo and your team installs it with /plugin install. No separate distribution story to figure out.
$, e and nextYour module exports a register function. Inside it you call on(event, matcher, hook) to attach a function to one of Claude Code's internal events. There are a few dozen of them: tool.call, prompt.submit, ui.render, session.start, turn.complete and so on. Your hook runs every time that event fires, before Claude Code does its own thing.
Every hook gets the same three arguments:
$ is your handle back into Claude Code. Drawing UI, reading files, running processes, calling the model, reading session usage: it all goes through here. The module itself has no Node and no DOM, so if it isn't on $, you can't do it.e is the event's data, a plain frozen object. For a Bash tool call that's the command. For a render, it's the props of the thing about to be drawn.next passes the event down the chain, to other plugins and then to Claude Code's default behaviour. Whatever you hand to next is what actually happens.That gives you three moves, and once you see them every mod is just one of these:
const r = await next(e), look at the result, return it.return next({ ...e, command: somethingElse }). The rest of the chain sees your version.next entirely and return your own result, like { deny: "..." }. Claude Code takes your answer instead of doing the work.Here's a concrete one. I don't want Claude editing .env files in my Next.js and .NET repos, ever. Connection strings to a shared Azure SQL dev database live there, and one "helpful" cleanup can cost me an afternoon.
The existing way is a PreToolUse hook in .claude/settings.json. It runs a shell command for every matching tool call and talks over stdin and stdout.
// .claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "node .claude/hooks/guard-env.js" }]
}
]
}
}
// .claude/hooks/guard-env.js
let raw = "";
process.stdin.on("data", (chunk) => (raw += chunk));
process.stdin.on("end", () => {
const input = JSON.parse(raw);
const filePath = input.tool_input?.file_path ?? "";
if (/(^|[\\/])\.env(\.|$)/.test(filePath)) {
console.error(`${filePath} is protected. Edit it by hand.`);
process.exit(2); // exit code 2 blocks the tool call and shows stderr to Claude
}
process.exit(0);
});
It works. But it spawns a Node process per tool call, it's stateless, and the contract is "parse JSON, remember which exit code means what".
// hooks/register.ts
import type { Register } from 'claude-code'
const SECRET_FILE = /(^|[\\/])\.env(\.|$)/
export const register: Register = on => {
on('tool.call', { tool: 'Edit' }, ($, e, next) =>
SECRET_FILE.test(e.file_path)
? { deny: `${$.plugin.name}: ${e.file_path} is protected. Edit it by hand.` }
: next(e),
)
on('tool.call', { tool: 'Write' }, ($, e, next) =>
SECRET_FILE.test(e.file_path)
? { deny: `${$.plugin.name}: ${e.file_path} is protected. Edit it by hand.` }
: next(e),
)
}
The module is loaded once and stays resident, e is typed (the matcher narrows it, so e.file_path autocompletes), and denying is just returning an object. Claude Code writes the type declarations for your exact build into .claude-plugin/types/ when it loads the mod, so tsc catches typos before a session does.
Load it while developing with claude --plugin-dir ./env-guard. The folder is watched, so saving the file reloads the mod in your running session. Run claude plugin validate ./env-guard early; it reports which events you hook and anything the engine would refuse.
Rendering is also an event. Every assistant message passes through ui.render with the component name AssistantMessage and its markdown text in e.props.text. So if you record demos or screen-share with clients, you can mask email addresses on the way to the screen:
import type { Register } from 'claude-code'
const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi
export const register: Register = on => {
on('ui.render', { component: 'AssistantMessage' }, ($, e, next) => {
const text = e.props.text.replace(EMAIL, '[email hidden]')
return text === e.props.text
? next(e)
: next({ ...e, props: { ...e.props, text } })
})
}
This is the rewrite move: same component, different props. You can go further and return your own element tree from $.ui.resolve(e) with a hover-to-reveal box, but plain masking covers the screen-share case and is half the code.
Here's the part that trips people up. Ask Claude to draft a message to that person afterwards and it'll use the real address. Of course it does: a render hook only changes pixels. The model never saw your masked version, and the full text is still in the session transcript on disk.
That's fine for a demo. It is not redaction. If your actual goal is "client PII shouldn't reach the model", a render hook is the wrong layer. You'd need to work at prompt.submit and on tool results, and honestly at that point I'd fix the data source instead. Pick the event based on who you're hiding something from: the person looking at the screen, or the model.
My .env guard catches the Edit and Write tools. It does nothing if Claude decides to run sed -i on the file through Bash, or calls a script that does it. You can add a Bash matcher that greps the command for .env, but command-text matching is easy to slip past with subshells, variables or aliases. For a real hard stop, use permission deny rules in settings, and treat the mod as the friendly layer that explains why.
A mod runs inside Claude Code with the same reach Claude Code has on your machine. Installing a mod from a random marketplace repo is the same trust decision as running npm install on an unknown package with a postinstall script. Read the module before you install it, and for a team, host your own marketplace repo so people install reviewed versions, not whatever's on someone's main branch today.
Every save re-runs register. Any module-level let count = 0 starts over. If your mod tracks something across a session, like a running cost tally or a list of files Claude touched, keep it in $.state, which the host holds across reloads. You also have to declare each state key in a small types/index.d.ts contract, and claude plugin validate will complain until you do. Slightly annoying the first time. Useful after.
Each hook dispatch gets about ten seconds of its own compute. Time spent awaiting $ calls doesn't count, so calling a process or waiting on the user is fine. Doing heavy parsing in the hook body isn't. A slow tool.call hook also slows every single tool call, so keep the hot path tiny and push anything expensive behind next or into a separate process.
Mods shipped in Claude Code 2.1.287 and the API is still marked as early access. Event payloads and element props have already moved between builds. If your team shares mods, pin the Claude Code version you've tested against, and check the generated types after upgrading instead of trusting a blog snippet (including mine).
I don't think mods replace settings hooks. My rough split:
claude -p runs in CI. A shell command is language-agnostic and easy to audit in a PR. Formatting on save and blocking pushes to main belong here.The context meter is the one I'd build first, by the way. $.session.usage() gives you tokens, window size and percent for free, and an AbovePrompt render hook can draw it. Knowing you're at 70% before Claude starts forgetting your earlier instructions changes how you work more than any guard will.
Start with something read-only. An observe-only hook on tool.call for Bash that writes a status line when a command fails is a nice first mod, because it can't break anything:
import type { Register } from 'claude-code'
export const register: Register = on => {
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
const ran = await next(e)
const failed = ran.deny === undefined && ran.isError === true
$.ui.status(failed ? `failed: ${e.command.slice(0, 40)}` : undefined)
return ran
})
}
Load it with --plugin-dir, run claude --debug if nothing shows up (it tells you when a hook returned the wrong shape), and only then move on to hooks that deny or rewrite. Get the observe pattern into your fingers first. The rewrite and answer moves are where mistakes cost you, and you'll want to know your mod's behaviour before you hand it the power to say no.