
agent-kit-plugin
Comprehensive guides for extending the Hedera Agent Kit: creating BaseTool plugins, writing observation hooks, and writing blocking policies
- version
- 2.0.0
- GitHub stars
- 37
Install
/plugin install agent-kit-plugin@hedera-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add hedera-dev/hedera-skills.
Contents
Discovered from sourceSkills 4
Creating Hedera Agent Kit Hooks
Hooks are non-blocking extensions that run around the BaseTool lifecycle. They observe and can enrich execution: log calls, write audit trails, track metrics, persist state on Context. They do not block tool execution — that's the job of policies (see agent-kit-policy skill).
Hooks fire only for tools that extend
BaseTool. A tool that implements theToolinterface directly without extendingBaseToolbypasses the hook system entirely.
When to write a hook vs. a policy
| If you want to… | Use |
|---|---|
| Log/audit/track tool calls | Hook |
Enrich Context (counters, session state) | Hook |
| Stop a call from happening when a condition holds | Policy (see agent-kit-policy) |
| Reject specific tool methods | Policy |
Built-in hooks include HcsAuditTrailHook and HolAuditTrailHook (HCS-backed audit trails) — both live in @hashgraph/hedera-agent-kit/hooks.
The 7-stage lifecycle
BaseTool.execute() runs:
[1] preToolExecutionHook ← hook fires
[2] normalizeParams (tool internal)
[3] postParamsNormalizationHook ← hook fires
[4] coreAction (tool internal)
[5] postCoreActionHook ← hook fires
[6] secondaryAction (tool internal)
[7] postToolExecutionHook ← hook fires
Hooks tap into stages 1, 3, 5, 7. They never fire at stages 2, 4, 6.
For full param shapes at each stage see references/lifecycle.md.
AbstractHook contract
import { AbstractHook } from '@hashgraph/hedera-agent-kit';
export abstract class AbstractHook {
abstract name: string; // human-readable identifier
abstract description?: string; // what the hook does
abstract relevantTools: string[]; // tool methods this hook cares about
// Override only the stages you need; defaults are no-ops.
preToolExecutionHook(params, method): Promise<any>;
postParamsNormalizationHook(params, method): Promise<any>;
postCoreActionHook(params, method): Promise<any>;
postToolExecutionHook(params, method): Promise<any>;
}
Critical: the method signature is (params, method) — params is one of four typed objects, and context lives inside it (params.context). It is not a separate first argument.
| Stage | Params type | Notable fields |
|---|---|---|
| 1 | PreToolExecutionParams | context, rawParams, client |
| 3 | PostParamsNormalizationParams | + normalisedParams |
| 5 | PostCoreActionParams | + coreActionResult |
| 7 | PostSecondaryActionParams | + toolResult |
Skeleton
import {
AbstractHook,
Context,
PreToolExecutionParams,
PostSecondaryActionParams,
} from '@hashgraph/hedera-agent-kit';
export class MyHook extends AbstractHook {
name = 'My Hook';
description = 'What this hook does, in one sentence';
relevantTools = ['transfer_hbar', 'create_token'];
async preToolExecutionHook(params: PreToolExecutionParams, method: string) {
if (!this.relevantTools.includes(method)) return;
// ... your pre-execution logic ...
// params.context, params.rawParams, params.client
}
async postToolExecutionHook(params: PostSecondaryActionParams, method: string) {
if (!this.relevantTools.includes(method)) return;
// params.toolResult is the final tool output
}
}
The first line of every hook method should filter by relevantTools. The kit dispatches all hooks for all tool calls — relevantTools is informational unless you act on it.
Registering hooks
Hooks go on Context.hooks. The toolkit threads that context through to BaseTool.execute(), where the lifecycle dispatches them.
import { AgentMode } from '@hashgraph/hedera-agent-kit';
import { allCorePlugins } from '@hashgraph/hedera-agent-kit/plugins';
import { HederaLangchainToolkit } from '@hashgraph/hedera-agent-kit-langchain';
import { MyHook } from './my-hook';
const toolkit = new HederaLangchainToolkit({
client,
configuration: {
plugins: allCorePlugins,
context: {
mode: AgentMode.AUTONOMOUS,
hooks: [new MyHook()],
},
},
});
Multiple hooks can coexist — they run in array order at each stage. Policies (see agent-kit-policy) are also AbstractHook instances and go in the same array.
Multi-tool typing patterns
Hook params are generic (any) — the kit can't infer per-tool types because one hook can target many tools with different schemas. Three patterns:
1. Universal logic
When the hook is parameter-agnostic (counting calls, logging the whole payload as JSON):
async postToolExecutionHook(params: PostSecondaryActionParams, method: string) {
console.log(`[${method}]`, JSON.stringify(params.rawParams));
}
2. Type guards (small known set)
Switch on method, narrow with a cast or guard:
async postParamsNormalizationHook(
params: PostParamsNormalizationParams,
method: string,
) {
switch (method) {
case 'transfer_hbar':
case 'transfer_hbar_with_allowance': {
const p = params.normalisedParams as { transfers: Array<{ amount: number }> };
const total = p.transfers.reduce((s, t) => s + t.amount, 0);
console.log(`[${method}] total HBAR: ${total}`);
break;
}
}
}
3. Strategy map (pluggable, third-party tools)
Accept a Record<string, (params: any) => SomeResult> in the constructor. Validate each additionalTool has a strategy, throw at construction time if missing. This is the pattern used by MaxRecipientsPolicy.
State on Context
params.context is the same Context instance for the whole agent run. Use it as a per-session scratchpad:
async preToolExecutionHook(params: PreToolExecutionParams, method: string) {
if (!this.relevantTools.includes(method)) return;
const counts = ((params.context as any).callCounts ??= {} as Record<string, number>);
counts[method] = (counts[method] ?? 0) + 1;
}
(Context is structurally typed; cast to attach ad-hoc state. If you publish the hook, document the keys you write.)
Best practices
- Filter by
relevantToolsat the top of every method — cheap and idiomatic - Wrap in
try/catchif the hook does I/O (HCS write, HTTP) — a thrown hook aborts the whole tool call - Keep hooks lightweight — they sit on the hot path
- Don't block — if you need to stop execution, write a policy
- Don't mutate
rawParamsornormalisedParamsunless you really mean to; subsequent hooks see your changes - Use
descriptionto document side-effects (HCS topic writes, external API calls) so policy authors / agent operators know what the hook does - Tag log lines with
[<hook-name>]for easy grep
Resources
references/hook-interface.md— full param-type definitions, all four hook stagesreferences/lifecycle.md— what fires when, aroundBaseTool'snormalizeParams/coreAction/secondaryActionexamples/tx-timing-hook/— minimal hook that times tool execution and logs duration
Common imports
import {
AbstractHook,
Context,
PreToolExecutionParams,
PostParamsNormalizationParams,
PostCoreActionParams,
PostSecondaryActionParams,
} from '@hashgraph/hedera-agent-kit';
// Built-in implementations live in the /hooks subpath
import { HcsAuditTrailHook, HolAuditTrailHook } from '@hashgraph/hedera-agent-kit/hooks';
Creating Hedera Agent Kit Plugins
This skill provides guidance for creating custom plugins that extend the Hedera Agent Kit. Plugins allow adding new tools for Hedera network interactions—token operations, account management, consensus service, smart contracts, and custom integrations.
Quick Start
To create a Hedera plugin in 5 steps:
- Install dependencies: Set up a TypeScript project with
@hashgraph/hedera-agent-kitand@hiero-ledger/sdk - Create plugin structure: Create an
index.tswith the plugin definition and atools/directory - Define tools: Each tool is a class extending
BaseTool— this opts the tool into the hooks/policies lifecycle - Export properly: Export the plugin object and tool name constants
- Register with agent: Import and pass the plugin in the toolkit
configuration.pluginsarray
Plugin Interface
Every Hedera plugin implements this interface from @hashgraph/hedera-agent-kit:
import { Plugin } from '@hashgraph/hedera-agent-kit';
export interface Plugin {
name: string; // Unique kebab-case identifier
version?: string; // Semantic version (e.g., "1.0.0")
description?: string; // Brief explanation of plugin purpose
tools: (context: Context) => Tool[]; // Factory returning tools
}
The tools function receives a Context object containing network configuration and returns an array of Tool objects. BaseTool itself implements Tool, so a BaseTool subclass instance is a valid return value.
BaseTool
Tools are written as classes extending BaseTool, which implements Tool and runs a 7-stage lifecycle:
[1] preToolExecutionHook
[2] normalizeParams ← your logic
[3] postParamsNormalizationHook
[4] coreAction ← your logic
[5] postCoreActionHook
[6] secondaryAction ← your logic (skipped via shouldSecondaryAction for queries)
[7] postToolExecutionHook
Hooks and policies registered on the agent kit fire at stages 1, 3, 5, and 7 automatically — you never call them manually.
A subclass must provide:
| Member | Type | Notes |
|---|---|---|
method | string | Snake-case identifier with _tool suffix |
name | string | Human-readable display name |
description | string | LLM-facing description (typically built in the constructor from a prompt function) |
parameters | z.ZodObject | Zod schema for input validation |
normalizeParams(params, context, client) | async | Stage 2 — resolve defaults, validate format |
coreAction(normalised, context, client) | async | Stage 4 — build the transaction or perform the query |
secondaryAction(request, client, context) | async | Stage 6 — sign/submit the transaction (no-op for queries) |
Optional overrides: outputParser, shouldSecondaryAction (return false for query-only tools), handleError, and the four hook methods.
Tool Types
Mutation tools — state-changing operations (token create/mint/transfer, account update, topic submit). coreAction builds the Transaction, secondaryAction calls handleTransaction(). Use transactionToolOutputParser.
Query tools — read-only operations (token info, balances, mirror-node fetches). coreAction returns the result directly. Override shouldSecondaryAction to return false. Use untypedQueryOutputParser.
File Structure Pattern
Follow this structure for all Hedera plugins:
my-hedera-plugin/
├── index.ts # Plugin definition and exports
└── tools/
└── category/ # Group related tools
├── create-something.ts
└── get-something.ts
Creating a Tool
Step 1: Define the Tool Constant
export const MY_TOOL_NAME = 'my_tool_name_tool';
Use UPPER_SNAKE_CASE with _TOOL suffix for the constant. The value should be lowercase snake_case.
Step 2: Create the Prompt Function
const myToolPrompt = (context: Context = {}) => {
return `This tool does X on Hedera.
Parameters:
- param1 (str, required): Description of param1
- param2 (int, optional): Description of param2, defaults to 0`;
};
Step 3: Define Parameters with Zod
import { z } from 'zod';
const myToolParameters = (_context: Context = {}) => {
return z.object({
param1: z.string().describe('Description of param1'),
param2: z.number().optional().describe('Description of param2'),
});
};
type MyToolParams = z.infer<ReturnType<typeof myToolParameters>>;
See references/zod-schema-patterns.md for common Hedera parameter patterns.
Step 4: Implement the BaseTool subclass (mutation example)
import { Client, Status } from '@hiero-ledger/sdk';
import {
BaseTool,
Context,
handleTransaction,
RawTransactionResponse,
transactionToolOutputParser,
} from '@hashgraph/hedera-agent-kit';
const postProcess = (response: RawTransactionResponse) =>
`Operation completed.
Transaction ID: ${response.transactionId}`;
export class MyTool extends BaseTool<MyToolParams, MyToolParams> {
method = MY_TOOL_NAME;
name = 'My Tool Display Name';
description: string;
parameters: ReturnType<typeof myToolParameters>;
outputParser = transactionToolOutputParser;
constructor(context: Context) {
super();
this.description = myToolPrompt(context);
this.parameters = myToolParameters(context);
}
// Stage 2 — resolve defaults
async normalizeParams(params: MyToolParams) {
return params;
}
// Stage 4 — build the transaction (do not sign here)
async coreAction(params: MyToolParams, _context: Context, _client: Client) {
// return new SomeTransaction()...;
return undefined as any;
}
// Stage 6 — sign and submit
async secondaryAction(transaction: any, client: Client, context: Context) {
return handleTransaction(transaction, client, context, postProcess);
}
async handleError(error: unknown) {
const message = 'Failed to execute' + (error instanceof Error ? `: ${error.message}` : '');
console.error(`[${MY_TOOL_NAME}]`, message);
return { raw: { status: Status.InvalidTransaction, error: message }, humanMessage: message };
}
}
Step 5: Export a Factory
const tool = (context: Context): BaseTool => new MyTool(context);
export default tool;
The factory pattern lets the plugin's tools(context) function instantiate a fresh tool per request with the right context bound.
Query-tool variant — skip stage 6
For read-only tools, override shouldSecondaryAction so the lifecycle stops after coreAction, and have secondaryAction pass the result through unchanged:
export class MyQueryTool extends BaseTool<MyToolParams, MyToolParams> {
// ... method/name/description/parameters as above ...
outputParser = untypedQueryOutputParser;
async normalizeParams(params: MyToolParams) {
return params;
}
async coreAction(params: MyToolParams, _context: Context, client: Client) {
return await someHederaQuery(params, client);
}
async shouldSecondaryAction() {
return false;
}
async secondaryAction(result: any) {
return result;
}
}
Creating the Plugin Index
import { Context, Plugin } from '@hashgraph/hedera-agent-kit';
import myTool, { MY_TOOL_NAME } from './tools/category/my-tool';
export const myPlugin: Plugin = {
name: 'my-hedera-plugin',
version: '1.0.0',
description: 'A plugin for custom Hedera operations',
tools: (context: Context) => {
return [
myTool(context),
];
},
};
export const myPluginToolNames = {
MY_TOOL_NAME,
} as const;
export default { myPlugin, myPluginToolNames };
Post-Processing Results
secondaryAction typically delegates to handleTransaction, which calls a postProcess function with the raw transaction response:
const postProcess = (response: RawTransactionResponse) => {
if (response.scheduleId) {
return `Scheduled transaction created.
Transaction ID: ${response.transactionId}
Schedule ID: ${response.scheduleId.toString()}`;
}
return `Operation completed.
Transaction ID: ${response.transactionId}`;
};
RETURN_BYTES mode — raw.bytes is a Uint8Array
When a tool runs in RETURN_BYTES mode, raw.bytes returned by ResponseParserService is always a plain Uint8Array in both Node.js and browser environments. Pass it directly to Transaction.fromBytes() — no manual conversion is needed.
const bytes = toolCall.parsedData.raw.bytes;
const tx = Transaction.fromBytes(bytes);
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Plugin name | kebab-case | my-token-plugin |
| Plugin variable | camelCase | myTokenPlugin |
| Tool class | PascalCase + Tool | CreateTokenTool |
| Tool constant | UPPER_SNAKE_CASE + _TOOL | CREATE_TOKEN_TOOL |
| Tool method value | snake_case + _tool | create_token_tool |
| Tool file | kebab-case | create-token.ts |
| Tool names export | camelCase + ToolNames | myTokenPluginToolNames |
Common Imports
// From @hashgraph/hedera-agent-kit (core)
import {
Context,
Plugin,
BaseTool,
handleTransaction,
RawTransactionResponse,
transactionToolOutputParser,
untypedQueryOutputParser,
} from '@hashgraph/hedera-agent-kit';
// Built-in plugins live in the /plugins subpath
import { coreTokenPlugin, coreAccountPlugin } from '@hashgraph/hedera-agent-kit/plugins';
// Hedera SDK is a peer dependency
import { Client, Status } from '@hiero-ledger/sdk';
// For parameter validation
import { z } from 'zod';
Additional Resources
Reference Files
For detailed patterns and techniques, consult:
references/plugin-interface.md- Plugin interface,BaseToollifecycle in depthreferences/zod-schema-patterns.md- Common Zod schemas for Hedera parametersreferences/prompt-patterns.md- Prompt generation patterns for tool descriptionsreferences/error-handling.md- Error handling and output parsing patterns
Example Files
Working examples in examples/:
examples/simple-plugin/- MinimalBaseToolquery (starter template)examples/token-plugin/- Mutation (CreateTokenTool) and query (GetTokenInfoTool)BaseToolsubclasses
Best Practices
- One file per tool, named after the tool in kebab-case
- Group related tools under category directories in
tools/ - Stable class names:
<DoesWhat>Tool(e.g.,CreateTokenTool) - Resolve defaults in
normalizeParams, not incoreAction— keeps the build step pure - Build, don't submit, in
coreAction— submission belongs insecondaryActionwhere hooks can react - Override
handleErrorso logs are tagged with the tool method - Validate with Zod's
.describe()— every field; descriptions guide the agent - Export tool name constants so consumers can reference tools programmatically
Registering a Plugin with a Toolkit
Plugins are passed explicitly to the toolkit you choose. Toolkits live in dedicated packages — pick the one that matches your framework:
| Framework | Toolkit package |
|---|---|
| LangChain | @hashgraph/hedera-agent-kit-langchain |
| Vercel AI SDK | @hashgraph/hedera-agent-kit-ai-sdk |
| ElizaOS | @hashgraph/hedera-agent-kit-elizaos |
| MCP | @hashgraph/hedera-agent-kit-mcp |
Empty
pluginsarray means zero tools. List every plugin you need explicitly, or useallCorePluginsfrom the/pluginssubpath to load every built-in core plugin at once.
import { Client, PrivateKey } from '@hiero-ledger/sdk';
import { AgentMode } from '@hashgraph/hedera-agent-kit';
import { coreTokenPlugin, coreAccountPlugin } from '@hashgraph/hedera-agent-kit/plugins';
import { HederaLangchainToolkit } from '@hashgraph/hedera-agent-kit-langchain';
import { myPlugin } from './my-hedera-plugin';
const client = Client.forTestnet().setOperator(
process.env.ACCOUNT_ID!,
PrivateKey.fromStringECDSA(process.env.PRIVATE_KEY!),
);
const toolkit = new HederaLangchainToolkit({
client,
configuration: {
plugins: [coreTokenPlugin, coreAccountPlugin, myPlugin],
context: { mode: AgentMode.AUTONOMOUS },
},
});
const tools = toolkit.getTools();
To load every built-in core plugin at once, import allCorePlugins:
import { allCorePlugins } from '@hashgraph/hedera-agent-kit/plugins';
// ...
plugins: [...allCorePlugins, myPlugin],
Workflow Summary
- Create plugin directory with
index.tsandtools/subdirectory - For each tool, write a
BaseToolsubclass and a factory function in its own file - Export tools from
index.tsalong with tool name constants - Pass the plugin in the toolkit's
configuration.pluginsarray - Tools become available to the AI agent
For complete working examples, see the examples/ directory.
Creating Hedera Agent Kit Policies
Policies are blocking validation rules layered on the BaseTool lifecycle. A policy checks the call at one or more stages and throws to abort execution — the error propagates back to the LLM agent. Use them to enforce thresholds, allowlists/blocklists, rate limits, business hours, compliance rules, etc.
Policies fire only for tools that extend
BaseTool. A tool that implements theToolinterface directly without extendingBaseToolbypasses policies entirely.
Policy vs. hook
| Goal | Use |
|---|---|
| Stop a call when a condition holds | Policy (this skill) |
| Reject specific tool methods | Policy |
| Threshold / rate-limit / allowlist / blocklist | Policy |
| Log, audit, enrich context | Hook (see agent-kit-hook skill) |
AbstractPolicy extends AbstractHook, so policies live in the same Context.hooks array and run through the same lifecycle.
Built-in policies live in @hashgraph/hedera-agent-kit/policies:
RejectToolPolicy(relevantTools: string[])— blocks the listed tool methods unconditionallyMaxRecipientsPolicy(maxRecipients, additionalTools?, customStrategies?)— caps recipient count for transfer/airdrop tools
How blocking actually works
You never override preToolExecutionHook or any of the other *Hook methods on a policy — those are wired up by the base class to call your shouldBlock... method and throw if it returns true.
Override one or more of these instead:
abstract class AbstractPolicy extends AbstractHook {
abstract name: string;
abstract description?: string;
abstract relevantTools: string[];
protected shouldBlockPreToolExecution(params, method): boolean | Promise<boolean>;
protected shouldBlockPostParamsNormalization(params, method): boolean | Promise<boolean>;
protected shouldBlockPostCoreAction(params, method): boolean | Promise<boolean>;
protected shouldBlockPostSecondaryAction(params, method): boolean | Promise<boolean>;
}
Defaults all return false (allow). Returning true causes the base class to throw a generic block error. Throwing your own error from shouldBlock... lets you control the message.
Don't override
preToolExecutionHooketc. — those are@internalonAbstractPolicy. They drive the block flow. If you override them, your policy will never block.
Picking the stage
| Stage | What's available | Good for |
|---|---|---|
shouldBlockPreToolExecution | rawParams only | allowlist/blocklist by tool method, time-based, rate limits |
shouldBlockPostParamsNormalization | + normalisedParams | thresholds on resolved values, recipient counts |
shouldBlockPostCoreAction | + coreActionResult | inspect the built Transaction before submission |
shouldBlockPostSecondaryAction | + toolResult | very rare — call already executed; usually too late to "block" |
Most policies live at stage 1 (cheapest) or stage 3 (after defaults are filled in).
Skeleton
import {
AbstractPolicy,
PreToolExecutionParams,
PostParamsNormalizationParams,
} from '@hashgraph/hedera-agent-kit';
export class MyPolicy extends AbstractPolicy {
name = 'My Policy';
description = 'What this policy blocks, in one sentence';
relevantTools = ['transfer_hbar', 'transfer_fungible_token'];
// Stage 1 — block by raw input or method
protected shouldBlockPreToolExecution(
params: PreToolExecutionParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
// throw new Error('<custom message>') for tailored errors
return /* condition */ false;
}
// Stage 3 — block on resolved/normalised values
protected shouldBlockPostParamsNormalization(
params: PostParamsNormalizationParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
return /* condition */ false;
}
}
relevantTools is informational unless you check it — the kit dispatches your policy for every tool call. Always filter by method first thing in the method.
Registering policies
Policies are AbstractHook instances. They go in the same Context.hooks array as observation hooks:
import { AgentMode } from '@hashgraph/hedera-agent-kit';
import { allCorePlugins } from '@hashgraph/hedera-agent-kit/plugins';
import { RejectToolPolicy, MaxRecipientsPolicy } from '@hashgraph/hedera-agent-kit/policies';
import { HederaLangchainToolkit } from '@hashgraph/hedera-agent-kit-langchain';
import { MyPolicy } from './my-policy';
const toolkit = new HederaLangchainToolkit({
client,
configuration: {
plugins: allCorePlugins,
context: {
mode: AgentMode.AUTONOMOUS,
hooks: [
new RejectToolPolicy(['delete_account', 'freeze_token']),
new MaxRecipientsPolicy(5),
new MyPolicy(),
],
},
},
});
Policies run in array order at each stage — the first one to return true (or throw) wins.
Common patterns
Threshold
protected shouldBlockPostParamsNormalization(
params: PostParamsNormalizationParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
const p = params.normalisedParams as { amount?: number };
return (p.amount ?? 0) > this.maxAmount;
}
Allowlist / Blocklist
protected shouldBlockPreToolExecution(
params: PreToolExecutionParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
const accountId = (params.rawParams as { accountId?: string }).accountId;
return accountId !== undefined && this.blockedAccounts.has(accountId);
}
Time-based
protected shouldBlockPreToolExecution(
_params: PreToolExecutionParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
const hour = new Date().getUTCHours();
return hour < 9 || hour > 17; // outside business hours
}
Rate limiting (uses Context as scratchpad)
protected shouldBlockPreToolExecution(
params: PreToolExecutionParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
const counters = ((params.context as any).__rateCounts ??= {} as Record<string, number>);
counters[method] = (counters[method] ?? 0) + 1;
return counters[method] > this.maxCallsPerSession;
}
Strategy map (pluggable for custom tools)
When a single policy needs to support tools the kit doesn't know about, accept a Record<string, (params) => SomeMetric> and validate that every tool added via additionalTools has a strategy. This is the pattern of MaxRecipientsPolicy:
constructor(
private maxRecipients: number,
additionalTools: string[] = [],
private customStrategies: Record<string, (p: any) => number> = {},
) {
super();
this.relevantTools = [...DEFAULT_TOOLS, ...additionalTools];
for (const tool of additionalTools) {
if (!this.customStrategies[tool]) {
throw new Error(`Custom tool "${tool}" requires a strategy function`);
}
}
}
Custom error messages
The default block error is generic. To control the message, throw from your shouldBlock... method instead of returning true:
protected shouldBlockPostParamsNormalization(
params: PostParamsNormalizationParams,
method: string,
): boolean {
if (!this.relevantTools.includes(method)) return false;
const p = params.normalisedParams as { amount?: number };
if ((p.amount ?? 0) > this.maxAmount) {
throw new Error(
`[max-amount-policy] Refusing ${method}: amount ${p.amount} exceeds limit ${this.maxAmount}`,
);
}
return false;
}
The agent receives the thrown message verbatim — make it informative.
Best practices
- Filter by
relevantToolsat the top of everyshouldBlock...method - Pick the earliest stage that has the data you need — stage 1 is cheapest
- Throw with a clear message when blocking; the LLM sees this
- Don't override
*Hookmethods — onlyshouldBlock... - Don't do I/O on the hot path unless you must — policies run synchronously in the lifecycle
- Document
relevantToolsdefaults so consumers understand what your policy guards - Tag the error message with
[<policy-name>]for easy log correlation
Resources
references/policy-interface.md— fullAbstractPolicycontract, when eachshouldBlockfiresexamples/max-amount-policy/— threshold policy that blocks transfers above a cap
Common imports
import {
AbstractPolicy,
Context,
PreToolExecutionParams,
PostParamsNormalizationParams,
PostCoreActionParams,
PostSecondaryActionParams,
} from '@hashgraph/hedera-agent-kit';
// Built-in implementations live in the /policies subpath
import { RejectToolPolicy, MaxRecipientsPolicy } from '@hashgraph/hedera-agent-kit/policies';
Migrating Hedera Agent Kit v3 → v4
This skill drives a complete v3 → v4 migration. v4 is the current major; v3 (hedera-agent-kit@3.x) no longer receives updates. Use this skill whenever you see code importing from hedera-agent-kit (unscoped) or @hashgraph/sdk.
Quick triage — what kind of v3 code is this?
Before editing anything, classify the file you are migrating. The migration steps differ.
| If the file… | It's a… | Apply |
|---|---|---|
Defines a Plugin and exports tool factories that return object literals with an execute function | Custom plugin | Plugin migration + BaseTool migration |
Calls new HederaLangchainToolkit / HederaAIToolkit / HederaElizaOSToolkit / HederaMCPToolkit | Toolkit consumer | Toolkit migration |
Imports plugins like coreTokenPlugin, coreAccountPlugin, coreHTSPlugin | Toolkit consumer (uses built-in plugins) | Toolkit migration + alias rename |
Imports ResponseParserService or HederaMCPServer from hedera-agent-kit | Toolkit consumer | Toolkit migration (these moved to toolkit packages) |
| Both | Run toolkit migration first, then plugin migration for each tool |
Migration workflow
Step 1 — find every v3 entry point
Run these searches at the project root before editing anything. They give you the migration surface in one shot:
# Old package name in source and dependency manifests
grep -rn "from ['\"]hedera-agent-kit" .
grep -n '"hedera-agent-kit"' package.json
# Old SDK package
grep -rn "from ['\"]@hashgraph/sdk" .
grep -n '"@hashgraph/sdk"' package.json
# Deprecated plugin aliases
grep -rn "coreHTSPlugin\|coreSCSPlugin\|coreQueriesPlugin" .
# Old subpath import
grep -rn "from ['\"]hedera-agent-kit/elizaos" .
# v3 functional Tool pattern (object literal with execute)
grep -rn "execute: " . --include="*.ts" | grep -i "tool"
Build a list of files to edit; do not start mutating yet.
Step 2 — update package.json
Replace dependencies, then run install. See references/breaking-changes.md § "Package mapping" for the complete table and § "Versioning" for version ranges. Quick form:
- Remove:
hedera-agent-kit,@hashgraph/sdk. Drop@langchain/core,langchain,@langchain/langgraph,aionly if your code never imports from them directly — they are transitive deps of the toolkit, so package managers with strict resolution (bun, pnpm) won't satisfy direct imports unless you keep them. When in doubt, keep them as devDeps. - Add:
@hashgraph/hedera-agent-kit(use^4.0.0) and@hiero-ledger/sdk(use^2.81.0), plus exactly one toolkit package for your framework. Toolkit packages are NOT on^4— they re-baselined at1.0.0for this release. Use^1.0.0for@hashgraph/hedera-agent-kit-langchain/-ai-sdk/-elizaos/-mcp. Runnpm view <pkg> versionto confirm before pinning. - Keep: the LLM provider (
@langchain/openai,@ai-sdk/openai,@langchain/anthropic, etc.) — toolkits never bundle providers. LangChain consumers must also bump the provider package to its1.xline (e.g.@langchain/openai@^1); the0.xline depends on@langchain/core@^0.3and produces dual-package type errors against the toolkit's@langchain/core@^1. Seereferences/breaking-changes.md§ "LangChain ecosystem bump".
Step 3 — rewrite imports
Apply the find-and-replace map from references/import-cheatsheet.md. Key moves:
- from 'hedera-agent-kit' → from '@hashgraph/hedera-agent-kit'
- from '@hashgraph/sdk' → from '@hiero-ledger/sdk'
- from 'hedera-agent-kit/elizaos' → from '@hashgraph/hedera-agent-kit-elizaos'
Plugins must come from the /plugins subpath:
- import { coreTokenPlugin } from 'hedera-agent-kit'
+ import { coreTokenPlugin } from '@hashgraph/hedera-agent-kit/plugins'
Rename deprecated aliases:
| Removed | Replacement |
|---|---|
coreHTSPlugin | coreTokenPlugin |
coreSCSPlugin | coreEVMPlugin |
coreQueriesPlugin | Individual plugins: coreAccountQueryPlugin, coreTokenQueryPlugin, coreConsensusQueryPlugin, coreEVMQueryPlugin, coreMiscQueriesPlugin, coreTransactionQueryPlugin |
Toolkits and their helpers each moved to a dedicated package:
- import { HederaLangchainToolkit, ResponseParserService } from 'hedera-agent-kit'
+ import { HederaLangchainToolkit, ResponseParserService } from '@hashgraph/hedera-agent-kit-langchain'
- import { HederaAIToolkit } from 'hedera-agent-kit'
+ import { HederaAIToolkit } from '@hashgraph/hedera-agent-kit-ai-sdk'
- import { HederaMCPToolkit } from 'hedera-agent-kit'
+ import { HederaMCPToolkit } from '@hashgraph/hedera-agent-kit-mcp'
AgentMode, Configuration, Context, Plugin, Tool, BaseTool, handleTransaction, output parsers, mirrornode types — all stay in @hashgraph/hedera-agent-kit.
Step 4 — fix the silent behaviour change in toolkit configuration
In v3 an empty plugins: [] may have loaded default tools. In v4, empty means zero tools. This will not throw — the agent will silently have nothing to call. Audit every toolkit construction:
// v4: pass plugins explicitly
import { allCorePlugins } from '@hashgraph/hedera-agent-kit/plugins';
new HederaLangchainToolkit({
client,
configuration: {
plugins: allCorePlugins, // or list specific plugins
context: { mode: AgentMode.AUTONOMOUS },
},
});
Use allCorePlugins to preserve v3's "everything" default. Prefer explicit lists when the user wants a smaller tool surface; bundlers tree-shake either way.
Step 5 — handle RETURN_BYTES consumers
If any code reads parsedData.raw.bytes from ResponseParserService and converts it (e.g. Buffer.isBuffer(...), Buffer.from(obj.data)), delete the conversion. v4 standardises raw.bytes to Uint8Array everywhere; passing it directly to Transaction.fromBytes() works in Node and browser. See references/breaking-changes.md § "RETURN_BYTES".
Step 6 — migrate every custom plugin tool to BaseTool
BaseTool is the supported shape for tools in v4. Every custom tool must be migrated — the v3 functional pattern (object literal with an execute function) is no longer the supported authoring style and bypasses the hooks/policies system (HcsAuditTrailHook, MaxRecipientsPolicy, RejectToolPolicy, and any subclass of AbstractHook/AbstractPolicy). Migrate every tool the plugin exports; do not leave a mix of old- and new-style tools.
Full step-by-step recipe with annotated before/after: references/basetool-migration.md.
Mechanical summary:
- Replace
import type { Tool }withimport { BaseTool }from@hashgraph/hedera-agent-kit. - Rewrite the factory:
(context: Context): Tool => ({ ... execute })becomes a class extendingBaseTooland a one-line factory(context) => new MyTool(context). - Split the body of the old
executefunction into:normalizeParams(resolve defaults, validate format)coreAction(build theTransactionfor mutations, fetch the data for queries)secondaryAction(callhandleTransaction(...)for mutations; pass-through for queries)
- For query-only tools, override
shouldSecondaryActionto returnfalseand provide a no-opsecondaryAction. - Move the
try/catchbody into anhandleError(error, context)override (BaseTool calls it from any failed stage). - Keep the factory return type
BaseTool—Plugin.tools()accepts it directly.
The example under examples/transfer-hbar-migration/ shows the full transformation on the canonical transfer_hbar tool.
Step 7 — verify
After mutating files, run in this order:
npm install(orbun install/pnpm install) — confirmspackage.jsonresolves. Watch for "no version matching X" errors; toolkit packages are on^1, not^4.tsc --noEmit(ornpm run build) — picks up missing imports and type drifts (e.g.setTreasuryAccountIdcomplaining because a normalised type was not declared, ornoImplicitOverridecomplaining about a missingoverridekeyword onhandleError/secondaryAction).- For LangChain consumers, type errors mentioning two different
@langchain/corepaths (one nested under your provider package, one nested under the toolkit) indicate a dual-package situation — the provider package is still on0.x. Bump it to1.xper Step 2. - For LangChain consumers, errors like
Cannot find module 'langchain/agents'or'langchain/memory'indicate the legacyAgentExecutor/BufferMemorypattern — these subpaths were removed inlangchain@1.x. The fix is a separate framework migration tocreateReactAgentfrom@langchain/langgraph/prebuilt. Seereferences/breaking-changes.md§ "LangChain ecosystem bump". - Smoke-test the agent: instantiate the toolkit, list tools (
toolkit.getTools().lengthmust be > 0), invoke one tool end-to-end. A passing build does not prove the migration worked — the empty-plugins-array footgun is type-safe and silent.
What this skill does NOT cover
- Solidity / system-contracts migration — see the
system-contractsplugin. - Native JS SDK changes inside
@hiero-ledger/sdkitself — only the import path changes; the API surface remained stable across the rename. - Plugin authoring patterns from scratch — see the
agent-kit-pluginskill. - Writing new hooks/policies — see
agent-kit-hookandagent-kit-policyskills. Migration toBaseToolis the prerequisite for those features. - LangChain framework migration (
AgentExecutor→createReactAgent,BufferMemory→messages-based history). The v4 LangChain toolkit forces a bump tolangchain@1.x, which removes these APIs, but rewriting the agent setup is a LangChain-side concern.references/breaking-changes.md§ "LangChain ecosystem bump" sketches the shape of the change; consult LangChain's own migration guide for details.
Reference index
references/breaking-changes.md— every breaking change, package mapping, install commands, version-bump notes.references/import-cheatsheet.md— flat find-and-replace table; load this when sweeping files.references/basetool-migration.md— annotated before/after for converting one tool from theToolobject literal to aBaseToolsubclass, including the query-only variant.examples/transfer-hbar-migration/—before-v3.tsandafter-v4.tsof the same tool, side by side, with aREADME.mdwalking through every change.
Sponsors
Details
- Marketplace
- hedera-dev/hedera-skills
- Source
- plugins/agent-kit-plugin
- Author
- Hedera Dev
- Category
- Development
- Keywords
- hedera, agent-kit, plugin, tools, hooks, policies, blockchain