Tool
Shows a tool call the agent made, from pending to finished, with its input and output on request.
Installation
pnpm dlx shadcn@latest add @silkware/ai-toolTo copy the pattern by hand, install the components it composes:
pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/code-block @silkware/message @silkware/traceThen the packages:
pnpm add ai @ai-sdk/react @shadcn/helpers lucide-reactCopy the source into components/ai-elements/tool.tsx. The file also needs @/lib/ai, the helper that streams scripted conversations in development:
"use client"
import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import { TerminalIcon } from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Message, MessageContent } from "@/components/ui/message"import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage< unknown, UIDataTypes, { runCommand: { input: { command: string } output: { stdout: string } } }>
type ToolPart = Extract< ChatMessage["parts"][number], { type: "tool-runCommand" }>
const chat = createChat<ChatMessage>() .user("Which package managers are installed?") .assistant(({ writer }) => { writer .tool("runCommand", { input: { command: "node --version" } }) .sleep(900) .output({ stdout: "v24.18.0" }) writer .tool("runCommand", { input: { command: "npm --version" } }) .sleep(900) .output({ stdout: "11.6.2" }) writer .tool("runCommand", { input: { command: "pnpm --version" } }) .sleep(900) .error("command not found: pnpm") writer.text("Node 24 and npm 11 are installed. pnpm is not.") })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function ToolRow({ part, streaming, defaultExpanded,}: { part: ToolPart streaming: boolean defaultExpanded?: boolean}) { const command = part.input?.command
if (part.state === "output-available" || part.state === "output-error") { const failed = part.state === "output-error"
return ( <TraceCollapsible defaultExpanded={defaultExpanded}> <TraceCollapsibleTrigger> <TraceLine status={failed ? "error" : undefined}> <TraceIcon> <TerminalIcon /> </TraceIcon> <TraceTitle> {failed ? "Failed to run" : "Ran"} {command} </TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <CodeBlock size="sm"> <CodeBlockContent wrap className="max-h-64"> {failed ? part.errorText : part.output.stdout} </CodeBlockContent> </CodeBlock> </TraceCollapsibleContent> </TraceCollapsible> ) }
return ( <TraceLine status={streaming ? "running" : "error"}> <TraceIcon> <TerminalIcon /> </TraceIcon> <TraceTitle> {streaming ? "Running" : "Failed to run"} {command} </TraceTitle> </TraceLine> )}
export function ToolDemo() { const { messages, sendMessage, setMessages, status } = useChat({ messages: transcript, transport, }) const busy = status === "submitted" || status === "streaming"
return ( <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm"> {messages.map((message) => { if (message.role === "user") { return ( <Message key={message.id} align="end"> <MessageContent> <Bubble align="end" variant="muted"> <BubbleContent>{getMessageText(message)}</BubbleContent> </Bubble> </MessageContent> </Message> ) }
const streaming = busy && message === messages.at(-1) const tools = message.parts.filter( (part) => part.type === "tool-runCommand" ) const text = getMessageText(message)
return ( <Message key={message.id}> <MessageContent className="gap-4"> {tools.length > 0 && ( <Trace> {tools.map((part) => ( <ToolRow key={part.toolCallId} part={part} streaming={streaming} defaultExpanded={ busy ? undefined : part.state === "output-error" } /> ))} </Trace> )} {text && <p>{text}</p>} </MessageContent> </Message> ) })} {!busy && ( <Button variant="outline" size="sm" className="mt-auto self-start" onPress={() => { setMessages([]) sendMessage(question) }} > Replay </Button> )} </div> )}Usage
A tool call is a line of text with an icon. The line names what the agent did, in the past tense once it is done. When the output matters, make the line a collapsible that opens onto it.
import { TerminalIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"<Trace> <TraceCollapsible> <TraceCollapsibleTrigger> <TraceLine> <TraceIcon> <TerminalIcon /> </TraceIcon> <TraceTitle>Ran git status --short</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <CodeBlock size="sm"> <CodeBlockContent wrap className="max-h-64"> {output} </CodeBlockContent> </CodeBlock> </TraceCollapsibleContent> </TraceCollapsible></Trace>Set status on TraceLine to "running" while the call is in flight and to "error" when it failed. Write the state in the title as well ("Running", "Failed to run"), because the status styling alone is a shimmer and a colour.
Examples
States
A tool call is running, finished, failed or denied. The title carries the state in words. A finished call opens onto its output, a failed call onto the error, and a denied call has nothing to open.
Long output
Cap the height of the output with max-h-* on CodeBlockContent so one call cannot push the rest of the conversation out of view. The output scrolls inside the block.
BM-2001 shipped 12 units
BM-2002 open 24 units
BM-2003 open 36 units
BM-2004 shipped 48 units
BM-2005 open 60 units
BM-2006 open 72 units
BM-2007 shipped 84 units
BM-2008 open 96 units
BM-2009 open 108 units
BM-2010 shipped 120 units
BM-2011 open 132 units
BM-2012 open 144 units
BM-2013 shipped 156 units
BM-2014 open 168 units
BM-2015 open 180 units
BM-2016 shipped 192 units
BM-2017 open 204 units
BM-2018 open 216 units
BM-2019 shipped 228 units
BM-2020 open 240 units
BM-2021 open 252 units
BM-2022 shipped 264 units
BM-2023 open 276 units
BM-2024 open 288 units
BM-2025 shipped 300 units
BM-2026 open 312 units
BM-2027 open 324 units
BM-2028 shipped 336 units
BM-2029 open 348 units
BM-2030 open 360 units
BM-2031 shipped 372 units
BM-2032 open 384 units
BM-2033 open 396 units
BM-2034 shipped 408 units
BM-2035 open 420 units
BM-2036 open 432 units
BM-2037 shipped 444 units
BM-2038 open 456 units
BM-2039 open 468 units
BM-2040 shipped 480 unitsOutput in a sheet
When the output is a whole file or a long report, open it in a Sheet instead of inline. The line becomes the trigger, and the chevron points to where the output opens.
Approval
A tool that changes something waits for a person. The call stays unresolved until the person approves or denies, then the line reports the decision. The decision prompt itself is the Confirmation pattern.
AI SDK
A tool call arrives as a message part whose type is tool-<name>. Its state says where it is, and the typed input and output come with it. Type the message with the tools you use, then render one row per part:
import type { UIDataTypes, UIMessage } from "ai"
type ChatMessage = UIMessage< unknown, UIDataTypes, { runCommand: { input: { command: string } output: { stdout: string } } }>{message.parts.map((part) => { if (part.type !== "tool-runCommand") { return null }
if (part.state === "output-available") { return <RanRow key={part.toolCallId} command={part.input.command} output={part.output.stdout} /> }
if (part.state === "output-error") { return <FailedRow key={part.toolCallId} command={part.input?.command} error={part.errorText} /> }
return <RunningRow key={part.toolCallId} command={part.input?.command} />})}part.state | What to show |
|---|---|
input-streaming | A running line. input is partial and may be undefined. |
input-available | A running line with the full input. |
approval-requested | The approval prompt. See Confirmation. |
approval-responded | A running line if part.approval.approved, a denied line if not. |
output-available | A done line and part.output. |
output-error | A failed line and part.errorText. |
output-denied | A denied line. |
input-streaming and input-available also appear on a call that never finished, for example when the stream was cut. The demo checks whether the message is still streaming and shows "Failed to run" when it is not, so a call never keeps shimmering after the stream has ended.
On the server, define the tools and return the stream with an agent. The tool states above are what useChat builds from that stream:
import { createAgentUIStreamResponse, ToolLoopAgent, tool } from "ai"import { z } from "zod"
const agent = new ToolLoopAgent({ model: "anthropic/claude-sonnet-4.5", tools: { runCommand: tool({ inputSchema: z.object({ command: z.string() }), execute: async ({ command }) => ({ stdout: await run(command) }), }), },})
export async function POST(request: Request) { const { messages } = await request.json() return createAgentUIStreamResponse({ agent, uiMessages: messages })}Scripted streams in development
createChat from @/lib/ai writes the same parts without a model. writer.tool opens a call, and output or error resolves it:
const chat = createChat<ChatMessage>() .user("Which package managers are installed?") .assistant(({ writer }) => { writer .tool("runCommand", { input: { command: "pnpm --version" } }) .sleep(900) .error("command not found: pnpm") })Pass chat.get(0) and chat.transport() to useChat. The live demos on this page run on this, with no model, route or key.
Accessibility
| Key | Action |
|---|---|
| Enter | Opens or closes the output of the focused tool line. |
| Space | Opens or closes the output of the focused tool line. |
| Tab | Moves focus to the next tool line or control. |
The composed components provide:
- A trigger that is a real button with
aria-expanded, and a panel linked to it, from the React Aria disclosure underTraceCollapsible. - A visible focus ring on the trigger.
- Output in a monospace code block with the height cap you set.
You provide:
- A title that says the state in words: "Running", "Ran", "Failed to run", "Denied". The shimmer and the crimson error colour are extra signals, never the only one.
- Plain-language titles. A screen reader reads the title, so "Ran git status --short" is better than a tool name.
- A live region when the conversation should announce a call that finishes. The tool line does not announce itself.
MessageScrollerContentsetsrole="log"for new messages, and a line that changes in place is not a new message. - An accessible name for an icon-only control you add to a line.
Guidelines
When to use
- To show that the agent did something, and what, without making the person read raw output.
- To let a person open the evidence behind an answer: the command that ran, the file that was read.
When not to use
- To ask permission before the agent acts. Use Confirmation.
- To show a list of steps planned ahead. Use Plan or Queue.
- To show another agent working on a sub-task. Use Subagent.
- For command output that is the point of the answer. Use Terminal.
Content
- Name the action and what it acted on: "Updated 3 prices in the Q1 price list", not "Used a tool".
- Use the past tense when done ("Ran"), the present when running ("Running") and "Failed to" when it failed.
- Show the input the agent used, not only its result. A person checks an action by seeing what it was asked to do.
- Do not hide a failure. A failed call opens by default, and the answer text says what the agent does next.
Name the action and what it acted on, so each line stands alone.
Don’t summarise every call as "Used a tool" or "Done". The person cannot tell what changed.
Human in the loop
A tool line is a record of what happened. It is not a control, and it is not the moment to decide.
- Show every call that changes something outside the conversation, including the ones that succeeded. A person must be able to see what the agent did after the fact.
- Gate the calls that cannot be undone, spend money, send messages or touch other people's data behind an approval before they run. Render the prompt with Confirmation, and let the tool line report the decision afterwards.
- Say when a call was denied and by whom. A denied call that disappears from the transcript makes the next message of the agent hard to follow.
- Give a running call a way to stop. A stop control for the whole turn (
stopfromuseChat) belongs in the prompt area, near where the person is looking. - Say what can be undone. If the call has an undo, put a button next to the line. If it has none, say so in the approval, before the call.
Composition
| Component | What it does here |
|---|---|
| Trace | Lays out the lines and carries the running and error status, the collapsible and the chevron. |
| Code Block | Shows the output or the error text in monospace, with a height cap and wrapping. |
| Message | Places the conversation in turns, with the assistant on the start side. |
| Bubble | Wraps the person's own message. |
| Button | The replay control of the demo. |
| Sheet | Opens long output beside the conversation, in the sheet example. |
| Item | Holds the approval prompt, in the approval example. |
components/ai-elements/tool.tsx exports ToolDemo, a chat that streams three scripted runCommand calls (two succeed, one fails) and renders each with the rows above. Copy the ToolRow function into your app and replace the scripted chat with useChat against your route.