ai icon indicating copy to clipboard operation
ai copied to clipboard

Feature request: allow onToolExecutionStart to return a denial/error result as a typed tool output (policy gate pattern)

Open vietnamesekid opened this issue 6 months ago • 6 comments

Background

I am using streamText with custom tools and need to block tool execution based on runtime conditions (e.g. quota exceeded per user, permission checks, tenant-level policy). I explored every available approach and ran into fundamental limitations.

Current API limitations

1. Throwing inside onToolExecutionStart is silently swallowed

// packages/ai/src/util/notify.ts
try {
  await callback(options.event);
} catch (_ignored) {}

Errors thrown inside the callback are caught and discarded. No signal reaches the SDK.

2. onToolExecutionStart return type is void, no way to signal denial

// packages/ai/src/generate-text/tool-execution-events.ts
export type OnToolExecutionStartCallback<TOOLS extends ToolSet = ToolSet> =
  Callback<ToolExecutionStartEvent<TOOLS>>;

// packages/ai/src/util/callback.ts
export type Callback<EVENT> = (event: EVENT) => PromiseLike<void> | void;

Return values are completely ignored by notify(). There is no hook that accepts a return value at this lifecycle point.

3. Calling controller.abort() is too coarse

This aborts the entire stream, not just the one tool call. The model loses its entire context and cannot recover. I also need to manually check abortSignal?.aborted at the top of every execute function, which pollutes tool implementations with policy logic.

4. The tool approval system does not fit this use case

toolApproval is designed for explicit user-facing approval flows (human-in-the-loop). It runs before onToolExecutionStart and requires a different architectural setup. It is not suitable for programmatic, server-side policy enforcement based on runtime state (quota, permissions, feature flags).

What I want: onToolExecutionStart as a policy gate

Allow onToolExecutionStart to optionally return a typed denial object. If a denial is returned, the SDK:

  1. Skips tool.execute() entirely
  2. Injects a tool-error stream part with the denial message tied to that toolCallId
  3. The model receives it as a normal tool result and can respond gracefully
const result = await streamText({
  model,
  tools: { searchWeb, readFile, deleteRecord },
  messages,

  onToolExecutionStart: async ({ toolCall }) => {
    // Quota enforcement
    if (toolCall.toolName === 'searchWeb') {
      const remaining = await getQuota(userId, 'search');
      if (remaining <= 0) {
        return { deny: 'Search quota exceeded for this billing period.' };
      }
    }

    // Permission check
    if (toolCall.toolName === 'deleteRecord') {
      const allowed = await checkPermission(userId, 'delete');
      if (!allowed) {
        return { deny: 'You do not have permission to delete records.' };
      }
    }

    // undefined = proceed normally
  },
});

The model sees the denial as a tool result and can explain it to the user or pivot to an alternative plan.

Proposed type change

// tool-execution-events.ts
export type ToolExecutionDenial = { deny: string };

export type OnToolExecutionStartCallback<TOOLS extends ToolSet = ToolSet> = (
  event: ToolExecutionStartEvent<TOOLS>,
) => PromiseLike<ToolExecutionDenial | void> | ToolExecutionDenial | void;

The deny field name (rather than error) makes the intent explicit: this is an intentional policy decision, not a runtime exception. This distinction matters as @utsavtulsyan pointed out -- the API contract needs a clear separation between deliberate denial and hook failure (which should still be silently swallowed).

Implementation touch points (all in execute-tool-call.ts):

// Check return value after onToolExecutionStart
const denial = await invokeWithResult({
  event: baseCallbackEvent as ToolExecutionStartEvent<TOOLS>,
  callbacks: onToolExecutionStart,
});

if (denial?.deny != null) {
  const toolError = {
    type: 'tool-error',
    toolCallId,
    toolName,
    input,
    error: new Error(denial.deny),
    ...
  } as TypedToolError<TOOLS>;

  return { output: toolError, toolExecutionMs: 0 };
}

// proceed with tool.execute() as normal

This is fully backward compatible. Callbacks that return nothing behave exactly as before.

Why this matters for agentic architectures

As highlighted by @utsavtulsyan, this is a scoped policy boundary, not a convenience hook. The key architectural goal is separation of concerns:

  • Tool layer: pure domain logic, no knowledge of quotas, tenants, or user tiers
  • Policy layer: onToolExecutionStart as the single enforcement point across all tools

This pattern is already established in other agent frameworks. Google ADK's before_tool_callback works exactly this way: if the callback returns a value, the framework skips tool.execute() and sends that value back to the LLM as the tool result. It is their primary mechanism for guardrails and policy enforcement.

The current AI SDK design treats onToolExecutionStart as an observation hook. This feature request promotes it to a control hook, a meaningful distinction that unlocks the policy gate pattern for production agentic systems.

SDK version

[email protected]

vietnamesekid avatar Jun 05 '26 06:06 vietnamesekid

This would be useful as a scoped tool-call policy boundary, not just as a convenience hook.

The part I would want to preserve is that rejecting one tool call should still look like a tool result to the model, tied to that specific toolCallId. In quota / permission / tenant-policy cases, aborting the whole stream is too coarse: the model loses the chance to recover, ask for a cheaper action, or explain the denial in normal conversation.

One detail worth making explicit in the API contract: a callback rejection should probably be treated differently from an exception thrown by the callback. Today swallowed callback errors make sense for telemetry-style hooks, but if this hook becomes a policy gate, callers need a clear path for intentional denial versus hook failure. Something like a typed deny / error tool result return value would make that boundary easier to reason about and test.

utsavtulsyan avatar Jun 05 '26 21:06 utsavtulsyan

Hi @utsavtulsyan,

Thanks for framing this perfectly! Using experimental_onToolCallStart as a scoped tool-call policy boundary is exactly what I am aiming for.

My architectural goal is to keep the Tool Implementation Layer completely decoupled from the Policy/Guardrail Layer. The tool's execute function should only contain pure domain logic, without being bloated by user tiers, tenant quotas, or permission checks.

Other modern frameworks already implement this beautifully. For instance, Google's Agent Development Kit (ADK) utilizes a before_tool_callback pattern for Guardrails & Policy Enforcement. In their design, this callback acts as a gatekeeper: if a violation occurs, it can directly return a predefined instruction or custom message. The framework then skips the tool execution entirely and passes that response back to the LLM.

Following your suggestion on distinguishing intentional denial from runtime exceptions, having this hook return a typed deny/error object would be the ideal solution:

  • Clean Architecture: Tools remain modular, reusable, and focused strictly on their own logic.
  • Resilient Agent Behavior: The LLM receives a graceful, structured error tied to the toolCallId, allowing it to explain the denial to the user or pivot to an alternative plan.

I’d love to hear the maintainers' thoughts on this!

vietnamesekid avatar Jun 09 '26 09:06 vietnamesekid

I would keep this as a policy decision result, not as a callback exception path.

If this hook becomes a gate, the returned denial should be bound to the same tool-call envelope the SDK was about to execute: toolCallId, tool name, canonical input digest, run or request id, policy id/version, reason code, and a terminal denied state.

Then the runtime behavior can stay very narrow:

  • intentional denial skips tool.execute() for that one call;
  • hook failure remains a hook failure, not a policy denial;
  • the stream receives a typed non-execution tool result for the same toolCallId;
  • the model can recover or explain instead of losing the whole stream;
  • audit can prove which exact pending call was denied and why.

The important test cases I would add:

  1. one denied tool call does not abort the rest of the stream;
  2. throwing inside the hook is distinguishable from returning a denial;
  3. a changed input digest cannot reuse a prior denial or approval result;
  4. the model sees the denial as the result of that specific tool call;
  5. execute() is never entered for the denied call;
  6. parallel tool calls cannot cross-consume another call's denial result.

That keeps the tool implementation clean while making the policy layer a first-class control boundary instead of observational telemetry.

rpelevin avatar Jun 17 '26 14:06 rpelevin

@vietnamesekid did you take a look at https://ai-sdk.dev/docs/agents/policy-tool-approvals / https://www.npmjs.com/package/@ai-sdk/policy-opa - that should cover this! Let me know if you have other suggestions/feedback

dnukumamras avatar Jul 01 '26 04:07 dnukumamras

Identify issue type

{
  "evidence": [
    "Title explicitly requests a feature: allowing `onToolExecutionStart` to return a denial/error result as typed tool output.",
    "Description says the current API has limitations: callback return type is `void`, return values are ignored, aborting is too coarse, and tool approval does not fit the use case.",
    "The requested behavior is a new policy-gate capability: skip `tool.execute()`, emit a `tool-error` stream part tied to the `toolCallId`, and let the model recover gracefully.",
    "Comments discuss desired API semantics, policy-boundary behavior, and suggested test cases for the proposed new capability."
  ],
  "rationale": "The issue asks for an API expansion and behavior change to support programmatic tool-call denial from `onToolExecutionStart`. Although it notes current limitations, it is framed as a new capability rather than a concrete broken behavior contradicting existing documented behavior.",
  "type": "feature",
  "confidence": "high"
}

lgrammel avatar Jul 02 '26 08:07 lgrammel

Thanks @dnukumamras , I took another look at both.

This does seem to cover the programmatic policy decision before tool execution that I was looking for. I had understood tool approvals primarily as a human-in-the-loop flow, so I missed the policy-based API. Sorry if the way I framed the issue made that unclear.

One thing I’m still not clear on: when the policy denies a tool call, is that denial automatically surfaced back to the model so the agent can continue within the same execution, or does the application still need to handle an approval response and resume the flow separately?

If the denial is returned to the model and the loop continues automatically, then this should cover my use case.

vietnamesekid avatar Jul 02 '26 08:07 vietnamesekid