Live Radio Channel: Streaming AG-UI Events and Tool Calls from Spring AI
Opening a real-time AG-UI Server-Sent Events frequency from Spring Boot 4 and Spring AI, with multi-provider LLMs, Jackson 3 mixins, serialised transmissions, and dual-channel @Tool methods.
Series Context: Part 03 of Spring Traffic Control
Audience: Spring / Kotlin / AI Developers · Reading Track: Full-Stack, Spring & Agentic UI Tracks
Previous: Part 02: Airspace Boundaries · Next: Part 04: Building the Radar Scope (upcoming)
Companion Reference Guides: AG-UI · A2UI
In Part 02: Airspace Boundaries, we divided the Control Tower into six clean Spring Modulith sectors backed by embedded DuckDB and guarded by ArchUnit tests. Now it is time to open the live radio channel between our Spring AI backend and the Angular Flight Deck.
Most Spring AI tutorials stop at chatClient.prompt(q).stream().content(), piping raw Markdown strings to the browser. In an operations UI, that feels like radio static: the Flight Deck stays completely blind while the model is thinking or invoking tools, and you end up inventing fragile JSON delimiters the moment you want the tower to pan a map or hand over a flight strip.
Instead, we wire Spring AI directly to the AG-UI protocol over standard Spring WebMVC Server-Sent Events (SSE), all inside the JVM with zero Python or Node.js sidecar.
Tuning to the Same Frequency: Why AG-UI Beats Custom SSE Formats
In aviation, everyone on a frequency speaks standard phraseology so pilots and controllers never have to guess what a transmission means. AG-UI brings that same discipline to agent-to-frontend streaming by defining a discriminated JSON envelope for everything that happens in a single turn:
- Clearance & Lifecycle:
RUN_STARTED,RUN_FINISHED,RUN_ERROR - Reasoning & Readbacks:
REASONING_*andTEXT_MESSAGE_* - Live Tool Telemetry:
TOOL_CALL_START,TOOL_CALL_ARGS,TOOL_CALL_END - Flight Deck Side Channels:
CUSTOM(webapp:actionfor map and route commands) andACTIVITY_SNAPSHOT(a2ui-surfacefor native Angular cards)
(For the full protocol reference and event table, see the companion AG-UI Guide.)
Because every frame is typed and transmitted the instant it occurs, the Angular client (@ag-ui/client) can display live tool progress pills, mount a flight card, and fly the MapLibre camera while the model is still streaming its final summary sentence:
data: {"type":"RUN_STARTED","threadId":"t-1","runId":"r-42"}
data: {"type":"TOOL_CALL_START","toolCallId":"tc-1","toolCallName":"findFlightByCallsign"}
data: {"type":"TOOL_CALL_ARGS","toolCallId":"tc-1","delta":"{\"callsign\":\"KLM1298\"}"}
data: {"type":"TOOL_CALL_END","toolCallId":"tc-1"}
data: {"type":"ACTIVITY_SNAPSHOT","messageId":"a2ui-9c1a","activityType":"a2ui-surface","content":{"surfaceId":"a2ui-9c1a","component":"FlightCard","data":{...}}}
data: {"type":"CUSTOM","name":"webapp:action","value":{"action":"selectFlightOnMap","params":{"icao24":"484162"}}}
data: {"type":"TEXT_MESSAGE_START","messageId":"msg-1","role":"assistant"}
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg-1","delta":"KLM1298 is currently en route..."}
data: {"type":"TEXT_MESSAGE_END","messageId":"msg-1"}
data: {"type":"RUN_FINISHED","threadId":"t-1","runId":"r-42"}
Switching Frequencies: Multi-Provider ChatClient (Local + Cloud)
A good exploration playground should let you switch radio frequencies without rebuilding the tower. Spring Traffic Control lets the operator toggle between a local model (Docker Model Runner / Ollama via Spring AI's OpenAI-compatible starter) and Google Gemini (via Spring AI's Google GenAI starter) per request.
Rather than locking onto one auto-configured ChatClient, a lightweight factory resolves the requested ChatModel at turn time and wires three essentials onto every client:
- Flight Data Recorder (Observability): Passing the
ObservationRegistryandToolCallingAdvisorbuilder ensures every model call, advisor, and tool execution emits OpenTelemetry GenAI spans automatically (covered in Part 07). - Ordered Advisor Chain:
- Pre-flight context (before tool calling): a context advisor augments the system prompt with live UI state and synced capabilities.
- Autopilot tool loop: Spring AI's built-in
ToolCallingAdvisordrives recursive tool execution, preserving provider-specific metadata such as Gemini'sthought_signatureand reasoning parts automatically. - Live telemetry tap (after tool calling): our
StreamAdvisorobserves every streamed chunk read-only across every recursive iteration and translates reasoning, text, and tool calls into AG-UI events.
- Stateless
@Toolbeans: Registered once as Spring singletons with no per-request tool instantiation.
// Resolving a provider-specific ChatClient with an ordered advisor chain (simplified)
fun createChatClient(requestedProvider: AgentProvider?): ChatClient {
val chatModel = resolveChatModel(requestedProvider ?: defaultProvider)
return ChatClient.builder(chatModel, observationRegistry, toolCallingAdvisorBuilder)
.defaultSystem(systemPrompt)
.defaultTools(aviationTools, frontendControlTools)
.defaultAdvisors(
uiContextAdvisor, // order < ToolCallingAdvisor (augments prompt)
agUiStreamAdvisor, // order > ToolCallingAdvisor (observes every stream loop)
)
.build()
}
The Tower Transmitter: Spring WebMVC SseEmitter, ag-ui-java-core, and Jackson 3
Spring Boot 4 migrates to Jackson 3 (tools.jackson.*). Rather than pulling in an older community starter that drags Jackson 2 (com.fasterxml.jackson.databind.*) onto the classpath and trips our ArchUnit rules from Part 02, we depend solely on the lightweight, dependency-free com.ag-ui.community:java-core artifact (ag-ui-java-core).
To make its plain Java types serialise and deserialise natively across Spring WebMVC @RequestBody and SSE frames, we register a tiny Jackson 3 SimpleModule with three mixins:
// Minimal Jackson 3 module for dependency-free AG-UI core types (simplified)
@Component
class AgUiJacksonModule : SimpleModule("ag-ui") {
init {
setMixInAnnotation(Event::class.java, EventMixin::class.java) // maps type() -> "type", drops nulls
setMixInAnnotation(Role::class.java, RoleMixin::class.java) // serialises enum via value()
setMixInAnnotation(Message::class.java, MessageMixin::class.java) // polymorphic "role" subtypes
}
}
With that module auto-registered into Spring's primary JsonMapper, the tower transmitter stays compact: accept @RequestBody input: RunAgentInput, return an SseEmitter(0L) (disabling Servlet's short default async timeout), bridge the agent's reactive Flow.Publisher<Event>, and cancel the upstream subscription the moment the browser disconnects:
// Spring WebMVC SSE controller bridging Flow.Publisher<Event> to SseEmitter (simplified)
@PostMapping("/api/agui", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun run(@RequestBody input: RunAgentInput): SseEmitter {
val emitter = SseEmitter(0L)
agent.run(input).subscribe(
onSubscribe = { sub ->
emitter.onCompletion { sub.cancel() }
emitter.onTimeout { sub.cancel() }
emitter.onError { sub.cancel() }
sub.request(Long.MAX_VALUE)
},
onNext = { event ->
emitter.send(SseEmitter.event().data(jsonMapper.writeValueAsString(event)))
},
onError = { err ->
emitter.send(SseEmitter.event().data(jsonMapper.writeValueAsString(RunErrorEvent(err.message))))
emitter.complete()
},
onComplete = { emitter.complete() },
)
return emitter
}
No Stepping on the Frequency: Serialising Transmissions with StreamAdvisor, ToolContext, and TurnEmitter
On a busy ATC frequency, two pilots keying the mic at the same time produces garbled audio. An agentic backend faces the exact same concurrency hazard: during a single turn, AG-UI events originate from two independent execution paths:
- Streaming LLM chunks, observed by our
StreamAdvisoron the reactive stream thread (REASONING_*,TEXT_MESSAGE_*,TOOL_CALL_*). - Side-channel Flight Deck events, emitted from inside
@Toolmethods on tool-execution threads (ACTIVITY_SNAPSHOTfor A2UI cards andCUSTOMforwebapp:actioncommands).
One serialised TurnEmitter per turn: streaming LLM chunks from StreamAdvisor and side-channel events from stateless @Tool beans converge safely into Flux.create<Event> before reaching SseEmitter.
To merge both channels cleanly without dropped frames, interleaved state, or per-turn bean allocation, we create one lightweight TurnEmitter backed by Reactor's Flux.create<Event> (whose FluxSink.next(...) serialises concurrent calls safely) and pass that same emitter into both Spring AI's advisor context and ToolContext:
// Wiring one serialised TurnEmitter into both advisor context and ToolContext (simplified)
fun run(input: RunAgentInput): Flow.Publisher<Event> {
val flux = Flux.create<Event> { sink ->
val emitter = TurnEmitter { event ->
if (!sink.isCancelled) sink.next(event)
}
emitter.emit(RunStartedEvent(input.threadId, input.runId))
val disposable = chatClient
.prompt()
.messages(toSpringMessages(input.messages))
.advisors { spec ->
spec.param("agui.emitter", emitter)
spec.param("agui.uiState", input.uiState)
}
.toolContext(mapOf("agui.emitter" to emitter, "agui.appVersion" to input.appVersion))
.stream()
.chatResponse()
.subscribeOn(Schedulers.boundedElastic())
.subscribe(
{ /* chunks translated inside StreamAdvisor */ },
{ err -> emitter.emit(RunErrorEvent(err.message)); sink.complete() },
{ emitter.emit(RunFinishedEvent(input.threadId, input.runId)); sink.complete() },
)
sink.onDispose(disposable)
}
return FlowAdapters.toFlowPublisher(flux)
}
Inside the StreamAdvisor, a small per-turn state machine keeps transmissions well-formed: closing an open reasoning block before opening text, closing text before emitting tool-call markers, and deduplicating tool-call IDs across streamed chunks:
// Read-only StreamAdvisor translating streamed chunks into AG-UI events (simplified)
fun onChunk(message: AssistantMessage, state: TurnStreamState, emitter: TurnEmitter) {
for (part in message.reasoning) {
state.closeTextIfOpen()
state.openReasoningIfNeeded()
emitter.emit(ReasoningMessageContentEvent(state.reasoningId, part.text))
}
if (!message.text.isNullOrEmpty()) {
state.closeReasoningIfOpen()
state.openTextIfNeeded()
emitter.emit(TextMessageContentEvent(state.messageId, message.text))
}
if (message.hasToolCalls()) {
state.closeAllOpenBlocks()
for (call in message.toolCalls) {
if (state.markEmitted(call.id)) {
emitter.emit(ToolCallStartEvent(call.id, call.name, state.messageId))
emitter.emit(ToolCallArgsEvent(call.id, call.arguments))
emitter.emit(ToolCallEndEvent(call.id))
}
}
}
}
Clearance Readbacks: Dual-Channel Domain @Tool Methods
Because of the Spring Modulith airspace boundaries we enforced in Part 02: Airspace Boundaries, our domain @Tool bean injects only the public service interfaces (stations, schedule, flightstate). Every tool follows the dual-channel pattern:
- Flight Deck side channel (Browser): Emit rich domain objects as A2UI flight strips (
StationCard,FlightCard,NearestAirportsCard) and map commands (showClosestAirportsOnMap) directly viaToolContext. - Concise readback (LLM): Return a short, token-efficient operational summary so the model can reason accurately without burning context tokens on raw JSON payloads.
// Dual-channel aviation @Tool using public Modulith services + ToolContext (simplified)
@Tool(description = "Find the closest airports to a live airborne flight and highlight them on the map.")
fun findNearestAirportsForFlight(
icao24: String,
limit: Int = 5,
emergencyOnly: Boolean = false,
category: AircraftCategory = AircraftCategory.LIGHT,
toolContext: ToolContext? = null,
): String {
val nearest = inFlightService.findNearestAirports(icao24, emergencyOnly, category, limit)
if (nearest.isEmpty()) return "No nearest airports found for $icao24."
val codes = nearest.map { it.station.routeCode }
// Side channel: render native card + highlight airports on MapLibre immediately
toolContext.turnEmitter()?.let { emitter ->
emitter.emitSurface("NearestAirportsCard", mapOf("icao24" to icao24, "airports" to nearest))
emitter.emitWebappAction("showClosestAirportsOnMap", mapOf("icao24" to icao24, "stationCodes" to codes))
}
// Concise operational readback for the LLM
return nearest.joinToString("\n") { "${it.station.name} (${it.station.routeCode}) — ${it.distanceKm} km" }
}
A few small aviation-specific details make these tools noticeably more reliable across both cloud and compact local models:
- Station lookups (
findStations,findStationByCode): Accept natural names, IATA, or ICAO codes ("Schiphol","AMS","EHAM"), return runways and radio frequencies in compact text, and emitStationCardsurfaces. - Callsign normalisation (
findFlightByCallsign): ATC callsigns likeKLM844often correspond to scheduled flight numbers likeKL844. Extracting the numeric digits as a fallback lets a single tool search live OpenSky states first and fall back gracefully to scheduled flights, emitting aFlightCardwhenever a schedule exists. - Scheduled search (
findScheduledFlights): Filters by query and arrival/departure direction, while capping emitted cards so the chat drawer never floods with dozens of strips at once.
Gotchas & Trade-Offs: Advisor Order, Concurrent Transmissions & Dead Sockets
Ordering StreamAdvisor After ToolCallingAdvisor
If your streaming observer runs before ToolCallingAdvisor, you miss intermediate tool-calling iterations. Worse, manually intercepting and reconstructing AssistantMessage turns yourself can strip provider metadata like Gemini's PAYLOAD_THOUGHT_SIGNATURE and break multi-step tool calls. Ordering a read-only StreamAdvisor strictly after ToolCallingAdvisor.DEFAULT_ORDER lets Spring AI own the recursive loop while you observe every chunk cleanly.
Flux.create vs. Sinks.many().unicast()
When LLM streaming threads and @Tool execution threads emit into the same sink concurrently, Sinks.many().unicast() can reject emissions with FAIL_NON_SERIALIZED. Flux.create wraps FluxSink in a serialised sink automatically, preventing silent event drops.
Always Cancel Upstream on SSE Disconnect
Setting SseEmitter(0L) prevents Spring WebMVC from terminating long-running reasoning turns at 30 seconds, but you must bind emitter.onCompletion, emitter.onTimeout, and emitter.onError to subscription.cancel(). Otherwise, closing a browser tab leaves the tower transmitting tokens from the LLM into a dead socket.
Staying Zero Jackson 2 on Spring Boot 4
Our ArchUnit rule from Part 02 forbids com.fasterxml.jackson.databind.*. Using ag-ui-java-core with a 30-line Jackson 3 SimpleModule instead of a legacy starter keeps the entire stack strictly on tools.jackson.* and eliminates subtle Kotlin and java.time.* serialisation mismatches.
Handing Over to Approach: Clearing the Runway for Part 04
The Control Tower can now transmit live reasoning, tool telemetry, A2UI flight strips, and validated frontend actions over a single AG-UI SSE frequency, while keeping @Tool beans stateless, observable, and strictly bounded by Spring Modulith.
Next up in Part 04: Building the Radar Scope, we cross over to the Angular 22 Flight Deck to see how MapLibre GL, NgRx SignalStore, and per-layer MapLayerAdapter services turn an imperative WebGL map into a reactive radar scope ready for AI autopilot.