Mental model
In agentic applications, a tool invocation is not a generic loading spinner: the moment an LLM emits a JSON tool call, no real-world effect has safely succeeded yet. Trustworthy agent interfaces model each tool action as an auditable finite state machine anchored to a unique operation_id, separating the model's proposal cleanly from deterministic schema/policy validation, explicit human approval checkpoints (showing exact parameters before committing irreversible side effects), live progress/timeout states, typed failure classifications, and environment-verified completion (completed only after downstream ledger/API confirmation, never merely because an HTTP enqueue returned 202).
Theory
Collapsing multiple distinct backend phases into a vague "Thinking..." or "Running" badge hides crucial distinctions users need to steer agents safely and recover cleanly from failures.
| Execution State | Meaning & Backend Ownership | UI Exposure & Next Available User Control | Critical Safety Invariant |
|---|---|---|---|
proposed -> validating | Model emitted tool JSON; app verifies schema, RBAC, and target scope | Display tool name, target entity, read/write badge (readonly vs destructive) | Never pass unvalidated model arguments straight into execution or UI rendering |
awaiting_approval | High-consequence mutation paused behind deterministic server gate | Render exact diff/amount/recipient + Approve / Edit / Reject controls | Hash/bind approved arguments so later stream drift cannot mutate what user approved! |
queued -> running | Operation accepted by worker / external provider with unique operation_id | Elapsed timer, cancel/abort control (explicitly stating whether upstream stop is supported!) | Show real step telemetry, never fake progress bars |
timeout_unknown vs failed | Network timeout (result uncertain!) vs deterministic rejection (validation/auth/business rule) | Offer Safe Retry only on idempotency-protected calls; offer Reconcile / Inspect Status on ambiguous timeouts! | Never mark ambiguous HTTP timeouts as "cancelled" cleanly without checking downstream side effects |
completed | Downstream ledger/filesystem/MCP tool returned verified canonical confirmation | Summarized structured receipt + expandable audited payload (sanitized cleanly!) | Treat tool outputs strictly as untrusted data, escaping any raw HTML/Markdown XSS! |
Distinguishing Failure Taxonomy, Cancel Honesty, and XSS Sanitization
Different failure categories demand completely distinct UI recovery affordances:
- Schema / Input Validation Failure (
recoverable_by_model): Safe to reveal cleanly in compact timeline text while letting the agent auto-correct malformed parameters. - Authorization / Policy Denied (
blocked_policy): Must surface cleanly to the user ("Access denied tobilling-prod") rather than letting the agent retry identically in a tight spin loop. - Ambiguous Network Timeout (
unknown_outcome): The most dangerous state in payment, email, or cloud-provisioning UIs! Because the downstream provider may have executed the refund right before the HTTP socket dropped, never pretend the action didn't happen or fire blind duplicate retries unless backed by a strictidempotency_keymatching the originaloperation_id. Similarly, when a user clicks Cancel, update state accurately (cancelling->cancelledif worker ACKed early stop, or"cancel_requested — action had already started"if external API lacked rollback).
typescriptexport type ToolConsequenceLevel = "read_only" | "reversible_write" | "destructive_external";export type ToolExecutionState =| { status: "awaiting_approval"; operationId: string; toolName: string; argsPreview: Record<string, unknown>; argsHash: string }| { status: "running"; operationId: string; toolName: string; startedAtMs: number; cancellable: boolean }| { status: "reconcile_needed"; operationId: string; providerTxId?: string; reason: string }| { status: "failed"; operationId: string; category: "validation" | "auth" | "business"; retrySafeWithIdempotencyKey: boolean; message: string }| { status: "completed"; operationId: string; verifiedReceipt: string };export function canOfferOneClickRetry(state: ToolExecutionState): boolean {// Never expose blind retry on failures lacking idempotency guarantees or uncertain timeoutsreturn state.status === "failed" && state.retrySafeWithIdempotencyKey;}
And crucially: MCP tool results from web fetches, GitHub issues, emails, or external DB records frequently carry adversarial Markdown, HTML links, or prompt-injection payloads! Always render untrusted tool result text inside escaped plain-text containers or strict Markdown allowlists (rel="noopener noreferrer" + zero raw dangerouslySetInnerHTML) so viewing a failed tool card cannot hijack user sessions (Indirect XSS / UI Injection).
Alternatives and trade-offs
- Compact Inline Action Pills (Low-Consequence Read Tools): Keeping
search_docsorread_fileunobtrusive ("Searched 12 docs · 140ms" collapsed drawer) preserves conversational reading flow without overwhelming users with verbose chrome; keeps full audit log expandable on click. - Dedicated Side-Panel Activity Ledger & Approval Cards (Multi-Step / Mutating Tools): Essential whenever agents edit databases, issue refunds, execute terminal commands, or batch dozens of calls—exposing real-time states, parameter diffs, explicit
Approvesignatures (argsHash), and structured failure categories cleanly. - Optimistic UI Updates: Strictly acceptable only for local, instantly reversible UI actions (like bookmarking a draft note with deterministic server reconciliation), and dangerous on irreversible external side effects (
send_email,drop_table,refund_charge).
Failure modes and misconceptions
- Promoting
"Queued"or Optimistic Proposals Straight to"Completed": Displaying a green checkmark"Refund sent"the instant an agent emits a tool call—or when an HTTP worker merely returns202 Queued—deceives operators if the downstream job subsequently fails authentication or business balance checks! Require verified downstream receipt state. - Showing Generic
"Something Went Wrong [Retry]"Buttons on Non-Idempotent Writes: Letting users hammer"Retry"blindly after a504 Gateway Timeoutoncreate_invoiceorcharge_cardcreates duplicate financial transactions! Classify failures into deterministic errors vs. ambiguous timeouts and require immutableidempotency_keyenforcement before showing retry actions. - Hiding Crucial Arguments Inside Ambiguous Confirmation Modals (
"Approve run_sql?"): Asking humans to clickApprovewithout visibly surfacing target database, exact amount, recipient address, or SQL mutation causes rubber-stamp approval fatigue and costly human error. - Rendering Unsanitized Tool Outputs as Interactive Markup: Passing raw
toolResult.contentinto permissive Markdown renderers or HTML templates lets malicious external records render spoofed phishing links, credential prompts, or XSS payloads inside the trusted agent workspace!
Decision scenario
Your finance & DevOps AI assistant executes both harmless knowledge-base searches (read_only) and production Stripe refunds (destructive_external) via MCP tools. Collapse read_only tool calls cleanly into compact expandable inline summary pills showing latency and source count; route every destructive_external tool call into a sticky awaiting_approval state card displaying exact customer email, refund cents, ledger account, and a server-signed argsHash approval token; track active execution using persistent operation_id + server-emitted status events; classify network timeouts accurately as reconcile_needed (querying Stripe with the original idempotency_key before enabling retry or completion); and render all third-party tool outputs strictly plain-escaped without raw HTML execution.
Learning outcomes
- Model agentic tool execution cleanly as an explicit finite state machine anchored to
operation_idrather than a generic loading spinner. - Separate low-consequence inline status pills from parameter-explicit approval cards bound via cryptographic
argsHash. - Handle ambiguous timeouts (
reconcile_needed), honest cancellation semantics, and idempotency-gated retry affordances safely. - Mitigate indirect XSS and UI spoofing by treating external MCP/tool outputs strictly as untrusted data.
Trade-offs
Modeling explicit tool state transitions, failure taxonomies, and parameter-bound human approvals eliminates silent phantom completions and duplicate-write bugs cleanly, while demanding tighter backend-to-UI event schemas (idempotency_key, categorized error codes, SSE state envelopes) and restrained inline grouping so chat streams remain readable.