Tool
A collapsible card for a tool call, with the call's status, its input and what came back.
UpdatedInstallation
Copy and paste the following code into your project.
1'use client';23import { AnimatePresence, motion, useReducedMotion, type Variants } from 'motion/react';4import * as React from 'react';5import { cn } from '../lib/cn';6import {7 ARRIVE,8 AUTO_HEIGHT,9 Arrivals,10 STATUS_IN,11 useArrival,12 useAutoHeight,13 useChanged,14} from '../lib/arrival';15import { collapse, springs, still } from '../lib/motion';16import { useControllableState } from '../lib/use-controllable-state';1718type IconProps = React.SVGProps<SVGSVGElement> & {19 size?: number | string;20};2122function WrenchIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {23 return (24 <svg25 xmlns="http://www.w3.org/2000/svg"26 width={size}27 height={size}28 viewBox="0 0 24 24"29 fill="none"30 stroke="currentColor"31 strokeWidth={strokeWidth}32 strokeLinecap="round"33 strokeLinejoin="round"34 aria-hidden="true"35 {...props}36 >37 <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />38 </svg>39 );40}4142function ChevronDownIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {43 return (44 <svg45 xmlns="http://www.w3.org/2000/svg"46 width={size}47 height={size}48 viewBox="0 0 24 24"49 fill="none"50 stroke="currentColor"51 strokeWidth={strokeWidth}52 strokeLinecap="round"53 strokeLinejoin="round"54 aria-hidden="true"55 {...props}56 >57 <path d="m6 9 6 6 6-6" />58 </svg>59 );60}6162function CheckIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {63 return (64 <svg65 xmlns="http://www.w3.org/2000/svg"66 width={size}67 height={size}68 viewBox="0 0 24 24"69 fill="none"70 stroke="currentColor"71 strokeWidth={strokeWidth}72 strokeLinecap="round"73 strokeLinejoin="round"74 aria-hidden="true"75 {...props}76 >77 <path d="M20 6 9 17l-5-5" />78 </svg>79 );80}8182function LoaderIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {83 return (84 <svg85 xmlns="http://www.w3.org/2000/svg"86 width={size}87 height={size}88 viewBox="0 0 24 24"89 fill="none"90 stroke="currentColor"91 strokeWidth={strokeWidth}92 strokeLinecap="round"93 strokeLinejoin="round"94 aria-hidden="true"95 {...props}96 >97 <path d="M12 3a9 9 0 1 0 9 9" />98 </svg>99 );100}101102function AlertIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {103 return (104 <svg105 xmlns="http://www.w3.org/2000/svg"106 width={size}107 height={size}108 viewBox="0 0 24 24"109 fill="none"110 stroke="currentColor"111 strokeWidth={strokeWidth}112 strokeLinecap="round"113 strokeLinejoin="round"114 aria-hidden="true"115 {...props}116 >117 <circle cx="12" cy="12" r="9" />118 <path d="M12 8v4" />119 <path d="M12 16h.01" />120 </svg>121 );122}123124function DotIcon({ size = 24, ...props }: IconProps) {125 return (126 <svg127 xmlns="http://www.w3.org/2000/svg"128 width={size}129 height={size}130 viewBox="0 0 24 24"131 fill="currentColor"132 aria-hidden="true"133 {...props}134 >135 <circle cx="12" cy="12" r="4" />136 </svg>137 );138}139140function ShieldIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {141 return (142 <svg143 xmlns="http://www.w3.org/2000/svg"144 width={size}145 height={size}146 viewBox="0 0 24 24"147 fill="none"148 stroke="currentColor"149 strokeWidth={strokeWidth}150 strokeLinecap="round"151 strokeLinejoin="round"152 aria-hidden="true"153 {...props}154 >155 <path d="M12 3 5 6v5c0 4.5 3 8 7 10 4-2 7-5.5 7-10V6z" />156 <path d="M12 9v3" />157 <path d="M12 15h.01" />158 </svg>159 );160}161162function BanIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {163 return (164 <svg165 xmlns="http://www.w3.org/2000/svg"166 width={size}167 height={size}168 viewBox="0 0 24 24"169 fill="none"170 stroke="currentColor"171 strokeWidth={strokeWidth}172 strokeLinecap="round"173 strokeLinejoin="round"174 aria-hidden="true"175 {...props}176 >177 <circle cx="12" cy="12" r="9" />178 <path d="m5.6 5.6 12.8 12.8" />179 </svg>180 );181}182183const INSTANT_COLLAPSE: Variants = {184 closed: { height: 0, opacity: 0, transition: still },185 open: { height: 'auto', opacity: 1, transition: still },186};187188type ToolStatus = 'pending' | 'awaiting-approval' | 'running' | 'complete' | 'error' | 'denied';189190type ToolStatusLabels = Record<ToolStatus, string>;191192const DEFAULT_STATUS_LABELS: ToolStatusLabels = {193 pending: 'Pending',194 'awaiting-approval': 'Waiting for approval',195 running: 'Running',196 complete: 'Completed',197 error: 'Failed',198 denied: 'Denied',199};200201const STATUS_ICON: Record<ToolStatus, React.ComponentType<IconProps>> = {202 pending: DotIcon,203 'awaiting-approval': ShieldIcon,204 running: LoaderIcon,205 complete: CheckIcon,206 error: AlertIcon,207 denied: BanIcon,208};209210const STATUS_TONE: Record<ToolStatus, string> = {211 pending: 'text-muted-foreground',212 'awaiting-approval': 'text-warning-text',213 running: 'text-foreground',214 complete: 'text-success-text',215 error: 'text-destructive-text',216 denied: 'text-muted-foreground',217};218219interface ToolContextValue {220 open: boolean;221 setOpen: (open: boolean) => void;222 status: ToolStatus;223 id: string;224}225226const ToolContext = React.createContext<ToolContextValue | null>(null);227228const useToolContext = (): ToolContextValue => {229 const context = React.use(ToolContext);230 if (!context) {231 throw new Error('Tool components must be used within Tool');232 }233 return context;234};235236interface ToolProps extends React.HTMLAttributes<HTMLDivElement> {237 status?: ToolStatus;238 defaultOpen?: boolean;239 open?: boolean;240 onOpenChange?: (open: boolean) => void;241}242243interface ToolHeaderProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {244 name: string;245 description?: string;246 statusLabels?: Partial<ToolStatusLabels>;247}248249type ToolContentProps = React.HTMLAttributes<HTMLDivElement>;250251interface ToolInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> {252 label?: string;253 value?: unknown;254 children?: React.ReactNode;255}256257interface ToolOutputProps extends ToolInputProps {258 error?: boolean;259}260261function formatValue(value: unknown): string {262 if (typeof value === 'string') return value;263 if (value === undefined) return '';264 try {265 return JSON.stringify(value, null, 2);266 } catch {267 return String(value);268 }269}270271const ToolRoot = ({272 className,273 status = 'complete',274 defaultOpen = false,275 open: controlledOpen,276 onOpenChange,277 children,278 ref,279 ...props280}: ToolProps & { ref?: React.Ref<HTMLDivElement> }) => {281 const [open, setOpen] = useControllableState({282 value: controlledOpen,283 defaultValue: defaultOpen,284 onChange: onOpenChange,285 });286 const id = React.useId();287 const previousStatus = React.useRef<ToolStatus | undefined>(undefined);288289 React.useEffect(() => {290 if (status === 'awaiting-approval' && previousStatus.current !== status) setOpen(true);291 previousStatus.current = status;292 }, [status, setOpen]);293294 const value = React.useMemo<ToolContextValue>(295 () => ({ open, setOpen, status, id }),296 [open, setOpen, status, id],297 );298299 const arrived = useArrival();300 return (301 <ToolContext value={value}>302 <div303 ref={ref}304 data-state={open ? 'open' : 'closed'}305 data-status={status}306 className={cn(307 'bg-card text-card-foreground data-[status=awaiting-approval]:ring-warning-border w-full overflow-hidden rounded-lg shadow-sm data-[status=awaiting-approval]:ring-2',308 arrived && ARRIVE,309 className,310 )}311 {...props}312 >313 {children}314 </div>315 </ToolContext>316 );317};318319ToolRoot.displayName = 'Tool';320321const ToolHeader = ({322 className,323 name,324 description,325 statusLabels,326 onClick,327 ref,328 ...props329}: ToolHeaderProps & { ref?: React.Ref<HTMLButtonElement> }) => {330 const { open, setOpen, status, id } = useToolContext();331 const shouldReduceMotion = useReducedMotion();332 const StatusIcon = STATUS_ICON[status];333 const statusChanged = useChanged(status);334 const statusLabel = statusLabels?.[status] ?? DEFAULT_STATUS_LABELS[status];335336 return (337 <button338 ref={ref}339 type="button"340 id={`${id}-trigger`}341 aria-expanded={open}342 aria-controls={open ? `${id}-content` : undefined}343 onClick={(event) => {344 setOpen(!open);345 onClick?.(event);346 }}347 className={cn(348 'text-foreground hover:bg-muted/60 focus-visible:ring-ring flex w-full items-center gap-3 px-3 py-2.5 text-start transition-colors focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset',349 className,350 )}351 {...props}352 >353 <span aria-hidden="true" className="text-muted-foreground flex shrink-0">354 <WrenchIcon size={14} />355 </span>356 <span className="flex min-w-0 flex-1 flex-col gap-0.5">357 <span358 className={cn(359 'truncate font-mono text-xs',360 status === 'denied' && 'text-muted-foreground line-through',361 )}362 >363 {name}364 </span>365 {description ? (366 <span className="text-muted-foreground truncate text-xs">{description}</span>367 ) : null}368 </span>369 <span className={cn('flex shrink-0 items-center gap-1.5 text-xs', STATUS_TONE[status])}>370 <span371 key={status}372 aria-hidden="true"373 className={cn(374 'flex shrink-0',375 status === 'running' ? 'motion-safe:animate-spin' : statusChanged && STATUS_IN,376 )}377 >378 <StatusIcon size={14} />379 </span>380 <span className="sr-only">{statusLabel}</span>381 </span>382 <motion.span383 aria-hidden="true"384 className="text-muted-foreground flex shrink-0"385 animate={shouldReduceMotion ? undefined : { rotate: open ? 180 : 0 }}386 transition={springs.snappy}387 >388 <ChevronDownIcon size={14} />389 </motion.span>390 </button>391 );392};393394ToolHeader.displayName = 'ToolHeader';395396const ToolContent = ({397 className,398 children,399 ref,400 ...props401}: ToolContentProps & { ref?: React.Ref<HTMLDivElement> }) => {402 const { open, id } = useToolContext();403 const shouldReduceMotion = useReducedMotion();404405 const [growRef, growStyle] = useAutoHeight();406407 return (408 <AnimatePresence initial={false}>409 {open && (410 <motion.div411 ref={ref}412 id={`${id}-content`}413 role="region"414 aria-labelledby={`${id}-trigger`}415 variants={shouldReduceMotion ? INSTANT_COLLAPSE : collapse}416 initial="closed"417 animate="open"418 exit="closed"419 className="overflow-hidden"420 >421 <div style={growStyle} className={AUTO_HEIGHT}>422 <div ref={growRef} className="flow-root">423 <Arrivals>424 <div425 className={cn(426 'border-border flex flex-col gap-3 border-t px-3 py-3 [&_[data-slot=confirmation]]:rounded-md',427 className,428 )}429 {...props}430 >431 {children}432 </div>433 </Arrivals>434 </div>435 </div>436 </motion.div>437 )}438 </AnimatePresence>439 );440};441442ToolContent.displayName = 'ToolContent';443444const ToolBlock = ({445 className,446 label,447 value,448 children,449 error = false,450 ref,451 ...props452}: ToolOutputProps & { ref?: React.Ref<HTMLDivElement> }) => {453 const body = children ?? formatValue(value);454455 return (456 <div457 ref={ref}458 data-error={error ? '' : undefined}459 className={cn('flex flex-col gap-1.5', className)}460 {...props}461 >462 <span463 className={cn(464 'font-mono text-[11px]',465 error ? 'text-destructive-text' : 'text-muted-foreground',466 )}467 >468 {label}469 </span>470 {typeof body === 'string' ? (471 <pre472 className={cn(473 'overflow-x-auto rounded-md px-3 py-2 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap',474 error ? 'bg-destructive-surface text-destructive-text' : 'bg-secondary text-foreground',475 )}476 >477 {body}478 </pre>479 ) : (480 <div481 className={cn(482 'rounded-md px-3 py-2 text-sm',483 error ? 'bg-destructive-surface text-destructive-text' : 'bg-secondary text-foreground',484 )}485 >486 {body}487 </div>488 )}489 </div>490 );491};492493const ToolInput = ({494 label = 'Input',495 ref,496 ...props497}: ToolInputProps & { ref?: React.Ref<HTMLDivElement> }) => {498 return <ToolBlock ref={ref} label={label} {...props} />;499};500501ToolInput.displayName = 'ToolInput';502503const ToolOutput = ({504 label = 'Output',505 ref,506 ...props507}: ToolOutputProps & { ref?: React.Ref<HTMLDivElement> }) => {508 return <ToolBlock ref={ref} label={label} {...props} />;509};510511ToolOutput.displayName = 'ToolOutput';512513const Tool = Object.assign(ToolRoot, {514 Header: ToolHeader,515 Content: ToolContent,516 Input: ToolInput,517 Output: ToolOutput,518});519520export { Tool };521export type {522 ToolContentProps,523 ToolHeaderProps,524 ToolInputProps,525 ToolOutputProps,526 ToolProps,527 ToolStatus,528 ToolStatusLabels,529};
Update the import paths to match your project structure.
Anatomy
1import { Tool } from '@/ai/tool';
1<Tool status="complete">2 <Tool.Header name="get_projects" description="Lists the public projects" />3 <Tool.Content>4 <Tool.Input value={{ locale: 'en', limit: 3 }} />5 <Tool.Output value={projects} />6 </Tool.Content>7</Tool>
A tool call starts closed. The name and the status are what the reader needs at a glance; the payloads are there for whoever wants to check them. Pass
defaultOpen to the calls worth showing, like a failed one.Tool.Input and Tool.Output take any value: a string is printed as is, anything else is pretty-printed as JSON. Give Tool.Output children instead when the result deserves real markup.Composition
Use the following composition to build a
Tool:Toolโโโ Tool.Headerโโโ Tool.Contentโโโ Tool.Inputโโโ Tool.Outputโโโ Confirmation (with awaiting-approval)
Statuses
status lives on the root and drives the indicator in the header: pending waits with a dot, running spins, complete checks off, error flags, and awaiting-approval and denied cover calls that need the reader's go-ahead. Pair error with <Tool.Output error /> so the payload reads as the failure it is.Input
{
"to": "contact@ignaciofigueroa.dev",
"subject": "Hi"
}Output
422 Unprocessable Entity: recipient domain is not verified
1'use client';23import { Tool } from '@/ai/tool';45export function Statuses() {6 return (7 <div className="flex w-full max-w-md flex-col gap-3">8 <Tool status="pending">9 <Tool.Header name="analyze_job_description" description="Waiting for the previous call" />10 <Tool.Content>11 <Tool.Input value={{ body: 'Senior frontend engineer, remote, React and Next.js' }} />12 </Tool.Content>13 </Tool>14 <Tool status="running">15 <Tool.Header name="get_experience" description="Reading the work history" />16 <Tool.Content>17 <Tool.Input value={{ locale: 'en' }} />18 </Tool.Content>19 </Tool>20 <Tool status="complete">21 <Tool.Header name="get_projects" description="3 projects returned" />22 <Tool.Content>23 <Tool.Input value={{ locale: 'en', limit: 3 }} />24 <Tool.Output value={['nachui', 'portfolio', 'links']} />25 </Tool.Content>26 </Tool>27 <Tool status="error" defaultOpen>28 <Tool.Header name="send_contact_email" description="The mail provider rejected it" />29 <Tool.Content>30 <Tool.Input value={{ to: 'contact@ignaciofigueroa.dev', subject: 'Hi' }} />31 <Tool.Output error value="422 Unprocessable Entity: recipient domain is not verified" />32 </Tool.Content>33 </Tool>34 </div>35 );36}
Approval
Some calls should not run until the reader says so. Set
status="awaiting-approval": the card opens on its own, its border turns to the warning tone and screen readers hear "Waiting for approval". Put a Confirmation inside Tool.Content and move the status on with the answer: to running when approved, to denied when not. A denied call keeps its name struck through, so the thread shows what did not happen.1'use client';23import { useState } from 'react';4import { Confirmation } from '@/ai/confirmation';5import { Tool, type ToolStatus } from '@/ai/tool';67const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));89export function Approval() {10 const [status, setStatus] = useState<ToolStatus>('awaiting-approval');1112 const describe: Record<string, string> = {13 'awaiting-approval': 'Waiting for your approval',14 running: 'Sending',15 complete: 'Sent to ana@northwind.io',16 denied: 'You denied this call',17 };1819 return (20 <div className="w-full max-w-md">21 <Tool status={status}>22 <Tool.Header name="send_contact_email" description={describe[status]} />23 <Tool.Content>24 <Tool.Input value={{ to: 'ana@northwind.io', subject: 'Your invoice for October' }} />25 {status === 'awaiting-approval' ? (26 <Confirmation>27 <Confirmation.Title>Send this email?</Confirmation.Title>28 <Confirmation.Actions>29 <Confirmation.Deny onClick={() => setStatus('denied')} />30 <Confirmation.Approve31 onClick={async () => {32 setStatus('running');33 await wait(1200);34 setStatus('complete');35 }}36 >37 Send38 </Confirmation.Approve>39 </Confirmation.Actions>40 </Confirmation>41 ) : null}42 {status === 'complete' ? (43 <Tool.Output value={{ id: 'msg_8f2c', status: 'sent' }} />44 ) : null}45 </Tool.Content>46 </Tool>47 </div>48 );49}
API Reference
Tool
| Prop | Type | Default | Description |
|---|---|---|---|
status | 'pending' | 'awaiting-approval' | 'running' | 'complete' | 'error' | 'denied' | 'complete' | State of the call |
defaultOpen | boolean | false | Open state when uncontrolled |
open | boolean | - | Controlled open state |
onOpenChange | (open: boolean) => void | - | Called when the open state changes |
className | string | - | Additional CSS classes |
Tool.Header
| Prop | Type | Default | Description |
|---|---|---|---|
name | string | - | Name of the tool |
description | string | - | One line under the name |
statusLabels | Partial<Record<Status, string>> | - | Screen reader labels for each status |
className | string | - | Additional CSS classes |
Tool.Content
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Tool.Input
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | 'Input' | Label above the block |
value | unknown | - | Printed as is when a string, as JSON otherwise |
children | ReactNode | - | Replaces value when given |
className | string | - | Additional CSS classes |
Tool.Output
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | 'Output' | Label above the block |
value | unknown | - | Printed as is when a string, as JSON otherwise |
error | boolean | false | Destructive tones for a failed call |
children | ReactNode | - | Replaces value when given |
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.