Skip to content

feat: add onToolError hook for customizing tool error payloads befo…#1054

Merged
omeraplak merged 2 commits intomainfrom
feat/add-ontoolerror-hook
Feb 12, 2026
Merged

feat: add onToolError hook for customizing tool error payloads befo…#1054
omeraplak merged 2 commits intomainfrom
feat/add-ontoolerror-hook

Conversation

@omeraplak
Copy link
Member

@omeraplak omeraplak commented Feb 12, 2026

…re serialization

PR Checklist

Please check if your PR fulfills the following requirements:

Bugs / Features

What is the current behavior?

What is the new behavior?

fixes (issue)

Notes for reviewers


Summary by cubic

Add onToolError hook to let agents customize or replace tool error payloads before they are serialized and sent to the model. This makes it easy to normalize, redact, or compact errors without changing tool code.

  • New Features
    • Added onToolError({ agent, tool, args, error, originalError, context, options }) hook.
    • Runs before onToolEnd when a tool throws or returns an error payload.
    • Return { output } to override the default serialized error result; otherwise defaults apply.
    • Hook merging supported (method-level first, then agent-level; agent-level override wins).
    • Tests added and docs updated with examples.

Written for commit 452ab68. Summary will update on new commits.

Summary by CodeRabbit

  • New Features

    • Added onToolError hook to customize and optionally override tool error payloads (works for batch and streaming)
  • Documentation

    • Added docs and examples showing how to intercept original errors and transform serialized error payloads
  • Tests

    • Added tests validating onToolError invocation and its ability to override error outputs

@changeset-bot
Copy link

changeset-bot bot commented Feb 12, 2026

🦋 Changeset detected

Latest commit: 452ab68

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@voltagent/core Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@joggrbot

This comment has been minimized.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 12, 2026

📝 Walkthrough

Walkthrough

This PR adds an onToolError hook to @voltagent/core, exposing structured error args and an optional output override. The agent invokes the hook when tools throw (batch and streaming paths) and applies a returned output override in place of the default serialized error.

Changes

Cohort / File(s) Summary
Hook Type Definitions
packages/core/src/agent/hooks/index.ts
Adds OnToolErrorHookArgs, OnToolErrorHookResult, AgentHookOnToolError; extends AgentHooks with onToolError; adds default no-op and wires into createHooks.
Agent Implementation
packages/core/src/agent/agent.ts
Invokes onToolError on tool failures across standard, provider-tool, and streaming flows; detects and applies output overrides from the hook; updates merged-hooks behavior and imports OnToolErrorHookResult.
Type Declarations
packages/core/src/agent/agent.spec-d.ts
Adds typings for onToolError args and return shape to validate the hook signature.
Tests
packages/core/src/agent/agent.spec.ts, packages/core/src/agent/hooks/index.spec.ts
Adds tests ensuring onToolError is called on failure and can override serialized error output; verifies interaction with onToolEnd and operation tracing.
Documentation
website/docs/agents/hooks.md, website/docs/agents/tools.md
Documents onToolError usage and examples (e.g., Axios error handling), and adds it to hook-merging docs.
Changeset Entry
.changeset/good-bottles-wave.md
Adds changeset announcing the new minor feature: onToolError hook.

Sequence Diagram(s)

sequenceDiagram
    participant Agent as Agent
    participant Tool as Tool
    participant Hook as onToolError Hook
    participant Output as Output Handler

    Agent->>Tool: Execute tool(args)
    Tool-->>Agent: throws error (originalError)

    Agent->>Hook: Invoke with {tool, args, error, originalError, context}
    alt Hook returns output override
        Hook-->>Agent: { output: {...} }
        Agent->>Output: Use override output
    else Hook returns undefined
        Hook-->>Agent: undefined
        Agent->>Output: Use default serialized error
    end

    Output-->>Agent: Final output payload
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I sniffed a bug and gave a cheer,
A tool fell flat, its error near.
I hopped in quick with hooks to mend,
Transforming errors end-to-end.
Now payloads bloom, all tidy, dear. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add onToolError hook for customizing tool error payloads befo…' is directly related to the main feature being added—a new onToolError hook that allows customizing tool error payloads before serialization.
Description check ✅ Passed The PR description provides a clear summary of the feature, checks off all completed requirements (commit guidelines, tests, docs, changesets), and includes an auto-generated summary detailing the hook's functionality and usage.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-ontoolerror-hook

No actionable comments were generated in the recent review. 🎉


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 8 files

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Feb 12, 2026

Deploying voltagent with  Cloudflare Pages  Cloudflare Pages

Latest commit: 452ab68
Status:⚡️  Build in progress...

View logs

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/src/agent/agent.ts (1)

5315-5368: ⚠️ Potential issue | 🟠 Major

Avoid invoking tool onEnd twice on error.

tool.hooks?.onEnd is executed twice with identical arguments, which can double side effects (logging, cleanup, external calls). Please remove the duplicate invocation.

Suggested fix
-        await tool.hooks?.onEnd?.({
-          tool,
-          args,
-          output: undefined,
-          error: voltAgentError,
-          options: executionOptions,
-        });
-
-        await tool.hooks?.onEnd?.({
-          tool,
-          args,
-          output: undefined,
-          error: voltAgentError,
-          options: executionOptions,
-        });
+        await tool.hooks?.onEnd?.({
+          tool,
+          args,
+          output: undefined,
+          error: voltAgentError,
+          options: executionOptions,
+        });
🤖 Fix all issues with AI agents
In `@packages/core/src/agent/hooks/index.spec.ts`:
- Around line 341-395: The test currently creates a plain Error for toolError
but OnToolErrorHookArgs requires VoltAgentError; replace the plain Error with a
VoltAgentError instance (or wrap a native Error inside a VoltAgentError) and
pass that as the error in the onToolError call (you can keep a separate native
Error as originalError if you want to assert both). Update the toolError
declaration used in the expect/assert and the agent.hooks.onToolError invocation
(references: OnToolErrorHookArgs, toolError, onToolErrorSpy,
agent.hooks.onToolError) so the test uses the proper VoltAgentError type.
🧹 Nitpick comments (1)
packages/core/src/agent/agent.spec.ts (1)

984-1027: Remove unnecessary as any cast when assigning to Error.stack.
Error.stack is optional and writable in TypeScript's Error interface; the cast is not needed and violates type safety principles.

♻️ Proposed fix
-          (error as any).stack = "should-not-be-returned";
+          error.stack = "should-not-be-returned";

@omeraplak omeraplak merged commit 3556385 into main Feb 12, 2026
22 of 23 checks passed
@omeraplak omeraplak deleted the feat/add-ontoolerror-hook branch February 12, 2026 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant