The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
// Live call steering over MCP (LIN-873): an owner's or admin's agent watches a running call (calls_get with since_ms)
// and steers it (call.guide): the API sends the instruction to the voice agent through LiveKit's SendData, signed.
import { createHmac, randomUUID } from 'node:crypto'
import { CALL_GUIDE_TOPIC, callGuideSigned } from '@linedesk/actions'
import { calls, transcript_segments, workspace_settings } from '@linedesk/db'
import { eq } from 'drizzle-orm'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { db } from '../src/db.ts'
import { act, addMember, appRequest, createWorkspace, type User, type Workspace } from './helpers.ts'
const LIVEKIT = {
LIVEKIT_URL: 'ws://livekit.internal:7880',
LIVEKIT_API_KEY: 'test-key',
LIVEKIT_API_SECRET: 'test-secret-test-secret-test-secret',
}
const saved = { ...process.env }
const realFetch = globalThis.fetch
/** What the API sent to LiveKit. */
const sent: { url: string; auth: string; body: Record<string, string> }[] = []
let refuseSend = false
let ws: Workspace
let other: Workspace
let member: User
let admin: User
let live: string
let room: string
beforeAll(async () => {
Object.assign(process.env, LIVEKIT)
vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
if (String(url).startsWith('http://livekit.internal:7880/')) {
const headers = new Headers(init?.headers)
sent.push({ url: String(url), auth: headers.get('authorization') ?? '', body: JSON.parse(String(init?.body)) })
return new Response('{}', { status: refuseSend ? 503 : 200 })
}
return realFetch(url, init)
})
ws = await createWorkspace('Brightwater Plumbing & Heating')
// Outbound calls are off until a server admin turns them on (workspace.setOutboundCalls).
await db
.update(workspace_settings)
.set({ outbound_calls_enabled: true })
.where(eq(workspace_settings.workspace_id, ws.id))
other = await createWorkspace('Other Business')
await db
.update(workspace_settings)
.set({ outbound_calls_enabled: true })
.where(eq(workspace_settings.workspace_id, other.id))
member = await addMember(ws.id, 'member')
admin = await addMember(ws.id, 'admin')
room = `outbound-${randomUUID()}`
await db.update(calls).set({ source: 'phone', room, ended_at: null }).where(eq(calls.id, ws.call.id))
live = ws.call.id
})
afterAll(() => {
vi.restoreAllMocks()
process.env = saved
})
const instruction = 'Offer Thursday at 2 pm instead; Monday is taken.'
test('an owner steers a running call: LiveKit gets a signed packet on the guide topic for that room', async () => {
const { status, body } = await act(ws.owner, 'call.guide', { callId: live, instruction })
expect(status).toBe(200)
expect(body.data).toMatchObject({ callId: live })
const last = sent.at(-1)!
expect(last.url).toBe('http://livekit.internal:7880/twirp/livekit.RoomService/SendData')
expect(last.body).toMatchObject({ room, kind: 'RELIABLE', topic: CALL_GUIDE_TOPIC })
// The token may administer that one room only.
const claims = JSON.parse(Buffer.from(last.auth.split('.')[1]!, 'base64url').toString())
expect(claims.video).toEqual({ roomAdmin: true, room })
const packet = JSON.parse(Buffer.from(last.body.data!, 'base64').toString())
expect(packet).toMatchObject({ instruction, at: body.data.at })
expect(typeof packet.by).toBe('string')
const sig = createHmac('sha256', LIVEKIT.LIVEKIT_API_SECRET)
.update(callGuideSigned(room, { instruction, at: packet.at, by: packet.by }))
.digest('base64url')
expect(packet.sig).toBe(sig)
// Admins may too.
expect((await act(admin, 'call.guide', { callId: live, instruction })).status).toBe(200)
})
test('members, other workspaces, ended, test and unknown calls are refused, and nothing is sent', async () => {
const before = sent.length
expect((await act(member, 'call.guide', { callId: live, instruction })).status).toBe(403)
expect((await act(other.owner, 'call.guide', { callId: live, instruction })).status).toBe(404)
expect((await act(ws.owner, 'call.guide', { callId: 'call_nope', instruction })).status).toBe(404)
expect((await act(ws.owner, 'call.guide', { callId: live, instruction: '' })).status).toBe(422)
expect((await act(ws.owner, 'call.guide', { callId: live, instruction: 'x'.repeat(1001) })).status).toBe(422)
await db.update(calls).set({ source: 'test' }).where(eq(calls.id, live))
expect((await act(ws.owner, 'call.guide', { callId: live, instruction })).status).toBe(409)
await db.update(calls).set({ source: 'phone', ended_at: new Date().toISOString() }).where(eq(calls.id, live))
expect((await act(ws.owner, 'call.guide', { callId: live, instruction })).status).toBe(409)
await db.update(calls).set({ ended_at: null }).where(eq(calls.id, live))
expect(sent.length).toBe(before)
})
test('LiveKit not taking the packet is a refusal, not a success', async () => {
refuseSend = true
try {
expect((await act(ws.owner, 'call.guide', { callId: live, instruction })).status).toBe(409)
} finally {
refuseSend = false
}
})
let rpc = 0
async function callsGet(key: string, args: Record<string, unknown>) {
const res = await appRequest('/mcp', {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
authorization: `Bearer ${key}`,
},
body: JSON.stringify({
jsonrpc: '2.0',
id: ++rpc,
method: 'tools/call',
params: { name: 'calls_get', arguments: args },
}),
})
const text = await res.text()
const json = text.startsWith('{')
? text
: (text
.split('\n')
.find(l => l.startsWith('data: '))
?.slice(6) ?? 'null')
return JSON.parse(json).result.structuredContent
}
test('calls_get: live while the call runs, and since_ms gives only newer lines; call_guide is an MCP tool', async () => {
const key = (await act(ws.owner, 'apiKey.create', { name: 'Claude', role: 'admin' })).body.data.key as string
const line = (at_ms: number, text: string) => ({
id: `seg_${randomUUID().slice(0, 8)}`,
workspace_id: ws.id,
call_id: live,
speaker: 'caller' as const,
text,
at_ms,
})
await db.insert(transcript_segments).values([line(1000, 'Hi, about Monday.'), line(5000, 'Can we move it?')])
const all = await callsGet(key, { callId: live })
expect(all.live).toBe(true)
expect(all.untrusted_caller_content.transcript).toHaveLength(2)
const newer = await callsGet(key, { callId: live, since_ms: 1000 })
expect(newer.untrusted_caller_content.transcript).toEqual([
{ speaker: 'caller', text: 'Can we move it?', at_ms: 5000 },
])
await db.update(calls).set({ ended_at: new Date().toISOString() }).where(eq(calls.id, live))
expect((await callsGet(key, { callId: live, since_ms: 5000 })).live).toBe(false)
await db.update(calls).set({ ended_at: null }).where(eq(calls.id, live))
const list = await appRequest('/mcp', {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
authorization: `Bearer ${key}`,
},
body: JSON.stringify({ jsonrpc: '2.0', id: ++rpc, method: 'tools/list', params: {} }),
})
const text = await list.text()
const json = text.startsWith('{')
? text
: (text
.split('\n')
.find(l => l.startsWith('data: '))
?.slice(6) ?? 'null')
const tool = JSON.parse(json).result.tools.find((t: { name: string }) => t.name === 'call_guide')
expect(tool.annotations).toMatchObject({ readOnlyHint: false, openWorldHint: true })
})