[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 1 comment on GitHub. Read the full discussion on GitHub ↗