Herramientas de UI
El crate adk-ui permite a los agentes de IA generar dinΓ‘micamente interfaces de usuario enriquecidas mediante llamadas a herramientas. Los agentes pueden renderizar formularios, tarjetas, alertas, tablas, grΓ‘ficos y mucho mΓ‘s, todo mediante una API de Rust con seguridad de tipos que se serializa a JSON para el consumo en el frontend.
Lo que construirΓ‘s

Conceptos clave:
- Formularios - Recopilar datos del usuario con diversos tipos de campos
- Tarjetas - Mostrar informaciΓ³n con botones de acciΓ³n
- Tablas - Presentar datos estructurados en filas y columnas
- GrΓ‘ficos - Visualizar datos con grΓ‘ficos de barras, lΓneas, Γ‘reas y circulares
- Alertas - Mostrar notificaciones y mensajes de estado
- Modales - DiΓ‘logos de confirmaciΓ³n e interacciones enfocadas
- Toasts - Notificaciones breves de estado
- Interoperabilidad de protocolos - Emitir UI como cargas ΓΊtiles de A2UI, AG-UI o MCP Apps
Ejemplo: Panel de anΓ‘lisis

Ejemplo: Formulario de registro

CΓ³mo funciona
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 1: User requests something β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β User: "I want to register for an account" β
β β
β β β
β β
β ββββββββββββββββββββββββββββββββββββββββ β
β β AI AGENT (LLM) β β
β β "I should show a registration form" β β
β ββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 2: Agent calls render_form tool β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β π Tool Call: render_form({ β
β title: "Registration", β
β fields: [ β
β {name: "email", type: "email"}, β
β {name: "password", type: "password"} β
β ] β
β }) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 3: Frontend renders the form β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β π Registration β β
β β ββββββββββββββββββββββββββββββββββββββββββββ β β
β β Email: [________________________] β β
β β Password: [________________________] β β
β β β β
β β [ Register ] β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β β
User sees an interactive form, fills it out, clicks Register β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 4: Form submission sent back to agent β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β π© Event: { β
β type: "form_submit", β
β data: { email: "user@example.com", password: "***" } β
β } β
β β
β Agent: "Great! I'll process your registration and show a success alert" β
β β
β π Tool Call: render_alert({ β
β title: "Registration Complete!", β
β variant: "success" β
β }) β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DescripciΓ³n general
Las herramientas de UI permiten a los agentes:
- Recopilar datos del usuario mediante formularios dinΓ‘micos con compatibilidad con Γ‘reas de texto
- Mostrar informaciΓ³n con tarjetas, alertas y notificaciones
- Presentar datos en tablas y grΓ‘ficos interactivos (Recharts)
- Mostrar estados de progreso y carga (spinner, skeleton)
- Crear diseΓ±os de paneles con mΓΊltiples componentes
- Solicitar la confirmaciΓ³n del usuario mediante modales
- Mostrar notificaciones toast para actualizaciones de estado
Inicio rΓ‘pido
AΓ±Γ‘delo a tu Cargo.toml:
[dependencies]
adk-ui = { git = "https://github.com/zavora-ai/adk-ui" }
adk-agent = "2.1.0"
adk-model = "2.1.0"
Uso bΓ‘sico
use adk_rust::prelude::*;
use adk_ui::UiToolset;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let model = Arc::new(GeminiModel::from_env("gemini-3.7-flash")?);
// Get all 10 UI tools
let ui_tools = UiToolset::all_tools();
// Create AI agent with UI tools
let mut builder = LlmAgentBuilder::new("ui_agent")
.model(model)
.instruction(r#"
You are a helpful assistant that uses UI components to interact with users.
Use render_form for collecting information.
Use render_card for displaying results.
Use render_alert for notifications.
Use render_modal for confirmation dialogs.
Use render_toast for brief status messages.
"#);
for tool in ui_tools {
builder = builder.tool(tool);
}
let agent = builder.build()?;
Ok(())
}
A2UI JSONL (render_screen / render_page / render_kit)
Estas herramientas emiten JSONL de A2UI v0.9 para garantizar la compatibilidad con renderizadores de A2UI.
render_screen (superficie ΓΊnica)
{
"surface_id": "main",
"components": [
{ "id": "root", "component": "Column", "children": ["title", "cta"] },
{ "id": "title", "component": "Text", "text": "Welcome", "variant": "h1" },
{ "id": "cta_label", "component": "Text", "text": "Continue", "variant": "body" },
{ "id": "cta", "component": "Button", "child": "cta_label", "action": { "event": { "name": "continue" } } }
]
}
render_page (pΓ‘gina con varias secciones)
{
"title": "Release Notes",
"description": "Highlights for the latest launch.",
"sections": [
{
"heading": "Whatβs new",
"body": "Three big improvements shipped this week.",
"bullets": ["Faster onboarding", "Better search", "New dashboards"],
"actions": [{ "label": "View details", "action": "view_details", "variant": "borderless" }]
}
]
}
render_kit (catΓ‘logo + tokens + plantillas)
{
"name": "Fintech Pro",
"version": "0.1.0",
"brand": { "vibe": "trustworthy", "industry": "fintech" },
"colors": { "primary": "#2F6BFF" },
"typography": { "family": "Source Sans 3" },
"templates": ["auth_login", "dashboard"]
}
Usa el renderizador de React para consumir JSONL de A2UI:
import {
A2uiStore,
A2uiSurfaceRenderer,
applyParsedMessages,
parseJsonl,
} from "@zavora-ai/adk-ui-react";
const store = new A2uiStore();
const parsed = parseJsonl(jsonl);
applyParsedMessages(store, parsed);
export function App() {
return <A2uiSurfaceRenderer store={store} surfaceId="main" />;
}
Herramientas disponibles
render_form
Renderiza formularios interactivos para recopilar datos del usuario.
{
"title": "Registration Form",
"description": "Create your account",
"fields": [
{"name": "username", "label": "Username", "type": "text", "required": true},
{"name": "email", "label": "Email", "type": "email", "required": true},
{"name": "password", "label": "Password", "type": "password", "required": true},
{"name": "newsletter", "label": "Subscribe to newsletter", "type": "switch"}
],
"submit_label": "Register"
}
Se renderiza como:
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β π Registration Form β
β Create your account β
β βββββββββββββββββββββββββββββββββββββββββββββ β
β β
β Username * β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β
β Email * β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β
β Password * β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β β’β’β’β’β’β’β’β’ β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β
β Subscribe to newsletter [β] β
β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β Register β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
Tipos de campo: text, email, password, number, date, select, multiselect, switch, slider, textarea
render_card
Muestra tarjetas informativas con botones de acciΓ³n opcionales.
{
"title": "Order Confirmed",
"description": "Order #12345",
"content": "Your order has been placed successfully. Expected delivery: Dec 15, 2025.",
"actions": [
{"label": "Track Order", "action_id": "track", "variant": "primary"},
{"label": "Cancel", "action_id": "cancel", "variant": "danger"}
]
}
Variantes de botΓ³n: primary, secondary, danger, ghost, outline
render_alert
Muestra notificaciones y mensajes de estado.
{
"title": "Payment Successful",
"description": "Your payment of $99.00 has been processed.",
"variant": "success"
}
Variantes: info, success, warning, error
render_confirm
Solicita la confirmaciΓ³n del usuario antes de realizar acciones.
{
"title": "Delete Account",
"message": "Are you sure you want to delete your account? This action cannot be undone.",
"confirm_label": "Delete",
"cancel_label": "Keep Account",
"variant": "danger"
}
render_table
Muestra datos tabulares.
{
"title": "Recent Orders",
"columns": [
{"header": "Order ID", "accessor_key": "id"},
{"header": "Date", "accessor_key": "date"},
{"header": "Amount", "accessor_key": "amount"},
{"header": "Status", "accessor_key": "status"}
],
"data": [
{"id": "#12345", "date": "2025-12-10", "amount": "$99.00", "status": "Delivered"},
{"id": "#12346", "date": "2025-12-11", "amount": "$149.00", "status": "Shipped"}
]
}
render_chart
Crea visualizaciones de datos.
{
"title": "Monthly Sales",
"chart_type": "bar",
"x_key": "month",
"y_keys": ["revenue", "profit"],
"data": [
{"month": "Jan", "revenue": 4000, "profit": 2400},
{"month": "Feb", "revenue": 3000, "profit": 1398},
{"month": "Mar", "revenue": 5000, "profit": 3800}
]
}
Tipos de grΓ‘fico: bar, line, area, pie
render_progress
Muestra el progreso de las tareas con pasos opcionales.
{
"title": "Installing Dependencies",
"value": 65,
"description": "Installing package 13 of 20...",
"steps": [
{"label": "Download", "completed": true},
{"label": "Extract", "completed": true},
{"label": "Install", "current": true},
{"label": "Configure", "completed": false}
]
}
render_layout
Crea diseΓ±os de paneles con varias secciones.
{
"title": "System Status",
"description": "Current system health overview",
"sections": [
{
"title": "Services",
"type": "stats",
"stats": [
{"label": "API Server", "value": "Healthy", "status": "operational"},
{"label": "Database", "value": "Degraded", "status": "warning"},
{"label": "Cache", "value": "Down", "status": "error"}
]
},
{
"title": "Recent Errors",
"type": "table",
"columns": [{"header": "Time", "key": "time"}, {"header": "Error", "key": "error"}],
"rows": [{"time": "10:30", "error": "Connection timeout"}]
}
]
}
Tipos de secciΓ³n: stats, table, chart, alert, text
render_modal
Muestra diΓ‘logos modales para confirmaciones o interacciones centradas.
{
"title": "Confirm Deletion",
"message": "Are you sure you want to delete this item? This action cannot be undone.",
"size": "medium",
"closable": true,
"confirm_label": "Delete",
"cancel_label": "Cancel",
"confirm_action": "delete_confirmed"
}
TamaΓ±os: small, medium, large, full
render_toast
Muestra breves notificaciones emergentes para actualizaciones de estado.
{
"message": "Settings saved successfully",
"variant": "success",
"duration": 5000,
"dismissible": true
}
Variantes: info, success, warning, error
Herramientas filtradas
Selecciona ΓΊnicamente las herramientas que necesita tu agente:
let toolset = UiToolset::new()
.without_chart() // Disable charts
.without_table() // Disable tables
.without_progress() // Disable progress
.without_modal() // Disable modals
.without_toast(); // Disable toasts
// Or use forms only
let forms_only = UiToolset::forms_only();
GestiΓ³n de eventos de la interfaz de usuario
Cuando los usuarios interactΓΊan con la interfaz renderizada (envΓan formularios, hacen clic en botones), los eventos se envΓan de vuelta al agente:
use adk_ui::{UiEvent, UiEventType};
// UiEvent structure
pub struct UiEvent {
pub event_type: UiEventType, // FormSubmit, ButtonClick, InputChange
pub action_id: Option<String>,
pub data: Option<HashMap<String, Value>>,
}
// Convert to message for agent
let message = ui_event.to_message();
Actualizaciones de la interfaz de usuario en streaming
Para actualizaciones de la interfaz de usuario en tiempo real, usa UiUpdate para aplicar cambios a los componentes por ID:
use adk_ui::{UiUpdate, UiOperation};
let update = UiUpdate {
target_id: "progress-bar".to_string(),
operation: UiOperation::Patch,
payload: Some(Component::Progress(Progress {
id: Some("progress-bar".to_string()),
value: 75,
label: Some("75%".to_string()),
})),
};
Operaciones: Replace, Patch, Append, Remove
Esquema de componentes
Los 28 tipos de componentes admiten campos opcionales id para actualizaciones mediante streaming:
Γtomos: Text, Button, Icon, Image, Badge Entradas: TextInput, NumberInput, Select, MultiSelect, Switch, DateInput, Slider, Textarea DiseΓ±os: Stack, Grid, Card, Container, Divider, Tabs Datos: Table, List, KeyValue, CodeBlock VisualizaciΓ³n: Chart (barras, lΓneas, Γ‘reas y circular mediante Recharts) Comentarios: Alert, Progress, Toast, Modal, Spinner, Skeleton
Cliente de React
Se proporciona una implementaciΓ³n de referencia de React en el repositorio independiente adk-ui:
npm install @zavora-ai/adk-ui-react
El cliente de React incluye:
- Tipos TypeScript que coinciden con el esquema de Rust
- Renderizador de componentes para los 28 tipos
- IntegraciΓ³n con Recharts para grΓ‘ficos interactivos
- Compatibilidad con la renderizaciΓ³n de Markdown
- Compatibilidad con el modo oscuro
- GestiΓ³n del envΓo de formularios
- Componentes de modal y notificaciones emergentes
Arquitectura
Agent ββ[render_* tool]ββ> UiResponse (JSON)
β
β SSE
βΌ
Client (React)
β
βββ> UiEvent (user action) ββ> Agent
Interoperabilidad del protocolo
Las 13 herramientas de renderizado admiten resultados compatibles con el protocolo mediante el argumento protocol:
| Protocolo | DescripciΓ³n |
|---|---|
a2ui | Interfaces JSONL alineadas con A2UI v0.9 (predeterminadas para render_screen, render_page) |
ag_ui | Compatibilidad hΓbrida con AG-UI: envoltorios de compatibilidad de forma predeterminada, ademΓ‘s de transporte adicional nativo del protocolo en tiempo de ejecuciΓ³n para clientes adk-server |
mcp_apps | Compatibilidad de las cargas ΓΊtiles de aplicaciones MCP con recursos ui://, asistentes puente aditivos, flujos de notificaciΓ³n, campos de solicitud en tiempo de ejecuciΓ³n y adaptadores de HTML/recursos |
Cuando se omite protocol, las herramientas utilizan su formato de salida predeterminado (el legado UiResponse JSON para la mayorΓa de las herramientas, A2UI para render_screen/render_page/render_kit).
Ejemplo con selecciΓ³n de protocolo:
{
"protocol": "mcp_apps",
"mcp_apps": {
"resource_uri": "ui://demo/surface"
}
}
Adaptadores de interoperabilidad
adk-ui incluye primitivas de adaptador para la conversiΓ³n de protocolos:
A2uiAdapterβ Convierte superficies canΓ³nicas a A2UI JSONLAgUiAdapterβ Convierte a cargas ΓΊtiles de eventos de AG-UIMcpAppsAdapterβ Convierte a cargas ΓΊtiles de recursos de MCP Apps
Estos implementan un rasgo UiProtocolAdapter compartido para una conversiΓ³n coherente en todas las herramientas.
CronologΓa de obsolescencia
El perfil de ejecuciΓ³n heredado adk_ui incluye metadatos de obsolescencia:
| Fecha | Hito |
|---|---|
| 2026-02-07 | Anuncio de obsolescencia |
| 2026-12-31 | Objetivo de retirada |
Reemplazos: a2ui, ag_ui, mcp_apps
Estos metadatos se exponen mediante las constantes UI_PROTOCOL_CAPABILITIES y se muestran a travΓ©s de adk-server en /api/ui/capabilities.
La respuesta de capacidades tambiΓ©n informa de implementationTier, specTrack, summary y limitations, de modo que los clientes puedan distinguir los subconjuntos hΓbridos o de compatibilidad de la compatibilidad totalmente nativa con el protocolo.
Cuando adk-server es el lΓmite orientado al host, tambiΓ©n expone helpers aditivos del puente de Apps MCP en /api/ui/initialize, /api/ui/message, /api/ui/update-model-context, /api/ui/notifications/poll, /api/ui/notifications/resources-list-changed y /api/ui/notifications/tools-list-changed. Estos endpoints conservan los contratos de runtime existentes de ADK y aceptan tanto cuerpos de solicitud directos como envoltorios similares a JSON-RPC con mΓ©todos ui/....
Para los consumidores del runtime, adk-server tambiΓ©n admite:
x-adk-ui-transport: protocol_nativeouiTransport: "protocol_native"para la serializaciΓ³n SSE nativa de AG-UI- Entradas de solicitud de doble ruta de AG-UI mediante
input/agUiInputjunto anewMessage, que ya existΓa - Envoltorios del puente de Apps MCP dentro de
/api/run_ssemediantemcpAppsInitialize,mcpAppsRequestymcpAppsInitialized
Estas adiciones son opcionales. Los consumidores existentes de /api/run y /api/run_sse siguen recibiendo el envoltorio genΓ©rico ADK, a menos que soliciten explΓcitamente un modo de transporte AG-UI nativo.
Para las respuestas de herramientas de Apps MCP gestionadas por el framework, adk-server::ui_types ahora expone:
McpUiBridgeSnapshotpara el estado tipado del puente entre el host y la aplicaciΓ³nMcpUiToolResultpara el envoltorio de respuesta aditivoMcpUiToolResultBridgepara los metadatos del puente (protocolVersion,structuredContent,hostInfo,hostCapabilities,hostContext,appInfo,appCapabilities,initialized)
Se recomienda McpUiBridgeSnapshot::build_tool_result(...) al promover el estado del puente o de la sesiΓ³n a una respuesta de herramienta. Esto estandariza la estructura del resultado de la herramienta, al tiempo que conserva resourceUri y las alternativas html insertadas para los hosts orientados a la compatibilidad.
Para las asignaciones de hosts integrados o de navegador, el puente aditivo HTTP corresponde a los flujos del host y la aplicaciΓ³n de la siguiente manera:
ui/initialize->/api/ui/initializeui/message->/api/ui/messageui/update-model-context->/api/ui/update-model-contextnotifications/resources/list_changed->/api/ui/notifications/resources-list-changednotifications/tools/list_changed->/api/ui/notifications/tools-list-changed- notificaciones del host en cola ->
/api/ui/notifications/poll
Los endpoints del puente directo /api/ui/* son la ruta de ciclo de vida preferida para los hosts de Apps MCP. Los campos de solicitud de Apps MCP del lado del entorno de ejecuciΓ³n siguen disponibles como ruta de compatibilidad aditiva para clientes mixtos o heredados.
Ejemplos
El repositorio independiente adk-ui contiene los ejemplos ejecutables de interfaz de usuario:
| Ejemplo | DescripciΓ³n | Comando de ejecuciΓ³n |
|---|---|---|
ui_agent | Demo de consola | cargo run --bin ui_agent |
ui_server | servidor HTTP con SSE | cargo run --bin ui_server |
ui_react_client | frontend de React | cd ui_react_client && npm run dev |
Ejecuta esos ejemplos del repositorio adk-ui para que los paquetes de Rust y React se mantengan en la misma lΓnea de lanzamiento.
Prompts de ejemplo
Prueba las herramientas de la interfaz de usuario con estos prompts:
# Forms
"I want to register for an account"
"Create a contact form"
"Create a feedback form with a comments textarea"
# Cards
"Show me my profile"
"Display a product card for a laptop"
# Alerts
"Show a success message"
"Display a warning about expiring session"
# Modals
"I want to delete my account" (shows confirmation modal)
"Show a confirmation dialog before submitting"
# Toasts
"Show a success toast notification"
"Display an error toast"
# Tables
"Show my recent orders"
"List all users"
# Charts
"Show monthly sales chart"
"Display traffic trends as a line chart"
"Show revenue breakdown as a pie chart"
# Progress & Loading
"Show upload progress at 75%"
"Display a loading spinner"
"Show skeleton loading state"
# Dashboards
"Show system status dashboard"
Anterior: β Herramientas del navegador | Siguiente: Herramientas de MCP β