How Claude Code mods change the agent loop
By Flavio
Updated
Tagged: AI
Build a small Claude Code mod that pauses Bash calls for an explicit decision. Understand event handlers, fail-closed behavior, and the limits of previews.
Claude Code mods let you hook right into a coding session. You can intercept a tool call, add UI elements, or rewrite an event before the rest of Claude Code sees it.
That’s handy for custom workflows, though it also means a mod has a lot of power. It’s code running directly with access to your session and your machine.
We’ll build a small mod using the official mods API that pauses every Bash call until you explicitly approve it. We’ll also test the handler directly in Node, with no model or live session needed.
How a mod differs from a settings hook
With a settings hook, you attach an external command or another supported handler to an event like tool use. Claude Code passes the input to your hook and reads the result back.
A mod works differently because it registers JavaScript or TypeScript functions right inside Claude Code. Those handlers form a chain: you can call next(e) to let the event continue, pass a modified event to rewrite it, or return a result yourself to take over.
Reach for a mod when you want to customize the interface or replace built-in behavior (see the mods announcement for more). If a regular settings hook already covers what you need, stick with the simpler setup.
For our Bash guard, what matters is when the tool is allowed to move forward. We want to prompt you before calling next, and return a denial unless you pick the exact approval option.
Make a minimal plugin
Mods ship as plugins. Start by creating this folder structure in a new directory:
bash-preview/
.claude-plugin/
plugin.json
hooks/
hooks.json
preview.mjs
preview.test.mjs
Next, save this manifest to .claude-plugin/plugin.json:
{
"name": "bash-preview",
"version": "0.1.0",
"description": "Ask before passing a Bash call to Claude Code."
}
The version field tracks your own plugin. Then add hooks/hooks.json so Claude Code knows where to load the module from, using a path relative to that file:
{
"modules": ["./preview.mjs"]
}
You’ll need a Claude Code build that supports mods. Check the create-a-mod guide for the exact details on these files, loading a plugin from a local directory, and the requirements for the interface you’re using.
Hold the call until the answer arrives
Save the complete module as hooks/preview.mjs:
export function register(on) {
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
let answer
try {
answer = await $.ui.ask(
'Run this exact Bash command?\n' + e.command,
['Run once', 'Cancel']
)
} catch {
return { deny: 'No approval was received. The command was not run.' }
}
if (answer !== 'Run once') {
return { deny: 'The command was not approved.' }
}
return next(e)
}).catch(async ($, e, next) => {
if (next.called) return next(e)
return { deny: 'The command guard failed: ' + next.error.kind }
})
}
Claude Code fires tool.call whenever a tool is about to run, putting the tool name in e.tool and the shell command in e.command (the events guide covers that shape and $.ui.ask). Our matcher limits this handler so it only sees Bash calls.
Notice that we preview every Bash call instead of trying to spot dangerous shell syntax with a regex. A pattern looking for --force will easily miss -f, a shell alias, or another command that has the same effect.
If you decline, the handler returns { deny: ... } without calling next. Dismissing the prompt or hitting an unavailable UI denies the call too, and each answer only applies to that single call.
Don’t skip the .catch on the registration. By default, Claude Code skips a hook that fails before calling next, letting the rest of the chain keep going after a host-enforced timeout or an invalid result. Our .catch closes that gap by denying the command if the guard hasn’t continued yet. If next already ran, it retrieves the existing result instead of claiming the command was blocked or running it a second time. Time spent waiting inside $.ui.ask doesn’t count against the hook timeout.
Choosing Run once continues the chain with the same event, and Claude Code still applies its normal permission checks after that.
Test the decision without running a command
Because the handler is a plain JavaScript function, we can test every branch in Node by stubbing out the prompt and next so no shell command ever runs.
The test file calls register with a fake on function to capture both our handler and its .catch handler. From there, it calls them directly with three answers that must deny, a prompt that throws, an approval that forwards the same event, and host failures both before and after next.
Save this as preview.test.mjs:
import test from 'node:test'
import assert from 'node:assert/strict'
import { register } from './hooks/preview.mjs'
let handler
let failureHandler
register((event, matcher, callback) => {
assert.equal(event, 'tool.call')
assert.deepEqual(matcher, { tool: 'Bash' })
handler = callback
return { catch: (callback) => { failureHandler = callback } }
})
const event = Object.freeze({ tool: 'Bash', command: 'git diff --stat' })
for (const answer of ['Cancel', 'Maybe later', undefined]) {
test('deny answer: ' + String(answer), async () => {
let continued = false
const result = await handler(
{ ui: { ask: async () => answer } },
event,
async () => { continued = true }
)
assert.ok(result.deny)
assert.equal(continued, false)
})
}
test('a failed question denies the call', async () => {
const result = await handler(
{ ui: { ask: async () => { throw new Error('No interface') } } },
event,
async () => assert.fail('Must not continue')
)
assert.ok(result.deny)
})
test('approval forwards the identical event', async () => {
const marker = { result: 'Simulated tool result' }
const result = await handler(
{ ui: { ask: async (question, options) => {
assert.ok(question.includes(event.command))
assert.deepEqual(options, ['Run once', 'Cancel'])
return 'Run once'
} } },
event,
async (forwarded) => {
assert.equal(forwarded, event)
return marker
}
)
assert.equal(result, marker)
})
for (const kind of ['throw', 'timeout']) {
test('host failure before next: ' + kind, async () => {
const next = Object.assign(
async () => assert.fail('Must not continue'),
{ called: false, error: { kind } }
)
const result = await failureHandler({}, event, next)
assert.ok(result.deny.includes(kind))
})
}
test('host failure after next preserves the existing result', async () => {
const marker = { result: 'Already completed' }
let retrievals = 0
const next = Object.assign(async (forwarded) => {
assert.equal(forwarded, event)
retrievals += 1
return marker
}, { called: true, error: { kind: 'throw' } })
assert.equal(await failureHandler({}, event, next), marker)
assert.equal(retrievals, 1)
})
Run the eight tests with Node:
node --test preview.test.mjs
The final test simulates the host’s cached next result without running a tool twice. Once all eight pass, you know the handler logic holds up, and you’re ready to test it in a real Claude Code build with the live dialog and any other mods you have installed.
Validate before loading
On a compatible Claude Code build, inspect your plugin with the validator first:
claude plugin validate ./bash-preview
Check the hooks and calls it reports. Once that looks right, load the plugin inside a disposable project with no sensitive credentials:
claude --plugin-dir ./bash-preview
Ask for something harmless like git diff --stat instead of starting with a destructive command. Try both choices, and dismiss the prompt too. Make sure cancelling or dismissing stops the command from running, and that approving it hands control back to Claude Code’s normal tool flow.
A preview has limits
Reading a shell command only tells you part of the story, since its behavior depends on the working directory, environment variables, and the files it reads. Previewing the text helps you spot surprises, though for serious production controls you want a structured operation with a known target and a preview bound to that exact intent.
A mod isn’t a sandbox (see the mods overview). It has access to the same files, processes, network requests, and secrets as your user account, and any process a mod launches itself bypasses the Bash tool our handler watches.
Other mods can sit in the same event chain too, so check their ordering and see whether anything downstream can rewrite an event after your prompt. If you need organization-wide rules, use Claude Code’s managed controls and proper isolation instead of relying on a local mod you installed yourself.
Start small with your first experiment. Verify how it behaves in a real session, then add one workflow feature at a time and keep your cancellation tests alongside it.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: