Feature Request: Add `OnToolError` and `SessionEnd` Hooks for Advanced Automation, Error Handling, and Cleanup
Title: Feature Request: Add OnToolError and SessionEnd Hooks for Advanced Automation, Error Handling, and Cleanup
Labels: enhancement, feature-request, hooks, automation, error-handling
Body
Summary & Problem Description
The current hook system, as detailed in the official documentation, provides powerful events like PreToolUse and PostToolUse for integrating custom logic. However, for building truly robust, enterprise-grade automation, two key gaps remain:
- Lack of a Dedicated Error Handling Hook: The documentation confirms that the
PostToolUseevent "runs immediately after a tool completes successfully." This means there is no first-class mechanism to intercept, handle, or react to tool execution failures (e.g., aBashcommand with a non-zero exit code). The current workaround of parsing transcripts post-turn is inefficient and brittle.
- Absence of a Guaranteed Final Cleanup Hook: The
Stophook triggers when the agent finishes its response, but not necessarily after the session has fully terminated and the final transcript has been written. This makes reliable post-session artifact archival, reporting, and downstream job triggering challenging.
Proposed Solution
We propose introducing two new hook events, OnToolError and SessionEnd, designed to seamlessly integrate with the existing hook architecture.
---
1. OnToolError Hook
This hook would trigger whenever a tool call fails, providing a dedicated, real-time mechanism for runtime error handling and automated remediation.
- Trigger: A tool call fails due to an exception, a non-zero exit code, or an internal error.
- Matcher: Would use the same powerful regex and string matching as
PreToolUseandPostToolUseto target specific tools (e.g.,Bash,Write,mcp__*). - Hook Input (stdin): The hook would receive a JSON payload with detailed failure context, similar to other hooks.
``json``
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/path/to/project",
"hook_event_name": "OnToolError",
"tool_name": "Bash",
"tool_input": { "command": "npm run test:unit" },
"error_details": {
"exit_code": 1,
"stdout": "...",
"stderr": "Error: 1 test failed.",
"error_message": "Command exited with a non-zero code."
}
}
- Hook Output (Decision Control): The hook would leverage the existing output mechanisms (exit codes or JSON
stdout) to control the agent's flow. - Exit Code 0 (Ignore/Log): The error is noted for the user, but the agent continues. The hook's
stdoutwould be logged in transcript mode for debugging. - Exit Code 2 (Block & Inform Claude): This would block the agent's execution. The hook's
stderrwould be fed back to Claude as context, allowing the model to attempt a fix based on the hook's intelligent feedback. This mirrors the documented behavior for other hooks. - JSON Output for Advanced Control: For more granular control, the hook could return a JSON object like
{"decision": "block", "reason": "Tests failed. Analyzing logs..."}.
---
2. SessionEnd Hook
This hook would trigger after a session has completely finished and the final transcript has been successfully saved to disk.
- Trigger: The Claude Code process is terminating, and the session transcript is finalized. This occurs after the
Stophook. - Matcher: Not applicable, as this is a global, session-level event.
- Hook Input (stdin): The hook script would receive the final, essential session identifiers.
``json``
{
"session_id": "abc123",
"transcript_path": "/path/to/project/.claude/history/session-id.jsonl"
}
- Hook Output: Primarily for side effects. Its
stdoutcan be logged for debugging, but it would not influence agent behavior as the session is already over.
---
Use Cases & Rationale
These hooks are critical for unlocking enterprise-level automation and CI/CD workflows.
OnToolError Use Cases:
- Automated Remediation: A hook could catch a failing
npm install, parse thestderrfor a missing dependency, and feed a precise, actionable error message back to Claude to fix it. - Intelligent Alerting: On critical failures (e.g., a deployment script), a hook could trigger a structured alert to an observability platform, leveraging the detailed
error_detailspayload. This is a perfect fit for the OpenTelemetry integration. - Enhanced Security: A hook could watch for
Bashcommands that attempt to access sensitive files and block them, providing a more dynamic security layer than staticpermissionsrules alone.
SessionEnd Use Cases:
- Artifact Archival: Reliably copy the final session transcript and other artifacts to a centralized location (e.g., S3, Google Cloud Storage) for auditing, review, or fine-tuning.
- Automated Reporting & Analytics: Generate a summary report from the final, complete transcript and feed it into internal analytics or reporting tools.
- Downstream CI/CD Triggering: Kick off a subsequent CI/CD job (e.g., a full integration test suite) with the guarantee that the Claude Code session has fully completed and its outputs are ready.
---
Example Configuration (.claude/settings.json)
This configuration aligns perfectly with the documented format in the "Hooks reference."
{
"hooks": {
"OnToolError": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "/usr/local/bin/handle-bash-error.py"
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "python3 /usr/local/bin/archive_session.py"
}
]
}
]
}
}
By implementing OnToolError and SessionEnd, you would significantly improve Claude Code's robustness and make it a more powerful and reliable tool for complex, automated development pipelines.
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗