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

# Tools

> Let agents call APIs and Restate operations through durable tool calls, and run slow tools in the background.

You pass tools as a map, on the agent definition (`tools: {name: tool}`) or on a single run (`run(input, {tools})`).
The map key is the tool name that the model uses: 1 to 64 letters, digits, `_`, or `-`.
Tool inputs are Zod schemas, and Restate Harness validates the model's arguments before the tool runs. For `serviceTool`, the called handler validates the input.

| Tool | Use it to |
| - | - |
| `asyncTool` | Call an API or a database with an async function |
| `tool` | Compose Restate operations, such as service calls, timers, and state |
| `handlerTool`, `serviceTool` | Let the model call Restate handlers. See [Restate services as tools](https://docs.restate.dev/harness/service-tools.md). |
| `mcpTools` | Load the tools of an MCP server. See [MCP servers](https://docs.restate.dev/harness/mcp.md). |
| `agentTool`, `forkAgentTool`, `handoff` | Delegate work to other agents. See [Sub-agents, handoffs, and forks](https://docs.restate.dev/harness/sub-agents.md). |

For an agent with many tools, see [Code mode and tool search](https://docs.restate.dev/harness/code-mode.md).

## Async tools

`asyncTool` runs an async function as a journaled step:

```typescript {"CODE_LOAD::harness/src/tools.ts#async_tool"}  theme={null}
const lookupTicket = asyncTool({
  description: "Look up a ticket's status.",
  input: z.object({ticketId: z.string()}),
  retry: {maxAttempts: 5, initialInterval: {milliseconds: 250}, exponentiationFactor: 2},
  async execute({ticketId}, {signal}) {
    const ticket = await fetchTicket(ticketId, {signal});
    if (!ticket) throw new ToolError(`No ticket ${ticketId}`, "not_found");
    return ticket;
  },
});

const support = agent({
  model,
  instructions: "Use lookupTicket to answer questions about tickets.",
  tools: {lookupTicket},
});
```

* Restate Harness journals the result once `execute` succeeds. On replay, the tool returns the journaled result without running `execute` again. The result must be JSON.
* A thrown `Error` is retried under `retry`, which defaults to three attempts. After the last attempt, the model receives the error with the code `tool_failed`. A `retry` policy that you pass replaces the default, so set `maxAttempts` in it. `retry: {maxAttempts: 1}` turns off these retries, but a crash before Restate Harness journals the result still runs `execute` again, so make external writes idempotent.
* A `TerminalError`, or a `ToolError` with a code such as `not_found`, isn't retried. The model receives the error as the tool result, and the run continues. An `AgentTerminalError` fails the run instead: `run` throws it. See [Error handling](https://docs.restate.dev/harness/error-handling.md).
* `signal` aborts when the tool call is cancelled, for example because the run is interrupted, and when the invocation attempt ends. Pass it to APIs such as `fetch`. `callId` is stable across retries. Combine it with `invocationId` and the run's `name` into an idempotency key for external writes, for example `${invocationId}:${name}:${callId}`.

## Generator tools

`tool` takes a generator `execute`, so the tool can call other services, sleep, wait for signals, and use state:

```typescript {"CODE_LOAD::harness/src/tools.ts#tool"}  theme={null}
const reserve: Tool<Order> = tool({
  description: "Reserve stock for the current order.",
  input: z.object({sku: z.string(), quantity: z.number().int().positive()}),
  *execute({sku, quantity}, {context}) {
    // awaitChild cancels the call if the run is interrupted
    const reserved = yield* awaitChild(restate.client(inventory, sku).reserve(quantity));
    if (!reserved) throw new ToolError(`Not enough stock for ${sku}`, "out_of_stock");
    return {sku, quantity, orderId: context.orderId};
  },
});
```

Code in the generator body runs again on replay. Put external calls in `restate.run` or in an `asyncTool`.
Wrap service calls in `awaitChild`, so interrupting the run cancels the call. Without it, the called handler keeps running.

## Run context

A tool reads the [run context](https://docs.restate.dev/harness/agents.md#run-context) for data that the model must not control, such as customer IDs, prices, and clients:

```typescript {"CODE_LOAD::harness/src/tools.ts#context"}  theme={null}
type Ctx = {customerId: string};

const listOrders: Tool<Ctx> = asyncTool({
  description: "List the current customer's orders.",
  input: z.object({}),
  async execute(_input, {context}) {
    // The customer ID comes from the application, not from the model.
    return {customerId: context.customerId, orders: ["O-1", "O-2"]};
  },
});

const accountAgent = agent<Ctx>({model, tools: {listOrders}});
// in a handler: yield* accountAgent.run(question, {context: {customerId}});
```

Inside `agent<Ctx>({tools: {...}})`, the tool's `context` is typed from the agent. A tool defined on its own needs the `Tool<Ctx>` type on its variable.

## Background tools

With `background: true`, the model receives a pending result and continues without waiting for the tool. The tool's result arrives in a later step:

```typescript {"CODE_LOAD::harness/src/tools.ts#background"}  theme={null}
const researcher = agent({
  model,
  tools: {
    crawlSite: asyncTool({
      description: "Crawl a website and return its pages. Takes several minutes.",
      input: z.object({url: z.string()}),
      background: true,
      async execute({url}) {
        return {url, pages: 42};
      },
    }),
    sleep: sleepTool(),
    cancel: cancelOperationTool(),
  },
});
```

`sleepTool` lets the model wait durably, and `cancelOperationTool` lets it cancel a background tool call.

A run doesn't complete while background calls are pending. If the model returns a final answer, the run discards it, waits for the next background result or steering message, and calls the model again. If the run reaches `maxSteps` first, it cancels the pending calls and stops with `max_steps`.

## Tools for one run

`run(input, {tools})` adds tools to one run, next to the agent's own tools. A run tool can't use the name of an agent tool.
Use this for tools that depend on the request, such as [MCP tools](https://docs.restate.dev/harness/mcp.md), or tools that a client UI provides.
The [AG-UI lesson](https://github.com/restatedev/harness/blob/main/packages/examples/src/lessons/18_ag_ui.ts) turns the tools of an AG-UI client into run tools.


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