# OpenBooking: full documentation for AI tools > OpenBooking is an open-source TypeScript SDK and booking backend that makes any website or booking platform bookable by AI assistants (Claude, ChatGPT, Gemini, AI browsers) through MCP, WebMCP and UCP. It enforces agent safety: holds that expire, idempotent retries that never double-book, explicit customer consent, and cancellation terms shown before booking. Packages are published on npm as @openbooking-sh/*. # Recipes Copy-paste starting points. Every snippet uses the published `@openbooking-sh/*` packages. ## 1. A booking backend in one file ```sh npm install @openbooking-sh/server @openbooking-sh/provider-memory ``` ```ts // server.ts: run with `npx tsx server.ts` import { createOpenBookingApp, listen } from '@openbooking-sh/server'; import { MemoryBookingProvider, type MemoryProviderConfig } from '@openbooking-sh/provider-memory'; const salon: MemoryProviderConfig = { name: 'Studio Nord', venues: [ { venue: { id: 'studio-nord', name: 'Studio Nord', timezone: 'Europe/Oslo', currency: 'NOK', address: { street_address: 'Eksempelgata 12', postal_code: '0550', address_locality: 'Oslo', address_country: 'NO', }, }, currency: 'NOK', // Who or what gets booked. Tags let customers ask for someone by name. resources: [ { id: 'maria', venue_id: 'studio-nord', kind: 'staff', name: 'Maria', capacity: { min: 1, max: 1 }, tags: ['maria'], }, { id: 'jonas', venue_id: 'studio-nord', kind: 'staff', name: 'Jonas', capacity: { min: 1, max: 1 }, tags: ['jonas'], }, ], offerings: [ { id: 'haircut', venue_id: 'studio-nord', name: 'Haircut', duration_minutes: 45, price_per_person: { amount: 65000, currency: 'NOK' }, // minor units: 650.00 NOK resource_kinds: ['staff'], cancellation: { refundability: 'refundable', free_until_hours_before: 24, late_fee_per_person: 32500, no_show_fee_per_person: 32500, }, deposit: null, }, ], // Weekday 0 = Sunday … 6 = Saturday. Missing = closed. opening_hours: { 2: [{ open: '09:00', close: '18:00' }], 3: [{ open: '09:00', close: '18:00' }], 4: [{ open: '09:00', close: '18:00' }], 5: [{ open: '09:00', close: '18:00' }], 6: [{ open: '10:00', close: '16:00' }], }, slot_interval_minutes: 15, buffer_minutes: 10, // break between appointments with the same person min_lead_minutes: 60, max_days_ahead: 60, }, ], }; const { app } = createOpenBookingApp({ provider: new MemoryBookingProvider(salon), baseUrl: process.env.BASE_URL ?? 'http://localhost:3000', studio: { token: process.env.STUDIO_TOKEN }, // Studio is open without a token on localhost only }); await listen(app, { port: 3000 }); ``` You get: - `/book`: the booking page; - `/book/embed.js`: the website snippet; - `/mcp`: for Claude, ChatGPT and other MCP clients; - `/ucp` and `/.well-known/ucp`: UCP; - `/.well-known/agent-card.json`: A2A; - `/studio`: the dashboard. ## 2. Keep bookings in Postgres ```sh npm install @openbooking-sh/postgres ``` ```ts import { connectPostgres, migrate, postgresStores } from '@openbooking-sh/postgres'; const db = connectPostgres(process.env.DATABASE_URL!); await migrate(db); // creates and upgrades tables; safe on every start const stores = postgresStores(db); const { app } = createOpenBookingApp({ provider: new MemoryBookingProvider(salon, { store: stores.bookings }), serviceOptions: { idempotencyStore: stores.idempotency }, studio: { token: process.env.STUDIO_TOKEN, activity: stores.activity }, baseUrl: process.env.BASE_URL!, }); ``` Holds are reserved under a per-resource lock, so two servers can never sell the same time. ## 3. Deploy to Vercel Export the app as a Vercel Function and send every path to it: ```ts // api/index.ts const handle = (request: Request) => app.fetch(request); export const GET = handle; export const POST = handle; export const PUT = handle; export const DELETE = handle; export const OPTIONS = handle; ``` ```json // vercel.json { "rewrites": [{ "source": "/(.*)", "destination": "/api" }] } ``` Set `BASE_URL` to your public URL, plus `STUDIO_TOKEN` and `DATABASE_URL`. ## 4. Add booking to an existing website One line, before ``: ```html ``` What it does: - adds a floating Book button and a booking popup; - makes links to the booking page (and any element with `data-openbooking`) open the popup; - adds schema.org data for search engines and AI; - registers WebMCP booking tools for AI browsers. Options on the tag: `data-label`, `data-color`, `data-position="left"`, `data-button="none"`, `data-structured-data="off"`, `data-agents="off"`. On hosted OpenBooking, the snippet is `https://app.openbooking.sh/b//embed.js`. ## 5. Connect an existing booking system Implement `BookingProvider` from `@openbooking-sh/core`. The engine handles agent safety (consent, idempotency, hold expiry, cancellation rules); you translate to your system: ```ts import type { BookingProvider } from '@openbooking-sh/core'; export class MySystemProvider implements BookingProvider { readonly info = { name: 'My booking system' }; async listVenues() { /* your locations */ } async searchAvailability(query, ctx) { /* free slots with price and cancellation policy */ } async createHold(req, ctx) { /* reserve atomically until req.expires_at */ } async confirmHold(req, ctx) { /* turn the hold into a booking; re-check expiry */ } async getBooking(id, ctx) { /* … */ } async cancelBooking(req, ctx) { /* release a hold or cancel with req.fee / req.refund */ } } ``` The contract: - every mutation is atomic; - two overlapping holds must never both succeed (throw `BookingError('slot_unavailable')`); - expired holds stop blocking inventory. `@openbooking-sh/provider-memory` and `@openbooking-sh/provider-calcom` are complete examples. Test it with `@openbooking-sh/conformance` (`npm install -D @openbooking-sh/conformance vitest`): ```ts import { describeProviderConformance } from '@openbooking-sh/conformance/vitest'; describeProviderConformance('MySystemProvider', { create: () => new MySystemProvider(testConfig), // a fresh, empty provider per test now: new Date('2030-06-03T08:00:00Z'), // before the date you search query: { date: '2030-06-04', party_size: { total: 1 } }, // must return open slots }); ``` The suite never assumes one place per slot: it books a slot until the provider answers `slot_unavailable`, then checks that parallel holds cannot go past that point. `query` must return an open slot, and another slot at a different time once the first is full. ## 6. Get webhooks when bookings change Send `booking.held`, `booking.confirmed`, `booking.updated`, `booking.cancelled` and `booking.expired` to your CRM, SMS sender or own database: ```ts const { app, webhooks } = createOpenBookingApp({ provider, baseUrl: process.env.BASE_URL!, webhooks: { endpoints: [{ url: 'https://crm.example.com/hooks', secret: process.env.WEBHOOK_SECRET! }], }, }); // On Vercel and other serverless hosts, let retries finish after the response: // waitUntil(webhooks!.idle()); ``` Each delivery is a JSON POST with an `openbooking-signature` header (`t=…,v1=…`, HMAC-SHA256) and an `openbooking-event-id` header. Verify it on the receiving side with the raw body: ```ts import { verifyWebhook } from '@openbooking-sh/core'; const body = await request.text(); if (!(await verifyWebhook(body, request.headers.get('openbooking-signature'), secret))) { return new Response('bad signature', { status: 401 }); } const event = JSON.parse(body); // { id, type, created_at, data: { booking, actor } } ``` Failed deliveries are retried after 2 s, 15 s and 60 s. Events reach each endpoint in the order they happened, so a failing endpoint holds back its later events until the earlier one succeeds or gives up. Delivery is at least once, so dedupe on `event.id`. Retries (same idempotency key) and no-op cancels don't send events. Payloads include customer details, so never point a webhook at an analytics or logging service. Without the server, `createWebhooks()` returns a listener for `service.on()`. ## 7. Take deposits with Stripe A slot can require a deposit at confirmation. Give the service a payment provider and the engine handles the rest: ```ts import { StripePayments } from '@openbooking-sh/payments-stripe'; const service = new BookingService({ provider, payments: new StripePayments({ secretKey: process.env.STRIPE_SECRET_KEY!, // sk_test_… while you try it successUrl: 'https://example.com/booked', cancelUrl: 'https://example.com/book', }), }); ``` 1. `confirm_booking` without a token fails with `payment_required`. The error carries a `payment_url` (a Stripe Checkout page) and a `payment_token`. The agent gives the user the link. 2. After the user pays, `confirm_booking` again with that `payment_token`. The engine asks Stripe whether the session was paid, for this booking, for the deposit amount. Only then is the booking confirmed, and the payment reference is kept on it. Tokens an agent makes up are refused. 3. Cancelling refunds what the cancellation terms say (the whole deposit before the free-cancellation deadline, the deposit minus the late fee after it). If Stripe is down, the booking is still cancelled and `cancel_booking` replies `refund_failed`; calling it again retries, and the idempotency key means the customer is never refunded twice. 4. If the customer pays after the hold expired, the payment is refunded and the agent gets `hold_expired`. Staff taking a deposit in cash in Studio still works: Studio records it as collected, with no Stripe involved. For a connected account (Stripe Connect) pass `stripeAccount`. Not built yet: per-business Stripe accounts and the payment page in the hosted booking page and Studio. For now `payments` is for self-hosted setups. ## Rules for AI coding tools If you're an AI assistant adding OpenBooking to a project: - **Use the packages; don't reimplement booking logic.** Holds, idempotency and consent are subtle. - **Prices are in minor units:** `65000` = 650.00 NOK. - **Opening hours use weekday numbers,** 0 = Sunday. - **Never call `confirm` without the end user's explicit yes** to time, price and cancellation terms (`user_confirmed: true`). - **Every hold and confirm needs a fresh `idempotency_key`** (8+ characters); reuse it only to retry the same request. - **Protect Studio with `STUDIO_TOKEN` anywhere but localhost.** --- # OpenBooking **Make any booking system bookable by AI agents through one integration.** Restaurants, salons, clinics: implement one `BookingProvider` interface, and OpenBooking exposes it to agents over **MCP**, **UCP** and **A2A**. It enforces the rules that make agent bookings safe: - holds that expire; - idempotent retries that never double-book; - explicit user confirmation; - policy terms disclosed up front. | Protocol | Status | What you get | | ------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | **MCP** (Model Context Protocol) | ✅ Supported | 7 agent-friendly tools over Streamable HTTP (2025 and 2026-07-28 eras) and stdio | | **UCP** (Universal Commerce Protocol) | 🟡 Draft | `/.well-known/ucp` profile plus `dev.ucp.lodging.booking` REST sessions, extended for time slots ([spec notes](docs/SPEC-NOTES.md)) | | **A2A** (Agent2Agent) | 🟡 Beta | v1.0 Agent Card plus a JSON-RPC `SendMessage` endpoint (`/a2a`) for search, hold, confirm and cancel; no streaming or tasks | ## Start in one command ```sh npx create-openbooking@latest my-salon cd my-salon && npm run dev ``` You get a booking backend with a booking page, a website snippet, Studio and an MCP endpoint. Edit `business.ts` for staff, services and opening hours. ## Install into an existing app ```sh npm install @openbooking-sh/server @openbooking-sh/provider-memory ``` ```ts import { createOpenBookingApp, listen } from '@openbooking-sh/server'; import { createDemoSalonProvider } from '@openbooking-sh/provider-memory'; const { app } = createOpenBookingApp({ provider: createDemoSalonProvider(), // or your own BookingProvider baseUrl: 'http://localhost:3000', }); await listen(app, { port: 3000 }); // MCP at /mcp · booking page at /book · Studio at /studio · UCP at /.well-known/ucp ``` | Package | What it is | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | [`@openbooking-sh/core`](packages/core) | The engine and the `BookingProvider` interface | | [`@openbooking-sh/server`](packages/server) | One app for MCP, UCP, A2A, booking page and Studio | | [`@openbooking-sh/provider-memory`](packages/provider-memory) | Configured provider (services, staff, hours, rules) on a pluggable store | | [`@openbooking-sh/postgres`](packages/postgres) | Postgres storage for everything | | [`@openbooking-sh/booking-page`](packages/booking-page) | Booking page, embed snippet and WebMCP | | [`@openbooking-sh/client`](packages/client) | Typed fetch client for the booking API (and its OpenAPI document) | | [`@openbooking-sh/react`](packages/react) | React `` and hooks (`useAvailability`, `useBooking`) on the typed client | | [`@openbooking-sh/studio`](packages/studio) | Dashboard for the business | | [`@openbooking-sh/adapter-mcp`](packages/adapter-mcp), [`adapter-ucp`](packages/adapter-ucp), [`adapter-usp`](packages/adapter-usp), [`adapter-a2a`](packages/adapter-a2a) | The protocol adapters | | [`@openbooking-sh/provider-calcom`](packages/provider-calcom) | Cal.com connector (beta) | | [`@openbooking-sh/conformance`](packages/conformance) | Test suite that proves your `BookingProvider` never double-books | | [`@openbooking-sh/notifications`](packages/notifications), [`google-calendar`](packages/google-calendar) | Emails with .ics, Google Calendar sync | | [`@openbooking-sh/hosted`](packages/hosted) | Multi-business hosting (what runs app.openbooking.sh) | **More:** [recipes](docs/RECIPES.md) (Postgres, Vercel, website snippet, your own booking system) · [docs for AI coding tools](llms.txt) · [contributing](CONTRIBUTING.md) ## 5-minute quickstart Requires Node 22.12+ and pnpm. The published packages run on Node 20+. Run `corepack enable` or `npm i -g pnpm`. ```sh git clone openbooking && cd openbooking pnpm install pnpm dev ``` This starts **Studio Nord**, a fictional hair salon (in-memory) with three stylists, three services (haircut, beard trim, color & cut with a deposit), opening hours and a cancellation policy. Run `DEMO=restaurant pnpm dev` for the restaurant demo instead. ``` MCP (Streamable HTTP) http://localhost:3000/mcp UCP profile http://localhost:3000/.well-known/ucp UCP REST http://localhost:3000/ucp/booking-sessions A2A Agent Card http://localhost:3000/.well-known/agent-card.json Studio (dashboard) http://localhost:3000/studio ``` **Try it with an agent.** Point any MCP client at `http://localhost:3000/mcp`. For example, run `npx @modelcontextprotocol/inspector`. Then ask the agent to _"book me a haircut with Maria on Friday afternoon"_. For stdio clients, use `pnpm --dir examples/demo stdio` (config snippet in [`examples/demo/src/stdio.ts`](examples/demo/src/stdio.ts)). **Try it with curl (UCP REST).** ```sh # 1. find a slot (EXTENSION: sh.openbooking.availability) curl "localhost:3000/ucp/availability?date=2026-10-09&party_size=1&offering_id=haircut&time_from=15:00" # 2. hold it (a UCP booking session); copy an offer id from step 1 curl -X POST localhost:3000/ucp/booking-sessions \ -H 'content-type: application/json' -H "Idempotency-Key: $(uuidgen)" \ -d '{"stays":[{"id":""}],"booker":{"first_name":"Ada","last_name":"Lovelace","email":"ada@example.com"}}' # 3. confirm, only with explicit user consent curl -X POST localhost:3000/ucp/booking-sessions//complete \ -H 'content-type: application/json' -H "Idempotency-Key: $(uuidgen)" \ -d '{"user_confirmed":true}' ``` ## Keep bookings in Postgres The demos are in-memory by default. Set `DATABASE_URL` and bookings, holds, idempotency records and Studio activity are stored in Postgres (tables are created on start): ```sh DATABASE_URL=postgres://user:pass@localhost:5432/openbooking pnpm dev ``` On Vercel, add a Postgres database from the Marketplace (Neon, Supabase…) and use its pooled connection string. In code: ```ts import { connectPostgres, migrate, postgresStores } from '@openbooking-sh/postgres'; const db = connectPostgres(process.env.DATABASE_URL!); await migrate(db); const stores = postgresStores(db); createOpenBookingApp({ provider: createDemoSalonProvider({ store: stores.bookings }), // or new CalcomBookingProvider({ store: stores.calcom, ... }) serviceOptions: { idempotencyStore: stores.idempotency }, studio: { token: process.env.STUDIO_TOKEN, activity: stores.activity }, baseUrl, }); ``` Holds are reserved under a per-resource lock, so two servers can never hand out the same time. ## OpenBooking Studio The booking system for the people running the business, at `/studio`: - **Calendar:** a day view with a column per staff member or table, and the day's bookings and takings at a glance. - **New booking:** staff book phone calls and walk-ins. It finds free times, takes customer details, and records a deposit collected at the desk. - **Bookings:** filter by status. Open a booking for guest details, deposit, cancellation terms and history. Cancel or release a hold. - **Customers:** everyone who booked, with visits, spend, next visit and the channel they first came through. - **Services & staff:** what customers and AI assistants can book. - **Insights and agent log:** bookings per channel (Claude, ChatGPT, Studio…) and every agent call with its result. In local dev (`baseUrl` on localhost) the Studio opens without a login. Anywhere else, set a token: `createOpenBookingApp({ ..., studio: { token: process.env.STUDIO_TOKEN } })`. Without a token, the Studio API stays locked. Agent names are self-reported by clients, so use them for analytics only, never for access control. ## Hosted: many businesses, one deployment ```sh pnpm dev:hosted ``` Businesses sign up at `/signup` and set up services, staff, hours and cancellation rules in Studio. Each gets a booking page at `/b/`. Every listed business is bookable through one MCP app at `/mcp` (`find_business` → booking tools), with optional Google Calendar sync and confirmation emails. See [docs/HOSTED.md](docs/HOSTED.md). ## The MCP tools | Tool | Does | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `get_business_info` | Services (duration, price), staff customers can ask for by name, opening hours and how far ahead bookings are accepted. | | `search_availability` | Free times on a date, with who is booked, who else is free, price, deposit and cancellation policy. Nothing is reserved. | | `hold_slot` | Reserves a slot until `expires_at`. Returns `booking_id` and the terms to show the user. | | `confirm_booking` | Confirms a hold. Requires `user_confirmed: true`, customer details, and a `payment_token` if a deposit is due. | | `get_booking` | Current status and details. | | `reschedule_booking` | Moves a confirmed booking to a new time for the same service, keeping its id and code. Needs `user_confirmed`; allowed while cancelling is still free. | | `cancel_booking` | Releases a hold, or cancels a confirmed booking. A confirmed booking needs `user_confirmed`; the fee follows the policy. | **Design rules:** - Every mutating tool takes an `idempotency_key`. - Every error is `{ code, message, suggested_next_action, retryable }`. - Every response includes `next_step`, the instruction for the agent. - New holds are limited per caller IP (default 20 per 10 minutes), so nobody can tie up the calendar. Set `serviceOptions.holdLimit` to tune or disable it. ### Field reference **`search_availability`** | Field | Type | Notes | | ---------------------- | ------------ | ----------------------------------------------------------- | | `date` | `YYYY-MM-DD` | In the venue's time zone | | `party_size` | integer | Default 1 (an appointment); guests for a table | | `offering_id` | string | Service id from `get_business_info`, e.g. `haircut` | | `staff` | string | A staff member by name or id, any capitalisation (`"Kari"`) | | `preferences` | string[] | Other required features, e.g. `["outdoor"]` | | `time_from`, `time_to` | `HH:MM` | Venue local time, inclusive | | `limit` | integer | Default 20, max 50 | **`customer`** (on `hold_slot` or `confirm_booking`): `first_name`, `last_name`, and at least one of `email` or `phone_number` (international format, e.g. `+4791234567`). **Slots and bookings:** - Times (`start`, `end`) are ISO 8601 with the venue's offset, e.g. `2026-10-13T10:00:00+02:00`. - `expires_at` is in UTC. - Prices are in minor units: `{ amount: 45000, currency: "NOK" }` is 450.00 NOK. - `resource` says who or what is booked; `also_available` lists other staff free at that time. - Booking `status` is `held`, `confirmed`, `cancelled` or `expired`. ## Connect Cal.com (beta) Already on [Cal.com](https://cal.com) or self-hosted Cal.diy? Your event types become bookable by AI agents with no code: ```sh CAL_API_KEY=cal_live_... VENUE_NAME="Studio Nord" VENUE_TIMEZONE=Europe/Oslo pnpm dev # optional: CAL_EVENT_TYPE_IDS="123,456" CAL_BASE_URL=https://cal.example.com VENUE_CURRENCY=NOK ``` Or in code: ```ts import { CalcomBookingProvider } from '@openbooking-sh/provider-calcom'; const provider = new CalcomBookingProvider({ apiKey: process.env.CAL_API_KEY!, venue: { id: 'studio-nord', name: 'Studio Nord', timezone: 'Europe/Oslo', currency: 'NOK' }, }); ``` How it maps: - Each event type becomes an offering. - A hold is a Cal.com slot reservation for the hold time. - Confirm creates the Cal.com booking. Cal.com requires an email, so agents are asked for one. - Cancel cancels it in Cal.com. - Cancellations made in Cal.com show up in OpenBooking. Limits in this beta: - One person per appointment. - Paid event types aren't charged through OpenBooking. - Hold and booking records are in memory until a durable store is added. - Tested against the documented API v2 shapes, not yet end to end on a live account. ## Implementing `BookingProvider` You own inventory and persistence. OpenBooking owns validation, idempotency, hold expiry, consent and cancellation rules. ```ts import { BookingError, type BookingProvider } from '@openbooking-sh/core'; import { createOpenBookingApp, listen } from '@openbooking-sh/server'; class MySalonProvider implements BookingProvider { info = { name: 'Studio Nord', description: 'Hair salon in Bergen' }; async listVenues() { return [{ id: 'nord', name: 'Studio Nord', timezone: 'Europe/Oslo', currency: 'NOK' }]; } async searchAvailability(query, ctx) { // query: { venue_id, date, party_size, time_from?, time_to?, offering_id?, tags?, limit } // Return Slot[]: each with an opaque slot_id, start/end (ISO with offset), price, // deposit (or null) and a cancellation_policy computed for that slot. } async createHold({ slot_id, expires_at, customer, notes }, ctx) { // ATOMICALLY reserve the slot until expires_at (transaction / unique constraint). // If it's gone: throw new BookingError('slot_unavailable', 'Just taken.'); // Return the Booking with status 'held'. } async confirmHold({ booking_id, customer, payment_token }, ctx) { // Re-check expiry atomically, charge the deposit if any, mark confirmed, return the Booking. } async getBooking(id, ctx) { /* … */ } async cancelBooking({ booking_id, reason, fee, refund }, ctx) { // Release the hold, or cancel and record the fee/refund the engine computed. } // optional: updateBooking({ booking_id, customer?, notes? }, ctx) } const { app } = createOpenBookingApp({ provider: new MySalonProvider(), baseUrl: 'https://book.studionord.example', }); await listen(app, { port: 3000 }); ``` The contract is documented in [`packages/core/src/provider.ts`](packages/core/src/provider.ts). [`provider-memory`](packages/provider-memory/src/provider.ts) is a complete reference implementation. The four rules: 1. Mutations are atomic. 2. Overlapping holds never both succeed. 3. Expired holds stop blocking inventory. 4. Business failures throw `BookingError` with a specific code. Prove it with the conformance suite (vitest). It books slots until the provider says no, fires parallel holds, lets holds expire and cancels, and fails if any rule is broken: ```ts import { describeProviderConformance } from '@openbooking-sh/conformance/vitest'; describeProviderConformance('MySystemProvider', { create: () => new MySystemProvider(testConfig), // a fresh, empty provider per test now: new Date('2030-06-03T08:00:00Z'), // before the date you search query: { date: '2030-06-04', party_size: { total: 1 } }, // must return open slots }); ``` ## Repository layout ``` packages/ core/ Domain model, BookingProvider, BookingService (agent-safety rules) provider-memory/ Configured provider (catalog + slot rules) + demo salon and restaurant postgres/ Postgres storage: bookings, idempotency, Studio activity, Cal.com records create-openbooking/ npx create-openbooking: a ready-to-run booking backend adapter-mcp/ MCP tools (Streamable HTTP + stdio) adapter-ucp/ UCP discovery + booking sessions (draft) adapter-usp/ USP profile, catalog, availability, holds and bookings (draft) adapter-a2a/ A2A Agent Card + SendMessage endpoint studio/ OpenBooking Studio dashboard (/studio), incl. business settings booking-page/ Public booking page: pre-filled links, JSON-LD, WebMCP, manage links, OpenAPI client/ Typed fetch client for the booking page API react/ React booking widget and hooks, on the client notifications/ Confirmation/cancellation emails with .ics invites google-calendar/ Google Calendar sync (busy times, bookings as events) server/ One Hono app mounting everything hosted/ Many businesses on one deployment: sign-up, settings, the OpenBooking MCP app examples/demo/ bench/ Agent-success benchmark (tasks + runner) docs/ARCHITECTURE.md, docs/SPEC-NOTES.md, docs/HOSTED.md ``` ## Development ```sh pnpm dev # demo server with watch pnpm test # vitest (unit + MCP end-to-end + bench smoke test) pnpm typecheck pnpm lint pnpm build # tsup → dist/ per package pnpm bench # run the agent benchmark (scripted baseline) pnpm changeset # describe a change for release ``` The benchmark ([`bench/`](bench/README.md)) runs booking tasks against isolated servers. It measures: - completion rate; - double bookings; - expired-hold errors. LLM drivers plug into a stub interface. ## License [Apache-2.0](LICENSE) --- # @openbooking-sh/adapter-a2a **A2A Agent Card.** An Agent2Agent (A2A) Agent Card plus a `SendMessage` JSON-RPC endpoint that lets A2A agents search availability, hold, confirm and cancel bookings with the same safety guarantees as MCP. Most apps use it through `@openbooking-sh/server`. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/adapter-a2a ``` ## Usage ```ts import { buildAgentCard, AGENT_CARD_PATH } from '@openbooking-sh/adapter-a2a'; ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/adapter-mcp **MCP server for booking.** Seven booking tools for any MCP client (Claude, ChatGPT, Cursor and more): `get_business_info`, `search_availability`, `hold_slot`, `confirm_booking`, `get_booking`, `reschedule_booking` and `cancel_booking`. Served over Streamable HTTP or stdio. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/adapter-mcp ``` ## Usage ```ts import { createMcpHttpHandler } from '@openbooking-sh/adapter-mcp'; const mcp = createMcpHttpHandler({ service }); // service: a BookingService from @openbooking-sh/core // Web-standard handler: return mcp.fetch(request) from any route, e.g. /mcp ``` Most apps use this through `@openbooking-sh/server`, which mounts it with host and origin checks. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/adapter-ucp **Universal Commerce Protocol (draft).** Exposes a `BookingService` over the Universal Commerce Protocol: the business profile at `/.well-known/ucp`, booking sessions over REST and an availability extension. UCP booking support follows a draft and may change with the spec. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/adapter-ucp ``` ## Usage ```ts import { createUcpRouter, buildUcpProfile } from '@openbooking-sh/adapter-ucp'; app.route('/ucp', createUcpRouter({ service, baseUrl, ucpPath: '/ucp' })); app.get('/.well-known/ucp', (c) => c.json(buildUcpProfile({ baseUrl, ucpPath: '/ucp' }))); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/adapter-usp **Universal Scheduling Protocol (draft).** Exposes a `BookingService` over the Universal Scheduling Protocol (USP), the draft standard from Wix and Stripe that lets any platform or AI assistant discover and book a business: the profile at `/.well-known/usp`, the catalog, availability, holds and bookings over REST. Platforms sign in with a key they make themselves (no accounts), or, when you turn it on, by signing requests with a key they publish in their profile (HTTP message signatures, ES256). Each business chooses how a booking becomes real: the customer confirms on a page (default), or the assistant books immediately. Follows a draft spec and may change with it. Most apps use it through `@openbooking-sh/server` (`usp: {}`) or hosted OpenBooking. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/adapter-usp ``` ## Usage ```ts import { createUsp } from '@openbooking-sh/adapter-usp'; const usp = createUsp({ service, baseUrl: 'https://bistro.example.com', // the public address platforms sign continueUrl: (b) => bookingPage.confirmUrl(b), // where the customer confirms a held booking state: postgresStores(db).usp, // shared by every instance when you run more than one }); app.route(usp.path, usp.router); app.get('/.well-known/usp', async (c) => c.json(await usp.profile())); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/booking-page **Public booking page, embed and WebMCP.** A server-rendered booking page with schema.org data and pre-fill links, a manage-booking page, and `embed.js`: one line that adds a Book button, a booking popup and WebMCP booking tools to any website. Its JSON API is described by an OpenAPI 3.1 document at `/book/api/openapi.json`; call it with `@openbooking-sh/client`. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/booking-page ``` ## Usage ```ts import { createBookingPage } from '@openbooking-sh/booking-page'; const page = createBookingPage({ service, pageUrl: 'https://book.example.com/book', apiBase: 'https://book.example.com/book', }); app.route('/book', page.app); // On any website: // ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/client **Typed client for the booking API.** A small, typed `fetch` client for the booking API of one business: read its services, find free times, hold, confirm and cancel. No dependencies; works in browsers, edge functions and Node. Every write carries an idempotency key, consent is explicit (`user_confirmed: true`), and every failure is an `OpenBookingError` with a code and what to do next. The API is described by an OpenAPI 3.1 document at `/book/api/openapi.json`, for every other language. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/client ``` ## Usage ```ts import { createClient } from '@openbooking-sh/client'; const booking = createClient({ baseUrl: 'https://app.openbooking.sh/b/studio-nord/book' }); const { slots } = await booking.availability({ date: '2026-10-16', service: 'haircut' }); const hold = await booking.hold({ slot_id: slots[0].slot_id }); // reserved for a few minutes // Show the customer the time, price and cancellation terms. Only when they say yes: const confirmed = await booking.confirm({ booking_id: hold.booking_id, user_confirmed: true, customer: { first_name: 'Ada', last_name: 'Lovelace', email: 'ada@example.com' }, }); console.log(confirmed.confirmation_code); ``` Pass your own `idempotency_key` (and keep it) to retry a write safely after a network error: the same key never books twice. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/conformance **Conformance suite for booking providers.** Vitest checks that a `BookingProvider` keeps the promises the engine relies on: slots are never overbooked (even with parallel holds), expired holds stop blocking, cancellations free the place, and every failure is a `BookingError` with the right code. Optional methods (`updateBooking`, `rescheduleBooking`, `listBookings`) are tested only when implemented. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/conformance ``` ## Usage ```ts import { describeProviderConformance } from '@openbooking-sh/conformance/vitest'; describeProviderConformance('MySystemProvider', { create: () => new MySystemProvider(testConfig), // a fresh, empty provider per test now: new Date('2030-06-03T08:00:00Z'), // before the date you search query: { date: '2030-06-04', party_size: { total: 1 } }, // must return open slots }); ``` Also exports `runProviderConformance(options)`, which returns a pass/fail result per check without a test runner. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/core **The booking engine.** The domain model, the `BookingProvider` interface every booking system implements, and `BookingService`: the agent-safe engine that every protocol adapter runs through. It enforces holds that expire, idempotent retries, explicit customer consent, and cancellation and deposit terms shown before anything is confirmed. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/core ``` ## Usage ```ts import { BookingService } from '@openbooking-sh/core'; const service = new BookingService({ provider: myProvider }); const { slots } = await service.searchAvailability({ date: '2026-10-09', party_size: { total: 1 }, }); const hold = await service.hold({ slot_id: slots[0].slot_id, idempotency_key: crypto.randomUUID(), }); const booking = await service.confirm({ booking_id: hold.booking_id, idempotency_key: crypto.randomUUID(), user_confirmed: true, // only after the customer said yes to time, price and terms customer: { first_name: 'Ada', last_name: 'Lovelace', email: 'ada@example.com' }, }); ``` Implement `BookingProvider` (`listVenues`, `searchAvailability`, `createHold`, `confirmHold`, `getBooking`, `cancelBooking`) to make any booking system bookable by AI agents. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # create-openbooking **A booking backend that AI assistants can book, in one command.** ```sh npx create-openbooking my-salon # or: npm create openbooking@latest my-salon ``` You get a small TypeScript project built on [OpenBooking](https://openbooking.sh): - **booking page** at `/book`, plus a one-line snippet for any website; - **Studio** dashboard at `/studio`; - **MCP** at `/mcp` for Claude, ChatGPT and other AI assistants, plus UCP and A2A; - **storage:** in memory, or Postgres when `DATABASE_URL` is set; - **ready for Vercel:** `npx vercel`; - **`AGENTS.md`** so AI coding tools know the rules. Edit `business.ts` for your staff, services, prices and opening hours, then `npm run dev`. Options: `--name "Studio Nord"`, `--no-install`. ## Learn more - [Recipes](https://github.com/openbooking-sh/openbooking/blob/main/docs/RECIPES.md) - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking) Apache-2.0 --- # @openbooking-sh/google-calendar **Google Calendar sync.** OAuth for Google Calendar, busy times that block availability, and bookings written to the calendar as events (updated and deleted with the booking). Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/google-calendar ``` ## Usage ```ts import { googleAuthUrl, exchangeCode, attachCalendarSync, googleBusySource, } from '@openbooking-sh/google-calendar'; ``` See `@openbooking-sh/hosted` for a complete wiring. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/hosted **Hosted, multi-business OpenBooking.** Everything behind app.openbooking.sh: sign-up and a self-serve setup wizard (with website import), Studio per business, booking pages, one MCP app that finds and books any listed business (`find_business`), password reset, email confirmation, rate limits, Google Calendar, emails, analytics and Slack notifications. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/hosted ``` ## Usage ```ts import { createHostedApp } from '@openbooking-sh/hosted'; const hosted = createHostedApp({ baseUrl: 'https://app.example.com', sessionSecret: process.env.SESSION_SECRET!, // plus Postgres stores, mail, google, analytics, ops: see the docs }); // hosted.app is a web-standard app; serve it anywhere ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/notifications **Booking emails with calendar invites.** Confirmation and cancellation emails for customers (with an `.ics` invite) and new-booking notices for the business. Sends through Resend or any `Mailer`, deduplicated so agent retries never email twice. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/notifications ``` ## Usage ```ts import { attachNotifications, ResendMailer } from '@openbooking-sh/notifications'; attachNotifications({ service, mailer: new ResendMailer({ apiKey: process.env.RESEND_API_KEY! }), config: { from: 'Studio Nord ', ownerEmail: 'owner@example.com' }, }); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/payments-stripe **Stripe deposits.** Takes the deposit of a booking on a Stripe Checkout page and refunds it by the cancellation terms. The engine only confirms a booking after Stripe says the deposit was paid, for that booking and that amount, so an agent can never skip the payment with a made-up token. Plain `fetch`, no Stripe SDK. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/payments-stripe ``` ## Usage ```ts import { BookingService } from '@openbooking-sh/core'; import { StripePayments } from '@openbooking-sh/payments-stripe'; const service = new BookingService({ provider, payments: new StripePayments({ secretKey: process.env.STRIPE_SECRET_KEY!, successUrl: 'https://example.com/booked', cancelUrl: 'https://example.com/book', }), }); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/postgres **Postgres storage.** Durable stores for everything OpenBooking keeps: bookings and holds (with a per-resource lock so two servers can never sell the same time), idempotency records, Studio activity, Cal.com records, and the hosted account, calendar, email and rate-limit stores. Works with `pg` pools and PGlite. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/postgres ``` ## Usage ```ts import { connectPostgres, migrate, postgresStores } from '@openbooking-sh/postgres'; const db = connectPostgres(process.env.DATABASE_URL!); await migrate(db); // idempotent; safe on every start const stores = postgresStores(db); // stores.bookings, stores.idempotency, stores.activity, stores.calcom, ... ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/provider-calcom **Cal.com connector (beta).** A `BookingProvider` for Cal.com (hosted) and self-hosted Cal.com, via the Cal.com API v2. Makes an existing Cal.com account bookable by AI agents with holds, consent and cancellation terms. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/provider-calcom ``` ## Usage ```ts import { CalcomBookingProvider } from '@openbooking-sh/provider-calcom'; const provider = new CalcomBookingProvider({ apiKey: process.env.CAL_API_KEY!, venue: { id: 'venue', name: 'Studio Nord', timezone: 'Europe/Oslo', currency: 'NOK' }, }); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/provider-memory **Configured booking provider.** A `BookingProvider` driven by a plain config: venues, staff or tables, services, opening hours, buffers, deposits and cancellation rules. Bookings go to a pluggable store: memory by default, Postgres via `@openbooking-sh/postgres`. Includes a demo salon and a demo restaurant. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/provider-memory ``` ## Usage ```ts import { createDemoSalonProvider, MemoryBookingProvider } from '@openbooking-sh/provider-memory'; const provider = createDemoSalonProvider(); // or: new MemoryBookingProvider(myConfig, { store: postgresStores(db).bookings }) ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/react **React booking widget and hooks.** A drop-in `` and the hooks under it (`useInfo`, `useAvailability`, `useBooking`), built on `@openbooking-sh/client`. The customer picks a time (held for a few minutes), reads the price and cancellation terms, ticks a box and confirms: nothing is booked before they do. Each action carries one idempotency key until it succeeds, so a retry after a network error never books twice. Times that need an online deposit are sent to the booking page. Works with React 18 and 19, renders on the server, and has no other dependencies. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/react ``` ## Usage ```ts import { BookingWidget } from '@openbooking-sh/react'; export function Book() { return ( console.log(booking.confirmation_code)} /> ); } // Or build your own form on the hooks: // … useAvailability({ date, service }) · useBooking() ``` Style it with CSS variables (`--ob-accent`, `--ob-bg`, `--ob-fg`, `--ob-radius`, `--ob-font`), or pass `unstyled` and write your own CSS against the `ob-*` class names and `data-ob-*` attributes. ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/server **One app for every agent protocol.** Mounts a `BookingProvider` on one web-standard app (Hono): MCP for Claude and ChatGPT, UCP, an A2A Agent Card, a public booking page with WebMCP, and OpenBooking Studio. Runs on Node, Vercel, Cloudflare, Deno and Bun. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/server ``` ## Usage ```ts import { createOpenBookingApp, listen } from '@openbooking-sh/server'; import { createDemoSalonProvider } from '@openbooking-sh/provider-memory'; const { app } = createOpenBookingApp({ provider: createDemoSalonProvider(), // or your own BookingProvider baseUrl: 'https://book.example.com', }); await listen(app, { port: 3000 }); // MCP at /mcp · booking page at /book · Studio at /studio · UCP at /.well-known/ucp ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # @openbooking-sh/studio **OpenBooking Studio.** The dashboard for the people running the business: calendar per staff member, bookings, customers, services, settings, insights, and a log of every AI agent call. Mount it on any Hono app; protect it with a token. Part of [OpenBooking](https://openbooking.sh): open-source booking that every AI assistant can use. ```sh npm install @openbooking-sh/studio ``` ## Usage ```ts import { createStudio } from '@openbooking-sh/studio'; const studio = createStudio({ service, token: process.env.STUDIO_TOKEN }); app.route('/studio', studio.app); ``` ## Learn more - [OpenBooking on GitHub](https://github.com/openbooking-sh/openbooking): the full SDK, docs and examples - [openbooking.sh](https://openbooking.sh) Apache-2.0 --- # Architecture ``` AI agents / platforms ┌──────────────┬───────────────┬──────────────┐ │ MCP client │ UCP platform │ A2A client │ └──────┬───────┴───────┬───────┴──────┬───────┘ │ /mcp │ /ucp/* │ /a2a (+ /.well-known/ucp, /.well-known/agent-card.json) ┌──────▼───────────────▼──────────────▼───────┐ │ @openbooking-sh/server (one Hono app) │ │ adapter-mcp adapter-ucp adapter-a2a │ ← thin protocol translation └──────────────────────┬──────────────────────┘ │ ┌──────────────────────▼──────────────────────┐ │ @openbooking-sh/core BookingService │ ← agent-safety lives here, once │ validation · idempotency · hold TTL · │ │ explicit consent · cancellation rules │ └──────────────────────┬──────────────────────┘ │ BookingProvider (the ONE interface you implement) ┌──────────────────────▼──────────────────────┐ │ provider-memory | your POS / PMS / calendar │ ← inventory + persistence └─────────────────────────────────────────────┘ ``` ## Packages | Package | Responsibility | Depends on | | --------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | `@openbooking-sh/core` | Domain model (zod), `BookingProvider`, `BookingService`, errors, idempotency, cancellation rules, time-zone helpers | `zod` | | `@openbooking-sh/provider-memory` | Configured provider (catalog + slot rules) on a pluggable `BookingRecordStore`; demo salon and restaurant | core | | `@openbooking-sh/postgres` | Postgres stores: bookings/holds, idempotency, Studio activity, Cal.com records; `migrate()` | core, provider-memory, studio, `pg` | | `@openbooking-sh/adapter-mcp` | Seven MCP tools, Streamable HTTP handler, stdio | core, `@modelcontextprotocol/server` | | `@openbooking-sh/adapter-ucp` | UCP profile, booking-session REST, availability extension | core, `hono` | | `@openbooking-sh/adapter-a2a` | Agent Card builder plus the SendMessage endpoint | core | | `@openbooking-sh/server` | Mounts everything on one Hono app; `listen()` for Node | all adapters, `hono`, `@hono/node-server`, `@modelcontextprotocol/hono` | | `examples/demo` | `pnpm dev` | server, provider-memory | | `@openbooking-sh/booking-page` | Public booking page and its JSON API (zod schemas, OpenAPI 3.1), manage links, JSON-LD, WebMCP | core, `hono`, `zod` | | `@openbooking-sh/client` | Typed fetch client for the booking page API; no dependencies, runs in browsers, edge and Node | none | | `@openbooking-sh/react` | React `BookingWidget` and hooks on the client; React is a peer dependency | client | | `@openbooking-sh/notifications` | Booking emails with .ics invites (`Mailer`: Resend, console, memory) | core | | `@openbooking-sh/google-calendar` | Google OAuth, busy-time source, bookings → events | core, provider-memory | | `@openbooking-sh/hosted` | Many businesses: accounts, settings → catalog, per-business runtime, the OpenBooking MCP app (`find_business`) | all of the above | | `bench` | Agent-success benchmark | server, provider-memory, MCP client | ## Who owns what The split matters. Every protocol must behave identically, and booking-system vendors should only have to think about inventory. **The provider** (`BookingProvider`) owns: - what exists: venues, resources, offerings, opening hours, prices, policies; - what is free; - atomic reservation. Its contract: 1. Every mutating method is atomic: it fully succeeds, or throws without side effects. 2. `createHold` reserves capacity **exclusively** until `expires_at`. Two overlapping holds for the same capacity must never both succeed. 3. Expired holds stop blocking inventory. Report them as `expired`. 4. Business failures throw `BookingError` with a specific code. Anything else is reported to agents as a retryable `provider_error`. **The `BookingService`** owns the agent-safety rules: - **Validation.** Zod at the boundary. Failures become a `validation_error` that lists every bad field. - **Idempotency.** - Every mutating call needs an `idempotency_key`. Same key and same request replays the result; same key and a different request is `idempotency_conflict`. - Concurrent calls with the same key share one execution. The in-flight entry is registered synchronously, before any `await`. - Only successes are stored, because failed calls changed nothing. - Replays return the **current** state of the booking. - **Hold TTL.** The engine computes `expires_at`; every hold response carries it. Reads present a past-expiry hold as `expired` even if the provider hasn't swept it yet. - **Expiry events.** Nothing runs when a hold lapses, so the engine announces it (`booking.expired`, operation `expire`) when something first notices: any read of the booking, or `service.sweepExpired()`, which a cron or timer should call so lapses nobody reads are still reported. A claim per booking (`expiryClaims`; hosted and `PostgresNotificationLog` use the email dedupe table) makes it at-most-once across instances. A crash between claim and delivery loses the event rather than repeating it. A hold confirmed or cancelled in time never emits. The event has no actor. - **Consent.** `confirm` requires `user_confirmed === true`, as does cancelling a _confirmed_ booking. Releasing a hold doesn't need it. - **Prerequisites.** - Customer details (name plus email or phone) are required before confirmation. - A `payment_token` is required when a deposit is due at confirmation. - **Cancellation rules.** The pure function `evaluateCancellation()`: - free before `free_cancellation_until`; - the late fee after that (for `non_refundable`, the paid deposit is retained); - not cancellable online once the booking has started. The provider just records the computed fee and refund. - **State idempotency.** Confirming an already-confirmed booking returns it, even with a fresh key. Cancelling an already-cancelled booking is a no-op. An agent that loses a response and retries with a new key therefore still can't double-book or double-charge. - **Events.** `onEvent` fires after every operation (operation, ok, booking id, status, error code, replayed). The demo logs it; the bench counts with it. **Adapters** only translate. They never call the provider directly. ## Lifecycle ``` search_availability ──► slots (with price, deposit, cancellation policy; not reserved) │ hold_slot ─────────────► booking { status: held, expires_at } ── TTL passes ──► expired │ │ │ update (customer/notes) │ │ confirm_booking(user_confirmed=true) ──► confirmed { confirmation_code } │ cancel_booking ────────► held: released (no fee) confirmed: needs user_confirmed; fee/refund per policy ──► cancelled ``` The UCP status mapping is in [SPEC-NOTES §1.5](./SPEC-NOTES.md#15-status-mapping). ## Agent-friendly design choices - **Few tools, flat inputs.** Seven tools, and `party_size` is an integer. Each tool description says what it does and does **not** do, e.g. "hold does NOT confirm". - **Responses tell the agent what to do.** Every booking response includes `next_step`, and every error includes `suggested_next_action`. Holds carry both `expires_at` and `expires_in_seconds`. - **Policy terms up front.** Search results and holds carry the cancellation policy (human-readable `description` plus structured fields) and the deposit terms _before_ confirmation. - **Opaque slot ids.** A `slot_id` encodes everything needed to hold it, so the agent doesn't re-send dates and times and can't get them wrong. ## Scaling beyond the demo - **Postgres.** `@openbooking-sh/postgres` makes everything durable and safe across instances. `PostgresBookingStore` reserves under a transaction-scoped advisory lock per venue resource (check overlap, then insert), so overlapping holds can never both commit. Updates take the same lock, and a confirm that turns blocking re-checks for overlaps: a late confirm whose hold lapsed and was re-booked fails with `hold_expired` instead of double-booking. Expiry is applied on read, so no sweeper job is needed. Run `migrate(db)` on start (idempotent, lock-serialised). - **Idempotency store.** `PostgresIdempotencyStore` (or your own `IdempotencyStore` on Redis/SQL) as `serviceOptions.idempotencyStore`. Two simultaneous first calls with one key run once, also across instances: the first to claim the key (an optional `claim()`/`release()` on the store; the Postgres store has them) runs, and the other waits for its result and replays it. A claim that is never finished, because its instance died, expires after 60 seconds. A store without `claim()` still joins calls per process only, so across instances both can run (inventory stays safe through the atomic store, and the later record wins). - **USP state.** The USP adapter (`@openbooking-sh/adapter-usp`, in progress) remembers who owns each hold, booking credentials (by hash), proofs it has already seen, and what request each `Idempotency-Key` was first used for. In memory by default, which is fine for one process. With more than one instance (serverless), pass `postgresStores(db).usp` as `createUspRouter({ state })`: otherwise a credential issued by one instance is unknown to the others and a replayed proof is caught by only one. Each check-and-record is one atomic statement, so two instances racing on the same proof or key cannot both win. - **Clock.** Inject a `Clock` for tests and simulations (`ManualClock`, the bench's `OffsetClock`). - **MCP.** `createMcpHandler` is stateless, so any instance can serve any request. Set `allowedHosts` to your public hostnames. ## Development notes - **Source-first packages.** Each package's `exports` has a custom `@openbooking/source` condition that points at `src/index.ts`. `tsc` (`customConditions`), vitest (`resolve.conditions`) and `tsx --conditions` all use it, so `pnpm dev`, `pnpm test` and `pnpm typecheck` need no build. Published consumers get `dist/`. - **Build.** `tsup` builds ESM plus `.d.ts` per package. - **Tests.** - Unit tests per package live in `packages/*/test`. - The end-to-end MCP test in `packages/server/test` drives the full Hono app with a real MCP client, in-process, on both protocol eras. - The bench smoke test runs every task with the scripted driver. --- # Hosted OpenBooking Many businesses on one deployment (`@openbooking-sh/hosted`): sign-up and Studio settings, Google Calendar sync, confirmation emails, one OpenBooking app across every business, and a public booking page per business. ```sh pnpm dev:hosted # seeds "Studio Nord"; Studio login demo@openbooking.sh / openbooking-demo ``` ## Routes | Path | What | | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `GET /signup`, `POST /api/signup`, `POST /api/login` | Owner accounts (email + password, scrypt; 7-day signed session token, revoked by logout or a password reset) | | `GET /studio`, `/studio/api/*` | Studio for the logged-in business, including **Settings** | | `ALL /mcp` | **The OpenBooking app**: `find_business` plus the seven booking tools, each taking `business_id` | | `/b/{id}` | The business: booking page for browsers, JSON index otherwise | | `/b/{id}/mcp`, `/b/{id}/ucp/*`, `/b/{id}/.well-known/*` | Per-business MCP, UCP and A2A card (same as a self-hosted single business) | | `/b/{id}/book/*` | Booking page API, manage links (`/book/manage/{booking}?code=`), confirm links (`/book/confirm/{booking}`), `llms.txt` | | `/b/{id}/usp/*`, `/b/{id}/.well-known/usp` | USP, when the owner turned it on (see below) | | `GET /b/{id}/embed.js` | The website snippet (see below) | | `GET /reset`, `POST /api/password/*`, `GET /api/verify-email` | Password reset and email confirmation | | `GET /oauth/google/callback` | Google Calendar connection | `{id}` is the business's URL name (`studio-nord`), fixed at sign-up, and is also its `business_id` and the venue id on its bookings. ## Self-serve setup Sign-up asks for the business name, type, city, owner name, email and password, and creates a business that is bookable straight away: the owner as the only staff member, typical services for the type (example NOK prices), weekday hours, and free cancellation until 24 hours before. The owner then lands on **`/setup`**, one short screen per step, each saved as they go: 1. **Import from your website** (optional): `POST /studio/api/import` reads their site and proposes address, phone, opening hours and services. Sources: schema.org JSON-LD, page meta and `tel:` links, and, when `ANTHROPIC_API_KEY` is set, Claude reading the home page plus up to two likely prices pages. Only public http(s) addresses are fetched (every redirect re-checked), with an 8-second timeout and a 1.5 MB cap; 10 imports per business per hour. 2. **Contact:** street, postal code, city, phone, one line about the business. 3. **Services:** name, minutes, price; add and remove rows. 4. **Opening hours:** one-tap presets, then any day adjusted. 5. **Team:** names ("just me" is fine). 6. **Live:** "Try it yourself" in ChatGPT and Claude, the booking page link, the Google step and the website snippet. Everything stays editable in Studio **Settings**, which also has the checklist and links. Settings are in owner terms (`BusinessSettingsSchema` in `@openbooking-sh/studio`): profile, opening hours per weekday, closed dates, staff, services (duration, price, who does it), one cancellation rule as percentages of the price, booking rules, email preferences, and whether the business is listed in the OpenBooking app. `catalog.ts` turns them into the provider configuration. Deposits are set per business once it connects its own Stripe account: see [Deposits (Stripe)](#deposits-stripe) below. ## Getting found: Google, website, social Studio Settings has a **Get found on Google and your website** card with copy buttons: 1. **Google Business Profile:** paste the booking page link under Bookings, so a Book button shows in Google Search and Maps. 2. **Website:** one line, pasted once (Wix custom code, Squarespace code injection, WordPress via WPCode, Webflow footer code, Shopify `theme.liquid`): ```html ``` It adds a floating Book button and a booking popup, turns existing links to the booking page (and elements with `data-openbooking`) into popup triggers, adds schema.org `LocalBusiness` data with the services, and registers the booking tools for browser agents (WebMCP) on the business's own site. Options on the tag: `data-label`, `data-color`, `data-position="left"`, `data-button="none"`, `data-structured-data="off"`, `data-agents="off"`. The booking page API allows any origin (CORS) for this; no cookies are involved. 3. **Instagram and Facebook:** the booking page link in the bio and the Book now button. The schema.org block is added by script, which Google reads; crawlers that don't run JavaScript see the booking page's own server-rendered data instead. ## Google Calendar Set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` (a Google Cloud OAuth web client with the Calendar API enabled, redirect URI `{BASE_URL}/oauth/google/callback`). Scopes: `openid email`, `calendar.events`, `calendar.freebusy`, `calendar.calendarlist.readonly`. Google requires app verification for these scopes before outside users can connect without warnings; plan for that. - **Busy time blocks availability.** Each staff member maps to a calendar (default: the owner's primary). Events there hide those times from search and refuse holds. OpenBooking's own events, free (transparent), cancelled and declined events don't count. All-day events block the day. - **Bookings become events** (on confirm) and are deleted on cancel. - **Failures.** Google down → bookings fail with a retryable error (we can't promise the time is free). Access revoked → Studio shows "reconnect", and bookings continue without Google. ## Deposits (Stripe) Each business connects **its own** Stripe account in Studio → Settings → Online payments: paste a restricted key that may write Checkout Sessions and Refunds (or a secret key). Money goes straight to the owner, not through OpenBooking. The key is checked with Stripe before it is saved, and Studio only ever shows its last four characters. - **Deposit.** The owner sets a percentage of the service price (0 = none). A service has a deposit only while Stripe is connected and it has a price. - **Booking page.** The button says "Pay {amount} deposit", and the lines under it say what the deposit is and what becomes of it if the customer cancels (free until when, and what is kept after). It sends the customer to Stripe Checkout; Stripe returns them to the page with the session id, and the page confirms the booking. The engine asks Stripe whether that session was paid, for this booking and this amount, so a made-up token never works. - **Confirmation email.** After a paid booking the customer's email says what was paid, repeats the cancellation policy, and says what happens to the deposit if they cancel. It reads the same fields the refund does, so the email and the refund agree. - **Cancelling.** The email links to the manage page, which says what cancelling costs right now before anything is pressed. While it is free, one press cancels and refunds. When a fee applies, or the free time ran out after the page was opened, the page asks once more before it charges. - **Agents** get `payment_required` with `payment_url` and `payment_token` (see [RECIPES](RECIPES.md)). - **Refunds** follow the cancellation rules and run automatically. If Stripe is down the booking is still cancelled and the call answers `refund_failed`; cancelling again retries safely. A late cancellation refunds the deposit minus the fee (a partial refund). Before it refunds, OpenBooking asks Stripe what has already been refunded on that payment (including refunds the owner made in the Stripe dashboard) and sends only the difference, so a retry never pays twice, even after Stripe has forgotten the idempotency key (it does after 24 hours). If it cannot read the refunds already made, it refunds nothing and answers `refund_failed` rather than guess. This needs the key to be able to read Refunds as well as write them. - **Customers who never come back.** Connecting the key also registers a webhook at `/b/{id}/stripe/webhook` (the key needs the Webhook Endpoints permission; Studio says when it could not). The signature is checked, and a payment for a hold that has since expired or been released is refunded in full. While the hold is still live the webhook answers 503, so Stripe delivers it again later. Duplicate or out-of-order deliveries never refund twice. Events for payments that did not happen (failed, expired, or a delayed payment not yet received) are acknowledged and ignored. - **A checkout nobody pays.** The customer pays nothing and the hold simply runs out, so the slot is free again. The Stripe payment page itself stays open for up to 24 hours; a payment made on it after the hold ran out is refunded as above. - **What the owner sees.** The booking drawer in Studio has a Payment line: waiting for payment, not paid, paid online or in person, and for a cancelled booking the refund the terms gave and what was kept. It says what is due, not that the money has arrived: check the payment in Stripe when in doubt. A deposit taken in person is never refunded by Stripe, so the owner hands it back. - **Staff in Studio** record a deposit taken in person without Stripe. - **Disconnecting** Stripe stops new deposits. Deposits already paid can then no longer be refunded automatically. The Stripe key sits in the business record as-is, like the Google tokens (not exported, not shown). ## Assistants booking through USP USP is a draft standard from Wix and Stripe that lets any assistant or platform discover and book a business, signing in with a key it makes itself (no accounts). It is **off** for every business until the owner turns it on in Studio → Settings → AI assistants, where they also choose how bookings happen: - **The customer confirms on a page** (recommended): the assistant holds a time and gets a link to `/b/{id}/book/confirm/{booking}`. The customer sees the time, price and cancellation terms and confirms there; nothing is booked before. - **The assistant books immediately:** its request confirms the booking, trusting that it asked the customer first. The business's profile is at `/b/{id}/.well-known/usp` (there is no profile at the root, because the root is not one business). USP's MCP binding (`/b/{id}/usp/mcp`, the `usp_*` tools) is off unless the deployment passes `uspMcp: true`; it then serves every business that has USP on, with the same consent setting. Businesses saved before the setting existed have no `assistants` block and count as off. For several instances or serverless, pass `uspState` (`postgresStores(db).usp`, which the Vercel entry does when `DATABASE_URL` is set): it holds owners, credentials and replay protection, shared by every instance and kept apart per business. When a platform calls, hosted fetches the platform's own profile (public internet only, cached, shared by all businesses) and uses only what both sides support. Protocol details are in [SPEC-NOTES.md](SPEC-NOTES.md#6-usp-universal-scheduling-protocol-draft). ## API keys for the business's own website A site with no backend (an AI-built static page, say) can call its business's booking API straight from the browser or from a function. In Studio → Settings → API keys the owner makes a key and gives it a name and one of two scopes: - **Read availability:** `GET /b/{id}/book/api/info`, `/availability` and `/openapi.json`. - **Read and book:** also holds, confirming, cancelling and reading a hold or booking (`/b/{id}/book/api/*`), and the business's MCP endpoint (`/b/{id}/mcp`). Send it as `x-openbooking-key: obk_…` or as `Authorization: Bearer obk_…`. A key works for its own business only. The secret is shown once; only a hash is stored. Studio lists each key with when it was last used and revokes it on its own, and each key is limited to 300 calls a minute. A bad, revoked or other business's key gets `401 invalid_api_key`, and a read key asked to book gets `403 insufficient_scope`. A business holds at most ten active keys, and closing the account deletes them. **A key is not a lock.** Public access still works without one, as before, so a visitor (or a scraper) can call the same endpoints with no key. What a key adds is a name for who is calling, a way to give a site read-only access, a limit per site, and a way to cut one site off. A key in a browser's JavaScript is visible to anyone who opens the page, so give a site that only shows availability a read key. UCP, A2A and USP are not governed by keys. Studio never accepts one. ## Emails Set `RESEND_API_KEY` (and `MAIL_FROM`, default `bookings@openbooking.sh`, which must be a verified Resend domain). Without it nothing is sent (`pnpm dev:hosted` prints them instead). - Customer: confirmation with an `.ics` invite and a manage link; cancellation with `METHOD:CANCEL`. - Owner: new and cancelled bookings, except ones staff made in Studio. - Deduplicated per booking, so agent retries never send twice. ## Owner accounts - **Password reset:** `/reset` emails a link that works once (it is tied to the current password hash) and expires in an hour. Saving a new password logs out every other session. - **Log out** ends every session of the account, not just that browser, so a copied token stops working at once. Tokens last a week. - **Email confirmation:** sign-up sends a confirmation link. With email enabled, a business is listed in the OpenBooking app (`find_business`) only after the owner confirmed it; its booking page and per-business MCP work straight away. Studio shows a "Confirm your email" step. - **Unsubscribe:** every customer email has an unsubscribe link and `List-Unsubscribe` / `List-Unsubscribe-Post` headers (RFC 8058 one-click). The link is a signed token naming the business and a SHA-256 of the normalised address (no address in it). `GET /unsubscribe` only shows a button, so mail scanners change nothing; the POST (also what a mail client's one-click sends) records the hash for that business. After that the address gets no emails from that business at all, confirmations and cancellations included, and the business is still told about bookings. The list is per business, keeps no address, and is deleted with the account. The business's own notices have no link: they are switched off in Studio. - **Rate limits** (`LIMITS` in `limits.ts`): login per email and per IP, sign-up per IP (and 100 an hour across all addresses), reset emails per email and IP, holds per IP and business. The IP comes from `x-real-ip` / `x-forwarded-for`, which Vercel sets; pass `clientIp` when running without a proxy. See [Abuse and capacity](#abuse-and-capacity) for what is and is not limited. ## Storage Everything stateful sits behind an interface with an in-memory default, and `@openbooking-sh/postgres` implements all of them. `postgresStores(db)` returns them ready to pass to `createHostedApp`: | Option | Interface | Postgres | Notes | | ----------------- | --------------------- | --------------------------- | ------------------------------------------------------------ | | `businesses` | `BusinessStore` | `PostgresBusinessStore` | JSON record; unique id and lower-cased owner email. | | `bookings` | `BookingRecordStore` | `PostgresBookingStore` | One store for all businesses (venue id = business id). | | `idempotency` | `IdempotencyStore` | `PostgresIdempotencyStore` | Shared; hosted prefixes keys with the business id. | | `activityFor` | `(id) => ActivityLog` | `PostgresActivityLog` | One `scope` per business. | | `notificationLog` | `NotificationLog` | `PostgresNotificationLog` | Insert-if-absent, so no email goes out twice. | | `suppressions` | `SuppressionList` | `PostgresSuppressionList` | Unsubscribed addresses as hashes, per business. | | `apiKeys` | `ApiKeyStore` | `PostgresApiKeyStore` | Website API keys as hashes, per business. | | `calendarLinks` | `CalendarLinkStore` | `PostgresCalendarLinkStore` | Booking id → Google event. | | `rateLimiter` | `RateLimiter` | `PostgresRateLimiter` | Fixed windows shared by every instance. | | `uspState` | `UspStateStore` | `PostgresUspState` | USP owners, credentials, replay memory; scoped per business. | With `DATABASE_URL` set, the Vercel entry (`OPENBOOKING_MODE=hosted`) and `pnpm dev:hosted` use all of them and create the tables on start. ### Encrypting stored credentials A business record holds the owner's Google Calendar tokens and Stripe key (and its webhook secret). Set `TOKEN_ENCRYPTION_KEY` and they are encrypted (AES-256-GCM) before they reach the store, so a leaked backup or a copied database branch cannot use them. Each value is tied to its business and field. Make a key with `node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"` (32 bytes, base64 or 64 hex characters) and keep it in the environment, not in the database. - **Turning it on for an existing deployment.** Set the key, deploy, then call `GET /api/maintenance/encrypt-secrets` once with `Authorization: Bearer $CRON_SECRET`. It encrypts records written before the key existed (`{ businesses, encrypted }`) and is safe to repeat. Until then old records still work: plain values are read as they are and encrypted the next time their business is saved. A new key never rewrites already encrypted values. - **Without the key** new credentials are stored in plain text, and the Vercel entry logs a warning on each cold start in production. Set `TOKEN_ENCRYPTION_REQUIRED=1` to refuse to start without it. A record that already holds encrypted values and no key fails with a clear error instead of handing out ciphertext as a token. - **Losing or changing the key** makes the encrypted values unreadable (`could not be decrypted`): the owner reconnects Google and re-enters the Stripe key. There is no rotation yet: changing the key means re-connecting every business. The `enc:v1:` prefix leaves room for a second version. - **Not covered.** Backups made before the key was set still hold the old plain values. Session tokens, USP credentials and the password hash are not part of this (the last is a hash already). ## Customer data A customer can ask the business what it holds about them, or to delete it. The owner does it in Studio, under **Settings, Customer data**: enter the customer's email address or phone number, then download their data (a JSON file of their bookings) or delete it. Deleting removes the name, contact details and notes from their bookings. The bookings themselves (time, service, status) stay, so the calendar history and statistics remain right. Phone numbers match on their digits, email addresses ignore case. - **Upcoming bookings are kept.** A held or confirmed booking that has not ended yet is counted but not touched, so the business still knows who is coming. Cancel it first to erase it too. - **Retention.** Customer data is removed from every booking that ended more than `retentionDays` ago (default 730). `GET /api/maintenance/purge` applies it; `vercel.json` runs it daily. It needs `CRON_SECRET` set (Vercel sends it as a bearer token) and does not exist without it. - **Lapsed holds.** Nobody runs a job when a hold expires, so `booking.expired` is sent when something notices. The same daily purge now sweeps every business for lapsed holds, and `GET /api/maintenance/sweep` (same secret) does only that, for a more frequent cron. Vercel Hobby allows daily crons only; add a minute-level cron on Pro, or call the endpoint from any scheduler. - **What this does not reach.** Events already written to the owner's Google Calendar, emails already sent, and anything a webhook already delivered to an integrator are outside OpenBooking's storage. The owner has to remove those themselves. - **Self-hosted servers** can offer the same by passing `dataRights` to `createStudio`; the stores' `anonymize()` does the work. ### The owner's own data Under **Settings, Your account** the owner can download everything stored about the business (account, settings and every booking, as JSON; never the password hash or Google tokens) and close the account. Closing asks for the password and deletes, in this order: calendar links, activity and booked-via attribution, idempotency records, all bookings, and last the account itself, so a failure half way leaves an account the owner can still log into and retry. The booking page stops working and the id is free to register again. - Upcoming bookings are not cancelled and customers are not told. The owner should cancel or move them first. - The Google connection stays authorized in the owner's Google account until they remove it at myaccount.google.com/permissions; events already in their calendar are theirs and stay. - Expired rate-limit windows (keyed by IP address) are deleted by the same daily purge. - A store that lacks `BookingRecordStore.deleteVenue` or `BusinessStore.delete` makes closing refuse with 501 before anything is touched. ## Agent log and consent evidence Studio's **Agent log** lists every call an assistant made. For a confirm, a move or a cancellation that went through on `user_confirmed: true`, the entry also keeps what the booking said at that moment: service, time, party size, price, deposit and the cancellation terms (the text an agent must show the user), plus the fee and refund when cancelling. With the agent's name, protocol and the time, that answers "what did the customer agree to, and through whom". It shows under the action in the log and in the booking's history. - It names no customer: no name, email, phone or notes. The booking itself holds those and is erased with the customer. An entry is kept as long as the business's activity log is. - It records what the caller _claims_ the user approved. OpenBooking cannot see the conversation, so this is evidence of the terms shown to the agent and of the flag it sent, not a signature. - Replays (a retry with the same idempotency key) and releasing a hold carry none: nothing new was approved. Entries from before this change have none either. ## Observability All optional, set as environment variables on the Vercel project: | Variable | Tool | What it does | | ----------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SENTRY_DSN` | Sentry (EU region) | Server errors plus anything logged with `console.error` (failed emails, calendar syncs). No IPs, cookies or request bodies. | | `POSTHOG_KEY`, `POSTHOG_HOST` | PostHog (EU cloud by default) | Server events keyed by business id: `business_signed_up`, `email_verified`, `website_imported`, `google_calendar_connected`, `password_reset`, `slot_held`, `booking_confirmed` and `booking_cancelled` with their channel. Plus a cookieless browser snippet on owner pages (sign-up, setup, Studio), never on customer booking pages or the password reset page. It counts page views only: no autocapture, heatmaps or session recording, and all text is masked. | | `SLACK_WEBHOOK_URL` | Slack incoming webhook | Operator notifications: new business, email confirmed, Google connected, every booking and cancellation with its channel, server errors (at most one a minute). Business names only. Previews prefix `[preview]`. | No customer names, emails or phone numbers are sent to any of them. Background work (emails, calendar sync, analytics, Slack) finishes after the response through `waitUntil(hosted.idle())`. ## Cold starts Each new function instance logs one line, with stage names and milliseconds only: ``` [openbooking] cold start: imports=1900ms db_connect=850ms migrate=12ms app=6ms boot=870ms ``` - `imports`: process start until the entry module finished loading (Node start, bundle load; the largest single dependency is `@sentry/node`). - `db_connect`: opening the first Postgres connection: TCP, TLS, login, and a Neon compute waking from idle. This is the stage to check first when a cold start takes seconds. - `migrate`: the schema check. An up-to-date database costs one query; only a database with pending migrations takes the advisory lock, so instances booting together still serialise. - `app`: building the hosted app (stores, routes). Tenants are built lazily per request. Measured locally (PGlite, so no network): `app` is 2 to 5 ms, the up-to-date `migrate` is one query, and module loading dominates (Sentry alone is about 1 to 3 seconds on a loaded laptop). A real cold start adds what only production shows: Neon waking a suspended compute (typically a few hundred milliseconds up to a couple of seconds) and the round trips between the function and the database. Settings that matter, none of them code: - Keep the Vercel function region (`regions` in `vercel.json`, now `fra1`) in the same region as the Neon project, otherwise every query pays a transatlantic round trip. - Use Neon's pooled connection string (`-pooler` host) for `DATABASE_URL`. - Turn off Neon's scale-to-zero for the production compute (or lengthen the suspend delay), so the first request after a quiet period does not wait for the compute to start. ## Abuse and capacity An audit of what a stranger on the internet can do, and what happens when the free plans run out (OPE-89). What the code does is checked against the code; the plan limits are not, so read the numbers in your own Neon and Vercel dashboards. **Limited in code** - **Sign-up, login, password reset, unsubscribe:** per IP, plus per email where there is one, and a 100-an-hour cap on sign-ups across all addresses (each sign-up sends an email). It is counted only after the per-IP check, so one noisy address cannot use it up for everybody. - **Holds:** 20 per IP, per business, per 10 minutes. The count lives in the same limiter as the account limits (Postgres in production), so it survives cold starts and is the same on every instance. Before this it lived in each process and reset on every cold start. - **Request size:** every request body is capped at 256 KB (`maxBodyBytes`), 413 above it. Vercel itself stops bodies over 4.5 MB. Names, emails, ids and payment tokens in a booking request have length caps in `@openbooking-sh/core`; notes were already capped at 500 characters. - **Studio:** every `/studio/api` call needs a session. Importing a website is 10 an hour per business; deleting an account is 5 per 15 minutes. - **Stripe webhook:** signature checked before anything is read as an event. **Not limited in code (known gaps)** - **Reads.** Availability, the booking page and the MCP tools that only look (`find_business`, `get_business_info`, `search_availability`) have no limit. Every limiter check is itself a Postgres write, so counting reads would add database load instead of removing it. A scraper can keep the Neon compute awake and spend its hours. The fix belongs in front of the function: a rate-limit rule in the Vercel Firewall (a dashboard setting, not code). Keep it generous: AI assistants often share a few IP addresses, and a tight per-IP limit would block real customers booking through them. - **Slot hoarding from many addresses.** A holder with many IPs can hold every slot until the holds expire. Holds are short-lived and cost nothing to release, so this is a nuisance, not a double booking. Nothing is confirmed without `user_confirmed`. - **Fake sign-ups under 100 an hour.** They are real rows and real emails. Email confirmation keeps them out of the OpenBooking app (`find_business`) until the owner clicks the link. - **Self-hosted `createOpenBookingApp`** has the hold limit but no body cap; put a limit in front of it (most proxies have one). **Plan limits (cannot be fixed in code)** - **Connections.** Each function instance opens up to 3 Postgres connections (`max: 3` in `api/index.ts`), and a busy moment starts more instances. Use Neon's pooled (`-pooler`) host so those share a pool; without it a burst can hit the plan's connection limit and requests fail with a connection error. - **Compute hours.** Neon's free compute sleeps when idle and wakes in a few hundred milliseconds to seconds. Steady traffic, including scrapers, stops it sleeping and uses up the monthly hours. When they are gone the database stops answering until the month turns or you upgrade. - **Storage and branches.** The free project has a storage cap. Preview branches count (OPE-97). - **Vercel.** The free plan has monthly caps on function invocations and CPU time, and its terms limit it to non-commercial use: read them before taking payment from real customers. - **What failing looks like.** Out of connections, hours or storage, a request ends in a 500 (the app logs the error, and Sentry gets it if `SENTRY_DSN` is set). Nothing double-books, because the Postgres booking store does each check-and-reserve in one transaction under a lock. - **Watch:** Neon's usage page (compute hours, storage, connections) and Vercel's usage page once a week, and see OPE-90 for alerts. ## Not done yet - A per-business "require a key" switch (today keys identify and limit callers but do not lock the public API), and a key restricted to named website origins. - Custom domains or subdomains per business (paths only: `/b/{id}`). - Inbound calendar changes: an event moved or deleted in Google doesn't change the booking. - Rotating `TOKEN_ENCRYPTION_KEY` (a changed key means businesses reconnect). - Outlook (Nylas) and rescheduling. - A customer who pays in time but never returns is refunded, not booked (we do not keep their details until they come back). - Per-agent rate limits beyond the hold limit (see "Abuse and capacity").