🎤Micdrop

Testing a Voice Agent

@micdrop/testing runs your own MicdropServer config in a test: your agent, its tools, its handoffs and its first message. It offers three levels, from the fastest to the most faithful:

  • a text simulation, where the test says each turn as text and asserts on what the agent said and did, with no network but the requests of your agent to its model
  • a simulated caller, a persona played by a model or by a script, which talks to your agent until one of them hangs up, then assertions and judges decide whether the call went well
  • an audio simulation, which plays WAV files in real time through your real speech to text, VAD and turn detector, to check turn taking and interruptions

The assertions throw a standard AssertionError, so the package works in any test runner. The testing tutorial builds a full suite for a support agent, CI included.

Terminal window
npm install --save-dev @micdrop/testing

Build the config in one place

The kit starts a server with the config your app gives it. Build that config in a function, without its speech to text and voice, so the app and the tests share it:

src/agent.ts
import { AiSdkAgent } from '@micdrop/ai-sdk'
import {
endCallTool,
handoffTool,
MicdropPipelineConfig,
} from '@micdrop/server'
import { openai } from '@ai-sdk/openai'
export function createCallConfig(): MicdropPipelineConfig {
return {
agent: new AiSdkAgent({
model: openai('gpt-5.2'),
providerOptions: { openai: { reasoningEffort: 'none' } },
systemPrompt: 'You are the phone support of a small shop.',
tools: [
lookupOrder,
refundOrder,
handoffTool({ name: 'billing', to: createBillingAgent }),
endCallTool(),
],
}),
firstMessage: 'Hello, this is the shop support. How can I help?',
}
}
// src/server.ts
new MicdropServer(socket, {
...createCallConfig(),
stt: new GladiaSTT({ apiKey }),
tts: new ElevenLabsTTS({ apiKey, voiceId }),
})

The text simulation replaces stt and tts with fakes, and releases the ones it is given. A config built without them opens no connection to those providers.

Simulate a call with text

TestCall.start() starts the call and waits for the first message. Each say() is a turn of the user, heard by the fake speech to text as written, and resolves once the agent is done answering, tools and handoffs included.

import { describe, it } from 'node:test'
import {
expectAnswer,
expectHandoff,
expectNoToolCall,
expectToolCall,
TestCall,
} from '@micdrop/testing'
import { createCallConfig } from '../src/agent'
describe('Support agent', () => {
it('looks an order up before answering', async () => {
const call = await TestCall.start(createCallConfig())
expectAnswer(call.opening, 'how can I help')
const turn = await call.say('Hi, where is my order number 42?')
const lookup = expectToolCall(turn, 'lookup_order', { orderId: '42' })
console.log(lookup.output) // { status: 'shipped', total: 59 }
expectAnswer(turn, /shipped/i)
expectNoToolCall(turn, 'refund_order')
await call.end()
})
it('transfers invoice questions to billing', async () => {
const call = await TestCall.start(createCallConfig())
expectHandoff(await call.say('I need a copy of my invoice'), 'billing')
await call.end()
})
})

The same file runs in vitest or jest by importing describe and it from there.

Each say() returns a TurnRecord:

FieldWhat it holds
indexRank of the turn, from 1. call.opening is turn 0, before the user first spoke
userWhat the test said
answerThe answers of the turn joined, undefined when the agent said nothing
messagesEvery item the turn added to the conversation: user and assistant messages, tool calls and their results
toolCallsEach tool call with its name, its parsed parameters and its output
handoffsEach handoff, with the agents from and to, and the tool that asked for it
endedCallWhether the agent ended the call
skippedWhether the agent said nothing back, after ignoreNoiseTool() or semanticTurnTool() for instance
cancelledWhether the agent dropped the user message as a noise
interruptedWhether the user spoke again before the answer was over
metricsLatency and usage of the turn, see Measure the latency

The call itself holds turns, toolCalls, handoffs, assistantMessages, endedCall, the whole conversation, the current agent and the server.

Assertions

Every assertion takes a turn, a call or the result of a simulated conversation, and shows the conversation when it fails.

AssertionPasses when
expectToolCall(record, name, parameters?)The tool was called, with parameters that match. Returns the call
expectNoToolCall(record, name?)The tool was not called, or no tool at all
expectToolCallOrder(record, names)The tools were called in this order, other calls allowed in between
expectHandoff(record, to?)The call was handed over, to this agent or to the name given to handoffTool()
expectNoHandoff(record)The call stayed with its agent
expectEndCall(record) and expectNoEndCall(record)The agent ended the call, or kept it open
expectAnswer(record, matcher, { any? })The last answer matches, or any of them with any: true
expectNoAnswer(record, matcher?)No answer matches, or the agent said nothing
expectSkipped(turn)The agent said nothing back during the turn
expectLatency(metrics, limits)The turn or the call answered within the limits

A text matcher is a part of the answer (case aside), a RegExp or a predicate. Parameters match key by key: each key given must match, whatever else the parameters hold, and a value can be a RegExp or a predicate.

expectToolCall(turn, 'book_table', {
guests: 4,
date: /^2026-12-/,
name: (name: string) => name.length > 0,
})

The end of the call

When the agent ends the call, the simulation ends it too once the goodbye is written, as a client does, and a later say() throws. { endOnEndCall: false } keeps it open. call.end() hangs up and returns the summary of the call, with its conversation and metrics.

Interruptions

say(text, { wait: false }) resolves as soon as the turn is sent, so the next turn can speak over the answer:

const call = await TestCall.start(createCallConfig())
const story = call.say('Tell me about your return policy', { wait: false })
await call.waitForAssistantSpeech()
const stop = await call.say('Sorry, actually where is my order 42?')
assert.ok((await story).interrupted)
expectToolCall(stop, 'lookup_order')

The fake voice plays each word as a single sample, so an answer is over as soon as it is written. A longer voice, { tts: new TextTTS({ wordDuration: 200 }) }, keeps the answer audible long enough to speak over it.

Options

OptionDefaultWhat it does
ttsA TextTTSThe voice of the answers. false keeps the call textual, without voice metrics
sttA TextSTTThe speech to text, whose delay simulates the time a transcript takes
timeout30000How long a turn may take to settle, in ms
endOnEndCalltrueEnds the call once the agent hangs up
hangsUpfalseBehaves like a phone line, whose transport hangs up by itself
loggernoneLogs what the server does, with true or a Logger

Measure the latency

The server reports the metrics of each turn once its answer has been heard. call.waitForMetrics(turn) waits for them, and expectLatency() checks them. With the fakes, the speech to text and the voice take no time, so the latency you measure is the one of your agent and its tools.

const turn = await call.say('Where is my order 42?')
const metrics = await call.waitForMetrics(turn)
expectLatency(metrics, { llm: 1500 })
console.log(metrics.usage.inputTokens, metrics.model)
const summary = await call.end()
expectLatency(summary.metrics, { llm: { median: 1000, p95: 2500 } })

A limit on a step that was not measured fails, so a limit never passes for want of a measure.

Simulate a caller

simulateConversation() lets a caller talk to your agent until one of them hangs up, or until maxTurns (10 by default). It then runs your assertions and your judges, and gives a result that expectPassed() checks.

The model playing the caller and the one judging stay your choice. @micdrop/testing/ai-sdk makes them with any model of the AI SDK, installed next to it (npm install ai zod):

import { openai } from '@ai-sdk/openai'
import {
expectPassed,
expectToolCall,
simulateConversation,
} from '@micdrop/testing'
import { aiSdkCaller, aiSdkJudge } from '@micdrop/testing/ai-sdk'
it('refunds a lost order for an impatient customer', async () => {
const result = await simulateConversation({
config: createCallConfig,
caller: aiSdkCaller({
model: openai('gpt-5-mini'),
instructions:
'You are Sam, a bit impatient. Your order 43 never arrived and you want your money back.',
}),
maxTurns: 8,
assertions: (call) => {
expectToolCall(call, 'refund_order', { orderId: '43' })
},
judge: aiSdkJudge({
model: openai('gpt-5-mini'),
criteria: [
'The assistant asked before refunding',
'The assistant told the amount refunded',
],
}),
})
expectPassed(result)
})

The caller hangs up once its goal is reached or out of reach. result holds passed, endedBy (caller, agent, stopWhen or maxTurns), the call with all its turns, the transcript and the verdicts of the checks, by name.

Give config a function, so each conversation gets fresh agents. Several judges go in an object, judge: { tone: toneJudge, facts: factsJudge }, and each gets its verdict by name.

Without a model

A caller is a function returning what to say, or null to hang up, so a test can drive the conversation itself. scriptedCaller() says its lines in order, each one optionally after the agent said something:

const result = await simulateConversation({
config: createCallConfig,
caller: scriptedCaller([
'My order 43 never came',
{ say: 'Yes please', after: 'refund' },
'Thanks, goodbye',
]),
assertions: (call) => expectEndCall(call),
})

A judge is a function too, returning a boolean or { pass, reason }:

judge: ({ transcript, call }) => ({
pass: call.assistantMessages.every((answer) => answer.length < 300),
reason: 'An answer is too long to be spoken',
})

stopWhen: (call, turn) => boolean stops the conversation after any turn.

A model answers differently from one run to the next. Run the conversations that matter several times, and treat them as a measure of how often your agent succeeds rather than as a single pass or fail.

Test the wiring offline

A test that knows exactly what the model says checks everything around it: the parameters of the tools, their outputs, the handoffs and the end of the call. Two ways get there.

ScriptedAgent stands in for your agent, with your tools. Each answer is a text or a list of steps:

import { endCallTool } from '@micdrop/server'
import { expectEndCall, ScriptedAgent, TestCall } from '@micdrop/testing'
const call = await TestCall.start({
agent: new ScriptedAgent(
[
[
{ tool: 'lookup_order', args: { orderId: '42' } },
{ say: 'It has shipped.' },
],
[{ say: 'Goodbye!' }, { tool: 'end_call' }],
],
{ tools: [lookupOrder, endCallTool()] }
),
})

A step can also wait some ms, report usage, throw or hang, to test how your app handles a slow or failing model.

To keep your real agent and replace only its model, give it a mock model of its framework. The testing example does it with the MockLanguageModelV4 of the AI SDK, and runs the real AiSdkAgent offline in a few milliseconds.

Simulate a call with audio

AudioTestCall plays audio to your server in real time, 20 ms at a time, through your real speech to text, audio filters, VAD and turn detector. It checks what the text simulation leaves out: whether a pause cuts a sentence in two, how fast the turn closes, and what happens when the user speaks over the assistant.

import { AudioTestCall, expectAnswer, readWav } from '@micdrop/testing'
it('hears a question spoken with a pause', async () => {
const call = await AudioTestCall.start({
...createCallConfig(),
stt: new GladiaSTT({ apiKey }),
turns: { vad: 'silero', detector: new SmartTurn() },
})
await call.silence(500)
const turn = await call.say(readWav('fixtures/order-with-pause.wav'))
assert.equal(turn.userMessages.join(' '), 'Where is my order... number 42?')
expectAnswer(turn, 'shipped')
await call.end()
})

readWav() reads a PCM16 WAV file at any rate, mono or stereo, and brings it to mono at 16 kHz, the audio the server hears. tone(ms) and silence(ms) synthesize a loud tone and silence, enough for a volume VAD. encodeWav(pcm, sampleRate, path) writes a WAV file, to listen to what a test heard.

Who finds the turns

turnsDefault whenWhat the far end does
serverThe config has turns.vadStreams everything, silence included, as a phone line does. The server finds the turns
clientThe config has no turns.vadRuns its own VAD, clientVad ('volume' by default) with clientTurnDetector, as the Micdrop clients do, and sends StartSpeaking and StopSpeaking
manualNeverSends each play() as one turn

Timing and barge-in

play(audio, { at }) starts at a time of the call, in ms since it started, and play(audio, { delay }) some ms from now. In server and client modes, silence fills the line until then.

const call = await AudioTestCall.start(createAudioConfig())
const question = call.say(readWav('fixtures/long-question.wav'))
await call.waitForAssistantSpeech()
// The user speaks 300 ms into the answer
const bargeIn = call.elapsed + 300
const stop = await call.say(readWav('fixtures/stop.wav'), { at: bargeIn })
assert.ok((await question).interrupted)
const [speech] = call.assistantSpeech
assert.ok(speech.interrupted)
assert.ok(
speech.end - bargeIn < 800,
'the voice stopped soon after the user spoke'
)
console.log(call.formatTimeline())

assistantSpeech lists the stretches of assistant voice as the far end played them, cut where the server dropped the voice for a turn of the user. timeline records the audio played, the turns the server or the client found, the messages, the tool calls and the moments the voice was dropped, with their time.

An audio simulation runs your real speech to text and, when it answers, your real agent: each run calls their APIs. Keep these tests for the behaviors only audio shows, and run them on demand rather than on every change.

Testing the server itself

TestTransport is the far end of a simulated call, which records every message and chunk of voice the server sends and plays the user. With TextSTT, TextTTS and ScriptedAgent, it tests an application built around MicdropServer, such as how it saves the messages or handles errors, without a client. The reliability scenarios of the server are written the same way.