Agent Hooks and Policies
The Hedera Agent Kit provides a flexible and powerful system for putting limits on tool usage and enforcing business logic, effectively enabling you to limit the functionality of AI agents through Hooks and Policies. These hooks and policies can be used to enforce security, compliance, and other business rules.Table of Contents
Part 1: For Hooks and Policies Users
- Quick Overview
- When Hooks and Policies are Called
- How to Use Hooks and Policies
- Available Hooks
- Available Policies
Part 2: For Policy and Hook Developers
- Tool Lifecycle Deep Dive
- Hook Parameter Structures
- Hooks vs. Policies
- Type Safety & Multi-Tool Context
- Creating New Hooks/Policies
Part 1: For Hooks and Policies Users
Quick Overview
Hooks and Policies let you customize how tools behave:- Hooks: Extensions that observe and modify tool execution (logging, tracking, etc.)
- Policies: Validation rules that can block tool execution if certain conditions aren’t met
Only tools extending
BaseTool support hooks and policies. Tools that directly implement the basic Tool interface (the functional pattern) do not support these extensions. See Create JavaScript Plugins for instructions on using BaseTool.When Hooks and Policies are Called
Hooks can execute at 4 different points during a tool’s lifecycle:- Pre-Tool Execution - Before anything happens, when parameters are passed
- Post-Parameter Normalization - After parameters are validated and cleaned
- Post-Core Action - After the main logic executes (e.g., transaction created), before tool execution when a transaction has been formed
- Post-Tool Execution - After everything completes; after tool execution when a transaction has been signed and submitted
How to Use Hooks and Policies
Add hooks and policies to your agent’s context during initialization:Available Hooks
1. HcsAuditTrailHook (Hook)
1. HcsAuditTrailHook (Hook)
Description:
Provides an immutable audit trail by logging tool executions to a Hedera Consensus Service (HCS) topic.Prerequisites:
Provides an immutable audit trail by logging tool executions to a Hedera Consensus Service (HCS) topic.
Autonomous Mode Only: This hook is strictly available in
AUTONOMOUS mode. It will throw an error if used in
RETURN_BYTES mode.- Topic Creation: The HCS topic must be created before initializing the hook.
- Permissions: The Hedera account associated with the
loggingClient(or the agent’s operator account) must have permissions to submit messages to the topic (i.e., it must hold thesubmitKeyif one is defined).
relevantTools:string[]- List of tools to audit (e.g.,['transfer_hbar', 'create_token']).hcsTopicId:string- The pre-created Hedera topic ID (e.g.,'0.0.12345').loggingClient?:Client- (Optional) A separate Hedera client for logging. If not provided, defaults to the agent’s operator client. Must have submission access to the topic.
2. HolAuditTrailHook (Hook)
2. HolAuditTrailHook (Hook)
Description:
Hook that writes HOL-standards-compliant audit trails to an HCS session topic. It uses an HCS-2 INDEXED registry as the session topic to list audit entries.Prerequisites:
Hook that writes HOL-standards-compliant audit trails to an HCS session topic. It uses an HCS-2 INDEXED registry as the session topic to list audit entries.
Autonomous Mode Only: This hook is strictly available in
AUTONOMOUS mode. It will throw an error if used in
RETURN_BYTES mode.- Topic Creation: The HCS topic must be created before initializing the hook.
- Standard Compliance: To be fully compliant with the HCS-2 standard, the topic should be created with the memo
hcs-2:0:0.
relevantTools:string[]- List of tool names that trigger audit trail logging.sessionId:string- The Hedera topic ID (format0.0.xxx) used as the audit session registry.
Available Policies
1. MaxRecipientsPolicy (Policy)
1. MaxRecipientsPolicy (Policy)
Description:
A security policy that limits the number of recipients in transfer and airdrop operations. It blocks requests that exceed a defined threshold to prevent massive unauthorized transfers.Default Supported Tools: By default, the policy knows how to count recipients for:
A security policy that limits the number of recipients in transfer and airdrop operations. It blocks requests that exceed a defined threshold to prevent massive unauthorized transfers.Default Supported Tools: By default, the policy knows how to count recipients for:
transfer_hbartransfer_hbar_with_allowanceairdrop_fungible_tokentransfer_fungible_token_with_allowancetransfer_non_fungible_tokentransfer_non_fungible_token_with_allowance
maxRecipients:number- Maximum number of recipients allowed.additionalTools?:string[]- (Optional) Extra tools to apply this policy to.customStrategies?:Record<string, (params: any) => number>- (Optional) A mapping of tool names to functions that count recipients. If you add tools viaadditionalTools, you must provide a strategy for each one, otherwise the policy will throw an error at runtime.
2. RejectToolPolicy (Policy)
2. RejectToolPolicy (Policy)
Description:
A restrictive policy used to explicitly disable specific tools. Even if a tool is technically available in a plugin,
this policy ensures the agent cannot execute it under any circumstances.Parameters:
relevantTools:string[]- The list of tool methods to be blocked (e.g.,['delete_account', 'freeze_token']).
Part 2: For Policy and Hook Developers
Tool Lifecycle Deep Dive
Every tool in the kit follows a standardized 7-stage lifecycle.- Pre-Tool Execution: Before any processing begins. Use for early validation or logging.
- Parameter Normalization: The tool validates and cleans user input (not hookable).
- Post-Parameter Normalization: After parameters are normalized. Use for parameter-based validation.
- Core Action: Primary business logic executes (e.g., creating a transaction).
- Post-Core Action: After core logic completes. Use to inspect or modify the result before submission.
- Secondary Action: Transaction signing/submission happens (not hookable).
- Post-Tool Execution: After everything completes. Use for final logging or cleanup.
Hook Parameter Structures
Each hook receives specialized parameter objects and themethod name (string) representing the tool being
executed. This allows hooks to target specific tools or apply general logic.
| Hook Stage | Params Object Contains | Method Parameter | Use Case |
|---|---|---|---|
preToolExecutionHook | context, rawParams, client | method: string | Early validation, logging initial state |
postParamsNormalizationHook | context, rawParams, normalisedParams, client | method: string | Parameter-based policies, data enrichment |
postCoreActionHook | context, rawParams, normalisedParams, coreActionResult, client | method: string | Inspect/modify transaction before submission |
postToolExecutionHook | context, rawParams, normalisedParams, coreActionResult, toolResult, client | method: string | Final logging, audit trails, cleanup |
Hooks vs. Policies
Hooks (AbstractHook)
Hooks are non-blocking extensions that observe and modify execution flow. They can:
- Log data
- Modify context state
- Enrich parameters
- Track metrics
HcsAuditTrailHook logs execution details to an HCS topic without blocking.
Policies (AbstractPolicy)
Policies are specialized Hooks designed to validate and block execution. They use shouldBlock... methods that
return boolean values. If true is returned, the AbstractPolicy base class throws an error, immediately halting the tool’s
lifecycle.
Policy Implementation Rule: When creating a custom Policy, you should define logic in at least one of the
shouldBlock...
methods (e.g., shouldBlockPreToolExecution, shouldBlockPostParamsNormalization, etc.). While the tool won’t break
if they are undefined, the policy won’t perform any blocking logic. You must not override the native hook methods (
e.g., preToolExecutionHook) as the AbstractPolicy base class uses these internally to trigger the blocking logic and throw
errors.Type Safety & Multi-Tool Context
Hooks are configured for a specific set of tools (therelevantTools list). However, because AbstractHook is generic,
there is no compile-time type safety for parameters. When a hook targets multiple tools, you must handle the various
parameter structures using patterns like Universal Logic, Type Guards, or the Strategy Pattern.