FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Rendering Tool Call Execution States

Designing UI states for tool callbacks: loading skeletons, success parameters, and execution progress bars.

Freshness: current•13 min read•Full-Stack AI Engineering

Key Learning Outcomes

  • ✓Represent queued running blocked failed and completed actions
  • ✓Expose consequential inputs before execution
  • ✓Preserve correction retry and audit context
Full Technical Reference Document

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).

Model Proposes Tool + Args
Schema & Auth Policy Validation
Awaiting Human Approval (High Consequence)
Queued / Running + Operation ID
Verify Environment State -> Completed / Failed / Unknown
Conceptual teaching model synthesized from:mcp-specification,human-ai-guidelines

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 StateMeaning & Backend OwnershipUI Exposure & Next Available User ControlCritical Safety Invariant
proposed -> validatingModel emitted tool JSON; app verifies schema, RBAC, and target scopeDisplay tool name, target entity, read/write badge (readonly vs destructive)Never pass unvalidated model arguments straight into execution or UI rendering
awaiting_approvalHigh-consequence mutation paused behind deterministic server gateRender exact diff/amount/recipient + Approve / Edit / Reject controlsHash/bind approved arguments so later stream drift cannot mutate what user approved!
queued -> runningOperation accepted by worker / external provider with unique operation_idElapsed timer, cancel/abort control (explicitly stating whether upstream stop is supported!)Show real step telemetry, never fake progress bars
timeout_unknown vs failedNetwork 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
completedDownstream ledger/filesystem/MCP tool returned verified canonical confirmationSummarized 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:

  1. Schema / Input Validation Failure (recoverable_by_model): Safe to reveal cleanly in compact timeline text while letting the agent auto-correct malformed parameters.
  2. Authorization / Policy Denied (blocked_policy): Must surface cleanly to the user ("Access denied to billing-prod") rather than letting the agent retry identically in a tight spin loop.
  3. 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 strict idempotency_key matching the original operation_id. Similarly, when a user clicks Cancel, update state accurately (cancelling -> cancelled if worker ACKed early stop, or "cancel_requested — action had already started" if external API lacked rollback).
typescript
export 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 timeouts
return 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_docs or read_file unobtrusive ("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 Approve signatures (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

  1. 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 returns 202 Queued—deceives operators if the downstream job subsequently fails authentication or business balance checks! Require verified downstream receipt state.
  2. Showing Generic "Something Went Wrong [Retry]" Buttons on Non-Idempotent Writes: Letting users hammer "Retry" blindly after a 504 Gateway Timeout on create_invoice or charge_card creates duplicate financial transactions! Classify failures into deterministic errors vs. ambiguous timeouts and require immutable idempotency_key enforcement before showing retry actions.
  3. Hiding Crucial Arguments Inside Ambiguous Confirmation Modals ("Approve run_sql?"): Asking humans to click Approve without visibly surfacing target database, exact amount, recipient address, or SQL mutation causes rubber-stamp approval fatigue and costly human error.
  4. Rendering Unsanitized Tool Outputs as Interactive Markup: Passing raw toolResult.content into permissive Markdown renderers or HTML templates lets malicious external records render spoofed phishing links, credential prompts, or XSS payloads inside the trusted agent workspace!
Reflect before revealing the guide

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_id rather 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.

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.