> ## Documentation Index
> Fetch the complete documentation index at: https://trigger.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Tools

> Declare tools on chat.agent so toModelOutput survives across turns, get them back typed in run(), and type your messages from them.

`chat.agent` doesn't call the model for you. Your tools still go to [`streamText`](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling) inside `run()`. But you should **also declare them on the agent config**:

```ts theme={"theme":"css-variables"}
import { chat } from "@trigger.dev/sdk/ai";
import { stepCountIs, tool } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";

const tools = {
  searchDocs: tool({
    description: "Search the docs.",
    inputSchema: z.object({ query: z.string() }),
    execute: async ({ query }) => searchIndex(query),
  }),
};

export const myChat = chat.agent({
  id: "my-chat",
  tools, // ← declare here
  run: async ({ messages, tools, signal, streamText }) =>
    streamText({
      tools,
      model: anthropic("claude-sonnet-4-5"),
      messages,
      abortSignal: signal,
      stopWhen: stepCountIs(15),
    }),
});
```

Declaring `tools` on the config does two things you can't get by passing them to `streamText` alone:

* It threads your tools into the SDK's internal message conversion, so each tool's [`toModelOutput`](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling#tomodeloutput) is re-applied when prior-turn history is re-converted (see [`toModelOutput` across turns](#tomodeloutput-across-turns)).
* It hands the resolved set back, typed, on the `run()` payload as `tools`, so you declare them once and don't re-import the map.

## Where tools go

There are three places a tool set shows up. Declare once, reuse:

| Surface | What it's for |
| - | - |
| `chat.agent({ tools })` | Re-applies `toModelOutput` on prior-turn history; hands the set back typed on the `run()` payload. |
| `streamText({ tools })` on the `run` argument's `streamText` | What the model actually calls. Detects which calls need [HITL approval](https://trigger.dev/docs/ai-chat/patterns/human-in-the-loop.md) (`needsApproval`) and merges the auto-injected [skill](https://trigger.dev/docs/ai-chat/patterns/skills.md) tools on top. Naming `tools` replaces the config set for that call, so you can narrow it; omitting `tools` falls back to the config set. |
| `chat.toStreamTextOptions({ tools })` | The same job by hand, for a [custom agent](#manual-turn-loops-chatcustomagent), which has no `run` argument. |

The canonical pattern: declare `tools` on the config, read them back from the `run()` payload, and pass that set to the `streamText` the payload also carries.

```ts theme={"theme":"css-variables"}
run: async ({ messages, tools, signal, streamText }) =>
  streamText({ model, messages, tools, abortSignal: signal }),
```

> [!TIP]
>
> Conversion only reads each tool's `inputSchema` and `toModelOutput`, never `execute`. If you keep heavy `execute` dependencies out of a module (for bundle reasons), you can declare a lightweight schema-only tool map on the config and add the executes where you call `streamText`.

## `toModelOutput` across turns

`toModelOutput` transforms a tool's result before it enters the model's context, turning raw image bytes into an image content part, or compressing a long sub-agent transcript into a one-line summary. The full result still streams to the frontend; the model only sees the transformed version.

The catch is multi-turn. After each turn, `chat.agent` persists the conversation as `UIMessage[]` and re-converts it to model messages at the start of the next turn. That conversion needs your tools to find each `toModelOutput`. **If you only pass tools to `streamText` and not to the config, the transform runs on turn 1 but is skipped on every later turn.** The raw output gets stringified back into the prompt instead, and the model loses the transformed view.

Declaring `tools` on the config fixes this: the SDK threads them into the conversion, so `toModelOutput` is re-applied on every turn.

```ts theme={"theme":"css-variables"}
const tools = {
  renderChart: tool({
    description: "Render a chart and return it as an image.",
    inputSchema: z.object({ spec: z.string() }),
    execute: async ({ spec }) => renderToPng(spec), // raw bytes
    // The model should see an image part, not base64 bytes:
    toModelOutput: ({ output }) => ({
      type: "content",
      value: [{ type: "media", mediaType: "image/png", data: output.base64 }],
    }),
  }),
};

export const chartChat = chat.agent({
  id: "chart-chat",
  tools, // ← without this, the image is "remembered" on turn 1 and gone from turn 2
  run: async ({ messages, tools, signal, streamText }) =>
    streamText({
      tools,
      model: anthropic("claude-sonnet-4-5"),
      messages,
      abortSignal: signal,
      stopWhen: stepCountIs(15),
    }),
});
```

## Static or per-turn tools

`tools` accepts either a static `ToolSet` or a function that returns one per turn, for tools that depend on the user, a feature flag, or anything in the turn context:

```ts theme={"theme":"css-variables"}
export const myChat = chat
  .withClientData({ schema: z.object({ userId: z.string(), plan: z.string() }) })
  .agent({
    id: "my-chat",
    tools: ({ clientData }) => ({
      searchDocs,
      ...(clientData?.plan === "pro" ? { deepResearch } : {}),
    }),
    run: async ({ messages, tools, signal, streamText }) =>
      streamText({
        tools,
        model: anthropic("claude-sonnet-4-5"),
        messages,
        abortSignal: signal,
        stopWhen: stepCountIs(15),
      }),
  });
```

The function receives a `ResolveToolsEvent` and runs once per turn (after `clientData` is parsed):

| Field | Type | Description |
| - | - | - |
| `chatId` | `string` | The chat session ID. |
| `turn` | `number` | The current turn number (0-indexed). |
| `continuation` | `boolean` | Whether this run is continuing an existing chat. |
| `clientData` | `TClientData` | Parsed client data from the frontend. |

The resolved set is what lands on the `run()` payload's `tools`.

## Typed tools in `run()`

The `run()` payload's `tools` is typed to whatever you declared, so you can pass it straight through without re-importing the map:

```ts theme={"theme":"css-variables"}
run: async ({ messages, tools, signal, streamText }) => {
  // `tools` is typed as your tool set, not a broad `ToolSet`
  return streamText({
    tools,
    model: anthropic("claude-sonnet-4-5"),
    messages,
    abortSignal: signal,
  });
};
```

When no `tools` are declared, the payload's `tools` is an empty object and behaves exactly as before, so declaring tools is fully opt-in.

## Typing messages from your tools

To get typed tool parts (`tool-${name}` with typed input/output) on your `UIMessage`, in hooks like `onTurnComplete` and on the frontend, derive the message type from your tool set with `InferChatUIMessageFromTools`:

```ts theme={"theme":"css-variables"}
import type { InferChatUIMessageFromTools } from "@trigger.dev/sdk/ai";

const tools = { searchDocs, renderChart };

export type ChatUiMessage = InferChatUIMessageFromTools<typeof tools>;
```

This is shorthand for `UIMessage<unknown, UIDataTypes, InferUITools<typeof tools>>`. Pin it on the agent with [`chat.withUIMessage<ChatUiMessage>()`](https://trigger.dev/docs/ai-chat/types#custom-uimessage-with-chat-withuimessage) and reuse it on the client. If you also have custom `data-*` parts, build the `UIMessage` generic directly instead. See [Types](https://trigger.dev/docs/ai-chat/types.md).

## Skills

[Agent skills](https://trigger.dev/docs/ai-chat/patterns/skills.md) are auto-injected as tools (`loadSkill`, `readFile`, `bash`) by the managed `streamText`, or by `chat.toStreamTextOptions()` if you build the options yourself. They're separate from your config `tools`: declare your own tools on the config (so their `toModelOutput` survives across turns), and the merge happens at call time. Skill tools don't define `toModelOutput`, so they don't need to be on the config.

## Manual turn loops (`chat.customAgent`)

The `tools` config option belongs to the managed [`chat.agent`](https://trigger.dev/docs/ai-chat/backend#chat-agent). When you drive the loop yourself with [`chat.customAgent`](https://trigger.dev/docs/ai-chat/custom-agents#chat-customagent) (or build messages from `chat.history`), you own the conversion, so pass your tools to `convertToModelMessages` directly to get the same cross-turn `toModelOutput` behavior:

```ts theme={"theme":"css-variables"}
import { convertToModelMessages, streamText } from "ai";

// Inside your loop, with `tools` in scope:
const uiMessages = chat.history.all();
const messages = await convertToModelMessages(uiMessages, {
  tools,
  ignoreIncompleteToolCalls: true,
});

return streamText({ model: anthropic("claude-sonnet-4-5"), messages, tools });
```

## Learn more

* [Human-in-the-loop](https://trigger.dev/docs/ai-chat/patterns/human-in-the-loop.md): tools that pause for approval.
* [Sub-agents](https://trigger.dev/docs/ai-chat/patterns/sub-agents.md): tools that delegate to other agents and compress their output with `toModelOutput`.
* [Tool result auditing](https://trigger.dev/docs/ai-chat/patterns/tool-result-auditing.md): logging tool results as they resolve.
* [AI SDK: Tools and tool calling](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.