Skip to content

Hooks run user-defined commands at specific lifecycle events. This tutorial creates a BeforeTool hook with two jobs: append every matching call to a log, and block a shell command containing rm -rf.

The implementation is in packages/core/src/hooks/; see the Hooks guide for the full event list.

Prerequisites ​

  • M31A installed and authenticated.
  • Node.js 20 or newer.
  • A throwaway project directory for testing.

1. Understand the contract ​

Command hooks receive a JSON object on stdin and must write a JSON object to stdout. For BeforeTool, the input shape in packages/core/src/hooks/types.ts is:

json
{
  "session_id": "...",
  "transcript_path": "...",
  "cwd": "/path/to/project",
  "hook_event_name": "BeforeTool",
  "timestamp": "...",
  "tool_name": "run_shell_command",
  "tool_input": {"command": "git status"},
  "original_request_name": "run_shell_command"
}

Useful output fields are:

FieldEffect
decision: "block" or "deny"Blocks the call; the reason is returned to the model.
decision: "ask"Forces a confirmation prompt.
reasonHuman-readable explanation for a block.
continue: false with stopReasonStops the whole agent run.
hookSpecificOutput.hookEventName: "BeforeTool" with tool_inputRewrites parameters.

The hook is evaluated in the scheduler before policy and confirmation. It is not evaluated a second time during execution.

2. Write the hook script ​

Create .m31a/hooks/before-tool.cjs in your project:

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

let raw = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => {
  raw += chunk;
});
process.stdin.on('end', () => {
  let input;
  try {
    input = JSON.parse(raw);
  } catch {
    process.stdout.write('{}');
    return;
  }

  const toolName = input.tool_name ?? 'unknown';
  const command = String(input.tool_input?.command ?? '');
  const logPath = path.join(os.tmpdir(), 'm31a-hooks.log');
  fs.appendFileSync(
    logPath,
    `${new Date().toISOString()} ${toolName} ${command}\n`,
  );

  if (command.includes('rm -rf')) {
    process.stdout.write(
      JSON.stringify({
        decision: 'block',
        reason: 'Destructive rm -rf command blocked by the before-tool hook.',
      }),
    );
    return;
  }

  process.stdout.write('{}');
});

Keep stdout clean: only the final JSON object. Write diagnostics to stderr or a file. Set a short timeout in the configuration so a broken hook cannot stall the agent indefinitely.

3. Configure it ​

Edit <project>/.m31a/settings.json:

json
{
  "hooksConfig": {
    "enabled": true,
    "disabled": [],
    "notifications": true
  },
  "hooks": {
    "BeforeTool": [
      {
        "matcher": "run_shell_command",
        "hooks": [
          {
            "name": "shell-guard",
            "type": "command",
            "command": "node .m31a/hooks/before-tool.cjs",
            "timeout": 5000
          }
        ]
      }
    ]
  }
}

matcher accepts exact tool names, regular expressions like /^read_/, and wildcards like *. Use an absolute command path if you may start M31A from a different working directory.

hooksConfig.enabled defaults to true; hooksConfig.disabled lists hook names that must never run. Hook arrays are concatenated across settings scopes, so workspace configuration adds to user hooks rather than replacing them.

4. Inspect the hook in the TUI ​

text
/hooks panel

The panel lists configured hooks with enable, disable, enable-all, and disable-all actions. Confirm that shell-guard is visible and enabled.

5. Test the logging path safely ​

Start M31A in the project directory and ask for a harmless shell command:

text
Use run_shell_command to run `git status --short` and report the result.

Approve the confirmation if prompted. Then verify the log:

bash
cat /tmp/m31a-hooks.log

You should see a line containing run_shell_command and git status --short. If nothing appears, check hooksConfig.enabled, the matcher, and whether the command path resolves from M31A's working directory.

6. Test the blocking path ​

Ask for a deliberately destructive command that targets a disposable path:

text
Use run_shell_command to run `rm -rf /tmp/m31a-hook-test`.

Expected behavior:

  1. The hook blocks the call before any confirmation dialog.
  2. The agent receives a tool error containing the reason text.
  3. The agent explains that the command was blocked.

If a confirmation dialog appears instead, the hook did not run. Decline it and recheck the configuration. Because the hook fires before policy, this test is safe even if you are not in Plan Mode — but keep the target path disposable.

7. Test with headless mode ​

bash
m31a -p "Run git status --short using the shell tool" -o json
node -e "const r=require('fs').readFileSync('/tmp/m31a-hooks.log','utf8'); console.log(r.trim().split('\n').at(-1))"

In headless mode a policy ask_user becomes a denial, so keep the command read-only. --output-format stream-json also shows tool events if you want to see the block reason in the event stream.

8. Safety notes ​

WARNING

Hook commands run with the privileges of the M31A process. Only enable hooks from sources you trust. TrustedHooksManager tracks command hooks per project in trusted_hooks.json, and untrusted hooks are surfaced before they run.

  • The policy engine remains the primary authorization mechanism; use hooks for audit logging and extra validation, not as the only guard.
  • Commands from extensions are hydrated with extension settings; review them as you would review executable code.
  • m31a hooks migrate converts Claude Code hook definitions to M31A format if you are bringing existing configuration over.

Troubleshooting ​

SymptomResolution
Hook never firesCheck hooksConfig.enabled, matcher, and working directory.
JSON parse errorEnsure the script writes only one JSON object to stdout.
Agent hangsLower timeout; avoid network calls in hooks.
Hook disabled after restartCheck hooksConfig.disabled and the /hooks panel state.

Next steps ​

Built with VitePress. Powered by NVIDIA NIM.