MagicTools
Claude GuidesAugust 6, 20269 views3 min read

The Claude Code Hooks Stdin Trap: Python Heredocs Eat Your Hook JSON

What the official docs say

The Claude Code hooks mechanism is straightforward: register a command in settings.json, and when an event fires (say PostToolUse), Claude Code launches that command and passes the event data as JSON via stdin. The docs are concise — a hook reads JSON from stdin, does its work, and communicates back through exit codes.

Standard Unix piping. Building a "log every failed command" hook should take ten minutes.

What actually happened

The goal: whenever a Bash command fails, append it to a tasks/lessons-inbox.md inbox file (with dedup and benign-failure filtering). The logic is not complex, but it is verbose in shell, so the natural choice was to hand it to python. The first version of the hook looked like this:

#!/bin/sh
python3 - <<'PYEOF' 2>/dev/null
import json, sys

data = json.load(sys.stdin)   # read the hook JSON — or so you think
cmd = data.get("tool_input", {}).get("command", "")
# ... detect failure, append to inbox ...
PYEOF
exit 0

It ran without a single error. I then deliberately triggered several failing commands — the inbox file stayed empty. No error, no log output, the settings.json config triple-checked and fine. The hook simply "did not work".

The trap: the heredoc redirects stdin

Trace the data flow of that command and the bug becomes obvious:

  1. Claude Code launches the hook process with the event JSON attached to the process's stdin
  2. python3 - means "read the program itself from stdin"
  3. The <<'PYEOF' heredoc redirects python's stdin to the heredoc content — the python script

So python's stdin is fully occupied by the script text; once the program is read, the stream is at EOF. The json.load(sys.stdin) inside reads empty input and raises JSONDecodeError — which is then completely swallowed by 2>/dev/null and the "hooks must never block" fault-tolerant design. On the Claude Code side, the hook exits 0. Everything looks "successful".

And the real hook JSON? It is still sitting on the outer sh process's stdin, but once the heredoc takes effect, python can never reach it.

What makes this trap nasty is three layers of silence stacked together: the heredoc is perfectly legal shell (no shell error), the python exception is discarded by the redirect (no runtime error), and the hook exits 0 per best practice (no Claude Code error). Each layer is correct design on its own; combined, they form a soundless black hole.

The fix: spool to disk first, pass a path

The fix is two lines — before python starts, consume the outer process's stdin with cat into a temp file, then hand the file path in through an environment variable:

#!/bin/sh
TMP_IN="$(mktemp)" || exit 0
cat > "$TMP_IN" 2>/dev/null || true          # catch the hook JSON off stdin first
CL_HOOK_INPUT="$TMP_IN" python3 - <<'PYEOF' 2>/dev/null
import json, os, sys

try:
    data = json.load(open(os.environ["CL_HOOK_INPUT"], encoding="utf-8"))
except Exception:
    sys.exit(0)

if data.get("tool_name") != "Bash":
    sys.exit(0)
# ... failure detection, benign filtering, dedup by command hash, append to inbox ...
PYEOF
rm -f "$TMP_IN"
exit 0

It worked immediately: failed commands started landing in the inbox one by one, with dedup and filtering behaving as intended.

A few design points from the full version of this hook worth copying (all validated by real usage over time):

  • Never block: every exceptional path ends in exit 0, including a failed mktemp — a broken hook must not drag down the main loop
  • Benign-failure filtering: non-zero exits from grep / rg / diff / test are normal semantics, not worth recording
  • Dedup by command hash: the same command failing repeatedly is recorded once, so the inbox never bloats

Scope and boundaries

  • This only affects the pattern of "feeding an interpreter its script via heredoc inside a hook" — python3 - <<EOF and node - <<EOF fail identically; if your python code lives in a separate file (python3 hook.py), stdin passes through untouched and there is no issue
  • python3 -c 'one-liner' does not occupy stdin, so short logic can dodge the trap that way; beyond a few lines it becomes unmaintainable, and the spool-to-disk approach is sturdier
  • Verified in the environment stated at the top of this page; hooks receiving JSON via stdin is a documented, stable contract, and this trap comes from shell semantics rather than Claude Code version behavior, so it should hold long-term

The general lesson

Supporting-cast code like hooks is usually required to fail silently — rightly so, but during development, take the 2>/dev/null off first. Had I seen JSONDecodeError: Expecting value early, locating the bug would have taken ten minutes; debugging through a full stack of silence cost an order of magnitude more. Fault tolerance is for production, not for troubleshooting.

Related Articles

I Put My Opus 5 Config on the Recommended Diet, Then Ran 18 A/B Trials: 21% Cheaper, and I Can't Prove It's Better

"Opus 5 verifies itself, so delete your fallback prompts" is advice you hear everywhere. I took it, then isolated both configs with CLAUDE_CONFIG_DIR and ran 18 headless trials on identical tasks. Output tokens dropped 21% and wall clock 20-29%, with zero counterexamples. But two of the rewritten rules never fired at all, and one result points the other way: the old config's most thorough run covered a strict superset of what the new one found. Why cheaper and better are separate questions.

prompt-engineeringclaude-code+4
claudeAug 5, 20266 min
34

Half My openclaw Commands Ran, Half Didn't — It Looked Like a Permission Classifier, It Was launchd

Same machine, same user, same global config. Two Claude Code windows running the same CLI — one worked, one didn't. The obvious suspect was the permission classifier, which really does block commands. But the cause sat a layer down: the daemon's plist was installed and never loaded, so every gateway-bound subcommand died while purely local ones printed fine. That half-working shape is what sells the permission theory. Full trace, including the hypothesis I got wrong by misreading my own logs.

permissionstroubleshooting+4
developerAug 4, 20267 min
47

Claude Code's Auto Mode Judges a Model With a Model — When the Model Is Down, You Can't Even Run cat

Auto permission mode calls your session model to judge whether each Bash command is safe — the judge and the worker are the same model. When it goes unavailable you land in a counterintuitive half-paralysis: reading files works, but you can't run a single cat. This is a log of a real debugging session in which I proposed three entirely reasonable hypotheses and knocked all three down with controlled experiments, leaving exactly one dependable way out.

claude-codepermissions+5
claudeAug 3, 20268 min
79

Claude Code Skills: Turn Repeated Workflows into a Slash Command with SKILL.md

Skills are the most underrated feature in Claude Code: write a workflow into a SKILL.md file and invoke it with a slash command, or let Claude load it automatically when the task matches. This guide covers the file structure, frontmatter, auto-trigger mechanics, how skills differ from CLAUDE.md, hooks, and subagents, plus three ready-to-copy examples.

claude-codeslash-commands+4
claudeJul 28, 20263 min
117

Published by MagicTools