· 6 min read
Building a real-time AI transcription service: lessons learned
Architecture and lessons from AI Audio Text QA: browser audio streaming, local whisper.cpp, Ollama and Qdrant, MCP tools, .NET Aspire and web/mobile code sharing.

Over the past few months I built AI Audio Text QA, a real-time audio transcription service with built-in AI analysis. The starting idea was simple: speak into a microphone, see your words transcribed instantly, and be able to query the transcript in natural language. As always, reality turned out to be richer.
Here is an honest look at the architecture, the technical choices and what I took away from it.
Overview
The project is a full-stack .NET / React application organised as a monorepo:
AI.Audio.Text.QA/
├── AI.Audio.Text.QA.Server/ # REST API + WebSocket + AI services
├── AI.Audio.Text.QA.McpToolServer/ # MCP tool server (Qdrant, Ollama)
├── AI.Audio.Text.QA.AppHost/ # .NET Aspire orchestration + Keycloak
├── AI.Audio.Text.QA.Server.Tests/ # xUnit tests
├── frontend/ # React + Vite
├── mobile/ # Expo (React Native)
└── packages/shared/ # Types and API client shared by web/mobileOrchestration is handled by .NET Aspire. It starts the services (server, MCP server, Qdrant, Keycloak) and automatically injects the service discovery URLs. All the AI runs locally: whisper.cpp for transcription, Ollama for the LLM and embeddings, and Qdrant as the vector database.

The audio pipeline in the browser
The first challenge is capturing raw PCM audio in the browser and streaming it to the server. AudioContext and AudioWorkletNode make this possible, with a few subtleties.
I wrote a custom AudioWorkletProcessor (recorder-processor.js) that buffers samples before sending them. Sending every 128-sample block (256 bytes) produced around 625 messages per transcription window, which was far too much noise.
process(inputs) {
const channel = inputs[0]?.[0]
if (!channel?.length) return true
// Float32 → Int16 PCM conversion + buffering
for (let i = 0; i < channel.length; i++) {
const s = Math.max(-1, Math.min(1, channel[i]))
this._buf.push(s < 0 ? s * 32768 : s * 32767)
}
this._bufLen += channel.length
if (this._bufLen >= this._targetSamples) { // 3200 samples = 200 ms
const samples = this._buf.splice(0, this._targetSamples)
this._bufLen -= this._targetSamples
const pcm16 = new Int16Array(samples)
// RMS level for the visual indicator (separate message)
let sumSq = 0
for (let i = 0; i < samples.length; i++) sumSq += (samples[i] / 32767) ** 2
this.port.postMessage({ type: 'level', rms: Math.sqrt(sumSq / samples.length) })
// Send the audio buffer as a zero-copy transfer
this.port.postMessage(pcm16.buffer, [pcm16.buffer])
}
return true
}Each frame is 6,400 bytes, roughly 200 ms of PCM Int16LE audio at 16 kHz, mono — the format the server expects. Along the way, the processor computes the RMS level, which drives a small level meter in the UI.
The server: whisper.cpp, Ollama and Qdrant
On the server, each audio segment goes through several steps:
- Transcription with whisper.cpp (
whisper-cli), whose model is configured throughWhisperOptions - Embedding of the segment with Ollama (
mxbai-embed-large) - Storage of the vector in Qdrant, filtered by
conversationId - Detection of questions in the segment
- Answer from the AI agent, streamed, when a question is detected
WebSocket reception and Whisper inference are decoupled by a Channel<byte[]>. Without it, the receive loop stayed blocked for the few seconds each transcription takes:
var audioChannel = Channel.CreateBounded<byte[]>(
new BoundedChannelOptions(8) {
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = true
});
await Task.WhenAll(ReceiveLoopAsync(), TranscribeLoopAsync());DropOldest with 8 windows is deliberate: if Whisper falls behind, I would rather lose old audio than block network reception.
One detail matters: WebSocket.SendAsync is not thread-safe, and both the transcription loop and the agent's answers write to the same socket. A SemaphoreSlim(1, 1) therefore serialises every send:
using var sendLock = new SemaphoreSlim(1, 1);
async Task SendJsonAsync<T>(T message, CancellationToken ct = default)
{
var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message, JsonOptions));
await sendLock.WaitAsync(ct);
try
{
if (webSocket.State == WebSocketState.Open)
await webSocket.SendAsync(bytes, WebSocketMessageType.Text, true, ct);
}
finally { sendLock.Release(); }
}MCP: delegating tools to a dedicated service
The most interesting part of the project is the Model Context Protocol (MCP) integration. Rather than wiring tools directly into the main server, I created a standalone McpToolServer. It exposes tools to the AI agent, such as context search in Qdrant or question detection.
[McpServerToolType]
public sealed class DetectQuestionTool(IOllamaApiClient ollamaClient, IConfiguration config, ILogger<DetectQuestionTool> logger)
{
[McpServerTool, Description("Detects whether a transcript segment contains a question...")]
public async Task<string> DetectQuestion(
[Description("The transcript text to analyze")] string text,
CancellationToken cancellationToken = default)
{
if (!text.Contains('?')) return "NONE"; // short-circuit: no needless LLM call
// ... question extraction via Ollama
}
}In ConversationAgentService, the agent runs a tool-calling loop. It sends the tool definitions to the LLM (Qwen 2.5 via Ollama), executes the requested calls through the MCP client, sends the results back to the model and starts again — up to 5 iterations — until it gets a final answer.
The MCP client is initialised lazily on first use, with a double-checked lock:
private async Task<McpClient?> TryGetMcpClientAsync(CancellationToken cancellationToken)
{
if (_mcpClient is not null) return _mcpClient;
await _initLock.WaitAsync(cancellationToken);
try
{
if (_mcpClient is not null) return _mcpClient;
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = _mcpEndpoint
});
_mcpClient = await McpClient.CreateAsync(transport, null, _loggerFactory, cancellationToken);
return _mcpClient;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect to MCP server");
return null; // the agent falls back to a direct answer without tools
}
finally
{
_initLock.Release();
}
}If the MCP server is unavailable, the agent does not crash: it answers directly, without tools. In the AppHost, declaring the dependency is enough for Aspire to inject the URL:
var mcpTools = builder.AddProject<Projects.AI_Audio_Text_QA_McpToolServer>("mcp-tools")
.WithReference(qDrant)
.WaitFor(qDrant);
var server = builder.AddProject<Projects.AI_Audio_Text_QA_Server>("server")
.WithReference(mcpTools)
.WaitFor(mcpTools);A small anecdote: the
ModelContextProtocol2.2.0 SDK API had changed quite a bit compared to the examples found online (IMcpClient,McpClientFactoryandSseClientTransportno longer exist). It was the XML documentation embedded in the NuGet package that gave me the right names:McpClient.CreateAsyncandHttpClientTransport.
Authentication with Keycloak and PKCE
Authentication relies on Keycloak with a client-side PKCE flow, so no client secret is ever exposed in the browser. The realm is versioned in the repo (realm.json) and imported at startup by Aspire.
For the WebSocket, the browser's native API cannot send an Authorization header. The token is therefore passed in the query string when the connection opens:
const ws = new WebSocket(
`${proto}://${window.location.host}/ws/transcription?access_token=${keycloak.token}`
)The server picks up this parameter in the JWT Bearer events:
options.Events = new JwtBearerEvents
{
OnMessageReceived = ctx =>
{
var token = ctx.Request.Query["access_token"];
if (!string.IsNullOrEmpty(token))
ctx.Token = token;
return Task.CompletedTask;
}
};Conversations and PDF export
The frontend has a "Conversations" section that groups recordings by date: Today, Yesterday, This week, then by month. This logic lives in packages/shared so it can be reused on mobile, and it relies only on the native Date API, with no dependency:
export function groupByDate(recordings: RecordingItem[]): ConversationGroup[] {
const today = startOfDay(new Date())
const yesterday = today - 86_400_000
const weekAgo = today - 7 * 86_400_000
for (const r of recordings) {
const t = startOfDay(new Date(r.startedAt))
let label: string
if (t >= today) label = "Aujourd'hui"
else if (t >= yesterday) label = 'Hier'
else if (t >= weekAgo) label = 'Cette semaine'
else label = new Date(r.startedAt).toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })
// ...
}
}The PDF export is generated client-side with jsPDF, with no server round trip and no headless browser:
for (const seg of recording.segments) {
doc.setFontSize(8)
doc.text(formatTs(seg.start), margin, y)
doc.setFontSize(11)
const lines = doc.splitTextToSize(seg.text, maxWidth - 20) as string[]
doc.text(lines, margin + 20, y)
y += lines.length * 6 + 4
if (y > 272) { doc.addPage(); y = 20 }
}
doc.save(`${filename}.pdf`)Is generating the PDF on the client a security concern? Not here: the document only contains data the user has already received through the authenticated API, so generating it exposes nothing more. The real access control stays on the server, on GET /api/recordings/{id}.
The mobile app with Expo
The latest phase adds an Expo (React Native) mobile app. Thanks to the monorepo, sharing code is easy: the @ai-audio-qa/shared package exposes the types, the API client and the date-grouping logic.
The key is the TokenProvider abstraction. The API client does not know where the token comes from, which keeps it independent of how authentication is implemented:
export type TokenProvider = () => Promise<string>
export function createApiClient(baseUrl: string, getToken: TokenProvider) {
async function authFetch(path: string, init?: RequestInit): Promise<Response> {
const token = await getToken() // keycloak-js on the web, expo-auth-session on mobile
return fetch(`${baseUrl}${path}`, {
...init,
headers: { ...init?.headers, Authorization: `Bearer ${token}` },
})
}
// listRecordings, getRecording, deleteRecording...
}On mobile, Keycloak authentication goes through expo-auth-session with PKCE, using a custom deep link (com.aiaudioqa://auth) registered in the realm. Token refresh relies on shouldRefresh():
async function getToken(): Promise<string> {
const tr = tokenRef.current
if (!tr) throw new Error('Not authenticated')
if (tr.shouldRefresh()) {
const refreshed = await tr.refreshAsync({ clientId: CLIENT_ID }, discovery)
setTokenResponse(refreshed)
return refreshed.accessToken
}
return tr.accessToken
}Navigation uses Expo Router (file-based routing), which gives a readable tree:
mobile/app/
├── _layout.tsx # AuthProvider + auth guard
├── (auth)/login.tsx # Sign-in screen
└── (tabs)/
├── index.tsx # Transcription (coming soon)
└── conversations/
├── _layout.tsx # Navigation stack
├── index.tsx # List grouped by date
└── [id].tsx # Detail + export via the native share sheetWhat I took away
Aspire was a genuinely good surprise. Automatic service discovery removes all manual URL configuration between services, and the built-in dashboard (logs, traces, resource status) is very handy during development.
MCP clarifies the tool architecture. A dedicated MCP server, rather than tools wired into the agent, lets you test, deploy and evolve tools independently. The fallback to a direct answer also makes the system more resilient.
Sharing code between web and mobile takes discipline. No DOM dependency in the shared package, portable types, and a clean abstraction for everything platform-specific: authentication, storage, audio. The upfront effort pays off as soon as the second client arrives.
WebSockets and concurrency have to be earned. Without the semaphore, concurrent sends silently corrupt frames — the kind of bug that only shows up under load.
What's next
The next step is real-time transcription on mobile. It requires a native module such as react-native-audio-record to capture raw Int16 PCM at 16 kHz, then wiring that stream into the existing WebSocket. The server protocol does not change: the binary frame format stays exactly the same.