# Book appointments with Google Calendar

> An assistant that offers open times and books appointments in Google Calendar, in Hebrew or English, through two custom tools on your server. Runs in test mode with an in-memory calendar.

A caller asks for an appointment; the assistant checks the calendar, offers up to three open times, confirms the time and the name, and books it. The calendar is Google Calendar, reached from a small tool server of yours, so the rules stay yours: opening hours, slot length, who may book what.

MoreVoice can also book for you, with no server of your own: connect Google Calendar or Microsoft 365 on the app's **Integrations** page, and give the assistant the calendar's booking tools (or start from the *Appointment booking* flow template). The built-in tools:

| Tool | What it does | What the assistant is told |
| --- | --- | --- |
| `check_availability` | Offer open times | Find open appointment times in the calendar. Call it before booking or moving an appointment, with the day (and the time or part of the day) the caller prefers. It returns up to 3 times, each with a slot id, and a sentence offering them. Offer only these times; never invent one. |
| `book_appointment` | Book an appointment | Book one of the times check_availability offered: pass its slot id (never a time you made up) and the caller's name. Confirm the time and the name with the caller first. If the time was just taken, it returns other times to offer; if it can't book, it says what to tell the caller. |
| `reschedule_appointment` | Move an appointment | Move the caller's appointment to one of the times check_availability offered (pass its slot id). Without booking_ref it uses the appointment booked in this call, or finds the caller's upcoming one by their phone number; when there are several it asks which. |
| `cancel_appointment` | Cancel an appointment | Cancel the caller's appointment once they confirm. Without booking_ref it uses the appointment booked in this call, or finds the caller's upcoming one by their phone number; when there are several it asks which. |

Use the tool server on this page instead when the appointments live in your own system, when you need your own rules (which doctor, which branch, deposits), or when the booking must also update a CRM.

## How it works

The assistant has two [custom tools](https://docs.morevoice.ai/guides/custom-tools/). During the call, MoreVoice sends each tool call to your server, signed, and the assistant speaks from the answer:

| Tool | Arguments | Your server answers |
| --- | --- | --- |
| `find_slots` | `date` (YYYY-MM-DD) | Up to three open times, each with its `start` and a `label` written to be said aloud |
| `book_appointment` | `start`, `name`, optional `phone` | `booked: true` and the time, or `booked: false` when someone took it a moment ago |

The model never invents a time: it offers only what `find_slots` returned, and books by the `start` of one of them. The `get_current_time` tool turns "tomorrow" and "next Sunday" into a date.

## Before you start

- A **test key** (`mv_test_sk_…`) and your organisation's **tool signing secret** for test mode (`whsec_…`): tool calls are signed with it. See [custom tools](https://docs.morevoice.ai/guides/custom-tools/#check-the-signature).
- Node.js 18 or later, and the SDK: `npm install @morevoice/sdk`.
- For Google Calendar: a Google Cloud service account with a JSON key, and the calendar shared with the service account's e-mail address with **Make changes to events**. Without them, the recipe books in memory, which is how you try it first.

## Build it

1. **Define the tools once.** The same definitions go to the assistant (step 3) and to the server (step 4), so they never drift apart.

   ```ts title="tools.ts"
   // The two tools the assistant uses, defined once: setup.ts gives them to the assistant, tool-server.ts serves them.
   export const FIND_SLOTS = {
   	name: "find_slots",
   	description: "Find open appointment times on a date. Call it before offering any time, and offer only the times it returns.",
   	parameters: {
   		type: "object",
   		properties: { date: { type: "string", description: "The date the caller wants, YYYY-MM-DD" } },
   		required: ["date"],
   	},
   } as const;

   export const BOOK_APPOINTMENT = {
   	name: "book_appointment",
   	description: "Book one of the times find_slots returned, after the caller confirmed the time and their name.",
   	parameters: {
   		type: "object",
   		properties: {
   			start: { type: "string", description: "The `start` of a time find_slots returned" },
   			name: { type: "string", description: "The caller's full name" },
   			phone: { type: "string", description: "A phone number for the appointment, if the caller gave another one" },
   		},
   		required: ["start", "name"],
   	},
   } as const;
   ```

2. **Talk to the calendar.** `openSlots()` turns the opening hours into 30-minute slots in Israel time and removes the busy ones; `GoogleCalendar` reads busy times with the Calendar API's `freeBusy` and books with `events.insert`, checking again just before it books. It signs in as the service account with a signed JWT, so it needs no Google library.

   ```ts title="calendar.ts"
   // The calendar side of the booking assistant: open times and bookings. GoogleCalendar talks to the Google Calendar API
   // as a service account (share the calendar with the service account's e-mail, with "Make changes to events");
   // MemoryCalendar keeps bookings in memory, so the recipe runs without a Google account.
   import { createSign } from "node:crypto";

   /** When the clinic takes appointments. */
   export const HOURS = { timeZone: "Asia/Jerusalem", weekdays: [0, 1, 2, 3, 4], open: "09:00", close: "17:00", slotMinutes: 30 };

   export interface Slot {
   	start: string; // ISO-8601, UTC
   	end: string;
   }

   export interface Booking {
   	id: string;
   	slot: Slot;
   	name: string;
   	phone: string | null;
   }

   export interface Calendar {
   	/** Busy intervals between two instants. */
   	busy(from: Date, to: Date): Promise<{ start: Date; end: Date }[]>;
   	/** Books a slot; throws SlotTakenError when someone else just took it. */
   	book(slot: Slot, details: { name: string; phone: string | null; callId: string }): Promise<Booking>;
   }

   export class SlotTakenError extends Error {}

   /** The UTC instant of a wall-clock time in a time zone: atZone("2026-11-05", "09:30", "Asia/Jerusalem"). */
   export function atZone(day: string, time: string, timeZone: string): Date {
   	const [y, m, d] = day.split("-").map(Number) as [number, number, number];
   	const [hh, mm] = time.split(":").map(Number) as [number, number];
   	const wall = Date.UTC(y, m - 1, d, hh, mm);
   	const fmt = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" });
   	const offset = (at: number) => {
   		const p = Object.fromEntries(fmt.formatToParts(new Date(at)).map((x) => [x.type, Number(x.value)]));
   		return Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!) - at;
   	};
   	return new Date(wall - offset(wall - offset(wall))); // twice, for the days the clocks change
   }

   /** The calendar date (YYYY-MM-DD) of an instant in a time zone. */
   export const dayIn = (iso: string, timeZone: string) => new Intl.DateTimeFormat("en-CA", { timeZone }).format(new Date(iso));

   /** The open slots of a day, from the opening hours minus the calendar's busy times. */
   export async function openSlots(calendar: Calendar, day: string, now = new Date()): Promise<Slot[]> {
   	if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || !HOURS.weekdays.includes(new Date(`${day}T12:00:00Z`).getUTCDay())) return [];
   	const open = atZone(day, HOURS.open, HOURS.timeZone);
   	const close = atZone(day, HOURS.close, HOURS.timeZone);
   	const busy = await calendar.busy(open, close);
   	const step = HOURS.slotMinutes * 60_000;
   	const slots: Slot[] = [];
   	for (let t = open.getTime(); t + step <= close.getTime(); t += step) {
   		const start = new Date(t);
   		const end = new Date(t + step);
   		if (start > now && !busy.some((b) => b.start < end && b.end > start)) slots.push({ start: start.toISOString(), end: end.toISOString() });
   	}
   	return slots;
   }

   /** How the assistant says a slot: "יום חמישי, 5 בנובמבר, 09:30". */
   export const spoken = (slot: Slot, lang: "he" | "en") =>
   	new Intl.DateTimeFormat(lang === "he" ? "he-IL" : "en-GB", { timeZone: HOURS.timeZone, weekday: "long", day: "numeric", month: "long", hour: "2-digit", minute: "2-digit" }).format(new Date(slot.start));

   // ───────────────────────── Google Calendar ─────────────────────────

   interface ServiceAccount {
   	client_email: string;
   	private_key: string;
   }

   export class GoogleCalendar implements Calendar {
   	private token: { value: string; expires: number } | null = null;

   	constructor(
   		private readonly calendarId: string,
   		private readonly account: ServiceAccount,
   	) {}

   	async busy(from: Date, to: Date) {
   		const res = (await this.post("https://www.googleapis.com/calendar/v3/freeBusy", { timeMin: from.toISOString(), timeMax: to.toISOString(), items: [{ id: this.calendarId }] })) as {
   			calendars: Record<string, { busy?: { start: string; end: string }[] }>;
   		};
   		return (res.calendars[this.calendarId]?.busy ?? []).map((b) => ({ start: new Date(b.start), end: new Date(b.end) }));
   	}

   	async book(slot: Slot, details: { name: string; phone: string | null; callId: string }): Promise<Booking> {
   		// Check again right before booking: two callers may want the same time.
   		if ((await this.busy(new Date(slot.start), new Date(slot.end))).length) throw new SlotTakenError(slot.start);
   		const event = (await this.post(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(this.calendarId)}/events`, {
   			summary: `Appointment: ${details.name}`,
   			description: [details.phone ? `Phone: ${details.phone}` : "", `Booked by phone (MoreVoice call ${details.callId})`].filter(Boolean).join("\n"),
   			start: { dateTime: slot.start, timeZone: HOURS.timeZone },
   			end: { dateTime: slot.end, timeZone: HOURS.timeZone },
   			extendedProperties: { private: { morevoice_call_id: details.callId } },
   		})) as { id: string };
   		return { id: event.id, slot, name: details.name, phone: details.phone };
   	}

   	private async post(url: string, body: unknown): Promise<unknown> {
   		const res = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${await this.accessToken()}`, "content-type": "application/json" }, body: JSON.stringify(body) });
   		if (!res.ok) throw new Error(`Google Calendar: HTTP ${res.status} ${await res.text()}`);
   		return res.json();
   	}

   	/** An OAuth access token for the service account (a signed JWT exchanged at Google's token endpoint), cached. */
   	private async accessToken(): Promise<string> {
   		if (this.token && this.token.expires > Date.now() + 60_000) return this.token.value;
   		const now = Math.floor(Date.now() / 1000);
   		const part = (o: object) => Buffer.from(JSON.stringify(o)).toString("base64url");
   		const claims = {
   			iss: this.account.client_email,
   			scope: "https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.readonly",
   			aud: "https://oauth2.googleapis.com/token",
   			iat: now,
   			exp: now + 3600,
   		};
   		const unsigned = `${part({ alg: "RS256", typ: "JWT" })}.${part(claims)}`;
   		const signature = createSign("RSA-SHA256").update(unsigned).sign(this.account.private_key, "base64url");
   		const res = await fetch("https://oauth2.googleapis.com/token", {
   			method: "POST",
   			headers: { "content-type": "application/x-www-form-urlencoded" },
   			body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: `${unsigned}.${signature}` }),
   		});
   		if (!res.ok) throw new Error(`Google token: HTTP ${res.status} ${await res.text()}`);
   		const { access_token, expires_in } = (await res.json()) as { access_token: string; expires_in: number };
   		this.token = { value: access_token, expires: Date.now() + expires_in * 1000 };
   		return access_token;
   	}
   }

   // ───────────────────────── in memory, for trying it out ─────────────────────────

   export class MemoryCalendar implements Calendar {
   	readonly bookings: Booking[] = [];

   	async busy(from: Date, to: Date) {
   		return this.bookings.map((b) => ({ start: new Date(b.slot.start), end: new Date(b.slot.end) })).filter((b) => b.start < to && b.end > from);
   	}

   	async book(slot: Slot, details: { name: string; phone: string | null; callId: string }): Promise<Booking> {
   		if ((await this.busy(new Date(slot.start), new Date(slot.end))).length) throw new SlotTakenError(slot.start);
   		const booking = { id: `bk_${this.bookings.length + 1}`, slot, ...details };
   		this.bookings.push(booking);
   		return booking;
   	}
   }

   /** Google Calendar when GOOGLE_CALENDAR_ID and GOOGLE_SERVICE_ACCOUNT (the key file's JSON) are set, else in memory. */
   export function calendarFromEnv(): Calendar {
   	const id = process.env.GOOGLE_CALENDAR_ID;
   	const account = process.env.GOOGLE_SERVICE_ACCOUNT;
   	if (id && account) return new GoogleCalendar(id, JSON.parse(account) as ServiceAccount);
   	console.warn("No GOOGLE_CALENDAR_ID / GOOGLE_SERVICE_ACCOUNT: bookings are kept in memory");
   	return new MemoryCalendar();
   }
   ```

3. **Create the assistant.** Its instructions say when to call each tool and what to confirm; `request_start_message` fills the silence while the server works.

   ```ts title="setup.ts"
   // Create the booking assistant, with the two tools pointing at your tool server.
   import MoreVoice from "@morevoice/sdk";
   import { BOOK_APPOINTMENT, FIND_SLOTS } from "./tools.ts";

   const mv = new MoreVoice(); // reads MOREVOICE_API_KEY
   const url = process.env.TOOL_URL!; // https://clinic.example.com/morevoice/tools

   const assistant = await mv.assistants.create({
   	name: "Sharon Clinic: appointments",
   	language: "he",
   	first_message: "שלום, הגעתם למרפאת השרון, מדברת הנציגה הדיגיטלית. לאיזה יום תרצו לקבוע תור?",
   	system_prompt: [
   		"You book appointments for Sharon Clinic, in Hebrew. You are a digital assistant; say so if asked.",
   		"Use get_current_time to turn 'tomorrow' or 'next Sunday' into a date, then call find_slots with it.",
   		"Offer at most three times, in the words of their `label`. Never offer a time find_slots didn't return.",
   		"Before booking, read back the time and the caller's full name and wait for a yes. Then call book_appointment.",
   		"If the time was taken, apologise and offer the other times. When the booking is done, say goodbye and end the call.",
   	].join("\n"),
   	tools: {
   		end_call: true,
   		get_current_time: true,
   		custom: [
   			{ ...FIND_SLOTS, url, timeout_seconds: 10, request_start_message: "רגע, אני בודקת ביומן." },
   			{ ...BOOK_APPOINTMENT, url, timeout_seconds: 10, request_start_message: "קובעת את התור." },
   		],
   	},
   });
   console.log(`ASSISTANT_ID=${assistant.id}`);
   ```

4. **Serve the tools.** `tools.nodeHandler` verifies each call's signature before your code runs, checks the arguments against the schema, and answers within the time limit. A failure reaches the assistant as an error it can apologise for: the call goes on.

   ```ts title="tool-server.ts"
   // The tool server: MoreVoice calls it while the assistant talks to the caller. tools.nodeHandler checks the signature,
   // checks the arguments against each tool's schema and keeps every answer within the time limit.
   import { createServer } from "node:http";
   import { defineTool, tools } from "@morevoice/sdk";
   import { calendarFromEnv, dayIn, HOURS, openSlots, SlotTakenError, spoken } from "./calendar.ts";
   import { BOOK_APPOINTMENT, FIND_SLOTS } from "./tools.ts";

   const calendar = calendarFromEnv();
   const langOf = (language: string | null | undefined) => (language === "en" ? "en" : "he");

   const handle = tools.nodeHandler({
   	secret: process.env.MOREVOICE_TOOL_SECRET!, // whsec_…: the tool signing secret of the key's mode
   	timeoutMs: 8_000,
   	handlers: {
   		find_slots: defineTool({
   			parameters: FIND_SLOTS.parameters,
   			async handler({ date }, ctx) {
   				const slots = (await openSlots(calendar, date)).slice(0, 3);
   				if (!slots.length) return { result: { date, slots: [], note: "Nothing open that day: suggest another day." } };
   				// `label` is how to say the time; `start` is what book_appointment needs.
   				return { result: { date, slots: slots.map((s) => ({ start: s.start, label: spoken(s, langOf(ctx.call.language)) })) } };
   			},
   		}),
   		book_appointment: defineTool({
   			parameters: BOOK_APPOINTMENT.parameters,
   			async handler({ start, name, phone }, ctx) {
   				const slot = (await openSlots(calendar, dayIn(start, HOURS.timeZone))).find((s) => s.start === start);
   				const again = { booked: false, reason: "That time is not open any more: call find_slots and offer other times." };
   				if (!slot) return { result: again };
   				try {
   					const booking = await calendar.book(slot, { name, phone: phone ?? ctx.call.from ?? null, callId: ctx.call.id });
   					return { result: { booked: true, booking_id: booking.id, time: spoken(slot, langOf(ctx.call.language)) } };
   				} catch (err) {
   					if (err instanceof SlotTakenError) return { result: again };
   					throw err; // the assistant hears that the tool failed, and apologises
   				}
   			},
   		}),
   	},
   });

   createServer((req, res) => {
   	if (req.method === "POST" && req.url === "/morevoice/tools") return void handle(req, res);
   	res.writeHead(404).end();
   }).listen(Number(process.env.PORT ?? 3000));
   ```

## Try it in test mode

Start the tool server and give its URL to the assistant: `PORT=3000 MOREVOICE_TOOL_SECRET=whsec_… npx tsx tool-server.ts`, then `TOOL_URL=https://<your server>/morevoice/tools npx tsx setup.ts`. While developing, [`morevoice listen --forward-tools`](https://docs.morevoice.ai/guides/custom-tools/#develop-against-localhost) brings the tool calls to `localhost` without a public URL. `POST /v1/tools/test` then runs each tool exactly as a call would, signature included:

```ts title="test-tools.ts"
// Run each tool once, exactly as a call would (same body, same signature), against your tool server.
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // a test key: test calls are signed with the test-mode secret
const assistant_id = process.env.ASSISTANT_ID!;
const date = process.env.DATE!; // a clinic day, YYYY-MM-DD

// `result` is your server's answer as the assistant receives it: the SDK's handler answers { result, say, … }.
interface Answer<R> {
	result: R;
}

const found = await mv.tools.test({ assistant_id, tool_name: "find_slots", arguments: { date } });
if (!found.ok) throw new Error(`find_slots: ${JSON.stringify(found.error)}`);
const [first] = (found.result as Answer<{ slots: { start: string; label: string }[] }>).result.slots;
if (!first) throw new Error(`nothing open on ${date}`);
console.log(`find_slots offered ${first.label}`);

const booked = await mv.tools.test({ assistant_id, tool_name: "book_appointment", arguments: { start: first.start, name: "Dana Levi" } });
if (!booked.ok) throw new Error(`book_appointment: ${JSON.stringify(booked.error)}`);
console.log("book_appointment:", (booked.result as Answer<{ booked: boolean; time?: string }>).result);
```

```text title="Output"
find_slots offered יום רביעי, 7 באוקטובר בשעה 09:00
book_appointment: { booked: true, booking_id: 'bk_1', time: 'יום רביעי, 7 באוקטובר בשעה 09:00' }
```

Then talk to it: call the assistant from the dashboard, or place a [test call](https://docs.morevoice.ai/get-started/test-mode/), and ask for an appointment.

> **Two callers, one slot**
>
> Between offering a time and booking it, someone else may take it. `book()` checks the calendar again right before it books, and the assistant offers other times when it answers `booked: false`. With several servers, also use the calendar's own conflict check, or a lock in your database.

## Go live

- Set `GOOGLE_CALENDAR_ID` and `GOOGLE_SERVICE_ACCOUNT` (the key file's JSON) where the tool server runs, and keep the key out of your repository.
- Give the live assistant the live tool signing secret, and point `TOOL_URL` at your production server.
- Change `HOURS` to your opening hours, and add holidays: a closed day returns no slots, and the assistant offers another day.
- Send a confirmation the caller can keep: from `book_appointment`, by SMS or e-mail, or with a [`call.ended`](https://docs.morevoice.ai/webhooks/events/#call.ended) webhook.
