# Tool

A tool call, from its arguments to its result, as an expandable line.

Source: [tool.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/tool.tsx)

```tsx
import { GlobeIcon, SearchIcon } from "lucide-react";

import {
  Tool,
  ToolContent,
  ToolDescription,
  ToolIcon,
  ToolInput,
  ToolOutput,
  ToolTitle,
  ToolTrigger,
} from "@/components/ui/tool";
import { Trace } from "@/components/ui/trace";

const results = [
  { title: "Rate limits", url: "https://example.com/docs/rate-limits" },
  { title: "Errors", url: "https://example.com/docs/errors" },
];

export default function ToolCalls() {
  return (
    <Trace className="w-full max-w-md">
      <Tool state="done" defaultOpen>
        <ToolTrigger>
          <ToolIcon>
            <SearchIcon />
          </ToolIcon>
          <ToolTitle>Searched the docs for rate limits</ToolTitle>
          <ToolDescription>2 results</ToolDescription>
        </ToolTrigger>
        <ToolContent>
          <ToolInput value={{ query: "rate limits", limit: 5 }} />
          <ToolOutput value={results} />
        </ToolContent>
      </Tool>
      <Tool state="running">
        <ToolTrigger>
          <ToolIcon>
            <GlobeIcon />
          </ToolIcon>
          <ToolTitle>Fetching example.com/pricing</ToolTitle>
        </ToolTrigger>
      </Tool>
    </Trace>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/tool
```

## Usage

```tsx
import { TerminalIcon } from "lucide-react";

import {
  Tool,
  ToolContent,
  ToolIcon,
  ToolInput,
  ToolOutput,
  ToolTitle,
  ToolTrigger,
} from "@/components/ui/tool";

export function ToolCall() {
  return (
    <Tool state="done">
      <ToolTrigger>
        <ToolIcon>
          <TerminalIcon />
        </ToolIcon>
        <ToolTitle>Ran node --version</ToolTitle>
      </ToolTrigger>
      <ToolContent>
        <ToolInput value={{ command: "node --version" }} />
        <ToolOutput value="v24.18.0" />
      </ToolContent>
    </Tool>
  );
}
```

A tool call is a [Trace](https://ui.jarv.is/components/trace.md) line, so it goes in a `Trace` beside the other steps.
`ToolIcon`, `ToolTitle` and `ToolDescription` are the line's Trace parts. The line expands only when
a `ToolContent` is a direct child of `Tool`. Set `expandable` when the content is inside a fragment
or a component of your own.

`state` sets the line's status from the call's progress: `pending` before it starts, `running` while
it runs, `approval-requested` while it waits for someone to allow it, then `done`, `error` or
`denied`. The color and motion aren't announced, so say the state in the title too, as in "Running"
and "Ran".

`ToolIcon` follows the call's `state`. It shows a [Spinner](https://ui.jarv.is/components/spinner.md) while the call
runs, and a cross or a slashed circle once it has failed or been denied. Otherwise it shows its
children, usually the tool's icon. Without children, it shows a check once the call is done and a
dashed circle before then. Screen readers announce the state instead, as "Running", "Failed" and so
on, before the title. `ToolIcon`'s `label` changes that text.

`ToolInput` and `ToolOutput` render objects, arrays and JSON strings in a
[JSON Viewer](https://ui.jarv.is/components/json-viewer.md), and other strings in a [Code Block](https://ui.jarv.is/components/code-block.md).
Pass props to either one with `jsonViewerProps` and `codeBlockProps`, such as the code's
`language`.

### With an AI library

The tool-call parts from the AI SDK and TanStack AI each have their own `state`, which maps onto
Tool's. The [Chat guide](https://ui.jarv.is/docs/chat.md) has each mapping as a function.

**AI SDK**

| AI SDK                                               | Tool                                                           |
| ---------------------------------------------------- | -------------------------------------------------------------- |
| `input-streaming`                                    | `pending`                                                      |
| `input-available`                                    | `running`                                                      |
| `approval-requested`                                 | `approval-requested`, or `running` when `approval.isAutomatic` |
| `approval-responded`, when approved                  | `running`                                                      |
| `output-available`                                   | `done`                                                         |
| `output-error`                                       | `error`                                                        |
| `output-denied`, or `approval-responded` when denied | `denied`                                                       |

**TanStack AI**

In TanStack AI, a call that's denied or cancelled ends in `error`, like one that fails. The
`outcome` of its `tool-result` part tells them apart.

| TanStack AI                                                                     | Tool                 |
| ------------------------------------------------------------------------------- | -------------------- |
| `awaiting-input`, `input-streaming`                                             | `pending`            |
| `input-complete`                                                                | `running`            |
| `approval-requested`                                                            | `approval-requested` |
| `approval-responded`, when approved                                             | `running`            |
| `complete`                                                                      | `done`               |
| `error`                                                                         | `error`              |
| `approval-responded` when denied, or `error` when the result's `outcome` is set | `denied`             |

## Composition

- `Tool`
  - `ToolTrigger`
    - `ToolIcon`
    - `ToolTitle`
    - `ToolDescription`
  - `ToolContent`
    - `ToolInput`
    - `ToolOutput`
    - `ToolError`
  - `ToolApproval`

## Examples

### Failed

Put the error in a `ToolError` once a call fails.

```tsx
import {
  Tool,
  ToolContent,
  ToolError,
  ToolIcon,
  ToolInput,
  ToolTitle,
  ToolTrigger,
} from "@/components/ui/tool";

export default function ToolFailed() {
  return (
    <Tool state="error" defaultOpen className="w-full max-w-md">
      <ToolTrigger>
        <ToolIcon />
        <ToolTitle>Failed to look up example.com</ToolTitle>
      </ToolTrigger>
      <ToolContent>
        <ToolInput value={{ domain: "example.com", record: "MX" }} />
        <ToolError>DNS query timed out after 5 seconds.</ToolError>
      </ToolContent>
    </Tool>
  );
}
```

### Needs approval

`ToolApproval` asks someone to allow the call while its `state` is `approval-requested`. It hides
once the state changes and returns focus to the line. Return a promise from `onApprove` or
`onDeny` to keep that button pending and the other one disabled until the promise settles. This
example does that while it sends the response.

```tsx
"use client";

import { RotateCcwIcon, TerminalIcon } from "lucide-react";
import * as React from "react";
import { flushSync } from "react-dom";

import { Button } from "@/components/ui/button";
import {
  Tool,
  ToolApproval,
  ToolIcon,
  ToolTitle,
  ToolTrigger,
  type ToolState,
} from "@/components/ui/tool";

async function respond() {
  await new Promise((resolve) => setTimeout(resolve, 800));
}

async function runMigration() {
  await new Promise((resolve) => setTimeout(resolve, 1500));
}

const titles: Partial<Record<ToolState, string>> = {
  "approval-requested": "Run pnpm db:migrate",
  running: "Running pnpm db:migrate",
  done: "Ran pnpm db:migrate",
  denied: "Didn’t run pnpm db:migrate",
};

export default function ToolNeedsApproval() {
  const [state, setState] = React.useState<ToolState>("approval-requested");
  const toolRef = React.useRef<HTMLDivElement>(null);
  const answered = state === "done" || state === "denied";

  return (
    <div className="flex w-full max-w-md flex-col items-start gap-3">
      <Tool ref={toolRef} state={state} className="w-full">
        <ToolTrigger>
          <ToolIcon>
            <TerminalIcon />
          </ToolIcon>
          <ToolTitle>{titles[state]}</ToolTitle>
        </ToolTrigger>
        <ToolApproval
          onApprove={async () => {
            await respond();
            setState("running");
            await runMigration();
            setState("done");
          }}
          onDeny={async () => {
            await respond();
            setState("denied");
          }}
        >
          Run the migration on the production database?
        </ToolApproval>
      </Tool>
      <Button
        variant="secondary"
        size="sm"
        className={answered ? undefined : "invisible"}
        onClick={() => {
          flushSync(() => setState("approval-requested"));
          toolRef.current?.querySelector<HTMLElement>("[data-slot=tool-approval] button")?.focus();
        }}
      >
        <RotateCcwIcon />
        Ask again
      </Button>
    </div>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `Tool` | [`TraceCollapsible`](https://ui.jarv.is/components/trace.md) |
| `ToolTrigger` | — |
| `ToolIcon` | [`TraceIcon`](https://ui.jarv.is/components/trace.md) |
| `ToolTitle` | [`TraceTitle`](https://ui.jarv.is/components/trace.md) |
| `ToolDescription` | [`TraceDescription`](https://ui.jarv.is/components/trace.md) |
| `ToolContent` | [`TraceCollapsibleContent`](https://ui.jarv.is/components/trace.md) |
| `ToolInput` | `<div>` |
| `ToolOutput` | `<div>` |
| `ToolError` | `<div>` |
| `ToolApproval` | [`Item`](https://ui.jarv.is/components/item.md) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### Tool

| Prop            | Type                                                                                         | Default | Description                                                                                                                                                                                         |
| --------------- | -------------------------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open?`         | `boolean`                                                                                    | —       | Whether the collapsible panel is currently open. To render an uncontrolled collapsible, use the `defaultOpen` prop instead.                                                                         |
| `defaultOpen?`  | `boolean`                                                                                    | `false` | Whether the collapsible panel is initially open. To render a controlled collapsible, use the `open` prop instead.                                                                                   |
| `onOpenChange?` | `((open: boolean, eventDetails: CollapsibleRootChangeEventDetails) => void)`                 | —       | Event handler called when the panel is opened or closed.                                                                                                                                            |
| `disabled?`     | `boolean`                                                                                    | `false` | Whether the component should ignore user interaction.                                                                                                                                               |
| `state`         | `"approval-requested" \| "denied" \| "done" \| "error" \| "pending" \| "running"`            | —       | The call's state: `pending` before it starts, `running` while it runs, `approval-requested` while it waits for someone to allow it, then `done`, `error` or `denied`.                               |
| `expandable?`   | `boolean`                                                                                    | —       | Whether the line expands to show the call's content. By default, it does when a `ToolContent` is a direct child of `Tool`. Set it when the content is inside a fragment or a component of your own. |
| `className?`    | `string \| ((state: CollapsibleRootState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                                |
| `style?`        | `React.CSSProperties \| ((state: CollapsibleRootState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                             |
| `render?`       | `ComponentRenderFn<HTMLProps, CollapsibleRootState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.           |

### ToolTrigger

| Prop         | Type                  | Default | Description                                                                                                                        |
| ------------ | --------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`              | —       | CSS class applied to the element.                                                                                                  |
| `style?`     | `React.CSSProperties` | —       | Style applied to the element.                                                                                                      |
| `render?`    | `React.ReactElement`  | —       | Replaces the element, merging their props: the line's `<span>`, or the `<button>` that expands the line when the call has content. |

### ToolIcon

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label?`     | `string`                                                 | —       | Labels the call's state for screen readers, since the icon is hidden from them. Defaults to "Pending", "Running", "Needs approval", "Done", "Failed" or "Denied".                         |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolTitle

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolDescription

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolContent

| Prop                | Type                                                     | Default | Description                                                                                                                                                                                             |
| ------------------- | -------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hiddenUntilFound?` | `boolean`                                                | `false` | Allows the browser's built-in page search to find and expand the panel contents. Overrides the `keepMounted` prop and uses `hidden="until-found"` to hide the element without removing it from the DOM. |
| `keepMounted?`      | `boolean`                                                | `false` | Whether to keep the element in the DOM while the panel is hidden. This prop is ignored when `hiddenUntilFound` is used.                                                                                 |
| `className?`        | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                                       |
| `style?`            | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                                           |
| `render?`           | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.               |

### ToolInput

| Prop               | Type                                                     | Default   | Description                                                                                                                                                                               |
| ------------------ | -------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label?`           | `React.ReactNode`                                        | `"Input"` | The heading above the value.                                                                                                                                                              |
| `codeBlockProps?`  | `Omit<CodeBlockProps, "code">`                           | —         | Props for the Code Block that renders a string that isn't JSON, such as `language`.                                                                                                       |
| `jsonViewerProps?` | `Omit<JsonViewerProps, "data">`                          | —         | Props for the JSON Viewer that renders objects, arrays and JSON strings, such as `defaultExpandDepth`, which defaults to `2` here.                                                        |
| `value`            | `unknown`                                                | —         | The arguments the tool was called with. Objects, arrays and JSON strings render as a tree, other strings as code, and `undefined` renders nothing.                                        |
| `className?`       | `string`                                                 | —         | CSS class applied to the element.                                                                                                                                                         |
| `style?`           | `React.CSSProperties`                                    | —         | Style applied to the element.                                                                                                                                                             |
| `render?`          | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —         | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolOutput

| Prop               | Type                                                     | Default    | Description                                                                                                                                                                               |
| ------------------ | -------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label?`           | `React.ReactNode`                                        | `"Output"` | The heading above the value.                                                                                                                                                              |
| `codeBlockProps?`  | `Omit<CodeBlockProps, "code">`                           | —          | Props for the Code Block that renders a string that isn't JSON, such as `language`.                                                                                                       |
| `jsonViewerProps?` | `Omit<JsonViewerProps, "data">`                          | —          | Props for the JSON Viewer that renders objects, arrays and JSON strings, such as `defaultExpandDepth`, which defaults to `2` here.                                                        |
| `value`            | `unknown`                                                | —          | What the tool returned. Objects, arrays and JSON strings render as a tree, other strings as code, and `undefined` renders nothing.                                                        |
| `className?`       | `string`                                                 | —          | CSS class applied to the element.                                                                                                                                                         |
| `style?`           | `React.CSSProperties`                                    | —          | Style applied to the element.                                                                                                                                                             |
| `render?`          | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —          | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolError

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ToolApproval

| Prop                   | Type                                                        | Default     | Description                                                                                                                                                                               |
| ---------------------- | ----------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onApprove?`           | `((event: React.MouseEvent<HTMLButtonElement>) => unknown)` | —           | Called when someone approves the call. Return a promise to keep the button pending, and the other button disabled, until it settles.                                                      |
| `onDeny?`              | `((event: React.MouseEvent<HTMLButtonElement>) => unknown)` | —           | Called when someone denies the call. Return a promise to keep the button pending, and the other button disabled, until it settles.                                                        |
| `approveLabel?`        | `React.ReactNode`                                           | —           | The approve button's label.                                                                                                                                                               |
| `denyLabel?`           | `React.ReactNode`                                           | —           | The deny button's label.                                                                                                                                                                  |
| `pendingAnnouncement?` | `string`                                                    | `"Loading"` | What screen readers announce when the promise from `onApprove` or `onDeny` hasn't settled after a second. Pass an empty string to announce nothing.                                       |
| `className?`           | `string`                                                    | —           | CSS class applied to the element.                                                                                                                                                         |
| `style?`               | `React.CSSProperties`                                       | —           | Style applied to the element.                                                                                                                                                             |
| `render?`              | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement`    | —           | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |
