hedera-dev avatar

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-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add hedera-dev/hedera-skills.

Contents

Discovered from source

Skills 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 the Tool interface directly without extending BaseTool bypasses the hook system entirely.

When to write a hook vs. a policy

If you want to…Use
Log/audit/track tool callsHook
Enrich Context (counters, session state)Hook
Stop a call from happening when a condition holdsPolicy (see agent-kit-policy)
Reject specific tool methodsPolicy

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.

StageParams typeNotable fields
1PreToolExecutionParamscontext, rawParams, client
3PostParamsNormalizationParams+ normalisedParams
5PostCoreActionParams+ coreActionResult
7PostSecondaryActionParams+ 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

  1. Filter by relevantTools at the top of every method — cheap and idiomatic
  2. Wrap in try/catch if the hook does I/O (HCS write, HTTP) — a thrown hook aborts the whole tool call
  3. Keep hooks lightweight — they sit on the hot path
  4. Don't block — if you need to stop execution, write a policy
  5. Don't mutate rawParams or normalisedParams unless you really mean to; subsequent hooks see your changes
  6. Use description to document side-effects (HCS topic writes, external API calls) so policy authors / agent operators know what the hook does
  7. Tag log lines with [<hook-name>] for easy grep

Resources

  • references/hook-interface.md — full param-type definitions, all four hook stages
  • references/lifecycle.md — what fires when, around BaseTool's normalizeParams/coreAction/secondaryAction
  • examples/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:

  1. Install dependencies: Set up a TypeScript project with @hashgraph/hedera-agent-kit and @hiero-ledger/sdk
  2. Create plugin structure: Create an index.ts with the plugin definition and a tools/ directory
  3. Define tools: Each tool is a class extending BaseTool — this opts the tool into the hooks/policies lifecycle
  4. Export properly: Export the plugin object and tool name constants
  5. Register with agent: Import and pass the plugin in the toolkit configuration.plugins array

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:

MemberTypeNotes
methodstringSnake-case identifier with _tool suffix
namestringHuman-readable display name
descriptionstringLLM-facing description (typically built in the constructor from a prompt function)
parametersz.ZodObjectZod schema for input validation
normalizeParams(params, context, client)asyncStage 2 — resolve defaults, validate format
coreAction(normalised, context, client)asyncStage 4 — build the transaction or perform the query
secondaryAction(request, client, context)asyncStage 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

ElementConventionExample
Plugin namekebab-casemy-token-plugin
Plugin variablecamelCasemyTokenPlugin
Tool classPascalCase + ToolCreateTokenTool
Tool constantUPPER_SNAKE_CASE + _TOOLCREATE_TOKEN_TOOL
Tool method valuesnake_case + _toolcreate_token_tool
Tool filekebab-casecreate-token.ts
Tool names exportcamelCase + ToolNamesmyTokenPluginToolNames

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, BaseTool lifecycle in depth
  • references/zod-schema-patterns.md - Common Zod schemas for Hedera parameters
  • references/prompt-patterns.md - Prompt generation patterns for tool descriptions
  • references/error-handling.md - Error handling and output parsing patterns

Example Files

Working examples in examples/:

  • examples/simple-plugin/ - Minimal BaseTool query (starter template)
  • examples/token-plugin/ - Mutation (CreateTokenTool) and query (GetTokenInfoTool) BaseTool subclasses

Best Practices

  1. One file per tool, named after the tool in kebab-case
  2. Group related tools under category directories in tools/
  3. Stable class names: <DoesWhat>Tool (e.g., CreateTokenTool)
  4. Resolve defaults in normalizeParams, not in coreAction — keeps the build step pure
  5. Build, don't submit, in coreAction — submission belongs in secondaryAction where hooks can react
  6. Override handleError so logs are tagged with the tool method
  7. Validate with Zod's .describe() — every field; descriptions guide the agent
  8. 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:

FrameworkToolkit 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 plugins array means zero tools. List every plugin you need explicitly, or use allCorePlugins from the /plugins subpath 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

  1. Create plugin directory with index.ts and tools/ subdirectory
  2. For each tool, write a BaseTool subclass and a factory function in its own file
  3. Export tools from index.ts along with tool name constants
  4. Pass the plugin in the toolkit's configuration.plugins array
  5. 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 the Tool interface directly without extending BaseTool bypasses policies entirely.

Policy vs. hook

GoalUse
Stop a call when a condition holdsPolicy (this skill)
Reject specific tool methodsPolicy
Threshold / rate-limit / allowlist / blocklistPolicy
Log, audit, enrich contextHook (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 unconditionally
  • MaxRecipientsPolicy(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 preToolExecutionHook etc. — those are @internal on AbstractPolicy. They drive the block flow. If you override them, your policy will never block.

Picking the stage

StageWhat's availableGood for
shouldBlockPreToolExecutionrawParams onlyallowlist/blocklist by tool method, time-based, rate limits
shouldBlockPostParamsNormalization+ normalisedParamsthresholds on resolved values, recipient counts
shouldBlockPostCoreAction+ coreActionResultinspect the built Transaction before submission
shouldBlockPostSecondaryAction+ toolResultvery 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

  1. Filter by relevantTools at the top of every shouldBlock... method
  2. Pick the earliest stage that has the data you need — stage 1 is cheapest
  3. Throw with a clear message when blocking; the LLM sees this
  4. Don't override *Hook methods — only shouldBlock...
  5. Don't do I/O on the hot path unless you must — policies run synchronously in the lifecycle
  6. Document relevantTools defaults so consumers understand what your policy guards
  7. Tag the error message with [<policy-name>] for easy log correlation

Resources

  • references/policy-interface.md — full AbstractPolicy contract, when each shouldBlock fires
  • examples/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 functionCustom pluginPlugin migration + BaseTool migration
Calls new HederaLangchainToolkit / HederaAIToolkit / HederaElizaOSToolkit / HederaMCPToolkitToolkit consumerToolkit migration
Imports plugins like coreTokenPlugin, coreAccountPlugin, coreHTSPluginToolkit consumer (uses built-in plugins)Toolkit migration + alias rename
Imports ResponseParserService or HederaMCPServer from hedera-agent-kitToolkit consumerToolkit migration (these moved to toolkit packages)
BothRun 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, ai only 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 at 1.0.0 for this release. Use ^1.0.0 for @hashgraph/hedera-agent-kit-langchain / -ai-sdk / -elizaos / -mcp. Run npm view <pkg> version to 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 its 1.x line (e.g. @langchain/openai@^1); the 0.x line depends on @langchain/core@^0.3 and produces dual-package type errors against the toolkit's @langchain/core@^1. See references/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:

RemovedReplacement
coreHTSPlugincoreTokenPlugin
coreSCSPlugincoreEVMPlugin
coreQueriesPluginIndividual 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:

  1. Replace import type { Tool } with import { BaseTool } from @hashgraph/hedera-agent-kit.
  2. Rewrite the factory: (context: Context): Tool => ({ ... execute }) becomes a class extending BaseTool and a one-line factory (context) => new MyTool(context).
  3. Split the body of the old execute function into:
    • normalizeParams (resolve defaults, validate format)
    • coreAction (build the Transaction for mutations, fetch the data for queries)
    • secondaryAction (call handleTransaction(...) for mutations; pass-through for queries)
  4. For query-only tools, override shouldSecondaryAction to return false and provide a no-op secondaryAction.
  5. Move the try/catch body into an handleError(error, context) override (BaseTool calls it from any failed stage).
  6. 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:

  1. npm install (or bun install / pnpm install) — confirms package.json resolves. Watch for "no version matching X" errors; toolkit packages are on ^1, not ^4.
  2. tsc --noEmit (or npm run build) — picks up missing imports and type drifts (e.g. setTreasuryAccountId complaining because a normalised type was not declared, or noImplicitOverride complaining about a missing override keyword on handleError / secondaryAction).
  3. For LangChain consumers, type errors mentioning two different @langchain/core paths (one nested under your provider package, one nested under the toolkit) indicate a dual-package situation — the provider package is still on 0.x. Bump it to 1.x per Step 2.
  4. For LangChain consumers, errors like Cannot find module 'langchain/agents' or 'langchain/memory' indicate the legacy AgentExecutor/BufferMemory pattern — these subpaths were removed in langchain@1.x. The fix is a separate framework migration to createReactAgent from @langchain/langgraph/prebuilt. See references/breaking-changes.md § "LangChain ecosystem bump".
  5. Smoke-test the agent: instantiate the toolkit, list tools (toolkit.getTools().length must 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-contracts plugin.
  • Native JS SDK changes inside @hiero-ledger/sdk itself — only the import path changes; the API surface remained stable across the rename.
  • Plugin authoring patterns from scratch — see the agent-kit-plugin skill.
  • Writing new hooks/policies — see agent-kit-hook and agent-kit-policy skills. Migration to BaseTool is the prerequisite for those features.
  • LangChain framework migration (AgentExecutor → createReactAgent, BufferMemory → messages-based history). The v4 LangChain toolkit forces a bump to langchain@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 the Tool object literal to a BaseTool subclass, including the query-only variant.
  • examples/transfer-hbar-migration/ — before-v3.ts and after-v4.ts of the same tool, side by side, with a README.md walking 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

More from hedera-dev/hedera-skills

All 10