# Animated Tool Call for UI SDK (/docs/components/tool-call)

One agent tool call as a card: the status mark, a title, the tool's name and the time it took, with the input and the output (or the error) in a body that opens. A failed call opens on its own. Agents read the name, status and summaries of the input and output, and open the card through its collapsible.

<ComponentPreview slug="tool-call" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport { ToolCall, type ToolCallStatus } from \&#x22;@/components/keyframery/tool-call\&#x22;\n\ntype Call = {\n  name: string\n  title: string\n  /** The title while it runs. */\n  doing: string\n  input: unknown\n  output?: unknown\n  error?: string\n  took: number\n}\n\nconst calls = (failCourier: boolean): Call[] => [\n  {\n    name: \&#x22;find_order\&#x22;,\n    title: \&#x22;Looked up order #1048\&#x22;,\n    doing: \&#x22;Looking up order #1048\&#x22;,\n    input: { order_id: \&#x22;1048\&#x22; },\n    output: { status: \&#x22;shipped\&#x22;, carrier: \&#x22;Royal Mail\&#x22;, shipped: \&#x22;2026-11-18\&#x22;, items: [\&#x22;Linen shirt\&#x22;, \&#x22;Canvas tote\&#x22;], total: \&#x22;£84.00\&#x22; },\n    took: 420,\n  },\n  failCourier\n    ? {\n        name: \&#x22;track_parcel\&#x22;,\n        title: \&#x22;Couldn't reach the courier\&#x22;,\n        doing: \&#x22;Checking the courier\&#x22;,\n        input: { carrier: \&#x22;royal_mail\&#x22;, tracking: \&#x22;RM 2048 1196 GB\&#x22; },\n        error: \&#x22;Royal Mail's tracking page didn't answer within 10 seconds.\&#x22;,\n        took: 10_000,\n      }\n    : {\n        name: \&#x22;track_parcel\&#x22;,\n        title: \&#x22;Found the parcel in Leeds\&#x22;,\n        doing: \&#x22;Checking the courier\&#x22;,\n        input: { carrier: \&#x22;royal_mail\&#x22;, tracking: \&#x22;RM 2048 1196 GB\&#x22; },\n        output: { last_scan: \&#x22;Leeds Mail Centre\&#x22;, at: \&#x22;2026-11-19T07:42:00Z\&#x22;, delivered: false },\n        took: 1840,\n      },\n  {\n    name: \&#x22;send_email\&#x22;,\n    title: \&#x22;Emailed Priya an update\&#x22;,\n    doing: \&#x22;Writing to Priya\&#x22;,\n    input: { to: \&#x22;priya@example.com\&#x22;, subject: \&#x22;Your order #1048\&#x22;, template: \&#x22;parcel_delayed\&#x22; },\n    output: { sent: true, id: \&#x22;msg_8f2c41\&#x22; },\n    took: 1260,\n  },\n]\n\n/* Where the calls stand when the demo first shows: two finished, the email still going. */\nconst START = 2\n\nexport default function ToolCallDemo({\n  showName = true,\n  durations = true,\n  failCourier = true,\n  openOnError = true,\n  openFirst = false,\n  themeFace = \&#x22;\&#x22;,\n  themeInk = \&#x22;\&#x22;,\n  themeMuted = \&#x22;\&#x22;,\n  themeSuccess = \&#x22;\&#x22;,\n  themeError = \&#x22;\&#x22;,\n  themeRadius = 12,\n  themeFont = 13,\n  themeCodeHeight = 220,\n}: {\n  showName?: boolean\n  durations?: boolean\n  failCourier?: boolean\n  openOnError?: boolean\n  openFirst?: boolean\n  themeFace?: string\n  themeInk?: string\n  themeMuted?: string\n  themeSuccess?: string\n  themeError?: string\n  themeRadius?: number\n  themeFont?: number\n  themeCodeHeight?: number\n}) {\n  const list = calls(failCourier)\n  const [run, setRun] = React.useState(0)\n  const [at, setAt] = React.useState(START)\n  const [startedAt, setStartedAt] = React.useState(() => Date.now())\n  const timers = React.useRef<ReturnType<typeof setTimeout>[]>([])\n  React.useEffect(() => () => timers.current.forEach(clearTimeout), [])\n\n  /* Run again: each call runs for a moment, then finishes or fails. */\n  const rerun = (e: React.MouseEvent<HTMLButtonElement>) => {\n    const speed = parseFloat(getComputedStyle(e.currentTarget).getPropertyValue(\&#x22;--kf-speed\&#x22;)) || 1\n    timers.current.forEach(clearTimeout)\n    setRun((r) => r + 1)\n    setAt(0)\n    setStartedAt(Date.now())\n    timers.current = list.map((_, i) =>\n      setTimeout(() => {\n        setAt(i + 1)\n        setStartedAt(Date.now())\n      }, (900 + i * 1300) * speed),\n    )\n  }\n\n  const statusOf = (i: number): ToolCallStatus =>\n    i < at ? (list[i].error ? \&#x22;error\&#x22; : \&#x22;done\&#x22;) : i === at ? \&#x22;running\&#x22; : \&#x22;pending\&#x22;\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeFace ? { \&#x22;--tool-call-face\&#x22;: themeFace } : null),\n    ...(themeInk ? { \&#x22;--tool-call-ink\&#x22;: themeInk } : null),\n    ...(themeMuted ? { \&#x22;--tool-call-muted\&#x22;: themeMuted } : null),\n    ...(themeSuccess ? { \&#x22;--tool-call-success\&#x22;: themeSuccess } : null),\n    ...(themeError ? { \&#x22;--tool-call-error\&#x22;: themeError } : null),\n    ...(themeRadius !== 12 ? { \&#x22;--tool-call-radius\&#x22;: `${themeRadius}px` } : null),\n    ...(themeFont !== 13 ? { \&#x22;--tool-call-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeCodeHeight !== 220 ? { \&#x22;--tool-call-code-height\&#x22;: `${themeCodeHeight}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;w-full max-w-[460px]\&#x22;>\n      <div className=\&#x22;flex justify-end\&#x22;>\n        <div className=\&#x22;max-w-[85%] rounded-[16px] rounded-br-[6px] bg-muted px-3.5 py-2.5 text-[13px] leading-snug\&#x22;>\n          Where's my order #1048? It was meant to arrive on Friday.\n        </div>\n      </div>\n\n      <div className=\&#x22;mt-5 flex items-center justify-between gap-3\&#x22;>\n        <div className=\&#x22;text-[12px] font-medium text-muted-foreground\&#x22;>{at >= list.length ? \&#x22;Used 3 tools\&#x22; : \&#x22;Working on it\&#x22;}</div>\n        <button\n          type=\&#x22;button\&#x22;\n          data-action=\&#x22;rerun\&#x22;\n          data-agent-hidden\n          onClick={rerun}\n          className=\&#x22;inline-flex h-7 items-center rounded-[8px] px-2.5 text-[12px] leading-none font-medium text-muted-foreground outline-none transition-[scale,color,background-color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop hover:bg-foreground/[0.045] hover:text-foreground active:scale-[calc(1-0.04*var(--kf-flourish,1))] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none\&#x22;\n        >\n          Run again\n        </button>\n      </div>\n\n      <div key={run} className=\&#x22;mt-3 flex flex-col gap-2\&#x22;>\n        {list.map((call, i) => {\n          const status = statusOf(i)\n          const done = i < at\n          return (\n            <ToolCall\n              key={`${call.name}-${openFirst}-${openOnError}`}\n              data-call={call.name}\n              name={showName ? call.name : undefined}\n              title={done ? call.title : call.doing}\n              status={status}\n              input={call.input}\n              output={done ? call.output : undefined}\n              error={done ? call.error : undefined}\n              duration={durations && done && !call.error ? call.took : undefined}\n              startedAt={durations && status === \&#x22;running\&#x22; ? startedAt : undefined}\n              defaultOpen={i === 0 ? openFirst : undefined}\n              openOnError={openOnError}\n            />\n          )\n        })}\n      </div>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;showName&#x22;:[1695,1699],&#x22;durations&#x22;:[1715,1719],&#x22;failCourier&#x22;:[1737,1741],&#x22;openOnError&#x22;:[1759,1763],&#x22;openFirst&#x22;:[1779,1784],&#x22;themeFace&#x22;:[1800,1802],&#x22;themeInk&#x22;:[1817,1819],&#x22;themeMuted&#x22;:[1836,1838],&#x22;themeSuccess&#x22;:[1857,1859],&#x22;themeError&#x22;:[1876,1878],&#x22;themeRadius&#x22;:[1896,1898],&#x22;themeFont&#x22;:[1914,1916],&#x22;themeCodeHeight&#x22;:[1938,1941]},&#x22;root&#x22;:[3937,5956],&#x22;importOffset&#x22;:127}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/tool-call
```

This adds `components/keyframery/tool-call.tsx` and its primitive to your project, and installs UI SDK, along with [collapsible](/docs/components/collapsible), [badge](/docs/components/badge), [code-block](/docs/components/code-block), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [collapsible](/docs/components/collapsible), [badge](/docs/components/badge), [code-block](/docs/components/code-block) the same way first.

**Copy the component**

**components/keyframery/tool-call.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/tool-call"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --tool-call-face: Card surface; default: bg-card.
   --tool-call-ink: Title text; default: text-foreground.
   --tool-call-muted: Name, time and labels; default: text-muted-foreground.
   --tool-call-success: Done tick; default: payoff green oklch(0.62 0.16 150).
   --tool-call-error: Failed call; default: text-destructive.
   --tool-call-radius: Card corners; default: rounded-[12px].
   --tool-call-font: Title size; default: text-[13px].
   --tool-call-code-height: Tallest input or output before it scrolls; default: max-h-[220px].
*/

/* Styled tool call: the animated primitive plus the Keyframery look. A quiet card on the card
   surface. The header reads like a line of a trace: the status mark, the title, the tool's name in
   a small mono chip, and the time it took on the right. The body holds the input and the output
   as small JSON code blocks; a failure shows its error in a destructive tint and opens on its own. */

import * as React from "react"

import { Badge } from "@/components/keyframery/badge"
import { CodeBlock, CodeBlockContent } from "@/components/keyframery/code-block"
import {
  ToolCall as ToolCallRoot,
  ToolCallContent as ToolCallContentPrimitive,
  ToolCallDuration as ToolCallDurationPrimitive,
  ToolCallIcon as ToolCallIconPrimitive,
  ToolCallLabel as ToolCallLabelPrimitive,
  ToolCallName as ToolCallNamePrimitive,
  ToolCallSection as ToolCallSectionPrimitive,
  ToolCallStatusText as ToolCallStatusTextPrimitive,
  ToolCallTitle as ToolCallTitlePrimitive,
  ToolCallTrigger as ToolCallTriggerPrimitive,
  formatDuration,
  serialize,
  type ToolCallStatus,
} from "@/components/keyframery/primitives/tool-call"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* The time since `from`, ticking while `live`. A clock, not an animation. */
function useElapsed(from: number | undefined, live: boolean) {
  const [now, setNow] = React.useState(() => Date.now())
  React.useEffect(() => {
    if (!live || from === undefined) return
    setNow(Date.now())
    const timer = setInterval(() => setNow(Date.now()), 100)
    return () => clearInterval(timer)
  }, [from, live])
  return from === undefined ? undefined : Math.max(0, now - from)
}

type ToolCallProps = React.ComponentProps<typeof ToolCallRoot> &
  SpeedProps & {
    /** When the call started (epoch ms): a running call shows the time since. */
    startedAt?: number
  }

/* With no children it renders the whole card from its props; pass parts to compose your own. */
function ToolCall({ speed, className, children, startedAt, ...props }: ToolCallProps) {
  return (
    <Speed speed={speed}>
      <ToolCallRoot
        className={withClass(
          cn(
            "@container w-full min-w-0 overflow-hidden rounded-[var(--tool-call-radius,12px)] bg-[var(--tool-call-face,var(--card))] text-[length:var(--tool-call-font,13px)] text-card-foreground",
            "shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]",
            "has-[[data-slot=collapsible-trigger]:focus-visible]:ring-2 has-[[data-slot=collapsible-trigger]:focus-visible]:ring-ring has-[[data-slot=collapsible-trigger]:focus-visible]:ring-offset-2 has-[[data-slot=collapsible-trigger]:focus-visible]:ring-offset-background",
          ),
          className,
        )}
        {...props}
      >
        {children ?? <ToolCallCard {...props} startedAt={startedAt} />}
      </ToolCallRoot>
    </Speed>
  )
}

/* The card the props describe: header, then input and output (or the error). */
function ToolCallCard({
  name,
  title,
  status = "done",
  input,
  output,
  error,
  duration,
  startedAt,
}: Pick<ToolCallProps, "name" | "title" | "status" | "input" | "output" | "error" | "duration" | "startedAt">) {
  const elapsed = useElapsed(startedAt, status === "running")
  const time = status === "running" ? formatDuration(elapsed) : formatDuration(duration)
  const hasOutput = output !== undefined && output !== null && output !== ""
  return (
    <>
      <ToolCallTrigger>
        <ToolCallIcon />
        <ToolCallTitle>{title || name}</ToolCallTitle>
        {title && name && <ToolCallName>{name}</ToolCallName>}
        <span className="ms-auto flex shrink-0 items-center gap-2 ps-1">
          {status === "approval" ? (
            <Badge variant="outline"><ToolCallStatusText /></Badge>
          ) : (
            status !== "done" && status !== "running" && <ToolCallStatusText />
          )}
          {status === "running" && <span className="sr-only"><ToolCallStatusText /></span>}
          {time && (status === "done" || status === "running") && <ToolCallDuration>{time}</ToolCallDuration>}
        </span>
      </ToolCallTrigger>
      <ToolCallContent>
        {input !== undefined && (
          <ToolCallSection kind="input">
            <ToolCallLabel>Input</ToolCallLabel>
            <ToolCallValue value={input} />
          </ToolCallSection>
        )}
        {status === "error" && error ? (
          <ToolCallSection kind="error">
            <ToolCallLabel>Error</ToolCallLabel>
            <ToolCallError>{error}</ToolCallError>
          </ToolCallSection>
        ) : hasOutput ? (
          <ToolCallSection kind="output">
            <ToolCallLabel>Output</ToolCallLabel>
            <ToolCallValue value={output} />
          </ToolCallSection>
        ) : status === "running" || status === "pending" || status === "approval" ? (
          <ToolCallSection kind="output">
            <ToolCallLabel>Output</ToolCallLabel>
            <p className="text-[12.5px] text-[color:var(--tool-call-muted,var(--muted-foreground))]">
              {status === "approval" ? "Waits for your approval." : status === "pending" ? "Not started yet." : "Waiting for the tool…"}
            </p>
          </ToolCallSection>
        ) : null}
      </ToolCallContent>
    </>
  )
}

/* The header row: a full-width button with the chevron at the end. */
function ToolCallTrigger({ className, ...props }: React.ComponentProps<typeof ToolCallTriggerPrimitive>) {
  return (
    <ToolCallTriggerPrimitive
      className={withClass(
        cn(
          "flex h-11 w-full min-w-0 cursor-pointer items-center gap-2.5 ps-3 pe-3 text-start outline-none select-none",
          "hover:bg-[color-mix(in_oklab,var(--foreground)_3%,transparent)] active:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)]",
          "*:data-[slot=tool-call-chevron]:text-[color:var(--tool-call-muted,var(--muted-foreground))]",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* 16px. Done takes the payoff green, a failure the destructive colour. */
function ToolCallIcon({ className, ...props }: React.ComponentProps<typeof ToolCallIconPrimitive>) {
  return (
    <ToolCallIconPrimitive
      className={withClass(
        cn(
          "grid size-4 shrink-0 place-items-center text-[color:var(--tool-call-ink,var(--foreground))] [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
          "[&_[data-mark=done]]:text-[color:var(--tool-call-success,oklch(0.62_0.16_150))]",
          "[&_[data-mark=error]]:text-[color:var(--tool-call-error,var(--destructive))]",
          "[&_[data-mark=denied]]:text-[color:var(--tool-call-muted,var(--muted-foreground))] [&_[data-mark=pending]]:text-[color:var(--tool-call-muted,var(--muted-foreground))]",
        ),
        className,
      )}
      {...props}
    />
  )
}

function ToolCallTitle({ className, ...props }: React.ComponentProps<typeof ToolCallTitlePrimitive>) {
  return (
    <ToolCallTitlePrimitive
      className={withClass(
        cn(
          "min-w-0 truncate leading-[1.35] font-medium text-[color:var(--tool-call-ink,var(--foreground))]",
          "group-data-[status=pending]/tool-call:text-[color:var(--tool-call-muted,var(--muted-foreground))] group-data-[status=denied]/tool-call:text-[color:var(--tool-call-muted,var(--muted-foreground))]",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The tool's own name, in a small mono chip. It gives way first when the row is narrow. */
function ToolCallName({ className, ...props }: React.ComponentProps<typeof ToolCallNamePrimitive>) {
  return (
    <ToolCallNamePrimitive
      className={withClass(
        "min-w-0 shrink-[2] truncate rounded-[5px] @max-[24rem]:hidden bg-[color-mix(in_oklab,var(--muted)_80%,transparent)] px-1.5 py-[3px] font-mono text-[11px] leading-none text-[color:var(--tool-call-muted,var(--muted-foreground))]",
        className,
      )}
      {...props}
    />
  )
}

/* The status in words; red when it failed. In the card it sits in an outline badge while it waits for a person. */
function ToolCallStatusText({ className, ...props }: React.ComponentProps<typeof ToolCallStatusTextPrimitive>) {
  return (
    <ToolCallStatusTextPrimitive
      className={withClass(
        cn(
          "text-[12px] leading-none font-medium whitespace-nowrap text-[color:var(--tool-call-muted,var(--muted-foreground))]",
          "data-[status=error]:text-[color:var(--tool-call-error,var(--destructive))]",
          "in-data-[slot=badge]:text-[length:inherit] in-data-[slot=badge]:text-[color:inherit]",
        ),
        className,
      )}
      {...props}
    />
  )
}

function ToolCallDuration({ className, ...props }: React.ComponentProps<typeof ToolCallDurationPrimitive>) {
  return (
    <ToolCallDurationPrimitive
      className={withClass("text-[12px] leading-none whitespace-nowrap text-[color:var(--tool-call-muted,var(--muted-foreground))] tabular-nums", className)}
      {...props}
    />
  )
}

/* The body sits under a hairline; its sections rise in one after another as it opens. */
function ToolCallContent({ className, ...props }: React.ComponentProps<typeof ToolCallContentPrimitive>) {
  return (
    <ToolCallContentPrimitive
      className={withClass(
        cn(
          "min-w-0 shadow-[inset_0_1px_0_rgb(0_0_0/0.06)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.07)]",
          "flex flex-col gap-3 *:first:mt-3 *:last:mb-3",
        ),
        className,
      )}
      {...props}
    />
  )
}

function ToolCallSection({ className, ...props }: React.ComponentProps<typeof ToolCallSectionPrimitive>) {
  return <ToolCallSectionPrimitive className={withClass("flex min-w-0 flex-col gap-1.5 px-3", className)} {...props} />
}

function ToolCallLabel({ className, ...props }: React.ComponentProps<typeof ToolCallLabelPrimitive>) {
  return (
    <ToolCallLabelPrimitive
      className={withClass("text-[11.5px] leading-none font-medium text-[color:var(--tool-call-muted,var(--muted-foreground))]", className)}
      {...props}
    />
  )
}

/* A value as a small code block: objects as pretty JSON, strings as they are. */
function ToolCallValue({ value, className }: { value: unknown; className?: string }) {
  const code = serialize(value)
  return (
    <CodeBlock code={code} language={typeof value === "string" ? "text" : "json"} wrap size="sm" className={cn("shadow-[0_0_0_1px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]", className)}>
      <CodeBlockContent className="max-h-[var(--tool-call-code-height,220px)]" />
    </CodeBlock>
  )
}

function ToolCallError({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="tool-call-error"
      className={cn(
        "rounded-[10px] px-3 py-2 text-[12.5px] leading-relaxed text-[color:var(--tool-call-error,var(--destructive))]",
        "bg-[color-mix(in_oklab,var(--tool-call-error,var(--destructive))_7%,transparent)] dark:bg-[color-mix(in_oklab,var(--tool-call-error,var(--destructive))_12%,transparent)]",
        className,
      )}
      {...props}
    />
  )
}

export {
  ToolCall,
  ToolCallContent,
  ToolCallDuration,
  ToolCallError,
  ToolCallTrigger,
  ToolCallIcon,
  ToolCallLabel,
  ToolCallName,
  ToolCallSection,
  ToolCallStatusText,
  ToolCallTitle,
  ToolCallValue,
}
export type { ToolCallStatus }
```

**components/keyframery/primitives/tool-call.tsx**

```tsx
"use client"

/* Animated tool call, on UI SDK's core. UI SDK ships no tool call, so its parts are defined in
   `@/components/core/tool-call` with `definePrimitive` and rendered here; the body that opens is UI
   SDK's collapsible (through Keyframery's animated collapsible primitive), controlled by the tool
   call's own `open`, so the card is one component to an agent. This file adds motion only.
   Colours, radii and spacing stay yours (style `data-status`).

   Feedback (runs at any --kf-flourish):
   - Spinner: a running call's mark turns; a running title has a light passing through it.
   - Height: the body opens to its real height; the chevron turns.
   - Fade: a status label that changes fades in.
   Flourish (scaled by --kf-flourish, gone at 0):
   - Rise: the card rises in when it arrives.
   - Draw and Pop: the done tick pops in and draws itself; the failed and denied marks pop.
   - Direction: a new status label rises into place; the body's sections cascade in.
   - Press depth on the header. */

import type { StateOf } from "@ui-sdk/core"
import { type PartProps, usePart, usePrimitive, type PrimitiveHandle } from "@ui-sdk/react/primitive"
import * as React from "react"

import {
  Collapsible as CollapsibleRoot,
  CollapsiblePanel as CollapsiblePanelPart,
  CollapsibleTrigger as CollapsibleTriggerPart,
} from "@/components/keyframery/primitives/collapsible"
import { statusLabels, toolCall, type ToolCallOptions } from "@/components/keyframery/core/tool-call-core"
import { cn } from "@/lib/utils"

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const keyframes = [
  "@keyframes kf-tool-call-in{from{opacity:0;translate:0 calc(8px*var(--kf-flourish,1));filter:blur(calc(4px*var(--kf-flourish,1)))}}",
  "@keyframes kf-tool-call-shimmer{from{background-position:100% 0}to{background-position:0% 0}}",
  "@keyframes kf-tool-call-tick{from{stroke-dashoffset:1}}",
  "@keyframes kf-tool-call-pop{from{scale:calc(1 - 0.6*var(--kf-flourish,1));opacity:0}}",
  "@keyframes kf-tool-call-label{from{opacity:0;translate:0 calc(6px*var(--kf-flourish,1));filter:blur(calc(3px*var(--kf-flourish,1)))}}",
].join("")

/* The instance, for the parts that hand changes back to it (the collapsible's open). */
const HandleContext = React.createContext<PrimitiveHandle<typeof toolCall> | null>(null)
/** The tool call around this part: its `state` and `api` (`setOpen`, `toggle`). */
function useToolCall() {
  const handle = React.use(HandleContext)
  if (!handle) throw new Error("Tool call parts must be inside <ToolCall>.")
  return handle
}

type RootProps = ToolCallOptions & Omit<PartProps<"div", StateOf<typeof toolCall, "root">>, "title">

/* The card rises in when it arrives. Its body is UI SDK's collapsible, controlled by the tool
   call's `open`: an agent's `setOpen` on the collapsible comes back here through `onOpenChange`. */
function ToolCall({
  name,
  title,
  status,
  input,
  output,
  error,
  duration,
  open,
  defaultOpen,
  onOpenChange,
  openOnError,
  className,
  children,
  ...props
}: RootProps) {
  const handle = usePrimitive(toolCall, { name, title, status, input, output, error, duration, open, defaultOpen, onOpenChange, openOnError })
  const root = usePart(
    handle,
    "root",
    {},
    {
      ...props,
      className: withClass(
        "group/tool-call animate-[kf-tool-call-in_calc(460ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-spring)_backwards] motion-reduce:animate-none",
        className,
      ),
      children: (state) => (
        <CollapsibleRoot
          open={state.open}
          onOpenChange={(next, details) => handle.api.setOpen(next, details.event, "trigger-press")}
          className="contents"
        >
          {typeof children === "function" ? children(state) : children}
        </CollapsibleRoot>
      ),
    },
    "div",
  )
  return (
    <HandleContext value={handle}>
      <style href="kf-tool-call" precedence="default">
        {keyframes}
      </style>
      {root}
    </HandleContext>
  )
}

/* The header: a button that opens the body, with a chevron after it that turns as it opens. */
function ToolCallTrigger({ className, children, ...props }: React.ComponentProps<typeof CollapsibleTriggerPart>) {
  return (
    <CollapsibleTriggerPart
      className={withClass(
        "group/tool-call-trigger transition-[scale,background-color,color] duration-[calc(220ms*var(--kf-speed,1))] ease-pop active:scale-[calc(1-0.01*var(--kf-flourish,1))] motion-reduce:transition-none!",
        className,
      )}
      {...props}
    >
      {(state) => (
        <>
          {typeof children === "function" ? children(state) : children}
          <span
            data-slot="tool-call-chevron"
            aria-hidden
            className="inline-grid shrink-0 place-items-center transition-[rotate] duration-[calc(420ms*var(--kf-speed,1))] ease-spring group-data-open/tool-call-trigger:rotate-180 motion-reduce:transition-none!"
          >
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-3.5">
              <path d="m4 6 4 4 4-4" />
            </svg>
          </span>
        </>
      )}
    </CollapsibleTriggerPart>
  )
}

/* The body: opens to its real height, its sections rising in one after another. */
const ToolCallContent = CollapsiblePanelPart

/* The mark for each status, when the icon is given no children. All six are there; the card's
   `data-status` shows one. A mark that starts showing replays its animation, so the tick pops in
   and draws itself the moment the call finishes. */
const pop = "animate-[kf-tool-call-pop_calc(380ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-pop)_backwards] motion-reduce:animate-none"

function StatusMarks() {
  return (
    <>
      <svg data-mark="pending" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeDasharray="2 2.2" className={"hidden group-data-[status=pending]/tool-call:block"}>
        <circle cx="8" cy="8" r="5.25" />
      </svg>
      <svg data-mark="running" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={cn("hidden group-data-[status=running]/tool-call:block", "animate-spin [animation-duration:calc(800ms*var(--kf-speed,1))] motion-reduce:[animation-duration:calc(2400ms*var(--kf-speed,1))]")}>
        <circle cx="8" cy="8" r="5.75" opacity="0.22" />
        <path d="M8 2.25A5.75 5.75 0 0 1 13.75 8" />
      </svg>
      <svg data-mark="approval" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={cn("hidden group-data-[status=approval]/tool-call:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path d="M6.5 6v4M9.5 6v4" />
      </svg>
      <svg data-mark="error" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={cn("hidden group-data-[status=error]/tool-call:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path d="M8 5v3.25M8 10.75v.01" />
      </svg>
      <svg data-mark="denied" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={cn("hidden group-data-[status=denied]/tool-call:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path d="m4 4 8 8" />
      </svg>
      <svg data-mark="done" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={cn("hidden group-data-[status=done]/tool-call:block", pop)}>
        <circle cx="8" cy="8" r="5.75" />
        <path
          d="M5.5 8.25 7.25 10l3.25-3.75"
          pathLength={1}
          className="[stroke-dasharray:1] animate-[kf-tool-call-tick_calc(320ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-house)_calc(120ms*var(--kf-speed,1)*var(--kf-flourish,1))_backwards] motion-reduce:animate-none"
        />
      </svg>
    </>
  )
}

/* Decorative. With no children it shows the call's status; pass your own icon to name the tool. */
function ToolCallIcon({ children, ...props }: PartProps<"span", StateOf<typeof toolCall, "icon">>) {
  return usePart(toolCall, "icon", {}, { ...props, children: children ?? <StatusMarks /> }, "span")
}

/* The light runs across a running title. Its colour is the text's own, so it works on any theme. */
function ToolCallTitle({ className, ...props }: PartProps<"span", StateOf<typeof toolCall, "title">>) {
  return usePart(
    toolCall,
    "title",
    {},
    {
      ...props,
      className: withClass(
        cn(
          "group-data-[status=running]/tool-call:bg-[linear-gradient(90deg,currentColor_0%,currentColor_38%,color-mix(in_oklch,currentColor_30%,transparent)_50%,currentColor_62%,currentColor_100%)]",
          "group-data-[status=running]/tool-call:bg-[length:250%_100%] group-data-[status=running]/tool-call:bg-clip-text group-data-[status=running]/tool-call:[-webkit-text-fill-color:transparent]",
          "group-data-[status=running]/tool-call:animate-[kf-tool-call-shimmer_calc(1800ms*var(--kf-speed,1))_var(--ease-house)_infinite]",
          "motion-reduce:animate-none! motion-reduce:bg-none! motion-reduce:[-webkit-text-fill-color:currentColor]!",
        ),
        className,
      ),
    },
    "span",
  )
}

function ToolCallName(props: PartProps<"code", StateOf<typeof toolCall, "name">>) {
  return usePart(toolCall, "name", {}, props, "code")
}

/* The status in words. With no children it says the status ("Running", "Needs approval"); a new
   label rises into place. */
function ToolCallStatusText({ className, children, ...props }: PartProps<"span", StateOf<typeof toolCall, "status">>) {
  return usePart(
    toolCall,
    "status",
    {},
    {
      ...props,
      className: withClass("inline-grid", className),
      children: (state) => (
        <span
          key={state.status}
          className="col-start-1 row-start-1 animate-[kf-tool-call-label_calc(360ms*var(--kf-speed,1))_var(--ease-spring)_backwards] motion-reduce:animate-none"
        >
          {typeof children === "function" ? children(state) : (children ?? statusLabels[state.status])}
        </span>
      ),
    },
    "span",
  )
}

function ToolCallDuration(props: PartProps<"span", StateOf<typeof toolCall, "duration">>) {
  return usePart(toolCall, "duration", {}, props, "span")
}

/* "Input", "Output" or "Error": a label and its value. */
function ToolCallSection({ kind, ...props }: PartProps<"div", StateOf<typeof toolCall, "section">> & { kind?: "input" | "output" | "error" }) {
  return usePart(toolCall, "section", { kind }, props, "div")
}

function ToolCallLabel(props: PartProps<"div", StateOf<typeof toolCall, "caption">>) {
  return usePart(toolCall, "caption", {}, props, "div")
}

export {
  ToolCall,
  ToolCallContent,
  ToolCallDuration,
  ToolCallIcon,
  ToolCallLabel,
  ToolCallName,
  ToolCallSection,
  ToolCallStatusText,
  ToolCallTitle,
  ToolCallTrigger,
  useToolCall,
}
export { formatDuration, serialize, statusLabels, summarize, type ToolCallStatus } from "@/components/keyframery/core/tool-call-core"
```

**components/keyframery/core/tool-call-core.ts**

```ts
/* A tool call: one call an AI agent made to a tool, shown as a card, as a UI SDK primitive. UI SDK
   ships none, so it is defined with its core: the same definition renders in React, Vue, Svelte,
   Solid and web components.

   The card has a header (the status mark, a human title, the tool's name, the time it took) and a
   body with the call's input and its output or error. The body opens and closes with UI SDK's
   collapsible, composed in the renderer and controlled from this primitive's `open`. To an agent the
   card reads as the tool's name, status, open state and short summaries of the input and output;
   it opens the card with the collapsible's own `setOpen`. A call that fails opens on its own
   (`openOnError`, on by default). When a call finishes or fails, screen readers hear its title
   and the new status once. */

import { announce, createChange, definePrimitive, type ChangeDetails } from "@ui-sdk/core"

/** Where the call is. `"approval"` waits for a person; `"denied"` is a call a person refused. */
type ToolCallStatus = "pending" | "running" | "approval" | "done" | "error" | "denied"

type ToolCallOpenReason = "trigger-press" | "status-error" | "imperative"

const statuses: ToolCallStatus[] = ["pending", "running", "approval", "done", "error", "denied"]
const statusOf = (status: unknown): ToolCallStatus => (statuses.includes(status as ToolCallStatus) ? (status as ToolCallStatus) : "done")

/** The words each status is read with, for screen readers and agents. */
const statusLabels: Record<ToolCallStatus, string> = {
  pending: "Queued",
  running: "Running",
  approval: "Needs approval",
  done: "Done",
  error: "Failed",
  denied: "Denied",
}

/* ------------------------------------------------------------------ serialising */

/** Pretty JSON for a tool's input or output. Strings stay as they are; cycles, functions and
    bigints never throw. */
function serialize(value: unknown): string {
  if (value === undefined) return ""
  if (typeof value === "string") return value
  const seen = new WeakSet<object>()
  try {
    return (
      JSON.stringify(
        value,
        (_key, next: unknown) => {
          if (typeof next === "bigint") return `${next}n`
          if (typeof next === "function") return `[function ${next.name || "anonymous"}]`
          if (next instanceof Error) return { name: next.name, message: next.message }
          if (next && typeof next === "object") {
            if (seen.has(next)) return "[circular]"
            seen.add(next)
          }
          return next
        },
        2,
      ) ?? String(value)
    )
  } catch {
    return String(value)
  }
}

/** One line, at most `max` characters, for an agent's snapshot or a collapsed preview. */
function summarize(value: unknown, max = 160): string {
  if (value === undefined || value === null || value === "") return ""
  let line: string
  if (typeof value === "string") line = value
  else {
    try {
      line = JSON.stringify(value, (_k, next: unknown) => (typeof next === "bigint" ? `${next}n` : next)) ?? String(value)
    } catch {
      line = serialize(value)
    }
  }
  line = line.replace(/\s+/g, " ").trim()
  return line.length > max ? `${line.slice(0, max - 1)}…` : line
}

/** "420ms", "2.4s", "1m 12s". */
function formatDuration(ms: number | undefined): string {
  if (ms === undefined || !Number.isFinite(ms) || ms < 0) return ""
  if (ms < 1000) return `${Math.round(ms)}ms`
  if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`
  const minutes = Math.floor(ms / 60_000)
  return `${minutes}m ${Math.round((ms % 60_000) / 1000)}s`
}

/* ------------------------------------------------------------------ the primitive */

type ToolCallOptions = {
  /** The tool's name, like `"search_orders"`. */
  name?: string
  /** A short human title, like "Looking up order #1048". It names the card. */
  title?: string
  /** Where the call is. @defaultValue "done" */
  status?: ToolCallStatus
  /** The call's arguments. Any value: objects are shown as pretty JSON. */
  input?: unknown
  /** What the tool returned. */
  output?: unknown
  /** Why it failed, with `status="error"`. */
  error?: string
  /** How long it took, in milliseconds. */
  duration?: number
  /** Whether the body is open. Set it to control the card yourself. */
  open?: boolean
  /** Whether the body starts open, when you don't control it. A failed call starts open. */
  defaultOpen?: boolean
  /** Runs when the body opens or closes; `details.reason` is `"status-error"` when a failure opened it. */
  onOpenChange?: (open: boolean, details: ChangeDetails<ToolCallOpenReason>) => void
  /** Open the body on its own when the call fails. @defaultValue true */
  openOnError?: boolean
}

type ToolCallState = {
  name: string
  title: string
  status: ToolCallStatus
  open: boolean
  /** One-line summaries, for agents. The renderer shows the full value. */
  input: string
  output: string
  error: string
  duration: string
  openOnError: boolean
}

const fromOptions = (options: ToolCallOptions) => ({
  name: options.name ?? "",
  title: options.title ?? "",
  status: statusOf(options.status),
  input: summarize(options.input),
  output: summarize(options.output),
  error: options.error ?? "",
  duration: formatDuration(options.duration),
  openOnError: options.openOnError !== false,
})

const toolCall = definePrimitive({
  name: "tool-call",
  options: {
    name: "string",
    title: "string",
    status: "string",
    input: "value",
    output: "value",
    error: "string",
    duration: "number",
    open: "boolean",
    defaultOpen: "boolean",
    onOpenChange: "callback",
    openOnError: "boolean",
  },
  state: (options: ToolCallOptions): ToolCallState => ({
    ...fromOptions(options),
    open: options.open ?? options.defaultOpen ?? (statusOf(options.status) === "error" && options.openOnError !== false),
  }),
  sync: (options) => ({ ...fromOptions(options), ...(options.open === undefined ? {} : { open: options.open }) }),
  controlled: ["open", "name", "status", "input", "output", "error", "duration"],
  api: (context) => {
    const change = createChange(context)
    return {
      /** Opens or closes the body. */
      setOpen(open: boolean, event?: Event, reason: ToolCallOpenReason = "imperative") {
        if (context.store.get().open === open) return
        change("open", open, { reason, event })
      },
      toggle(event?: Event) {
        change("open", !context.store.get().open, { reason: "trigger-press", event })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { status: ToolCallStatus; open: boolean }>({
      state: (state) => ({ status: state.status, open: state.open }),
      attrs: (state, part) => ({
        "data-status": state.status,
        "data-open": state.open ? "" : undefined,
        "aria-labelledby": `${part.id}-title`,
        "aria-busy": state.status === "running" ? "true" : undefined,
      }),
      /* A failure opens the body (after the render that set it, so the change is a real one the
         app hears), and the end of a call is read out once. */
      bind: (_el, part) => {
        let was = part.store.get().status
        return part.store.subscribe(() => {
          const { status, title, name, openOnError } = part.store.get()
          if (status === was) return
          const before = was
          was = status
          if (status === "error" && openOnError) part.api.setOpen(true, undefined, "status-error")
          const ended = (before === "running" || before === "approval") && status !== "running"
          if (ended) announce(`${title || name}: ${statusLabels[status]}`, { priority: status === "error" ? "assertive" : "polite" })
        })
      },
    }),
    /* Decorative: the status is also said in words, in the status part. */
    icon: slot({ attrs: () => ({ "aria-hidden": "true" }) }),
    title: slot({ attrs: (_state, part) => ({ id: `${part.id}-title` }) }),
    name: slot({ attrs: () => ({ translate: "no" }) }),
    status: slot<{}, { status: ToolCallStatus }>({
      state: (state) => ({ status: state.status }),
      attrs: (state) => ({ "data-status": state.status }),
    }),
    duration: slot({}),
    /* "Input", "Output" or "Error", and its value. */
    section: slot<{ kind?: string }, { kind: string }>({
      props: { kind: "string" },
      state: (_state, part) => ({ kind: part.props.kind ?? "input" }),
      attrs: (_state, part) => ({ "data-kind": part.props.kind ?? "input" }),
    }),
    /* "Input", "Output" or "Error". Not named `label`: UI SDK would take it as the card's name. */
    caption: slot({}),
  }),
  /* An agent reads the name, status, open state and the summaries. It opens the card through the
     body's own collapsible (its `setOpen`), which hands the change back here: one action, on one
     component, so a step that names the call by its title is never ambiguous. */
  agent: { actions: [] },
})

export { formatDuration, serialize, statusLabels, summarize, toolCall, type ToolCallOptions, type ToolCallStatus }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/tool-call.json
```

This adds `components/keyframery/tool-call/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { ToolCall } from "@/components/keyframery/tool-call"

export default function Usage() {
  return (
    <ToolCall
      name="find_order"
      title="Looked up order #1048"
      status="done"
      input={{ order_id: "1048" }}
      output={{ status: "shipped", carrier: "Royal Mail" }}
      duration={420}
    />
  )
}
```

**Vue**

```vue
<script setup lang="ts">
import { ToolCall } from "@/components/keyframery/tool-call"
</script>

<template>
  <ToolCall
    name="find_order"
    title="Looked up order #1048"
    status="done"
    :input="{ order_id: '1048' }"
    :output="{ status: 'shipped', carrier: 'Royal Mail' }"
    :duration="420"
  />
</template>
```

## Examples [#examples]

### Status [#status]

`status` is "pending", "running", "approval", "done", "error" or "denied". The mark follows it: a dashed ring, a spinner, a pause, a tick that draws itself, a mark, a slash. Pass `startedAt` and a running call counts up.

<ExamplePreview name="tool-call/status">
**React**

  ```tsx
  import * as React from "react"

  import { ToolCall } from "@/components/keyframery/tool-call"

  export default function ToolCallStatus() {
    const [startedAt] = React.useState(() => Date.now())
    return (
      <div className="flex w-full max-w-[420px] flex-col gap-2">
        <ToolCall name="find_order" title="Looked up order #1048" status="done" input={{ order_id: "1048" }} output={{ status: "shipped" }} duration={420} />
        <ToolCall name="send_email" title="Writing to Priya" status="running" input={{ to: "priya@example.com" }} startedAt={startedAt} />
        <ToolCall name="issue_refund" title="Refund £84.00" status="approval" input={{ order_id: "1048", amount: 84 }} />
        <ToolCall name="cancel_order" title="Cancel order #1048" status="denied" input={{ order_id: "1048" }} />
        <ToolCall name="notify_courier" title="Tell the courier" status="pending" input={{ carrier: "royal_mail" }} />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { ToolCall } from "@/components/keyframery/tool-call"

  const startedAt = Date.now()
  </script>

  <template>
    <div class="flex w-full max-w-[420px] flex-col gap-2">
      <ToolCall
        name="find_order"
        title="Looked up order #1048"
        status="done"
        :input="{ order_id: '1048' }"
        :output="{ status: 'shipped' }"
        :duration="420"
      />
      <ToolCall
        name="send_email"
        title="Writing to Priya"
        status="running"
        :input="{ to: 'priya@example.com' }"
        :started-at="startedAt"
      />
      <ToolCall
        name="issue_refund"
        title="Refund £84.00"
        status="approval"
        :input="{ order_id: '1048', amount: 84 }"
      />
      <ToolCall name="cancel_order" title="Cancel order #1048" status="denied" :input="{ order_id: '1048' }" />
      <ToolCall
        name="notify_courier"
        title="Tell the courier"
        status="pending"
        :input="{ carrier: 'royal_mail' }"
      />
    </div>
  </template>
  ```
</ExamplePreview>

### A call that fails [#a-call-that-fails]

With `status="error"` the card opens on its own and shows `error` in place of the output. `openOnError={false}` keeps it closed; `onOpenChange` hears `details.reason === "status-error"`.

<ExamplePreview name="tool-call/failure">
**React**

  ```tsx
  import { ToolCall } from "@/components/keyframery/tool-call"

  export default function ToolCallFailure() {
    return (
      <ToolCall
        className="max-w-[420px]"
        name="track_parcel"
        title="Couldn't reach the courier"
        status="error"
        input={{ carrier: "royal_mail", tracking: "RM 2048 1196 GB" }}
        error="Royal Mail's tracking page didn't answer within 10 seconds."
      />
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { ToolCall } from "@/components/keyframery/tool-call"
  </script>

  <template>
    <ToolCall
      class="max-w-[420px]"
      name="track_parcel"
      title="Couldn't reach the courier"
      status="error"
      :input="{ carrier: 'royal_mail', tracking: 'RM 2048 1196 GB' }"
      error="Royal Mail's tracking page didn't answer within 10 seconds."
    />
  </template>
  ```
</ExamplePreview>

### Your own card [#your-own-card]

Pass parts as children to lay the card out yourself. The trigger is the body's collapsible: an agent opens the card with its `setOpen`, and the tool call reads the name, status, input and output to it.

<ExamplePreview name="tool-call/compose">
**React**

  ```tsx
  import {
    ToolCall,
    ToolCallContent,
    ToolCallIcon,
    ToolCallLabel,
    ToolCallName,
    ToolCallSection,
    ToolCallStatusText,
    ToolCallTitle,
    ToolCallTrigger,
    ToolCallValue,
  } from "@/components/keyframery/tool-call"

  export default function ToolCallCompose() {
    const input = { query: "linen shirt", size: "M", in_stock: true }
    return (
      <ToolCall className="max-w-[420px]" name="search_products" title="Searching the shop" status="running" input={input} defaultOpen>
        <ToolCallTrigger>
          <ToolCallIcon />
          <ToolCallTitle>Searching the shop</ToolCallTitle>
          <ToolCallName>search_products</ToolCallName>
          <ToolCallStatusText className="ms-auto" />
        </ToolCallTrigger>
        <ToolCallContent>
          <ToolCallSection kind="input">
            <ToolCallLabel>Looking for</ToolCallLabel>
            <ToolCallValue value={input} />
          </ToolCallSection>
        </ToolCallContent>
      </ToolCall>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import {
    ToolCall,
    ToolCallContent,
    ToolCallIcon,
    ToolCallLabel,
    ToolCallName,
    ToolCallSection,
    ToolCallStatusText,
    ToolCallTitle,
    ToolCallTrigger,
    ToolCallValue,
  } from "@/components/keyframery/tool-call"

  const input = { query: "linen shirt", size: "M", in_stock: true }
  </script>

  <template>
    <ToolCall
      class="max-w-[420px]"
      name="search_products"
      title="Searching the shop"
      status="running"
      :input="input"
      default-open
    >
      <ToolCallTrigger>
        <ToolCallIcon />
        <ToolCallTitle>Searching the shop</ToolCallTitle>
        <ToolCallName>search_products</ToolCallName>
        <ToolCallStatusText class="ms-auto" />
      </ToolCallTrigger>
      <ToolCallContent>
        <ToolCallSection kind="input">
          <ToolCallLabel>Looking for</ToolCallLabel>
          <ToolCallValue :value="input" />
        </ToolCallSection>
      </ToolCallContent>
    </ToolCall>
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                          |
| ----------- | --------------------------------------------------------------------------------------------------------------------- |
| **Rise**    | The card rises in when it arrives (flourish).                                                                         |
| **Spin**    | A running call's mark turns and its title has a light passing through it; both say "working" and run at any flourish. |
| **Draw**    | When the call finishes, the tick pops in and draws itself (flourish); a failed or denied mark pops in.                |
| **Fade**    | A new status label fades in; it rises into place with flourish.                                                       |
| **Height**  | The body opens to its real height and the chevron turns.                                                              |
| **Cascade** | Input and output rise in one after the other as the body opens (flourish).                                            |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this tool call moves, pass `speed`:

```tsx
<ToolCall speed="fast">
  …
</ToolCall>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                  | What it changes                           | Default               |
| ------------------------- | ----------------------------------------- | --------------------- |
| `--tool-call-face`        | Card surface                              | bg-card               |
| `--tool-call-ink`         | Title text                                | text-foreground       |
| `--tool-call-muted`       | Name, time and labels                     | text-muted-foreground |
| `--tool-call-success`     | Done tick                                 | oklch(0.62 0.16 150)  |
| `--tool-call-error`       | Failed call                               | text-destructive      |
| `--tool-call-radius`      | Card corners                              | rounded-\[12px]       |
| `--tool-call-font`        | Title size                                | text-\[13px]          |
| `--tool-call-code-height` | Tallest input or output before it scrolls | max-h-\[220px]        |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### ToolCall [#toolcall]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;name&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The tool's name, like \&#x22;search_orders\&#x22;. Shown in a small mono chip.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;title&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A short human title, like \&#x22;Looked up order #1048\&#x22;. It names the card for screen readers and agents.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;status&#x22;,&#x22;type&#x22;:&#x22;\&#x22;done\&#x22; | \&#x22;error\&#x22; | \&#x22;approval\&#x22; | \&#x22;pending\&#x22; | \&#x22;denied\&#x22; | \&#x22;running\&#x22;&#x22;,&#x22;full&#x22;:&#x22;ToolCallStatus&#x22;,&#x22;default&#x22;:&#x22;\&#x22;done\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;pending\&#x22;, \&#x22;running\&#x22;, \&#x22;approval\&#x22;, \&#x22;done\&#x22; (the default), \&#x22;error\&#x22; or \&#x22;denied\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;input&#x22;,&#x22;type&#x22;:&#x22;{}&#x22;,&#x22;full&#x22;:&#x22;{}&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The call's arguments. Any value: objects show as pretty JSON in a code block.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;output&#x22;,&#x22;type&#x22;:&#x22;{}&#x22;,&#x22;full&#x22;:&#x22;{}&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the tool returned. Any value.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;error&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Why it failed, shown in place of the output when status is \&#x22;error\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;duration&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How long it took, in milliseconds: 420ms, 2.4s, 1m 12s.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;open&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Whether the body is open. Use with onOpenChange to control it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;defaultOpen&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Whether the body starts open. A failed call starts open.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onOpenChange&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;full&#x22;:&#x22;(open: boolean, details: ChangeDetails<\&#x22;trigger-press\&#x22; | \&#x22;imperative\&#x22; | \&#x22;status-error\&#x22;>) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Runs when the body opens or closes; details.reason is \&#x22;status-error\&#x22; when a failure opened it, and details.source is \&#x22;agent\&#x22; when an agent did.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;openOnError&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;true&#x22;,&#x22;description&#x22;:&#x22;Open the body on its own when the call fails. On by default.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;startedAt&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;When a running call started (epoch ms); the card counts up from it.&#x22;,&#x22;required&#x22;:false}]" />

### ToolCallContent [#toolcallcontent]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;keepMounted&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Whether the panel stays in the page, hidden, while closed.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;hiddenUntilFound&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:&#x22;false&#x22;,&#x22;description&#x22;:&#x22;Keeps the closed panel in the page as `hidden=\&#x22;until-found\&#x22;`, so the browser's find in page can match its text and open it.&#x22;,&#x22;required&#x22;:false}]" />

### ToolCallSection [#toolcallsection]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;kind&#x22;,&#x22;type&#x22;:&#x22;\&#x22;input\&#x22; | \&#x22;output\&#x22; | \&#x22;error\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;input\&#x22; | \&#x22;output\&#x22; | \&#x22;error\&#x22;&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:false}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `ToolCallDuration`: a `<span>`
* `ToolCallError`: a `<p>`
* `ToolCallTrigger`: a `<button>`
* `ToolCallIcon`: a `<span>`
* `ToolCallLabel`: a `<div>`
* `ToolCallName`
* `ToolCallStatusText`: a `<span>`
* `ToolCallTitle`: a `<span>`
* `ToolCallValue`: a `<div>`

## Hooks [#hooks]

### useToolCall [#usetoolcall]

Call it inside the component to read and change its state.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;primitive&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;The primitive it's an instance of.&#x22;},{&#x22;name&#x22;:&#x22;instance&#x22;,&#x22;type&#x22;:&#x22;function&#x22;,&#x22;description&#x22;:&#x22;The core instance `usePrimitive` made, with its `get()`, `part()` and `api`. In render, read `state` instead of its `get()`, which shows only what React has committed.&#x22;},{&#x22;name&#x22;:&#x22;state&#x22;,&#x22;type&#x22;:&#x22;ToolCallState&#x22;,&#x22;description&#x22;:&#x22;The state this render shows. Reading it doesn't subscribe; a part's `render` and class name functions get the state they render.&#x22;},{&#x22;name&#x22;:&#x22;api&#x22;,&#x22;type&#x22;:&#x22;{ setOpen(open: boolean, event?: Event, reaso…&#x22;,&#x22;description&#x22;:&#x22;The methods its definition declares, like Tabs' `setValue`.&#x22;}]" />

## Keyboard [#keyboard]

| Key                       | What it does                |
| ------------------------- | --------------------------- |
| <kbd>Tab</kbd>            | Moves to the card's header. |
| <kbd>Enter or Space</kbd> | Opens or closes the card.   |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a tool call, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/tool-call-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/tool-call`.

## Questions

### How does the animated Tool Call for UI SDK move?

Rise: The card rises in when it arrives (flourish). Spin: A running call's mark turns and its title has a light passing through it; both say "working" and run at any flourish. Draw: When the call finishes, the tick pops in and draws itself (flourish); a failed or denied mark pops in. Fade: A new status label fades in; it rises into place with flourish. Height: The body opens to its real height and the chevron turns. Cascade: Input and output rise in one after the other as the body opens (flourish).

### Do I need Motion or Framer Motion for the animated Tool Call?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no tool call. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/tool-call-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Tool Call when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
