Phil Leggetter Phil Leggetter

Building agency call routing with Vapi and Hookdeck

Published · Updated


Agencies that build voice agents for small businesses, such as a dental practice or a plumber, often run several clients from one Vapi account. Each client wants its call reports in its own systems, and its agent sometimes needs to look something up during the call, like the caller's next appointment. Vapi uses webhooks for both, so they have to reach the right client and arrive quickly.

In this tutorial you route calls for a voice AI agency that runs one Vapi assistant per client. Each assistant sends its call events to its own Hookdeck Event Gateway source, which verifies Vapi's signature and delivers them to that client's endpoint, so one client's calls never reach another client's system.

During a call, the assistant looks the caller up in the client's CRM with an async tool, and the endpoint speaks the result into the live call. Event Gateway rejects forged requests and retries a delivery when a client's server is down. The full code is in the Vapi agency routing demo on GitHub.

How the webhooks reach each client's endpoint

Two simulated clients, Acme Dental and Globex Plumbing, each have a Vapi assistant. Each assistant's Server URL is its own Event Gateway source, and each source delivers to that client's endpoint.

Acme Dental and Globex Plumbing each have a Vapi assistant whose Server URL is its own Event Gateway source. A status-update from each call is verified and delivered over HTTPS, signed by Event Gateway, to that client's deployed app, and each app posts its async tool result to the controlUrl of its own call.

  1. Acme Dental and Globex Plumbing each have a Vapi assistant. Each assistant's Server URL is that client's own Event Gateway source, and each source delivers to that client's app over HTTPS.
  2. A caller reaches Acme Dental. Vapi sends status-update (5.5 KB) to the Acme Dental source, and Event Gateway delivers it to Acme Dental's app over HTTPS and signs the delivery. The app verifies the Hookdeck signature.
  3. A caller then reaches Globex Plumbing. Its status-update goes to the Globex Plumbing source and on to Globex Plumbing's app. Acme Dental's app does not see it.
  4. Each assistant calls lookup_customer. The tool-calls (8.4 KB and 8.5 KB) follow the same routes, each to its own client's app.
  5. Each app posts its result to the controlUrl of its own call, so Acme Dental's result reaches Acme Dental's caller and Globex Plumbing's reaches Globex Plumbing's.

During development, the Hookdeck CLI tunnels the webhooks to the app running on your machine. The diagrams in How it works show that local setup.

The controlUrl connectors at the top and bottom are the async tool. The client's endpoint answers the webhook immediately, does the slow lookup, and then posts the result back to Vapi at the call's controlUrl. Use Next to step through two calls, one for each client.

What you'll need

  • A Vapi account with a private API key and a public key, both on the API keys page
  • A Hookdeck account, a project API key and the project signing secret
  • Node.js 22
  • A microphone, for the web call (or use the demo's npm run simulate command, which replays a signed sample call)

Get it running

Clone the demo, add your keys, run setup, then start the app and make a call.

Clone the demo and add your keys

Clone hookdeck-demos, open vapi/agency-routing, and copy .env.example to .env. Add four keys to .env:

  • VAPI_API_KEY: in the Vapi dashboard, open the API keys page and copy the Private API Key. Setup uses it to create the credential, the tool and the assistants.
  • VAPI_PUBLIC_KEY: on the same page, copy the Public Key, not the private one. The page uses it with the Vapi Web SDK to start calls from the browser.
  • HOOKDECK_API_KEY: in the Hookdeck dashboard, open Project settings, then Secrets, and copy the project API key. Setup uses it to call the Hookdeck API.
  • HOOKDECK_SIGNING_SECRET: copy the project signing secret from the same page. The app verifies each delivery with it and does not start without it.

Run setup and start the app

Install the dependencies, run setup, then start the listener and the app:

npm install
npm run setup
npm run listen   # hookdeck listen, forwarding to the app
npm start        # in a second terminal

npm run setup is a TypeScript script. It calls the Hookdeck API to create the Event Gateway sources and connections, and the Vapi API to create the credential, tool and assistants. It is safe to run again.

npm run listen is the only step that uses the Hookdeck CLI, which npm install added to the demo. It logs the CLI in with HOOKDECK_API_KEY, using its own config so your own hookdeck login isn't changed, then runs hookdeck listen 4000 vapi-acme-dental,vapi-globex-plumbing. Open http://localhost:4000.

To see what setup creates, read Create one source per client and the sections after it.

Make a call

Each client has a card that names its assistant and marks you as the caller. Click Call Acme Dental on the Acme Dental card, allow microphone access, and say "Hi, I'm Priya Shah, what's my next appointment?"

The assistant says it is checking, then about 6 seconds later speaks the CRM result. The While you wait panel on the card shows that gap. It lists the tool request, the CRM lookup counting down and the result being posted to the call's controlUrl.

Each card lists the webhooks that client's endpoint received. The Data flow pane at the bottom of the page shows each webhook travelling from Vapi through Event Gateway and hookdeck listen to the client's endpoint.

Click a packet or a node to see that webhook's verification result, each delivery attempt and a View in Hookdeck link. The pane's other tabs play the scenes behind the diagrams in this guide.

How it works

You first see what setup creates for each client, then follow the webhooks of one call from Vapi to the client's endpoint, including the async tool, and end with deduplication, retries and prompt trimming.

Create one source per client

For each client, the setup script creates a source of type Vapi and a connection from that source to a destination, and it sets the source's URL as the Server URL of that client's assistant.

There are two ways to keep clients apart.

ApproachWhat you getWhat it costs
One source per clientIts own URL, its own signing secret, its own request history, its own alerts, and a failure on one client doesn't touch anotherMore sources to create, which a setup script handles
One source, a filter per connection on body.message.call.assistantIdOne URL and one secret to manageEvery client's events share one history, one secret and one set of alerts, and a wrong filter sends a call to the wrong client

The demo uses one source per client, and we recommend it for an agency, because a client's request history and secret then belong to that client alone. The single-source option works well when the clients are teams inside one company and share an operations view anyway.

The setup script calls the Hookdeck API with a small hookdeck() helper, next to the vapi() helper it uses for the Vapi API. The helper sends the request with your project API key from HOOKDECK_API_KEY as a bearer token:

const HOOKDECK_API_BASE = 'https://api.hookdeck.com/2026-09-01';

async function hookdeck(method: string, route: string, body?: unknown) {
  const response = await fetch(`${HOOKDECK_API_BASE}${route}`, {
    method,
    headers: { authorization: `Bearer ${process.env.HOOKDECK_API_KEY}`, 'content-type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const text = await response.text();
  if (!response.ok) throw new Error(`Hookdeck API ${method} ${route} -> ${response.status}: ${text.slice(0, 300)}`);
  return text ? JSON.parse(text) : undefined;
}

Every connection gets the same deduplication and retry rules, which Deduplicate and retry events explains. The deduplication window is in milliseconds:

const CONNECTION_RULES = [
  { type: 'deduplicate', window: 600000, include_fields: ['body.message.type', 'body.message.call.id', 'body.message.status', 'body.message.toolCallList'] },
  { type: 'retry', strategy: 'exponential', count: 4, interval: 10000 },
];

PUT /connections creates or updates a connection, matched by name. Each client gets one connection, which creates the client's source and a CLI destination that delivers to your machine through hookdeck listen on that client's path.

For Acme Dental, client.source is vapi-acme-dental, client.destination is local-acme-dental and client.path is /clients/acme/webhook. Globex Plumbing uses vapi-globex-plumbing, local-globex-plumbing and /clients/globex/webhook.

const connection = await hookdeck('PUT', '/connections', {
  name: client.source,
  source: { name: client.source, type: 'VAPI' },
  destination: { name: client.destination, type: 'CLI', config: { path: client.path } },
  rules: CONNECTION_RULES,
});

The response includes connection.source.url, which is the Server URL for that client's assistant. The script runs this call for each client, and it does the Vapi side as well.

Have Vapi sign each request

Vapi signs a request only when the Server URL has a credential attached. You create the credential once and reference it from each assistant. The Vapi server authentication docs list the HMAC settings. These are the ones the Event Gateway Vapi source verifies:

const authentication_plan = {
  type: 'hmac',
  secretKey: secret,
  algorithm: 'sha256',
  signatureHeader: 'x-signature',
  signatureEncoding: 'hex',
  includeTimestamp: false,
  payloadFormat: '{body}',
};
await vapi('POST', '/credential', {
  provider: 'custom-credential',
  name: 'hookdeck-demo-hmac',
  authenticationPlan: authentication_plan,
});

payloadFormat: "{body}" with includeTimestamp: false makes Vapi sign the raw request body alone, which is what the Event Gateway Vapi source verifies. On the wire, each request has an x-signature header of 64 lowercase hex characters.

The same secret goes into the Event Gateway source's verification settings. Put it in the VAPI_WEBHOOK_SECRET environment variable (npm run setup generates a random 32-byte hex secret and writes it to .env), then set it on each source with PUT /sources:

const source = await hookdeck('PUT', '/sources', {
  name: client.source,
  type: 'VAPI',
  config: {
    trim_payload: false,
    auth: { webhook_secret_key: secret, algorithm: 'sha256', encoding: 'hex', header_key: 'x-signature' },
  },
});

The header_key, algorithm and encoding in auth match the signatureHeader, algorithm and signatureEncoding of the Vapi credential. trim_payload is the option that Trim system prompts describes, and it is off here.

Event Gateway verifies this signature before the request becomes an event. To see both outcomes, follow Send a signed and an unsigned request.

For the dashboard steps, see how to secure and verify Vapi webhooks with Hookdeck.

Choose which messages Vapi sends

Each assistant sets serverMessages, the list of server messages Vapi posts to the Server URL. Set the list explicitly so you know what your endpoint will receive:

const assistant_body = {
  name: 'Hookdeck demo - Acme Dental',
  firstMessage: "Hello, you've reached Acme Dental. How can I help you today?",
  model: { provider: 'openai', model: 'gpt-4o', messages: [{ role: 'system', content: system_prompt }], toolIds: [tool.id] },
  server: { url: source_url, credentialId: credential.id, timeoutSeconds: 20 },
  serverMessages: ['status-update', 'end-of-call-report', 'tool-calls'],
  monitorPlan: { controlEnabled: true, listenEnabled: false },
};

Three message types give four webhooks per call. monitorPlan.controlEnabled: true is what puts a controlUrl in the payload, which Answer the webhook and post the result uses. Adding transcript or conversation-update turns a call into a stream of webhooks that grows with the length of the conversation, so add them only when the client needs a live transcript.

The ended status update and the end-of-call report include the call's artifact (messages, recording URLs and metrics), so they grow with call length, to about 40 KB on a call of a few minutes.

Verify that each delivery came from Event Gateway

Event Gateway signs every delivery to your endpoint with an x-hookdeck-signature header. The value is the base64 HMAC-SHA256 of the raw request body, keyed with the project signing secret, which is the HOOKDECK_SIGNING_SECRET you added to .env in Get it running.

The signature has no timestamp. Event Gateway verified Vapi's x-signature when it accepted the request, so a retry or a replay hours later is a legitimate delivery and still passes. See Hookdeck webhook signature verification for the full scheme.

The endpoint computes the signature from the raw body and compares it with the header. timingSafeEqual throws when the two buffers differ in length, so the function checks the length first:

import { createHmac, timingSafeEqual } from 'crypto';

function verifyHookdeckSignature(raw_body: Buffer, signature_header: string | undefined, secret: string | undefined): boolean {
  if (!secret || !signature_header) return false;
  const expected = Buffer.from(createHmac('sha256', secret).update(raw_body).digest('base64'), 'utf8');
  const received = Buffer.from(signature_header, 'utf8');
  // timingSafeEqual throws when the lengths differ, so check the length first
  return expected.length === received.length && timingSafeEqual(expected, received);
}

// First check in each client's webhook handler, before the body is parsed or acted on
if (!verifyHookdeckSignature(req.raw_body, req.get('x-hookdeck-signature'), process.env.HOOKDECK_SIGNING_SECRET)) {
  return void res.status(401).json({ error: 'invalid Hookdeck signature' });
}

req.raw_body holds the bytes exactly as they arrived, because parsing the JSON and serializing it again can change the bytes and break the match. A delivery with a missing or wrong signature gets 401, and a valid one continues to the handler in Answer the webhook and post the result.

While you roll the signing secret, Event Gateway also sends x-hookdeck-signature-2, signed with the previous secret. The demo's src/hookdeck-signature.ts accepts either header.

Define the async tool

The lookup_customer tool is an async function tool with no server of its own, so Vapi sends its tool-calls message to the Server URL of the assistant on the call. One tool then serves every client, and each client's calls still reach that client's source.

A call to Acme Dental. Vapi sends status-update and then a tool-calls message to the Acme source, which Event Gateway delivers through hookdeck listen to the Acme endpoint. About six seconds later the endpoint posts the lookup result to the call's controlUrl in Vapi and the assistant speaks it. At hang-up Vapi sends status-update (ended) and end-of-call-report.

  1. Each client has its own Vapi assistant, its own Event Gateway source and its own endpoint in the demo app. This call is to Acme Dental.
  2. The caller connects. Vapi sends status-update (5.5 KB) to the Acme Dental source, and Event Gateway delivers it through hookdeck listen to the Acme endpoint. Globex Plumbing receives nothing.
  3. The caller gives a name and the assistant calls lookup_customer, an async tool. Vapi sends tool-calls (8.4 KB) by the same route, and the endpoint answers at once without a result.
  4. About 6 seconds later the endpoint finishes its lookup and posts the result to the call's controlUrl in Vapi. The assistant speaks it.
  5. When the caller hangs up, Vapi sends status-update (ended, 18.2 KB) and then end-of-call-report (39.2 KB, with the transcript) by the same route.
const tool_body = {
  type: 'function',
  async: true,
  function: {
    name: 'lookup_customer',
    description: 'Look up a customer in the business CRM by name. Runs in the background; the result is added to the conversation a few seconds later.',
    parameters: {
      type: 'object',
      properties: { customer_name: { type: 'string' } },
      required: ['customer_name'],
    },
  },
};

Vapi doesn't use the response to an async tool's webhook. It answers the model with a placeholder result, Success., straight away, so the assistant's prompt tells it that this isn't the answer.

Answer the webhook and post the result

The real result goes back through the call's monitor.controlUrl, which is in the tool-calls payload. After the signature check, the endpoint answers the webhook, waits for the lookup, then posts to Vapi's Live Call Control:

function handleToolCalls(client, message, event_id, res) {
  const control_url = message.call?.monitor?.controlUrl;
  // The URL comes from the request body, so check it before the lookup starts
  assertControlUrl(control_url);
  for (const tool_call of message.toolCallList || []) {
    // Event Gateway may redeliver a webhook, so look each tool call up once
    if (seen_tool_calls.has(tool_call.id)) continue;
    seen_tool_calls.add(tool_call.id);
    void runLookup(client, tool_call, control_url);
  }
  return { results: (message.toolCallList || []).map((t) => ({ toolCallId: t.id, result: 'Lookup started' })) };
}

async function sendToCall(control_url: string, command: object) {
  const res = await fetch(control_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(command),
    signal: AbortSignal.timeout(10_000),
  });
  if (!res.ok) throw new Error(`controlUrl responded ${res.status}`);
}

function assertControlUrl(control_url: string) {
  const url = new URL(control_url);
  if (url.protocol !== 'https:' || !url.hostname.endsWith('.vapi.ai')) {
    throw new Error('controlUrl is not an https *.vapi.ai URL');
  }
}

// after the CRM answers:
await sendToCall(control_url, {
  type: 'add-message',
  message: { role: 'system', content: `Account lookup finished. ${summary}` },
  triggerResponseEnabled: true,
});

The add-message command with triggerResponseEnabled: true puts the result into the conversation and makes the assistant speak. The say command is the alternative when you want exact words spoken instead.

The controlUrl arrives in a request body, so assertControlUrl checks that it is an https URL on a *.vapi.ai host before the lookup starts. Never POST to a URL that a request body hands you without checking it.

The seen_tool_calls set is in memory, which is enough for the demo. A production app stores the seen tool call IDs durably, for example in a database or Redis, so a restart doesn't repeat a lookup.

Prompt the assistant to wait for the tool result

The first version of the demo's prompt said to tell the caller it was checking "and keep chatting briefly". Both test calls showed the model filling the six seconds with small talk ("How's your day going so far?") and then reading the result without waiting for an answer. A later version stopped the small talk, but the model then answered the tool's placeholder Success. with a made-up result and date, a few seconds before the real one arrived. The prompt that works says what to do, what not to do, and what to wait for:

- After calling it, say one short sentence such as "One moment while I check that."
  and then say nothing more. Do not ask anything, do not fill the silence, and do
  not guess the result.
- When lookup_customer replies "Success.", you have already said your holding line,
  so say nothing at all. Do not speak again until the lookup message arrives.
- The real result arrives a few seconds later as a system message that starts with
  "Account lookup finished." When it arrives, read the key facts out to the caller
  in one or two sentences, then ask if there is anything else.
- Never say a date, time, appointment, order, name or account detail unless you read
  it in that system message.

The result message starts with "Account lookup finished." rather than a label like "CRM result:", because the model copied that label when it invented a result.

The prompt also says what the assistant can't do. It can look up an existing account and what is booked, but it can't create accounts or book appointments. In a test call where the caller asked to book, an earlier prompt without that rule promised to check availability and then went silent. With the rule, the assistant says it can't do that on this line and offers a call-back.

The assistant's firstMessage is one greeting and one question, so the caller has one thing to answer.

Deduplicate and retry events

Event Gateway answers Vapi as soon as it accepts the request, so a client endpoint that is down never causes a failed webhook on Vapi's side. The CONNECTION_RULES from Create one source per client add a deduplication rule and a retry rule to each connection. Production would use a longer retry interval and more attempts:

const CONNECTION_RULES = [
  { type: 'deduplicate', window: 600000, include_fields: ['body.message.type', 'body.message.call.id', 'body.message.status', 'body.message.toolCallList'] },
  { type: 'retry', strategy: 'exponential', count: 4, interval: 10000 },
];

The deduplication fields include the status, so a call's in-progress and ended updates are different messages, and the tool calls, so two lookups in one call are too.

Vapi sends the same end-of-call-report a second time. Event Gateway matches it to the first inside the deduplication window, drops it, still answers 200, and forwards nothing to the client's endpoint.

  1. The Acme endpoint has handled this call's end-of-call-report.
  2. Vapi sends the same end-of-call-report again, because senders can deliver a message more than once.
  3. Event Gateway sees the same end-of-call-report for the same call inside the 10 minute window and drops it. Vapi still gets a 200.
  4. Nothing is forwarded, so the endpoint is not called a second time.

When a client's endpoint returns an error, Event Gateway retries the delivery with the retry rule.

The client's endpoint answers a delivery with a 503. Event Gateway had already answered Vapi with a 200, keeps the event, and retries with exponential backoff starting 10 seconds after the failed attempt, up to four retries. The second attempt succeeds once the endpoint recovers.

  1. The Acme endpoint is down: it answers every delivery with a 503.
  2. The call ends and Vapi sends end-of-call-report. Event Gateway stores it and answers Vapi with a 200.
  3. Event Gateway delivers it through hookdeck listen. Attempt 1 gets a 503 from the endpoint.
  4. Event Gateway keeps the event and retries with exponential backoff: the first retry is 10 seconds after the failed attempt, then it waits longer each time, up to 4 retries.
  5. The endpoint recovers. Attempt 2 succeeds about 10 seconds later, and the event is delivered once.

Trim system prompts

The Vapi source has a trim_payload option in its config. When it is on, Event Gateway removes the assistant's system prompt from the payload after verification. The assistant's prompt is the first message in artifact.messages. A client's endpoint and your stored events don't need a prompt that contains internal instructions.

In the demo, replaying the same 40,161-byte end-of-call report with the option on gave 37,003 bytes, an 8% saving, and the prompt message shrank from 586 characters to 47. The saving scales with prompt length. Trimming does not remove the recordings, metrics or transcript, so don't expect it to make reports small.

Try the failure cases

Run each case against the demo from Get it running, with npm run listen and npm start running.

Send a signed and an unsigned request

Event Gateway verifies the signature before the request becomes an event. You can see both outcomes by signing a body yourself with the secret from .env:

body='{"message":{"type":"status-update","status":"in-progress"}}'
sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$VAPI_WEBHOOK_SECRET" -hex | sed 's/^.* //')

curl -i -X POST "$ACME_SOURCE_URL" \
  -H 'content-type: application/json' -H "x-signature: $sig" -d "$body"   # 200
curl -i -X POST "$ACME_SOURCE_URL" \
  -H 'content-type: application/json' -H 'x-signature: deadbeef' -d "$body"   # 401

A correctly signed request gets 200 and the request is marked verified. A wrong or missing signature gets 401 with an empty body.

Event Gateway stores the request as rejected with the cause VERIFICATION_FAILED, and creates no event, so nothing reaches the client's endpoint. The npm run probe command in the demo runs this check against both sources.

A request signed with the wrong secret reaches a client's Event Gateway source. Event Gateway fails the signature check, records VERIFICATION_FAILED, creates no event, answers the sender with a 401, and the client's endpoint is never called.

  1. A request claims to come from Vapi, but its signature was made with the wrong secret.
  2. Event Gateway receives the request and checks x-signature against the source's secret.
  3. Verification fails. The request is recorded as VERIFICATION_FAILED and no event is created.
  4. Event Gateway answers the sender with a 401, and the endpoint is never called.

In the demo's Data flow pane, a rejected request appears as a red packet that stops at Event Gateway, and Vapi's side shows got 401.

Send a duplicate

Run npm run simulate -- --duplicate to see a repeat dropped. It sends the same signed end-of-call-report twice, and Event Gateway accepts both requests and delivers one.

Make a client's endpoint fail

To see a retry, use the Failure injection section on a client's card. It makes that client's endpoint return 503 for the next N deliveries. The Data flow pane then shows a failing next N badge on that endpoint, and the detail strip for the webhook lists attempt 1 as 503 and attempt 2 as 200 about 10 seconds later.

Failure injection skips tool-calls deliveries unless you tick include tool calls. A failed tool-calls delivery delays the CRM lookup until a retry succeeds, 10 seconds or more later, and the caller may have moved on by then.

Going to production

  • Retry schedule: use a longer interval and more attempts than the demo's 10 seconds, sized to how long a client's endpoint might be down
  • Secrets: use a different signing secret per source, which the one-source-per-client layout allows
  • Verify the caller: the demo reads out any customer's appointment to whoever gives their name. Before an assistant reads account details, confirm who is calling, for example by matching the calling number to the customer record or asking for a date of birth
  • Replay: a delivery that exhausts its retries, or one a client wants again, can be retried or replayed from the Hookdeck dashboard, as shown in how to test and replay Vapi webhooks locally

What to build next

  • Add transcript[transcriptType="final"] to serverMessages on one assistant if a client needs a live transcript, and measure the webhook volume first
  • Replace the demo's in-memory CRM and its 6-second delay with a call to a client's real API
  • Add a filter on a connection to send only end-of-call-report messages to a client's reporting system

The code for this tutorial is in the Vapi agency routing demo. For Vapi's events, authentication levels and best practices, see the guide to Vapi webhooks.

Get started with Hookdeck


Phil Leggetter

Phil Leggetter

Head of Developer and Agentic Experiences

Phil is Head of Developer and Agentic Experiences at Hookdeck with expertise in real-time communications technologies, and creator of the AAARRRP Developer Relations strategy framework.