PreToolUse hooks not called for Read tool when file doesn't exist
PreToolUse hooks are not invoked when Claude calls the Read tool with a file path that doesn't exist. The hook is only called when the file exists. This contradicts the official documentation which states that PreToolUse hooks execute "after Claude creates tool parameters and before processing the tool call".
This breaks legitimate use cases like path translation where hooks need to modify file paths before validation occurs.
Expected Behavior
According to the documentation, PreToolUse hooks should be called before the tool processes the call, allowing hooks to:
- Validate inputs
- Modify tool parameters using
updatedInput - Block execution with
permissionDecision: "deny"
The hook should be invoked regardless of whether the file exists.
Actual Behavior
When Claude calls Read with a non-existent file path:
- The SDK validates that the file doesn't exist
- The SDK returns "File does not exist" error
- The PreToolUse hook is never called
When Claude calls Read with an existing file path:
- The PreToolUse hook is called ✅
- The file is read successfully ✅
Reproduction
See the minimal reproduction script: reproduce_hook_bug.py
Run it:
pip install claude-agent-sdk
python reproduce_hook_bug.py
Expected output:
[HOOK CALLED] for TEST 1 (/workspace/test.txt)
[HOOK CALLED] for TEST 2 (/tmp/hook_test/test.txt)
Actual output:
[HOOK CALLED] for TEST 2 only (/tmp/hook_test/test.txt)
Environment
- Claude Code: 2.0.35 (latest)
- claude-agent-sdk: 0.1.6 (latest - tested on 0.1.4, 0.1.5, 0.1.6)
- Python: 3.11
- OS: Linux
Impact
This bug breaks:
- Path translation hooks - Cannot translate paths like
/workspace/*to actual locations before validation - Custom file resolution - Cannot implement custom file lookup logic
- Input sanitization - Cannot normalize/validate file paths before they're checked
- Audit logging - Cannot log all Read attempts, only successful ones
The updatedInput feature is essentially useless for file path modification because hooks don't fire early enough.
Workaround
None found. The only way to make hooks work is to ensure files exist at the exact paths Claude uses, which defeats the purpose of path translation hooks.
Related Issues
Similar to #7082 but different - that issue was about permission deny rules, this is about hooks not being called at all for non-existent paths.
I have also encountered this problem, and the client is a Mac server and the server is Linux. I have also encountered many issues with file path permissions, and cannot create files in advance
@vassain -- there seems to be a workdaround (related to #213 )
"""PreToolUse hooks bug: https://github.com/anthropics/claude-agent-sdk-python/issues/213"""
import asyncio
import sys
import subprocess
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
try:
from claude_agent_sdk import ClaudeSDKClient
HAS_CLIENT = True
except ImportError:
HAS_CLIENT = False
def print_diagnostics():
import claude_agent_sdk
print(f"Python: {sys.version.split()[0]}")
print(f"SDK: {getattr(claude_agent_sdk, '__version__', 'unknown')}")
try:
cli = subprocess.run(['claude', '--version'], capture_output=True, text=True, timeout=5)
print(f"CLI: {(cli.stdout or cli.stderr).strip()}")
except:
print("CLI: Not found")
async def test_with_query_function():
print("\nTEST 1: query() function")
hook_called = []
async def hook(input_data, tool_use_id, context):
hook_called.append(True)
print(f" ✓ Hook called: {input_data.get('tool_name')}")
return {}
options = ClaudeAgentOptions(hooks={"PreToolUse": [HookMatcher(hooks=[hook])]})
async for msg in query(prompt="Read bug.py", options=options):
pass
print(f" Result: {'❌ BROKEN - hook not called' if not hook_called else '✅ Works'}")
async def test_with_client():
if not HAS_CLIENT:
print("\nTEST 2: SKIPPED - ClaudeSDKClient not available")
return
print("\nTEST 2: ClaudeSDKClient (workaround)")
hook_called = []
async def hook(input_data, tool_use_id, context):
hook_called.append(True)
print(f" ✓ Hook called: {input_data.get('tool_name')}")
return {}
options = ClaudeAgentOptions(hooks={"PreToolUse": [HookMatcher(hooks=[hook])]})
try:
async with ClaudeSDKClient(options=options) as client:
await client.query("Read bug.py")
async for _ in client.receive_response():
pass
print(f" Result: {'❌ Failed' if not hook_called else '✅ WORKS!'}")
except Exception as e:
print(f" Result: ❌ Error - {e}")
async def main():
print_diagnostics()
await test_with_query_function()
await test_with_client()
print("\nSee: https://github.com/anthropics/claude-agent-sdk-python/issues/213")
if __name__ == "__main__":
asyncio.run(main())
@bgbg Not sure what the workaround here is as it looks like regular usage and it doesn't work for me (the hook isn't called).
+1 on this issue, I wanted to use the PreToolUse hook for a similar use case (specifically, download requested files from a bucket) and cannot do that due to this bug.
+1 on this issue as well - I wanted to use the PreToolUse hook for a usecase involving .docx/other binary files the Read tool does not work with. The SDK immediately returns with an error without running the PreToolUse hook which is supposed to convert/redirect the call to a readable file.