Open5
Claude Codeに現在時刻を与える(UserPromptSubmit Hook)
Problem
Claude Codeを用いる際、現在日時を正確に取得できないことがある。
Bashツールでの取得やmcpサーバーを与える解放もあるが、遅い。
結論
UserPromptSubmit
Hookを使う。
UserPromptSubmit
Runs when the user submits a prompt, before Claude processes it. This allows you to add additional context based on the prompt/conversation, validate prompts, or block certain types of prompts.
プロンプト送信時に、追加のcontextを与えることができる。
実装
pythonを呼ぶ実装とした。
#!/usr/bin/env python3
import sys
import json
from datetime import datetime, timezone, timedelta
def main():
try:
# Read stdin (the original prompt from user)
# prompt = sys.stdin.read()
# Get current JST time
jst_tz = timezone(timedelta(hours=9))
current_time_jst = datetime.now(jst_tz)
time_string = current_time_jst.strftime("%Y-%m-%d %H:%M:%S JST")
# Create the context to inject
time_context = f"[Current Time: {time_string}]\n"
# Prepare JSON output
output = {
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": time_context,
},
}
# Output as JSON
print(json.dumps(output))
sys.exit(0)
except Exception as e:
error_output = {
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": "Failed to get current JST time",
},
}
print(json.dumps(error_output))
sys.exit(0)
if __name__ == "__main__":
sys.exit(main())
設定ファイル
"hooks": {
"UserPromptSubmit": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "python3 <path>/.claude/hooks/inject_jst_time.py"
}
]
}
]
のように設定。