~/dev.log

Full-Stack Architecture

AG-UI: Building Agentic Web Apps with Spring Boot & Angular

2026-11-22•8 min read•#AG-UI#Spring AI#Spring Boot#Angular#Signals#SSE

Standardizing real-time communication between Spring AI agents and reactive Angular UIs with Server-Sent Events, Signals, and typed UI actions.

AG-UI in 30 Seconds

Streaming raw Markdown tokens falls short when an AI assistant lives inside a real web application. AG-UI (Agent–User Interaction Protocol) provides a lightweight, event-driven SSE protocol that connects an AI agent backend directly to a reactive frontend—streaming reasoning, live tool execution, and validated UI commands over a single real-time pipeline.

Introduction

Companion Reference Guide for the Spring Traffic Control series.
Looking for how native Angular cards render inside chat? See the A2UI Guide. Looking for monorepo setup? See the Mise Guide.

AG-UI (Agent–User Interaction Protocol) is an open, lightweight, event-based protocol that standardizes how an AI agent backend communicates with a user-facing frontend.

Traditional AI apps treat the browser as a dumb terminal: you send a prompt and stream back raw Markdown tokens. That works for Q&A, but it breaks down the moment you want an AI assistant that lives inside a real application, one that knows what the user has selected, shows live tool execution, and can drive routes, filters, or an interactive map in real time.

AG-UI in action inside Spring Traffic Control: querying flight KLM1298 streams tool execution, renders a native flight card, and focuses the live map

AG-UI in action: asking about flight KLM1298 streams live tool calls, displays structured flight data, and drives the interactive map in real time.

Comparison: MCP vs. AG-UI vs. A2UI in Agentic Stacks

It helps to place AG-UI alongside the two other protocols you will encounter in modern agentic architectures:

ProtocolConnectsResponsibility
MCPAgent ↔ Tools / DataGives an agent access to external APIs, databases, and backend tools
AG-UIAgent ↔ Frontend UIStreams run lifecycle, text/reasoning, tool visibility, app state, and UI commands
A2UIAgent → Frontend ComponentsDeclares native UI surfaces to render safely inside the conversation

How Can AG-UI Help Me?

Wiring an LLM into an interactive web app usually devolves into ad-hoc JSON parsing, duplicated action contracts, and brittle DOM side effects. Adopting AG-UI solves these problems at the protocol level:

1. Real-Time Contextual Grounding

Instead of forcing users to repeat identifiers ("which flight?"), the frontend attaches a lean snapshot of the user's current view and active selections to every turn—giving the agent immediate situational awareness.

2. Live Visibility Into Agent Execution

Because run lifecycle, reasoning, tool invocations, and text deltas are first-class typed events, the UI can display live progress indicators and execute side effects while the model is still thinking or composing its response.

3. Bidirectional UI Control Over One Stream

Rather than bolting on a separate WebSocket or polling channel for agent-driven navigation and state changes, AG-UI carries validated UI commands over the exact same real-time event stream as the conversation itself.

4. Stack-Agnostic Transport

AG-UI is built on standard HTTP POST requests and Server-Sent Events (SSE). You can pair any frontend framework with any backend runtime: Java, Kotlin, Python, or Node.js, without introducing a proprietary gateway or sidecar.


Understanding the Protocol

At its core, an AG-UI turn is a single HTTP POST request from the frontend carrying a RunAgentInput JSON payload, answered by a text/event-stream (SSE) response emitting typed AG-UI events until the run finishes.

Request (RunAgentInput)

Each turn sends a structured input payload:

  • threadId / runId — identifies the conversation and the current execution
  • messages — chronological conversation history (user, assistant, system)
  • forwardedProps — application-specific metadata and context (e.g., appVersion, currentRoute, model provider, and a lean uiState snapshot)

Why forwardedProps? The AG-UI specification also defines top-level state, tools, and context fields on RunAgentInput. Putting a compact uiState snapshot and an appVersion key inside forwardedProps keeps per-turn payloads small and lets your backend resolve static action schemas from a cache instead of re-sending them on every request.

Response (SSE Event Stream)

Every SSE data: frame is a JSON object discriminated by type:

CategoryEvent TypesPurpose
Run lifecycleRUN_STARTED
RUN_FINISHED
RUN_ERROR
Bounds a single agent turn and reports failures cleanly
ReasoningREASONING_START
REASONING_MESSAGE_*
REASONING_END
Streams model thinking separately from the final answer
Text streamingTEXT_MESSAGE_START
TEXT_MESSAGE_CONTENT
TEXT_MESSAGE_END
Streams incremental assistant text deltas
Tool visibilityTOOL_CALL_START
TOOL_CALL_ARGS
TOOL_CALL_END
Lets the UI show live tool pills (e.g., findFlightByCallsign)
App controlCUSTOM
name: "webapp:action"
Sends validated UI commands (navigate, focus map, switch theme)

On the wire, an agent turn looks like a sequence of lightweight SSE frames:

data: {"type":"RUN_STARTED","threadId":"t-1","runId":"r-42"}

data: {"type":"TOOL_CALL_START","toolCallId":"tc-1","toolCallName":"findFlightByCallsign"}

data: {"type":"CUSTOM","name":"webapp:action","value":{"action":"selectFlightOnMap","params":{"callsign":"KLM1298"}}}

data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"m-9","delta":"Flight KLM1298 is currently approaching Amsterdam..."}

data: {"type":"RUN_FINISHED","threadId":"t-1","runId":"r-42"}

Looking for rich UI surface events (ACTIVITY_SNAPSHOT / a2ui-surface)? Those are covered in the companion A2UI Guide.

End-to-End Turn Flow

Because events stream as they are produced, the application can pan the map or highlight entities while the model is still composing its summary sentence:

AG-UI sequence diagram across Angular App, AG-UI Client, SSE Controller, Spring AI Agent, and @Tool Methods showing boot capability sync, RunAgentInput POST, agent run with RUN_STARTED, stream advisor TOOL_CALL_* events, @Tool invocation, CUSTOM webapp:action events, real-time SSE streaming, Angular Signal effect updates, and TEXT_MESSAGE_* plus RUN_FINISHED


Applying AG-UI: Spring AI & Angular Architecture

Pairing Spring Boot + Spring AI with Angular Signals is a natural fit for AG-UI. On the backend, com.ag-ui.community:java-core (ag-ui-java-core) streams agent turns natively over Spring WebMVC SSE alongside Spring AI @Tool methods—no Node.js or Python sidecar required. On the frontend, @ag-ui/client's HttpAgent consumes that stream and feeds directly into Angular Signals, so live UI state flows out with every request and incoming agent commands flow back through the same reactive stores as user clicks.

Syncing an Action Registry on the Backend

By default, the AG-UI protocol recommends sending frontend tools on every RunAgentInput request so the backend remains completely stateless. That works well for small toolsets, but in a richer application with many UI actions, re-sending full JSON Schemas on every message adds unnecessary network traffic and serialization overhead. Conversely, moving those definitions into static backend YAML introduces prompt and contract drift whenever the frontend changes.

To cut per-turn network payload size without sacrificing a single source of truth, this architecture deliberately splits static capability registration out of the per-turn request into a versioned startup sync: declare schemas once on the frontend, sync them once on boot, and cache them on the backend by appVersion.

Step 1: Define Typed Capabilities With a Schema Library

Use a TypeScript schema library such as Zod as the single source of truth for your frontend action contracts. Defining each action's parameters in a schema library gives you two wins without duplicating types: you can export standard JSON Schema for the backend LLM prompt and reuse the exact same schema for runtime validation before mutating frontend state.

// Pseudocode: frontend capability manifest
capabilities = {
  appVersion: "0.1.0",
  actions: [
    {
      name: "setTheme",
      description: "Switch the UI theme (spring, summer, autumn, winter)",
      parametersSchema: toJsonSchema(SetThemeSchema), // derived from Zod
    },
    {
      name: "navigate",
      description: "Navigate to an application route",
      parametersSchema: toJsonSchema(NavigateSchema),
    },
    // ...map focus, layer toggles, selection actions
  ],
}

Step 2: Sync Once on App Boot

During Angular application initialization (for example, inside provideAppInitializer), send the capability manifest once via POST /api/agui/sync.

Step 3: Cache Capabilities by Version on the Backend

The backend caches the synced manifest keyed by appVersion (in an application cache or a shared store like Redis for multi-instance deployments):

// Pseudocode: backend capability registry
class CapabilityRegistry(private val cache: VersionedCache) {

    fun sync(manifest: CapabilityManifest) {
        val version = manifest.appVersion.ifBlank { "default" }
        cache.put(version, manifest)
        cache.setLatestVersion(version)
    }

    fun resolve(appVersion: String?): CapabilityManifest? {
        return cache.get(appVersion) ?: cache.getLatest()
    }
}

Step 4: Send Only appVersion Per Turn

Every subsequent turn only includes appVersion in forwardedProps. On the backend, the agent resolves the cached manifest for that version to build its system prompt and validate any UI action before emitting a CUSTOM event.

Result: zero schema duplication, tiny per-turn requests, and automatic alignment across frontend deployments.


Leveraging Angular Signals

Angular Signals (signal, computed, effect, and signal-based stores) pair naturally with @ag-ui/client's HttpAgent in both directions: reading live UI state before a turn, and applying agent commands reactively as events stream in.

Grounding Each Turn With Live UI State

If a user clicks a flight on the map and asks "show me the 3 closest airports to this flight", the agent should not need to ask "which flight?".

Because route, theme, map projection, and active selections all live in reactive Angular stores, the client service reads a lean, synchronous snapshot right before invoking HttpAgent:

// Pseudocode: configuring HttpAgent and sending a grounded turn
const agent = new HttpAgent({
  url: "/api/agui",
  initialMessages: buildConversationHistory(),
});

const uiState = {
  currentPage: resolvePageContext(router.url),
  theme: themeStore.theme(),
  colorMode: themeStore.colorMode(),
  mapProjection: mapStore.projection(),
  selectedFlight: flightStore.selected(),
  selectedStations: stationStore.selectedList(),
};

await agent.runAgent(
  {
    forwardedProps: {
      appVersion: APP_VERSION,
      currentRoute: router.url,
      uiState,
    },
  },
  eventCallbacks,
);

What makes this snapshot effective:

  • Page-aware intent — currentPage and contextual hints clarify ambiguous requests (e.g., on /map, "show me KLM844" focuses the map, whereas "open flight details" navigates to the flight's detail route).
  • Active visual state — theme, colorMode, and mapProjection let the agent reason about toggles without guessing.
  • Simultaneous selections — tracking a selected flight and multiple highlighted stations lets the agent ground pronouns like "this flight" or "these airports" immediately.

Effect-Based Updates From Agent Responses

Rather than scattering imperative DOM or router calls inside SSE callbacks, treat incoming AG-UI CUSTOM (webapp:action) events as reactive state:

  1. The client handles CUSTOM events in onCustomEvent and appends each command to a signal-backed action queue:
// Pseudocode: enqueuing incoming UI commands
onCustomEvent: ({ event }) => {
  if (event.name !== "webapp:action") return;
  controlService.enqueueAction(event.value);
}
  1. A control service drains the queue inside an Angular effect(). Dequeue the item before executing it (inside untracked()) so downstream store reads do not re-trigger the effect and a failed action can never wedge the queue:
// Pseudocode: draining the reactive action queue safely
actionQueue = signal<WebappAction[]>([]);

constructor() {
  effect(() => {
    const queue = this.actionQueue();
    if (queue.length === 0) return;

    const [next, ...rest] = queue;
    untracked(() => {
      this.actionQueue.set(rest);
      this.validateAndExecute(next); // validates params with Zod before mutating stores
    });
  });
}
  1. validateAndExecute parses the payload against the action's schema (e.g., with Zod) and dispatches it to the application's standard stores and router—so human clicks and AI commands share one predictable, reactive path.

Building a Spring Boot Agent

With com.ag-ui.community:java-core, a standard Spring Boot WebMVC application can host the entire AG-UI SSE endpoint natively alongside Spring AI.

1. Minimal SSE Endpoint

Spring WebMVC's SseEmitter bridges directly to AG-UI's reactive Agent.run(RunAgentInput) publisher, using Spring's Jackson 3 JsonMapper (augmented with a tiny SimpleModule of AG-UI mixins) for both @RequestBody binding and SSE frames:

// Pseudocode: Spring WebMVC SSE controller
@PostMapping("/api/agui", produces = [TEXT_EVENT_STREAM])
fun runAgent(@RequestBody input: RunAgentInput): SseEmitter {
    val emitter = SseEmitter(NO_TIMEOUT)

    val subscription = agent.run(input).subscribe(
        onEvent = { event -> emitter.send(jsonMapper.writeValueAsString(event)) },
        onComplete = { emitter.complete() },
        onError = { err -> emitter.completeWithError(err) },
    )

    emitter.onDisconnect { subscription.cancel() }
    return emitter
}

2. Thread-Safe Event Merging

During a single agent turn, events originate from two concurrent sources:

  • Streaming LLM chunks (reasoning, text deltas, tool-call markers) observed by a Spring AI StreamAdvisor ordered after the tool-calling advisor so it sees every recursive tool loop.
  • Side-channel UI events (CUSTOM events for webapp:action) emitted directly from @Tool methods.

Wrapping a serialized reactive stream (such as Reactor's Flux.create) inside a per-turn emitter ensures concurrent emissions from streaming and tool-execution threads are ordered safely without drops or interleaving:

// Pseudocode: per-turn event emitter
class TurnEmitter(private val publish: (Event) -> Unit) {
    fun emit(event: Event) = publish(event)

    fun emitWebappAction(action: String, params: Map<String, Any?> = emptyMap()) {
        emit(CustomEvent("webapp:action", mapOf("action" to action, "params" to params)))
    }
}

3. Stateless @Tool Beans With Per-Turn ToolContext

Passing the turn's TurnEmitter through Spring AI's ToolContext keeps every @Tool bean a stateless Spring singleton—thread-safe across concurrent requests and trivial to unit test with an in-memory event list:

// Pseudocode: dual-channel @Tool method
@Tool(description = "Validate that a station exists and open its details page.")
fun openStationDetails(code: String, toolContext: ToolContext? = null): String {
    val station = stationDirectory.find(code)
        ?: return "No station found matching '$code'."

    toolContext.turnEmitter()?.emitWebappAction("navigate", mapOf("route" to "/stations/${station.code}"))
    return "Navigated user to station details for ${station.code}."
}

Notice the dual-channel pattern: the @Tool emits the structured AG-UI CUSTOM event to the browser and returns a short, token-efficient confirmation string to the LLM.

Gotchas, Practical Pitfalls & Troubleshooting

Real-world issues you are likely to encounter when wiring AG-UI with Spring Boot, Spring AI, and Angular:

Spring Boot 4, Jackson 3, and ag-ui-spring-webmvc-boot-starter

The community ag-ui-spring-webmvc-boot-starter provides a quick out-of-the-box integration, but it targets older Spring AI patterns and depends on Jackson 2 (com.fasterxml.jackson.*). On Spring Boot 4 (which migrates to Jackson 3 under tools.jackson.*) and Spring AI 2, pulling in only the dependency-free com.ag-ui.community:java-core artifact and registering a small Jackson 3 SimpleModule with mixins for Event, Role, and Message avoids classpath conflicts, keeps java.time.* serialization clean, and lets Spring WebMVC bind @RequestBody RunAgentInput natively.

Handling SSE Disconnects & Timeouts

Spring WebMVC's default Servlet async timeout (often 30 seconds) will abruptly terminate long-running LLM turns unless disabled (e.g., SseEmitter(0L)). Equally important, bind emitter.onCompletion, emitter.onTimeout, and emitter.onError to cancel the upstream Flow.Subscription—otherwise an aborted browser tab leaves the backend streaming tokens from the LLM into a closed socket.

Backend Restarts & Capability Cache Misses

If your capability registry is stored only in memory, a backend restart or rolling deploy while a user's SPA tab is open leaves the cache empty for that appVersion. Mitigate this by storing capabilities in a shared cache (such as Redis) in multi-instance setups, and/or having the frontend automatically re-run POST /api/agui/sync when the backend signals an unknown appVersion.

Reverse-Proxy SSE Buffering

Proxies like Nginx or Cloudflare often buffer responses by default, causing all AG-UI events to arrive in one burst at the end of the turn instead of streaming live. Disable buffering for /api/agui (for example, X-Accel-Buffering: no and Cache-Control: no-cache).

Smaller or Local Models Hallucinating Top-Level Tool Names

Even when your system prompt instructs the model to call "setTheme" via a generic triggerWebappAction tool, smaller models (such as compact local models) can occasionally invoke setTheme(...) directly as a top-level tool—causing Spring AI to fail with No ToolCallback found. If you target constrained local models, you can tighten the tool description examples or expose thin, dedicated @Tool wrappers that delegate to your action emitter.

Cross-Thread Event Drops (FAIL_NON_SERIALIZED)

In Spring AI, streaming token chunks and @Tool executions can emit from different threads. Using a serialized sink like Flux.create<Event> (which serializes FluxSink.next(...) calls) avoids dropped events and deadlocks compared to Sinks.many().unicast() combined with blocking calls.

Dropping Non-Text Turns From Conversation History

When building initialMessages for HttpAgent, filtering conversation history by m.text.trim().length > 0 drops assistant turns that only emitted structured UI actions or cards without prose—causing follow-up prompts like "open the station details" to lose context. Always include a compact summary (e.g., [Displayed UI: StationCard(icao=EHAM, iata=AMS)]) for non-text assistant turns.


Summary

Pairing AG-UI with Spring Boot, Spring AI, and Angular Signals turns an embedded chatbot into a first-class, context-aware interface for your application:

  • Lightweight SSE transport streams run lifecycle, reasoning, tool progress, and UI commands over a single real-time pipeline.
  • Versioned startup capability sync keeps per-turn forwardedProps lean while aligning frontend schemas and backend prompts.
  • Reactive Angular Signals and schema validation route human interactions and AI-driven commands through the exact same application stores.
  • Native JVM hosting with serialized event merging and stateless @Tool beans wired via ToolContext keeps your agentic backend clean, testable, and sidecar-free.

Next step: explore the companion A2UI Guide to see how ACTIVITY_SNAPSHOT payloads are validated and mounted as responsive native Angular components inside the chat stream.