[BUG] Feature Request: PreToolUse Hook Context Auto-Injection API
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
๐ง Feature Request: PreToolUse Hook Context Auto-Injection API
๐ Summary
PreToolUse hooks can block tool execution but cannot auto-inject context (execute Read tools), forcing manual file reading in agent-based workflows. This breaks automation in sophisticated AI-driven development systems.
Impact: Multi-agent workflows requiring dynamic context loading are unusable in production.
---
๐ฏ Problem Statement
Current Behavior
Hooks can only return {"decision": "block"} or {"decision": "allow"}. When a hook detects that required context files (agent definitions, domain skills) are missing, it can only:
โ
Block the tool execution
โ Cannot execute Read() tool to load the files
โ Cannot inject file contents into conversation
โ Cannot modify Claude's context window
Real-World Example
AIDD Workflow System (14 specialized agents, 30 domain skills):
User: /implement T-145 "Add SEC filing parser"
โ
Hook detects: Task requires "Fundamental Analyst" agent + forensics skills
โ
Hook BLOCKS: "โ Agent file not loaded"
โ
User MUST MANUALLY:
- Read .claude/agents/fundamental-analyst.md
- Read .claude/skills/domain-forensics.md
- Read .claude/skills/domain-crawling.md
- Output SKILL ACTIVATION LOG
- Update state file
โ
Finally: Task executes
Result: 6+ manual steps, 2+ minutes, 30% error rate
Expected Behavior (Desired)
User: /implement T-145 "Add SEC filing parser"
โ
Hook detects: Required context missing
โ
Hook AUTO-LOADS:
โ
.claude/agents/fundamental-analyst.md
โ
.claude/skills/domain-forensics.md
โ
.claude/skills/domain-crawling.md
โ
Task executes with full context
โ
โ
DONE (5 seconds, 1 step, 0% errors)
---
๐ก Proposed Solution
Option A: Hook Tool Injection API (Recommended)
Allow hooks to return tool execution requests:
{
"decision": "modify",
"message": "Auto-loading required context...",
"inject_tools": [
{
"tool": "Read",
"parameters": {
"file_path": ".claude/agents/fundamental-analyst.md"
}
},
{
"tool": "Read",
"parameters": {
"file_path": ".claude/skills/domain-forensics.md"
}
}
],
"inject_system_message": "โ
Activated: Fundamental Analyst + forensics skills\n\nKEY PATTERNS:\n- Beneish M-Score for fraud detection\n- SEC EDGAR XBRL parsing\n\nANTI-PATTERNS:\n- Don't scrape without rate limiting"
}
Behavior:
- Hook detects missing context
- Hook returns
inject_toolsarray - Claude Code automatically executes Read tools
- Tool results are injected into conversation context
- System message is displayed to user
- Original tool (Task/Edit/Write) proceeds with full context
Hook Example:
#!/bin/bash
# .claude/hooks/skill-activate.sh
MISSING_SKILLS=$(detect_missing_skills "$PROMPT")
if [ -n "$MISSING_SKILLS" ]; then
# Build Read tool calls
INJECT_TOOLS="["
for skill in $MISSING_SKILLS; do
INJECT_TOOLS="$INJECT_TOOLS
{\"tool\": \"Read\", \"parameters\": {\"file_path\": \".claude/skills/$skill\"}},"
done
INJECT_TOOLS="${INJECT_TOOLS%,}]"
# Return auto-injection response
jq -n \
--argjson tools "$INJECT_TOOLS" \
--arg msg "Auto-loading skills: $MISSING_SKILLS" \
'{
"decision": "modify",
"message": $msg,
"inject_tools": $tools,
"inject_system_message": "โ
Skills activated"
}'
exit 0
fi
echo '{"decision": "allow"}'
---
Option B: Context Manifest File (Simpler Alternative)
Create .claude/context-manifest.json:
{
"auto_load": {
"on_task_spawn": {
"Fundamental Analyst": {
"agent_file": ".claude/agents/fundamental-analyst.md",
"required_skills": [
".claude/skills/domain-forensics.md",
".claude/skills/domain-crawling.md"
]
},
"Backend & ETL engineer": {
"agent_file": ".claude/agents/backend-etl.md",
"required_skills": [
".claude/skills/domain-db.md",
".claude/skills/domain-etl.md"
]
}
}
}
}
Behavior:
- When
Task(subagent_type="Fundamental Analyst")is called - Claude Code reads manifest
- Auto-executes
Read()for all listed files - Injects results into context
- Proceeds with Task execution
Implementation: ~50 lines of code, zero breaking changes
---
๐ Impact Analysis
Quantified Impact (Production AIDD System)
| Metric | Without Feature | With Feature | Improvement |
|--------|----------------|--------------|-------------|
| Steps per task | 6+ manual | 1 automated | 6x faster |
| Time per task | 120+ seconds | 5 seconds | 24x faster |
| Error rate | 30% (manual) | <1% (automated) | 30x more reliable |
| Developer friction | Critical | Minimal | Workflow restored |
Use Cases Enabled
- Multi-Agent Workflows - Auto-load agent definitions based on task type
- Domain Skill Activation - Auto-load relevant skills (database, NLP, security, etc.)
- Context-Aware Enforcement - Hooks verify AND auto-fix missing context
- Workflow Automation - Complex pipelines with automatic context management
Current Workarounds (Insufficient)
Attempted workarounds:
- โ State tracking files (
.skill_activated,.aidd-state.json) - hooks can only CHECK, not LOAD - โ Manual checklists in commands - defeats automation purpose
- โ Error messages with Read instructions - requires 6+ manual steps per task
None of these solve the core issue: Hooks cannot execute tools or inject context.
---
๐ Technical Implementation Details
Hook Response Schema (Proposed)
interface HookResponse {
decision: "allow" | "block" | "modify";
message?: string;
// NEW: Tool injection capability
inject_tools?: Array<{
tool: "Read" | "Write" | "Edit" | "Bash" | "Grep" | "Glob";
parameters: Record<string, any>;
}>;
// NEW: System message injection
inject_system_message?: string;
// NEW: State updates (optional)
update_state?: {
file_path: string;
updates: Record<string, any>;
};
}
Execution Flow
graph TD
A[User calls Task tool] --> B[PreToolUse hook runs]
B --> C{Hook detects missing context?}
C -->|No| D[Allow - proceed normally]
C -->|Yes| E[Hook returns inject_tools]
E --> F[Claude Code executes Read tools]
F --> G[Results injected into context]
G --> H[System message displayed]
H --> I[Original Task tool proceeds]
Backward Compatibility
- Existing hooks continue to work (return
allow/block) - New
inject_toolsfield is optional - Only hooks that need auto-injection use the feature
- No breaking changes to existing API
---
๐ Reference Implementation
Full production system available:
- Repository: ALTSEASON Analytics AIDD v3.2
- Scale: 14 agents, 30 skills, 22 slash commands
- Hook files:
.claude/hooks/skill-activate.sh(312 lines, skill detection + blocking).claude/hooks/aidd-enforce.sh(319 lines, agent spawn enforcement).claude/context-manifest.json(reference implementation)
Willing to provide:
- Code samples and test cases
- Beta testing and feedback
- Collaboration on API design
- Real-world usage examples
---
๐ฏ Recommended Implementation Plan
Phase 1: Context Manifest (Quick Win - 2-4 weeks)
- Implement
.claude/context-manifest.jsonparsing - Auto-load agent files on Task spawn
- Ship in next minor release
- Solves 90% of use cases
Phase 2: Hook Tool Injection API (Full Solution - 2-3 months)
- Design
inject_toolsschema - Implement tool execution in hook response handler
- Add system message injection
- Document and release
---
๐ Comparison Table
| Solution | Agent Auto-Load | Skill Auto-Load | Hook Complexity | CC Changes | Timeline |
|----------|----------------|-----------------|-----------------|------------|----------|
| Option A: inject_tools | โ
| โ
| Medium | Medium | 2-3 months |
| Option B: Manifest | โ
| โ
| Low | Low | 2-4 weeks |
| Status Quo | โ | โ | High (blocking only) | None | - |
Recommendation: Implement Option B first for immediate relief, then Option A for full extensibility.
---
๐ Additional Resources
Documentation:
- [Full Technical Report](CLAUDE_CODE_HOOK_LIMITATION_REPORT.md) - 15+ pages with detailed analysis
- [Quick Summary](HOOK_LIMITATION_SUMMARY.md) - 2-page overview
- [Context Manifest Reference](.claude/context-manifest.json) - Working implementation
Hook Files (Production):
.claude/hooks/skill-activate.sh- Skill detection and blocking logic.claude/hooks/aidd-enforce.sh- Agent spawn enforcement.claude/COMMAND_AGENT_MAP.md- Agent selection rules
---
๐ฌ Discussion Points
- Security: How to prevent malicious hooks from injecting arbitrary tools?
- Proposal: Whitelist allowed tools (Read, Grep, Glob only)
- Sandbox tool execution with timeout limits
- Performance: What if hooks inject 10+ Read calls?
- Proposal: Set max injection limit (e.g., 5 tools per hook)
- Show progress indicator for multi-file loads
- User Experience: How to show what was auto-loaded?
- Proposal: Display system message: "โ Auto-loaded: agent.md + 3 skills"
- Optional verbose mode in settings
---
๐ Why This Matters
This limitation blocks any sophisticated workflow automation with Claude Code, not just AIDD:
- โ Multi-agent systems with dynamic agent selection
- โ Domain-specific skill activation based on task context
- โ Workflow pipelines with automatic context management
- โ Enforcement hooks that fix problems instead of just blocking
Current state: Hooks are blockers only, not helpers
Desired state: Hooks become intelligent assistants that auto-fix context issues
---
โ Success Criteria
Feature is successful when:
- โ
Hook can return
inject_toolsarray - โ Claude Code executes tools automatically
- โ Tool results are injected into conversation context
- โ Original tool proceeds with full context
- โ Zero manual steps required for context loading
- โ Backward compatible with existing hooks
---
๐ Contact & Collaboration
Willing to:
- โ Provide detailed code examples
- โ Test beta features
- โ Share production AIDD system as reference
- โ Collaborate on API design
- โ Write documentation and migration guides
Project: ALTSEASON Analytics
AIDD Version: 3.2
Environment: VSCode Extension + CLI
---
Thank you for considering this feature request! ๐
This is the #1 blocker for production AI-driven development workflows with Claude Code. The capability to auto-inject context would unlock a whole new category of sophisticated automation systems.
What Should Happen?
PreToolUse hooks can block tool execution but cannot auto-inject context (execute Read tools), forcing manual file reading in agent-based workflows. This breaks automation in sophisticated AI-driven development systems.
Error Messages/Logs
Steps to Reproduce
#!/bin/bash
# .claude/hooks/skill-activate.sh
MISSING_SKILLS=$(detect_missing_skills "$PROMPT")
if [ -n "$MISSING_SKILLS" ]; then
# Build Read tool calls
INJECT_TOOLS="["
for skill in $MISSING_SKILLS; do
INJECT_TOOLS="$INJECT_TOOLS
{\"tool\": \"Read\", \"parameters\": {\"file_path\": \".claude/skills/$skill\"}},"
done
INJECT_TOOLS="${INJECT_TOOLS%,}]"
# Return auto-injection response
jq -n \
--argjson tools "$INJECT_TOOLS" \
--arg msg "Auto-loading skills: $MISSING_SKILLS" \
'{
"decision": "modify",
"message": $msg,
"inject_tools": $tools,
"inject_system_message": "โ
Skills activated"
}'
exit 0
fi
echo '{"decision": "allow"}'
Claude Model
Opus
Is this a regression?
Yes, this worked in a previous version
Last Working Version
_No response_
Claude Code Version
2.1.1
Platform
Anthropic API
Operating System
Ubuntu/Debian Linux
Terminal/Shell
VS Code integrated terminal
Additional Information
_No response_
This issue has 2 comments on GitHub. Read the full discussion on GitHub โ