AG-UI Protocol: Connect AI Agents to Real-Time Frontends
> A practical AG-UI protocol guide for streaming agent events, tool calls, state, approvals, security, and Python frontend integrations.
🎧 Listen — ~10 min
Ready · AG-UI Protocol: Connect AI Agent
AG-UI is an open, event-based protocol for connecting an AI agent backend to a user-facing application. It sits between the agent runtime and the frontend: MCP connects agents to tools and data, A2A connects agents to other agents, while AG-UI carries streaming agent activity, tool calls, state changes, interrupts, and user context to an interface.
For developers, the practical value is not another chatbot endpoint. AG-UI gives an agentic application a typed event contract so a frontend can render work as it happens, show tool activity, synchronize state, and pause for human approval without inventing a private protocol for every framework.
What AG-UI solves
A conventional API often looks like this:
1request → backend work → JSON response → render resultThat model becomes awkward when an agent runs for minutes, calls several tools, streams partial output, changes shared application state, or needs a user to approve an action midway through execution. A frontend needs more than the final answer. It needs lifecycle boundaries, progress, tool visibility, structured updates, errors, and a way to resume work.
AG-UI uses a streaming event architecture for that contract. The official documentation describes events for lifecycle, text messages, tool calls, state management, activity, reasoning, and custom behavior. A typical run starts with RUN_STARTED and ends with either RUN_FINISHED or RUN_ERROR; intermediate events describe what the agent is doing.
The protocol is transport-flexible. The project describes support for SSE, WebSockets, webhooks, and other event transports. That makes AG-UI a protocol layer rather than a requirement to adopt one frontend framework or one hosting model.
Where AG-UI fits with MCP and A2A
AG-UI is easiest to understand as the user-facing layer in a broader agent stack:
Original architecture diagram by Essam A.; protocol roles cross-checked against the official AG-UI documentation.
| Layer | Protocol or system | Main job | Typical payload |
|---|---|---|---|
| Agent ↔ user interface | AG-UI | Stream agent activity and coordinate UI interaction | Text deltas, tool events, state diffs, interrupts |
| Agent ↔ tools and data | MCP | Discover and invoke external capabilities | Tool schemas, resources, prompts |
| Agent ↔ agent | A2A | Coordinate work across independent agents | Tasks, messages, artifacts |
| Application control | Your policy layer | Enforce identity, approvals, budgets, and audit | Authorization decisions, limits, trace IDs |
The boundaries matter. AG-UI does not replace MCP authorization, and a streamed event is not proof that a tool call is safe. Treat the protocol as an interaction contract, then apply authentication, authorization, validation, rate limits, and approval rules around it. For a related control-plane perspective, see the site’s MCP security threat-modeling guide.
The event lifecycle
The minimum useful lifecycle is deliberately small:
RUN_STARTEDidentifies the thread and run.- Optional
STEP_STARTEDandSTEP_FINISHEDevents expose meaningful phases. - Text events stream an assistant message incrementally.
- Tool events show a tool call and its streamed arguments or result.
- State events synchronize application data when the agent changes it.
RUN_FINISHEDorRUN_ERRORcloses the run.
A text response commonly uses TEXT_MESSAGE_START, one or more TEXT_MESSAGE_CONTENT events, and TEXT_MESSAGE_END. Each content event carries a delta; the frontend concatenates deltas associated with the same messageId.
Tool calls follow a similar pattern: TOOL_CALL_START, streamed argument events, and TOOL_CALL_END or a tool result event. That lets an interface show “searching documentation” or “updating the draft” instead of appearing frozen until the model completes.
The official events reference says that lifecycle boundaries are mandatory for a normal run. This gives a client a reliable place to start loading indicators, finalize a response, recover from failure, and release resources. It also makes observability less dependent on scraping model text.
Human approval and state synchronization
Agentic interfaces need more than streaming prose. AG-UI documents events for state snapshots and deltas, frontend tools, interrupts, and human-in-the-loop workflows.
A safe approval flow should be explicit:
Original approval-flow diagram by Essam A.; the tool remains responsible for final authorization and input validation.
Do not treat a button click as authorization by itself. The server should bind approval to a run, user, tenant, tool name, argument hash, and expiration time. Re-check permissions when the resumed run executes because identity, data, or policy may have changed while a human was reviewing the request.
State synchronization deserves the same care. State deltas should be schema-validated and scoped to the current user or workspace. Never allow a model-generated event to write arbitrary fields in a client store. Define an allowlist of mutable state, reject unknown paths, and record the before-and-after values in an audit trail.
Building a minimal AG-UI server in Python
The official quickstart demonstrates a standalone HTTP server that accepts AG-UI input and emits a stream of events. Pydantic AI also documents an AG-UI adapter for Starlette-compatible applications, including FastAPI. The following small example follows that documented integration shape and keeps the model call behind Pydantic AI.
1from fastapi import FastAPI
2from starlette.requests import Request
3from starlette.responses import Response
4from pydantic_ai import Agent
5from pydantic_ai.ui.ag_ui import AGUIAdapter
6
7app = FastAPI()
8agent = Agent(
9 "openai:gpt-5.2",
10 instructions="Answer briefly and identify uncertainty.",
11)
12
13@app.post("/agent")
14async def agent_endpoint(request: Request) -> Response:
15 return await AGUIAdapter.dispatch_request(
16 request,
17 agent=agent,
18 )Install the documented integration dependencies before running it:
1pip install "pydantic-ai-slim[ag-ui]" uvicorn
2uvicorn app:app --reloadThis is an integration starting point, not a production security boundary. Add authentication middleware, origin checks, request-size limits, per-user budgets, timeouts, cancellation handling, structured logs, and a tool policy before exposing the endpoint publicly. Keep provider credentials on the server and never place them in AG-UI messages or frontend state.
The Pydantic AI documentation distinguishes several integration paths. AGUIAdapter.run_stream() is useful when an application needs to transform input or output directly. dispatch_request() is a convenience path for Starlette requests. A standalone ASGI app can expose the adapter as its own service. Choose the narrowest integration that fits the application so the protocol boundary remains easy to test.
Frontend implementation checklist
A robust client should treat the stream as a state machine, not as a bag of text fragments.
Parse and validate every event
Validate the event discriminator, identifiers, and required fields. Reject malformed JSON, unknown critical event types, oversized deltas, and tool arguments that do not match the declared schema. Preserve the raw event only when it is safe to store and redact secrets before logging.
Make runs resumable
Track threadId, runId, message IDs, and tool-call IDs. A reconnect should not duplicate a side effect. Use idempotency keys for server-side tool execution and keep a durable record of which tool calls have already completed.
Render tool activity honestly
Show the tool name and a safe summary of arguments, but do not expose credentials, private headers, or sensitive tool output. The UI should distinguish “requested,” “approved,” “executing,” “completed,” and “failed.” Those states are more useful than a generic spinner.
Separate model text from trusted UI actions
A text delta should be rendered as content. A state delta or frontend tool event should pass through a stricter policy path. Do not interpret arbitrary Markdown, HTML, URLs, or event payloads as trusted commands.
Handle cancellation and disconnects
A browser tab can disappear while the agent continues working. Decide whether disconnects cancel the run, allow background completion, or require an explicit user action. Persist enough state to show the final result later, and make side-effecting operations idempotent.
For real-time applications that already use WebSockets, the site’s AI agent WebSockets guide provides useful transport and lifecycle context. AG-UI can run over more than one transport, but the application still needs one consistent event model.
Framework and ecosystem support
The official repository lists integrations across agent frameworks and client environments, including LangGraph, CrewAI, Microsoft Agent Framework, Google ADK, AWS Strands Agents, Mastra, Pydantic AI, Agno, LlamaIndex, and others. It also lists SDKs or community support for languages such as Python, TypeScript, Go, Java, Kotlin, Rust, Ruby, Dart, and C++.
Treat those support labels as an ecosystem map, not a guarantee that every feature has identical behavior in every SDK. Before adopting an integration, verify:
- which event types it emits;
- whether state, interrupts, and tool results are supported;
- whether the transport supports reconnection and backpressure;
- how authentication and tenant context are passed;
- whether cancellation reaches the agent runtime;
- and whether the integration is maintained at the version you plan to deploy.
The project’s public repository is also a useful implementation reference: it includes a quick-start path, a Dojo with examples, and framework integration packages. The official AG-UI documentation is the best place to verify the current event contract before writing a client.
Security, privacy, and performance
AG-UI makes agent behavior visible, but visibility does not remove risk. Apply the same controls you would use for any privileged agent API:
- authenticate the connection and bind every run to a tenant and user;
- authorize tools on the server, independently of model output;
- validate tool arguments against schemas and enforce resource limits;
- redact secrets from events, traces, browser logs, and persisted state;
- use origin and CSRF protections for browser clients;
- apply quotas to tokens, tool calls, concurrent runs, and event size;
- set deadlines for model calls and external tools;
- and retain an audit record for approvals and side effects.
Streaming improves perceived latency because users see progress before the final answer. It can also increase operational complexity: more open connections, reconnect logic, event buffering, and pressure on the browser’s rendering loop. Batch or coalesce tiny text deltas, cap queue sizes, and apply backpressure. Measure time to first event, time to first token, tool latency, total run duration, reconnect rate, and cost per completed run.
For production observability, emit protocol-level spans alongside model and tool spans. The event stream tells the UI what happened; tracing should tell operators why it happened, how long it took, and which policy decisions were applied. The site’s OpenTelemetry GenAI observability guide covers the complementary tracing layer.
Is AG-UI the right choice?
AG-UI is a strong fit when an application needs a portable, interactive agent-to-frontend contract across multiple runtimes or clients. It is especially useful for streaming chat, collaborative workspaces, tool-rich interfaces, human approvals, and generative UI experiments.
It may be unnecessary for a simple request/response assistant with no tools, no streaming, and no shared state. In that case, a conventional JSON API is easier to operate. It is also not a substitute for an application policy layer, a tool protocol, a durable workflow engine, or a tracing system.
The most practical adoption path is incremental: start with lifecycle and text events, add tool-call visibility, then introduce state synchronization and interrupts only after the server-side authorization model is ready. Keep the protocol boundary narrow, test event sequences as contracts, and make every side effect idempotent.
FAQ
What is AG-UI?
AG-UI is an open, lightweight, event-based protocol for connecting AI agent backends to user-facing applications. It standardizes streaming interaction, tool activity, state updates, and other agent-to-user events.
Is AG-UI the same as MCP?
No. MCP connects agents to tools, resources, and prompts. AG-UI connects an agent runtime to a frontend or other user-facing client. They can be used together.
Does AG-UI require React?
No. The protocol describes events and transports, not a single rendering framework. Web, mobile, terminal, and chat-platform clients can consume an AG-UI event stream.
Can AG-UI handle human approval?
Yes, the protocol includes interrupt and human-in-the-loop concepts. The server must still enforce authorization and validate the resumed action; the protocol alone does not make an operation safe.
Which languages can use AG-UI?
The ecosystem includes TypeScript and Python implementations plus SDKs or integrations for several other languages. Confirm feature parity and maintenance status for the specific SDK before production adoption.
Conclusion
AG-UI addresses the part of agent engineering that appears after a model can already call tools: making that work understandable, interactive, resumable, and portable in a real application. Its event model gives frontends reliable lifecycle boundaries instead of forcing them to infer progress from model prose.
The right architecture is layered. Use AG-UI for agent-to-user interaction, MCP for tools and data, A2A where agents coordinate, and a server-side policy and observability layer for trust. Start small, validate every event, protect every side effect, and measure the complete run rather than only token latency.
Sources and visual credits
- AG-UI official documentation — protocol overview, event model, integrations, and quickstart.
- AG-UI official GitHub repository — open-source reference implementation, SDKs, and examples.
- Pydantic AI AG-UI integration — independent framework documentation for a Python/Starlette adapter.
- AG-UI events reference — lifecycle, text, tool-call, state, and interrupt event details.
- Visuals: original Mermaid architecture and approval-flow diagrams by Essam A., based on the cited official protocol documentation; no external screenshots used.
Keep reading
Related reading
⚡ Daily AI Model Drop — Get Kimi K3 benchmarks before Twitter
Join 2,400+ AI engineers. 1 email/day, no spam, unsubscribe anytime