Agent Context Detention in Hook Events
Environment
- Platform (select one):
- [ ] Anthropic API
- [x] AWS Bedrock
- [ ] Google Vertex AI
- [ ] Other:
- Claude CLI version: 1.0.96
- Operating System: macOS
- Terminal: Ghostty
Feature Description
Add agent context information to hook events so that hooks can determine whether they're running within an agent workflow (e.g., when Claude is using the Task tool with subagents).
Use Case / Problem Statement
Currently, hooks receive rich context about tool usage, session information, and transcript data, but cannot determine if they're executing within an agent context. This limits the ability to:
- Apply different security policies for agent vs. direct user interactions
- Implement agent-specific logging or auditing
- Adjust hook behavior based on execution context
- Provide better debugging information for agent workflows
Example use case (git-sub agent)
It would be ideal for me to develop a hook that checks whether Bash(git:*) calls were being performed inside of a slash command kicked off to a sub-agent. To know what sub-agent(s) are being used to run it would let me determine if it's doing something outside of my instructions (such as saying "never commit to the repo without using @agent-git-expert").
Proposed Solution
Add agent context information to hook events, such as:
IsAgentContext bool- indicates if running within an agentAgentName string- type of agent (e.g., "general-purpose", "code-reviewer")ParentSessionID string- session ID of the parent contextAgentDepth int- nesting level for multi-agent scenarios
This could be added to existing event types (PreToolUseEvent, PostToolUseEvent, etc.) or provided through the hook context.
Expected Behavior
Using cchooks, it would work like this:
func (h *MyHook) preToolUseHandler(ctx context.Context, event *cchooks.PreToolUseEvent) {
if event.IsAgentContext {
// Apply agent-specific logic
log.Printf("Agent %s executing %s", event.AgentType, event.ToolName)
}
}
Alternative Solutions
If direct agent context isn't feasible, consider:
- Adding metadata fields to events that agents can populate
- Providing session hierarchy information
- Adding agent-related information to the existing SessionID structure
Additional Context
This feature would enhance the security and observability capabilities of Claude Code hooks, particularly for users building sophisticated agent workflows that require different governance policies than direct user interactions.
Showing cached comments. Read the full discussion on GitHub ↗
10 Comments
Hey,
This is a great feature request. I've been thinking about a similar problem for managing how my team uses
claude code, and being able to apply different policies for sub-agents vs. the main agent loop would be a huge security and governance win. Your proposed solution of addingAgentName,IsAgentContext, etc., directly to the hook payload is definitely the ideal, clean solution. +1 from me on that.In the meantime, I was digging through the docs and found a potential workaround that might get you most of the way there. It's not as clean as your proposal, but it seems workable.
Workaround: Inspecting the Session Transcript
The hook event payload includes the
transcript_path. We can use this to inspect the conversation history and figure out if we're inside a sub-agent task.When Claude decides to use a sub-agent, it calls the
Tasktool. The input to that tool call contains the name of the sub-agent being invoked. Any subsequent tool calls made by that sub-agent will appear in the transcript after thatTasktool call.So, a
PreToolUsehook forBash(git:*)could look something like this:transcript_path.tool_usemessage where the tool name wasTask.inputof thatTasktool call to see which sub-agent was invoked.@agent-git-expert(or whatever you've named your agent), the hook can block thegitcommand by exiting with code 2 and sending a message back to Claude.Here’s a rough sketch of what a Python script for this hook might look like.
.claude/hooks/validate-git-agent.pyThen in your
.claude/settings.json:Limitations of this workaround:
Taskinput's description string is a bit fragile and depends on Claude's phrasing.Still, it seems like a viable path until we get first-class support for agent context in hooks. Your proposal is much better for the long run.
Hope this helps
👍 This would be incredibly useful for my use case as well!
My Use Case: Content Isolation with File Access Controls
I'm implementing content isolation where the main agent should be restricted from reading certain files (to prevent context pollution), while subagents need access to these files. Currently, I have a PreToolUse hook that needs to distinguish between agent contexts:
Current hook structure
Current Workaround
I'm having to implement a hacky solution:
Track subagent lifecycle by detecting Task tool invocations
Use file-based flags to maintain agent state
Clean up with PostToolUse/SubagentStop hooks
Handle parallel subagents with counters
This is error-prone and doesn't scale well.
What I Need
For shell script hooks, having environment variables like:
CLAUDE_AGENT_NAME- to identify the current agentThis issue has been inactive for 30 days. If the issue is still occurring, please comment to let us know. Otherwise, this issue will be automatically closed in 30 days for housekeeping purposes.
This is a great feature request and would love to have it
+1 on this
More comprehensive proposal for this: #16424
In the meantime, there's a workaround using
tool_use_id+ transcript grepping to detect subagent context: https://github.com/anthropics/claude-code/issues/16424#issuecomment-3880522301🤖 Generated with Claude Code
I've submitted a pull request (#36279) that addresses this. It adds documentation, test utilities, and concrete examples for the four new agent-context fields (is_subagent, agent_name, parent_session_id, agent_depth).
This should make it much easier to implement targeted security policies and cleaner denial messages for subagents. Feel free to take a look!
This is still a relevant issue, and the feature would be very welcome.
Pretty sure this has been added for a few releases now. agent_id is populated if you're in the context of a subagent.
Hi @Nxt3, thanks for the heads up! I completely missed that agent context fields (
agent_idandagent_type) were natively added to the hook payload in v2.1.69.I've gone ahead and completely refactored this PR. Instead of trying to introduce new fields, this PR now strictly serves to document and provide examples for the native
agent_idandagent_typefields.I've just pushed updates that:
SKILL.md,advanced.md, andpatterns.mdto properly document the official schema, explaining how to useagent_idto branch for subagent contexts.test-hook.shdeveloper utility to properly injectagent_idandagent_typewhen generating--subagentsample payloads.validate-git-agent.py,agent-aware-bash-validator.sh, etc.) to demonstrate extracting and utilizing these specific native fields.Since the core engine functionality is already there, I hope this documentation-and-examples PR is a helpful addition to the repository! Let me know if any further tweaks are needed.