Skip to content

cianfhoghlaim/cianchosaint / .agents/skills/ag-ui


name: ag-ui description: AG-UI — the open SSE-based protocol for agent↔UI streaming. Use when wiring any UI (CopilotKit, custom React) to any agent backend (Pydantic AI, Agno, Google ADK, BAML), decoding agent event streams, or defining custom events / shared state across the UI↔agent boundary.

AG-UI — Agent-User Interaction Protocol

When to use this skill

Use when you need to:

  • "Wire a CopilotKit UI to my Pydantic AI / Agno / Google ADK / BAML agent"
  • "Stream partial agent results (tokens, tool calls) to the UI as they're produced"
  • "Define a custom event type that the UI subscribes to"
  • "Sync shared state between the UI and the agent (form values, user preferences, in-flight data)"

Overview

AG-UI is an open protocol (CopilotKit authored) that defines a standard wire format for agent↔UI communication. It uses Server-Sent Events (SSE) as the transport and a JSON event schema for the payload.

The key insight: agents and UIs are decoupled. The same agent can be served to CopilotKit, a custom React UI, a Slack bot, or a CLI — all via the same AG-UI event stream.

Install

# TypeScript
bun add @ag-ui/core

# Python
uv add ag-ui

# Pydantic AI (built-in adapter)
uv add 'pydantic-ai-slim[ag-ui]'

Wire format

AG-UI events are JSON-encoded SSE messages. The canonical event types:

EventPayloadWhen
token{ delta: str }Streaming a partial token
tool_call{ name, args }Agent is calling a tool
tool_result{ name, result }Tool returned a result
state{ key, value }Shared state update (form values, etc.)
message{ role, content }Complete message from agent
done{}Stream complete

The full schema is at https://ag-ui.com/spec.

Stack integration

The Cianfhoghlaim stack uses AG-UI as the bridge between the UI (CopilotKit) and the agent backends (Pydantic AI, Agno, Google ADK, BAML):

   ┌──────────────────┐
   │  CopilotKit      │  ← UI (web/apps/cianfhoghlaim-web, web/apps/tuatha-ui,
   │  (React)         │    web/apps/croilar-portal)
   └────────┬─────────┘
            │ consumes SSE
            ▼
   ┌──────────────────┐
   │  Hono (oRPC)     │  ← API gateway
   │  /api/agent/...  │
   └────────┬─────────┘
            │ proxies SSE
            ▼
   ┌──────────────────┐
   │  AG-UI adapter   │  ← server-side adapter
   │  (per backend)   │
   └────────┬─────────┘
            │ calls
            ▼
   ┌──────────────────┐
   │  Agent           │  ← Pydantic AI / Agno / Google
   │                  │    ADK / BAML
   └──────────────────┘

The AG-UI server-side adapter is per-backend:

  • Pydantic AI — pydantic_ai.ui.ag_ui.AGUIAdapter
  • Agno — agno.os.AGUIInterface (AgentOS)
  • Google ADK — google.adk.ag_ui.adapter
  • BAML — hand-rolled (BAML functions stream via b.stream.<Function>(...))

Server side — Starlette / FastAPI handler

from pydantic_ai import Agent
from pydantic_ai.ui.ag_ui import AGUIAdapter
from pydantic_ai.models.openai import OpenAIModel

agent = Agent(
    model=OpenAIModel("gpt-4o-mini"),
    system_prompt="You are a curriculum extraction agent.",
)
app = AGUIAdapter(agent).as_starlette_app()

Mount under any FastAPI app:

from fastapi import FastAPI
app = FastAPI()
app.mount("/api/agent", app)

The SSE stream is now served at POST /api/agent/... and compatible with any AG-UI client.

Client side — CopilotKit

import { CopilotChat } from "@copilotkit/react";

export function AgentChat() {
  return (
    <CopilotChat
      runtimeUrl="/api/agent"
      // CopilotKit auto-detects the AG-UI protocol
      // and handles SSE, tool calls, and shared state
    />
  );
}

CopilotKit auto-detects the AG-UI protocol from the response headers and uses the appropriate transport.

When to use AG-UI vs raw SSE / WebSockets

  • AG-UI: any time the UI is CopilotKit, or you want standard agent events (tokens, tool calls, state)
  • Raw SSE: custom protocols (e.g. streaming a video transcoding job)
  • WebSockets: bidirectional, long-lived connections (e.g. live cursor sync, multiplayer)

For agent↔UI streaming, always use AG-UI unless you have a strong reason not to. The CopilotKit integration is first-class; rolling your own SSE handler duplicates effort.

Custom events

AG-UI supports custom event types via a registry. The agent backend emits them; the UI subscribes:

# Server
from ag_ui import CustomEvent

@app.post("/api/agent/custom")
async def custom_event(request):
    yield CustomEvent(
        type="rag_chunk",
        payload={"doc_id": "...", "score": 0.92},
    )
// Client (CopilotKit)
useAgUiEvent("rag_chunk", (payload) => {
  console.log("RAG chunk received:", payload);
});

Use custom events for: RAG chunk streaming, progress indicators, intermediate tool results, multimodal artifacts (images, audio), etc.

Cianfhoghlaim integration

  • web/apps/cianfhoghlaim-web — web/apps/cianfhoghlaim-web/src/lib/ag-ui/ (the canonical AG-UI client wrappers)
  • CopilotKit UI — web/apps/cianfhoghlaim-web/src/components/copilot/
  • Hono (oRPC) proxy — web/apps/cianfhoghlaim-web/src/server/router.py
  • Langfuse — every AG-UI event is traced (token, tool_call, state, done) for full observability

A2UI — sibling protocol (Google)

A2UI is Google's "native-first" alternative to AG-UI for cross-platform generative UI. It's complementary to AG-UI, not a replacement.

ProtocolTransportUI renderingBest for
AG-UISSEHost app renders component treeReact web (CopilotKit)
A2UIJSON-RPCHost app renders JSON component blueprintFlutter / native mobile (Google SDKs)
MCP-AppsJSON-RPCHost app renders via MCP serverDesktop apps

A2UI sends JSON component blueprints (not opaque HTML), so the host app keeps its styling and accessibility. The host app renders the components natively (no iframe, no script injection).

A2UI is the canonical choice when the UI must inherit the host app's styling on Flutter / iOS / Android — exactly the Tuatha MMO mobile use case.

You can run A2UI over AG-UI / A2A as a transport, or directly via a JSON-RPC endpoint.

Kotlin mobile SDK (round-9 deep dive)

The AG-UI Kotlin SDK (community-contributed by Mark Fogle, Nov 2025) brings the AG-UI protocol to Android, iOS, and JVM through a single Kotlin Multiplatform SDK. For the Tuatha MMO mobile client this is the canonical pattern — the agent backend is the same regardless of whether the client is web, native, or desktop.

The SDK is modular:

ModulePurposeGradle dep
kotlin-clientHigh-level agent clients + HTTP transportcom.agui:kotlin-client:0.2.1
kotlin-coreProtocol types, events, kotlinx.serializationcom.agui:kotlin-core:0.2.1
kotlin-toolsToolExecutor + ToolRegistry + circuit-breakercom.agui:kotlin-tools:0.2.1

Platform support: Android API 26+, iOS 13+, JVM 11+.

Quick start (stateful agent):

val chatAgent = StatefulAgUiAgent("https://agent.tuatha.cianfhoghlaim.ie") {
    bearerToken = tuathaSession.token
    systemPrompt = "You are a Celtic mythology guide."
}

chatAgent.chat("Tell me about the Tuatha Dé Danann.").collect { state ->
    // state.messages updates as the SSE stream emits events
    // state.thinking surfaces THINKING_* events
    // state.errors contains any parse / network failures
}

Client-side tools (e.g. opening a quest log, showing inventory) execute on the device, not the server — this is the key privacy property:

val agent = agentWithTools(
    url = "https://agent.tuatha.cianfhoghlaim.ie",
    toolRegistry = toolRegistry {
        addTool(QuestLogToolExecutor())   // runs locally
        addTool(InventoryToolExecutor())  // runs locally
    }
) { bearerToken = tuathaSession.token }

agent.sendMessage("What quests do I have?").collect { state ->
    // Agent requested the local quest-log tool;
    // it ran on the device, not the server
}

Authentication is per-client: bearerToken(...), apiKey(...), or basicAuth(...). For the Cianfhoghlaim stack, the token is the SIWE session JWT from BetterAuth (agents/tuatha/auth/siwe.py).

Streamed events are auto-rewritten: chunked TEXT_MESSAGE_CHUNK / TOOL_CALL_CHUNK are expanded into start/content/end sequences, and THINKING_* events are surfaced alongside normal messages (so the UI can show a "reasoning" indicator before the response).

AG-UI vs A2UI vs MCP-UI vs Open-JSON-UI

AG-UI is not a generative UI specification — it is the bi-directional runtime connection between an agent and any UI. The generative UI specs (A2UI, MCP-UI, Open-JSON-UI) sit on top of it:

SpecOriginPurposeTransport
AG-UICopilotKitAgent↔UI runtime connectionSSE / WebSocket
A2UIGoogleJSON component blueprints (declarative)JSONL streaming
MCP-UI / MCP AppsMicrosoft + Shopifyiframe-based, sandboxed UIover MCP
Open-JSON-UIOpenAIOpenAI's internal declarative specJSON Schema

The flow:

  1. Agent generates a UI using a generative UI spec (e.g. A2UI), describing the components it wants
  2. AG-UI transports that spec from the agent to the app over the bi-directional runtime
  3. The app renders the components natively (no iframe, no script injection — host styling is preserved)
  4. User interactions flow back through AG-UI to the agent

For the Tuatha MMO mobile client, A2UI is the canonical choice when the UI must inherit the host's Celtic design language on Flutter / iOS / Android. For web frontends, CopilotKit's React renderer consumes AG-UI directly.

See references/kotlin-mobile-sdk.md for the blog announcement and references/kotlin-sdk-overview.md for the 191-line official Kotlin SDK reference.

Resources

brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall