$ cat tips/claude-code-userpromptsubmit-hook-context.md

Claude Code UserPromptSubmit hook: a script that adds context

An agent in Claude Code does not know what changed outside the conversation until it checks. A UserPromptSubmit hook runs your script on every message, and whatever the script prints in the additionalContext field reaches the agent together with it.

The script prints one JSON to standard output:

print(json.dumps({"hookSpecificOutput": {
    "hookEventName": "UserPromptSubmit",
    "additionalContext": news,
}}))

The hook goes into .claude/settings.local.json in the project directory:

{"hooks": {"UserPromptSubmit": [{"hooks": [{
  "type": "command",
  "command": "python3 $HOME/.config/board/news.py"
}]}]}}

My script asks the team’s task board for new comments. The agent has its own account there, and my boss asked it a question under a closed task. The agent had looked at the board four minutes earlier and did not check again, so it heard about the question from me.

Besides asking, the script takes care of three things:

  • When there is nothing new, it prints nothing. Nothing is added to the conversation then, and the whole run takes 0.2 seconds here.
  • It saves where it stopped in a file, so each piece of news is given once.
  • Every error ends quietly, with exit code 0, so that a missing network does not get in the way of the conversation.

Comments on the board are written by other people. So the text for the agent starts with a sentence saying that this is data from the board, not instructions from me.

I added the hook in the middle of a session, to a settings file that already existed. It ran on the next message, with no restart.

For the time when I write nothing, the agent runs the same script in the background, in a loop. With the --text flag my script prints the text alone, without the JSON:

until news=$(python3 news.py --text) && [ -n "$news" ]; do sleep 300; done; echo "$news"

The loop asks every five minutes and ends on the first piece of news, and the end of a background command wakes the agent. After each wake-up the agent starts it again. It is gone when the session ends.

checked: Claude Code 2.1.327, Python 3.10.12, Ubuntu 22.04

$ ls ./blog/tips
all tips →
↑