Python utility package for building Claude Code hooks
Recorded: May 29, 2026, 5:03 a.m.
| Original | Summarized |
GitHub - RasmusGodske/claude-hook-utils · GitHub Skip to content Navigation Menu Toggle navigation
Sign in
Appearance settings PlatformAI CODE CREATIONGitHub CopilotWrite better code with AIGitHub SparkBuild and deploy intelligent appsGitHub ModelsManage and compare promptsMCP RegistryNewIntegrate external toolsDEVELOPER WORKFLOWSActionsAutomate any workflowCodespacesInstant dev environmentsIssuesPlan and track workCode ReviewManage code changesAPPLICATION SECURITYGitHub Advanced SecurityFind and fix vulnerabilitiesCode securitySecure your code as you buildSecret protectionStop leaks before they startEXPLOREWhy GitHubDocumentationBlogChangelogMarketplaceView all featuresSolutionsBY COMPANY SIZEEnterprisesSmall and medium teamsStartupsNonprofitsBY USE CASEApp ModernizationDevSecOpsDevOpsCI/CDView all use casesBY INDUSTRYHealthcareFinancial servicesManufacturingGovernmentView all industriesView all solutionsResourcesEXPLORE BY TOPICAISoftware DevelopmentDevOpsSecurityView all topicsEXPLORE BY TYPECustomer storiesEvents & webinarsEbooks & reportsBusiness insightsGitHub SkillsSUPPORT & SERVICESDocumentationCustomer supportCommunity forumTrust centerPartnersView all resourcesOpen SourceCOMMUNITYGitHub SponsorsFund open source developersPROGRAMSSecurity LabMaintainer CommunityAcceleratorGitHub StarsArchive ProgramREPOSITORIESTopicsTrendingCollectionsEnterpriseENTERPRISE SOLUTIONSEnterprise platformAI-powered developer platformAVAILABLE ADD-ONSGitHub Advanced SecurityEnterprise-grade security featuresCopilot for BusinessEnterprise-grade AI featuresPremium SupportEnterprise-grade 24/7 supportPricing Search or jump to... Search code, repositories, users, issues, pull requests...
Search Clear
Search syntax tips Provide feedback Include my email address so I can be contacted Cancel Submit feedback Saved searches
Name Query To see all available qualifiers, see our documentation. Cancel Create saved search Sign in Sign up
Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. Dismiss alert RasmusGodske claude-hook-utils Public
Notifications
Fork
Star Code Issues Pull requests Actions Projects Security and quality Insights
Additional navigation options
Code Issues Pull requests Actions Projects Security and quality Insights
mainBranchesTagsGo to fileCodeOpen more actions menuFolders and filesNameNameLast commit messageLast commit dateLatest commit History15 Commits15 Commits.github/workflows.github/workflows docsdocs src/claude_hook_utilssrc/claude_hook_utils teststests .gitignore.gitignore LICENSELICENSE README.mdREADME.md pyproject.tomlpyproject.toml View all filesRepository files navigationREADMEContributingMIT licenseSecurityclaude-hook-utils Validate tool calls before they execute (PreToolUse) Why This Package? Parsing JSON from stdin claude-hook-utils handles all of this, letting you focus on your validation logic. One Pattern - Extend HookHandler, override the hooks you need Installation from claude_hook_utils import HookHandler, PreToolUseInput, PreToolUseResponse class DataClassValidator(HookHandler): # Check for required annotation return PreToolUseResponse.allow() if __name__ == "__main__": Hook Type PreToolUse PostToolUse UserPromptSubmit SessionStart API Reference class MyHandler(HookHandler): def pre_tool_use(self, input: PreToolUseInput) -> PreToolUseResponse | None: def post_tool_use(self, input: PostToolUseInput) -> PostToolUseResponse | None: def user_prompt_submit(self, input: UserPromptSubmitInput) -> UserPromptSubmitResponse | None: def session_start(self, input: SessionStartInput) -> SessionStartResponse | None: if __name__ == "__main__": # PreToolUse-specific # Helper methods def file_path_excludes(self, *globs: str) -> bool: # Convenience properties @property @property @staticmethod @staticmethod def with_updated_input(self, **updates) -> PreToolUseResponse: class MyHandler(HookHandler): def pre_tool_use(self, input: PreToolUseInput) -> PreToolUseResponse | None: Default location: {cwd}/.claude/logs/{namespace}/hooks.jsonl Examples content = input.content or '' # Check tag order: <script> before <template> before <style> if script_pos > template_pos or template_pos > style_pos: # Check for setup lang="ts" return PreToolUseResponse.allow() # Controllers must be in app/Http/Controllers/ return PreToolUseResponse.allow() content = input.content or '' if 'FormRequest' in content: return PreToolUseResponse.allow() def pre_tool_use(self, input: PreToolUseInput) -> PreToolUseResponse | None: def post_tool_use(self, input: PostToolUseInput) -> PostToolUseResponse | None: Decision allow deny ask Modifying Tool Input Invalid JSON input: Returns exit 0 (no output = allow) This "fail open" approach ensures your hooks don't block Claude Code if something goes wrong. Variable CLAUDE_PROJECT_DIR CLAUDE_CODE_REMOTE This package uses: Variable CLAUDE_HOOK_LOG_DIR CLAUDE_HOOK_LOG_NAMESPACE Access via input.cwd or os.environ. Create input dataclass in inputs/ See existing implementations for patterns to follow. About No description, website, or topics provided. Readme MIT license Contributing Contributing Security policy Security policy Uh oh! There was an error while loading. Please reload this page. Activity 5 0 0 Report repository Releases v0.4.0 Latest Packages
Uh oh! There was an error while loading. Please reload this page. Contributors Uh oh! There was an error while loading. Please reload this page. Languages Python
Footer © 2026 GitHub, Inc. Footer navigation Terms Privacy Security Status Community Docs Contact Manage cookies Do not share my personal information You can’t perform that action at this time. |
The claude-hook-utils package is a Python utility designed to streamline the process of building custom code hooks for Claude Code execution by minimizing boilerplate code. These hooks are custom scripts that execute at predefined stages of the AI's workflow, allowing for various types of validation, reaction, and state initialization. The package addresses the repetitive tasks involved in handling prompts, tool interactions, and session management by providing a structured framework. The core design philosophy centers on a pattern where users extend the HookHandler class to implement specific hook functionalities. This approach is bolstered by type safety using dataclasses for inputs and a builder pattern for responses, ensuring explicit control over whether a tool execution is allowed, denied, or requires user confirmation. The package supports multiple hook types, including PreToolUse, PostToolUse, UserPromptSubmit, and SessionStart, enabling comprehensive control over the lifecycle of an AI session. The structure of the hook system is defined by specific input and response data structures. For example, the PreToolUse hook involves input data detailing the session ID, the current working directory, the specific tool being invoked, and the tool's input parameters. The corresponding response mechanism allows the handler to return a decision: allow the tool to execute immediately, deny the execution with a provided reason, or ask the user for confirmation. The package also facilitates modifying tool input before execution, allowing for automated corrections based on validation checks. To facilitate detailed debugging and tracking, the utility includes a HookLogger component that implements JSONL-based logging. This logging system organizes information by namespace and provides granular details about file checks, decisions made, and execution flow, which is written to file within the project's configuration directory. This logging is configurable via environment variables to control the log directory and namespace. The package includes several illustrative examples demonstrating practical applications of the hook system. These examples show how to implement logic to validate file path matches against glob patterns, enforce specific coding standards, and block potentially unsafe operations. One example validates the structure and ordering of Vue component tags and enforces specific TypeScript syntax, while another validates the file location of controller classes. Furthermore, it provides a method to block the use of specific patterns, such as FormRequest classes, suggesting alternatives like data classes. The design emphasizes robustness through graceful error handling. The package employs a "fail open" strategy, ensuring that exceptions or invalid input do not necessarily block the execution of the AI code. This ensures that hooks do not halt the Claude Code process if runtime errors occur. The system also manages context through environment variables, allowing hooks to access project root directories and control logging locations. The architecture provides a clear path for extension, allowing developers to introduce support for entirely new hook types by defining corresponding input, response, and handler methods that integrate with the existing dispatch mechanism. |