Nexunia: an AI that orchestrates specialized agents, audited at every step
Over 8 years designing AI architectures led me to Nexunia: a multi-tenant SaaS platform where an AI orchestrates specialized agents — omnichannel customer service, voice, bookings, payments, customer reactivation, social media, website management, SEO, online stores and full verticals — and none of them touches a system directly. Every business action goes through a proprietary tool gateway, exposed as an MCP server, that validates the tenant, executes against the real backend and audits. This is what is built today, taken from the repository itself.
- 14
- applications and 5 packages in one monorepo
- 85
- tools in the MCP Tool Gateway
- 239
- data models, across 358 migrations
- 257
- documented architecture decisions (ADRs)
- ~11,700
- test cases, 23 suites against a real Postgres
- 15
- published specialized agents, plus sector modules
Measured on the repository on October 16, 2026.
The pieces that make this trustworthy
A modular monolith (NestJS, 92 modules) with rules that are not up for negotiation: each one is written down, enforced by tests or CI, and almost all of them were born from a real problem.
AI interprets, the system decides
The model understands intent and requests a tool; the backend validates, executes and confirms. The model never sees third-party credentials, never runs free SQL and never performs a business action on its own.
Tool Gateway as an MCP server
A single implementation of every tool, exposed over the real MCP protocol. It validates the session's tenant, executes, and logs every call. There is one client/server pair per conversation, and the trust boundary is set by the gateway itself, not by the network.
Multi-tenancy with RLS from day one
One shared database with Row-Level Security forced from the first migration, with an application role that has no BYPASSRLS. Each transaction sets the tenant in the Postgres context, and the identifier is always resolved from the authenticated session, never from the body or the query.
Own booking, no double-booking
An appointment only exists once the backend returns a real identifier. Three layers: a unique idempotency key, application validation and a partial unique index in the database, tested with simultaneous requests for the same slot. External calendars are a sync target, never the source of truth.
RAG limited to FAQ, never pricing or availability
Semantic search answers frequently asked questions and documentation. Pricing and availability live in structured tables and are queried in real time; they are never generated as free text.
An audit trail for every tool
Every execution is logged with tool, parameters, result, duration, conversation and tenant, with personal data redacted before persisting (stricter for healthcare businesses). The same table feeds the duplicate guards and can be queried from the panel.
Human handoff at any point
A human takes control over WhatsApp, voice, email or web and hands the conversation back to the AI without losing context. Explicit states: AI active, human requested, assigned, human active, resolved. On voice, the call is transferred live to a phone or to SIP.
Encrypted third-party credentials
Each customer's secrets (telephony, calendars, stores, social networks) are encrypted with AES-256-GCM using a versioned keyring that allows key rotation. They never reach a prompt or a log.
AI disclosure enforced by code
The notice that the caller is talking to an AI is injected by a versioned, localized module (es, en, ca, pt) covering voice, chat, widget, Instagram and email. It doesn't depend on the model or on each customer configuring it.
Staging first, always
Nothing reaches production without passing through staging and being validated there, with a separate database project per environment. Open decisions are written up as ADRs before being implemented.
What runs underneath, and which model does what
Every provider sits behind its own adapter: no module imports an external SDK outside its adapter, and the language model can be swapped without touching business logic.
Application
Monorepo in TypeScript. NestJS API (modular monolith); website, customer panel and admin panel in Next.js with React and Tailwind, exported as static. Shared contracts with Zod.
Data and queues
PostgreSQL on a managed database provider, with pgvector, pgcrypto and btree_gist; Prisma as the ORM. Redis with BullMQ for queues, locks, idempotency and throttling: around 55 queues with their processors, from reminders and payment reconciliation to social publishing.
Edge and hosting
An edge and CDN provider for the frontend, edge functions for the webhook gateway, page rendering and the subdomain proxy, and object storage for files and backups. The API runs on a hosting provider, with a healthcheck and connection draining on every deploy.
Language models
A language model reasons in chat and in the classic voice engine, with the model pinned in code; a more capable one plays the synthetic customer in voice QA. A real-time voice provider powers the native streaming voice engine. A proprietary interface isolates each provider.
Voice and audio
A telephony provider with conversation relay and audio streaming, with calls migrated to a European region. Speech recognition and speech synthesis providers, selectable by language and customer.
Embeddings, images and search
An embeddings provider for the RAG (1,024 dimensions, with an alternative). Image generation with AI providers, labeled as AI-generated. SEO audits with a proprietary crawler on an edge browser renderer.
Payments and messaging
A payments provider for subscriptions, usage metering and deposits; a single telephony and messaging provider for WhatsApp, SMS and voice (a direct connection to the WhatsApp platform was rejected to avoid multiplying providers). Email and corporate mailbox providers for email.
Observability
Structured JSON logs with correlation IDs and secret redaction, shipped to an observability platform. Per-tenant product metrics, voice latency metrics, a public status page and per-tenant alerts in the panel.
The same conversation, any channel
Every channel reaches the same Agent Runtime and the same Tool Gateway: there is no separate agent per channel and no parallel integrations.
- Voice: inbound and outbound calls — Available
- WhatsApp (with automatic signup) — Available
- Web chat (embeddable widget) — Available
- Email (corporate mailboxes) — Available
- SMS (notifications) — Available
- Instagram: DMs and comments — Beta on request
- "We call you" button — Beta on request
- Internal messaging: operations bridges — Internal
- WhatsApp: each business has its own telephony account and subaccount, created with integrated signup. Templates approved by the messaging platform are provisioned automatically per customer.
- Appointment reminders with Confirm / Change / Cancel buttons; the reply is read by a deterministic parser, never by the model.
- Respects WhatsApp's 24-hour window, normalizes formatting and returns the real result of the send, not an assumption.
- Web widget: an embeddable ES module with no login, with templates, an animated-orb avatar, a configurable launcher, quick replies and draft/publish.
- Email: AI-drafted replies with human approval, a periodic digest and learning from corrections.
- Instagram: DMs with WhatsApp parity and a comments agent that proposes drafts; a private reply to a comment can end in a real booking.
The most demanding channel: the phone is answered by AI too
Voice runs on a telephony provider and shares the same Agent Runtime and Tool Gateway MCP as every other channel. It is the channel with the most time in production and, for that reason, the one with the most accumulated mechanical guards.
- Nexunia Engine (the classic engine): the telephony provider's conversation relay in text transport, with a language model and MCP tools. Speech recognition and synthesis selectable per customer among several providers; Catalan uses specific providers.
- Nexunia Real Time Intelligence: audio streaming from the telephony provider into a real-time voice provider. Incremental per-sentence output with a semantic guard that switches to a full buffer on a tool call. It is the recommended engine for new customers and is enabled by plan entitlement.
- There are eleven engine identifiers in the code. The pilots (several real-time voice providers) are evaluated with real calls and only those that pass QA are promoted.
- Four separated responsibilities: telephony transport, audio engine, reasoning and business tools, which are always the authority.
- Spanish, English, Catalan and Portuguese, plus an automatic mode that answers in the caller's language (on voice, limited to es/en/ca with a heuristic on the first turn).
- The anti-hallucination guards cover all four languages at once.
- 24-hour appointment reminders, confirmations and change notices, with a deterministic greeting that confirms identity before revealing any data. If a voicemail picks up, it hangs up and reinforces over WhatsApp.
- Reactivation (recall) campaigns and, in beta, outbound sales calls for prospecting or reactivation, with clear identification and an immediate opt-out on the call itself.
- A public demo call, a test call from the panel and a manual click-to-call that bridges the customer to a person's phone, with no AI.
- Never unsolicited sales campaigns or predictive dialers.
- The outbound guard service applies, in several steps: per-tenant suppression and Do Not Call list, quiet hours and the recipient's local time, per-country destination policy, a guard for US healthcare numbers and marketing-consent evidence.
- Opt-out intent detection during the conversation, and unsubscribe by link.
- Real rescheduling during quiet windows, not just skipping.
- A handoff tool transfers the live call to a phone or to SIP, with recording and transcription of the human leg.
- A process recovers abandoned handoffs. The classic engine resumes the AI after the transfer and runs a silence clock ("are you still there?").
- Recording and transcription with a legal notice, a player in the inbox, configurable retention, export and audited playback.
- A summary and outcome classification for every call, and transcript translation.
- The Auditor role gives read-only access to conversations and recordings.
- A voice and WhatsApp setup wizard for a non-technical customer: they never see telephony or messaging technical jargon. It works with draft, publish, an immutable snapshot and rollback.
- Automatic provisioning: a telephony subaccount per customer, a Spanish voice number from a pool with automatic rental, and WhatsApp registration.
- Connection of the customer's own PBX over SIP.
- A per-customer selector for inbound and outbound engine, synthesis provider and voice, with a pilot gate and plan entitlement.
- A call robot with an LLM-based synthetic customer, different from the model under test, places real calls to a platform telephony number, only in local and staging.
- Campaigns of dozens of real calls document every finding, and the guards come out of them. Voice latency metrics in the admin panel and reconciliation of calls and costs against the telephony provider.
Guards matter as much as features
A language model can sound confident without being right. That is why the runtime includes a set of mechanical guards, hardened one by one from real calls, not just in theory.
Unbacked claims
Multilingual detectors that stop the model from saying it booked, cancelled, has availability or escalated without a real tool result behind it. They also apply to drafted emails.
Fingerprinted confirmation
Before writing, the AI asks for confirmation and a pending action is created with a deterministic fingerprint. Create, cancel or reschedule are rejected if the parameters differ from what was confirmed.
Real slots only
If the model announces a time that is not among the real slots, it is rejected and the backend returns the exact list.
Dictated phones and emails
They check that the digits or letters sent match what the customer dictated, before using them.
Durable write ledger
A customer interruption (barge-in) can't make the AI deny an appointment that exists or create it twice: the state comes from the execution log, not from the turn's memory.
Native-engine guards
In the native-reasoning engines, a semantic guard reviews every turn, and service selection, spoken time reading and the intent classifier are deterministic.
Closing and silence
Hang-up after a mutual goodbye, an inactivity prompt, and a check that internal notes are never heard on the call.
Domain guards
Specific rules for restaurant orders, academy enrollments and product sending, with guards against false denial and false sending.
Identity on sensitive actions
Configuring the business through chat requires a member with a sufficient role and, over voice, an OTP verified through WhatsApp, because caller ID can be spoofed.
Fifteen specialized agents, not just a chatbot
"Available" means it can be bought and it works; "beta on request" means it really works but is enabled by hand, case by case. Each agent is a module with a real backend, controlled by plan and enabled per customer.
Serve and sell
Customer service
AvailableWhatsApp, phone, web chat and email in a single inbox. Checks real availability, manages bookings and allows handoff at any point.
Quotes
AvailableA PDF with a public link by email or WhatsApp, and payment through the already configured method. In clinics it adds an AI-generated treatment plan, in beta.
Lead qualification
AvailableAsks one or two questions before offering slots and alerts the team if the lead does not meet the criteria, without ever blocking the booking.
Follow-up
Beta on requestOpens a case per contact, with status and next action, and follows up on the same channel as the last contact.
Sales calls ("We call you")
Beta on requestProspecting and reactivation by voice, with clear identification and immediate opt-out. An embeddable form calls whoever leaves their phone number.
Instagram (DMs and comments)
Beta on requestReplies to messages and comments with drafts and learning; a private reply can end in a booking.
Bookings and retention
Waitlist
AvailableNotifies over WhatsApp or voice only when a slot that fits opens up, with offer expiry.
Deposit
AvailableThe appointment is only created once the payment is recorded as received. The money always goes straight to the business; Nexunia is never an intermediary.
Customer reactivation (recall)
AvailableCampaigns over WhatsApp, voice, SMS or email with priority order between channels, respecting consent, hours and the do-not-call list.
Call recording
AvailableRecords and transcribes with a legal notice, configurable retention and audited playback.
Web, social and ranking
Social media
Beta on requestAdapts a piece to Instagram, X, TikTok, Threads and LinkedIn, with preview, scheduling and a publishing queue. Today it really publishes on X; the rest are enabled network by network.
Website management
Beta on requestMaintains content through chat on sites hosted in a code repository, a CMS or an online store, with a preview before publishing.
Search engine ranking
Beta on requestA read-only on-page SEO audit with a proprietary crawler and recommendations ordered by impact.
Store and stock
Online store management
Beta on requestSyncs the catalog, recommends products, looks up orders and customers, creates payment links and sends the product photo and link over WhatsApp or email, also from calls.
Stock control
AvailableAlerts on low stock and recommends how much to reorder, inside the restaurant hub.
Restricted access
Support agent
AvailableEach business's ticket board towards its own customers, with threaded replies.
Conversation translation and staff rota
Beta on requestAdd-ons for multilingual teams and for restaurants with shifts and rotation.
- Loyalty: sync with email marketing — Roadmap
- Search engine advertising — Roadmap
- Competitor analysis — Roadmap
- Website performance audit — Roadmap
- Content design — Roadmap
- Accounting assistant — Roadmap
- Financial analysis — Roadmap
- Automatic reports — Roadmap
- Proactive stock reordering — Roadmap
Eighty-five tools, one door
There are three MCP surfaces and a single real implementation of every tool, which validates, executes and audits. The tenant always comes from the session or the conversation, never from the model, and each agent only sees the tools enabled in its configuration, its modules and its plan.
- Knowledge and catalog: FAQ search, offerings, products, services and product sending.
- Calendar and waitlist: availability, slot proposal and selection, confirmation request, create, reschedule and cancel, find my bookings, join the waitlist.
- Payments and quotes: deposit status and link, generate and send a quote, check payment and send a reminder.
- Service and support: handoff, callback request, tickets, ending the conversation and suggesting replies.
- Contact and identity: marketing consent, confirming details, lead qualification, OTP over WhatsApp.
- Email: search a thread, create a draft and send the reply.
- Commerce: look up orders and customers, active discounts and create a payment link.
- Restaurant (9): availability, reservations, menu, orders and dish recommendation. Academy (9): courses, groups, trial classes, enrollment and placement test.
- Business configuration through chat (23): create, update or delete services, staff, locations, closures, absences, members and stock.
- WebOps and SEO: bootstrap a site on a repository, a CMS or an online store and request an audit. Sales: record the outcome of a call.
- Meant for manual use with desktop AI assistants. It translates each tool into a backend call with a session's JWT and a fixed tenant per process.
- Stateless Streamable HTTP with OAuth 2.1 and RFC 9728 metadata. It only registers the tools allowed by the token scopes: reading and creating contacts, conversations and bookings.
- Capped at 600 requests per minute per session and 120 writes, with no JSON-RPC batches and deterministic idempotency keys. The server's instructions treat returned content as data, not commands, as a defense against prompt injection.
- Every call goes through the same checks: session, tenant, role, plan, module and add-on.
- Writes require the fingerprinted confirmation; actions on the business require an OWNER or CONTRIBUTOR member and, over voice, a verified OTP.
- Every execution is logged, with success or error and duration, and personal data is redacted before persisting.
Full verticals, not just conversation
A single core with composable capabilities: the business type proposes a configuration, but it is not the source of truth and does not force rewriting the scheduling engine. There are fourteen sector pages and sixteen business types in signup.
Restaurants
Live floor plan, concurrency-safe reservations, deposits with a payment link, QR menu with allergens and branding, Digital Waiter (a human confirms every order before the kitchen), kitchen, staff rota, stock and a menu on a custom domain with a subdomain per business. Serves in es, ca and en.
Language academies
Enrollment, classrooms, courses, terms, groups, timetable, trial classes, a placement test with an oral test, absences and teacher absence, payments, analytics and a family portal, with a teacher role and its "My classes" view.
Dental clinics and medical centers
A 24-hour reminder with Confirm, Change or Cancel, booking by professional and treatment, custom fields (allergies, medication), inactive-patient recovery, reviewable quotes and treatment plans, and "Mi sonrisa", a digital twin for the patient. A local read-only connector with dental practice software, with health data handled in strict mode.
Online sales
Integration with e-commerce platforms: catalog, orders, customers, abandoned carts, discounts and payment links; click tracking on product links and re-engagement.
Public administration
Routes the procedure to the right civil servant and manages calendars per department or per worker.
Services, workshops, gyms and lodging
Hair salons, beauty, physiotherapy, veterinary clinics, workshops, professional firms, gyms with capacity and waitlist, and lodging with 24-hour availability and sync with external calendars.
Each sector comes with a demo kit: example sites with fictional data, with the widget and the sector-tinted brand, generated by script.
A panel designed for non-technical people
More than 330 pages across the website and the panel, in Spanish, English and Catalan, with a four-space layout: Business, Chat Nexunia, Agents and Connections.
- A unified inbox with takeover, an email inbox with AI drafts, external calendars, notifications and active agents with "what needs your attention".
- Learning suggestions: the AI proposes improvements after a handoff on a call.
- Clients with a profile, appointment reminders, campaign sends and metrics for appointments, conversations and tool executions.
- Identity, hours, policies, tools, training, knowledge, voice, handoff to a human and do-not-call list.
- Knowledge from PDF, URLs with crawling, text and authenticated sources; custom data to ask the customer for.
- Chat and call testing, with history.
- Details, hours, services, availability, offers, closures and holidays, brand and logo, team and permissions.
- Connections: WhatsApp, phone with PBX and SIP, web chat, email, calendars, CRM (in beta), the dental practice software, stores, sites, Instagram and SEO audits.
- API access, AI assistants over MCP, webhooks, enterprise SSO, audit log, privacy and providers, rights requests and account closure with data export.
- A persistent assistant that configures the business through conversation, with permissions by role.
- The same pattern serves the platform administrator, with two-step confirmation before enabling or disabling a customer's modules.
- Signup with SSO and a partner code; marking the business needs suggests the channel, and there are nine progress steps with a pending-setup banner.
- Ten interactive guides per section (inbox, services, availability, agent, knowledge, channels, calendar, clients, metrics and billing) with lightweight telemetry on the step where each one is abandoned.
- Public documentation in its own portal and a version history inside the panel.
- Three text sizes, high contrast, bold, link underlining and reduced motion, plus light and dark themes.
- Panel and public site in es, en and ca with localized URLs, hreflang and translated routes; a CI guard checks that keys are never left untranslated.
- A widget with three templates, four typefaces, an animated-orb avatar in two to four colors and ten icons; custom design for emails, quotes and the menu.
- A tenant list with status and attention required, a profile with masked credentials and audited reveal, custom entitlements and a per-customer AI key.
- Support with tickets from every customer, manual number provisioning in countries without API inventory, per-customer economics, partners and test calls.
Isolation, privacy and cost under control
How each customer is isolated, how their data is protected and how cost is kept under control.
Verified isolation
More than 220 RLS policies and a test that reads the Postgres catalog and fails if a table with tenant_id does not have RLS enabled, forced and with a policy.
Roles and access
Eight roles per business (owner, contributor, reader, billing, chat operator, limited calendar, teacher and auditor). TOTP MFA, enforceable by role with a grace date. SAML SSO and remote MCP are enabled per customer.
Webhooks and perimeter
Payment webhook signatures verified at the edge and again in the API; every other provider (telephony, commerce, repositories, messaging, CRM and social networks) with its own verifiers and constant-time comparison. Rate limiting by real IP, size caps, anti-bot on public forms and SSRF protection on outbound requests.
Secrets and logs
Redaction of headers, tokens and keys in logs, blocking secret scanning in CI on new commits, and personal-data redaction in the audit trail, with a strict mode for healthcare businesses that fails closed.
Privacy by design
Consent per purpose and channel with evidence, rights requests with deadline tracking, export and deletion per contact, configurable retention and a suppression list. A pseudonymization layer toward the model exists, off by default and mandatory for healthcare businesses if enabled.
Compliance documentation
Records of processing, impact assessment, AI Act classification, a vendor matrix and a breach response plan.
Plans and entitlements
Five plans (pay-as-you-go Flex, Starter, Growth, Scale and Enterprise) modeled as plan, feature and entitlement, plus 17 add-ons and seven sector packs. The backend is the authority and the interface only reflects its entitlements.
Usage and billing
Eighteen usage types metered per customer, a configurable overage policy (block, allow and flag, or allow) and usage billing with the payments provider's meters, with event queues and reconciliation.
Cost per customer
Each customer has its own AI provider workspace and key, from a pool of pairs, to measure exact spend. Costs move from estimated to provisional to reconciled against the AI provider's and the telephony provider's usage APIs.
How we check that it keeps working
Tests at three levels
789 files and about 11,700 cases. 23 integration suites against a real Postgres (isolation, RLS coverage, anti-double-booking concurrency) running as the application role, and 12 Playwright E2E specs, including that one customer cannot see another's data in the UI.
CI with concrete gates
Formatting, monorepo build, lint, types, tests, a translation check and a locale-route check, an architecture guard on data access, and secret scanning. Least-privilege permissions by default and dependencies updated weekly.
Voice QA with real calls
Batteries of dozens of calls with a synthetic customer, telephony audit reports and a guard with its test for every finding.
Observability
Structured logs with correlation IDs, per-tenant product metrics, voice latency, per-tenant alerts and a public status page that probes the API, the website, the docs and the critical external providers.
Backups and deployment
A daily dump of the staging and production databases to R2. API deployment with migrations at startup, healthcheck and connection draining; the website through Git integration with a preview per branch.
Documented decisions
257 ADRs with context, discarded alternatives and consequences. An ADR does not authorize executing what it proposes, and any change to the base rules requires explicit approval.
Agents that work on the product itself
An internal platform that governs agents able to run real tasks: code, customer websites, store catalogs. All with least-privilege permissions, human approvals and audit.
- A model with agents, capabilities, runtimes, tasks, executions, steps, permissions, approvals, artifacts and audit, with global or per-tenant scope and RLS.
- Every execution references a concrete capability and is checked before it is created; deny by default, with batch auto-approval protected by TOTP and revocable autonomy grants.
- The runner runs an agent SDK in a local Docker image or as a cloud job, with per-capability limits on turns, cost and time; moving to the cloud is never automatic.
- Capabilities: development on repositories, code improvement and promotion, deploy rollback, customer bootstrap and content, menu, product and coupon edits on CMS and commerce platforms.
- Connectors for code repositories (PR and merge), for frontend hosting (deploy and rollback) and for CMSs; a dev-branch flow with preview and later promotion.
- From web chat, WhatsApp or internal messaging, an administrator launches tasks and approves actions; by voice, with an OTP over WhatsApp. Cost metering and credits per execution with its own API key.
Want to talk about how this gets built?
If you're evaluating building an AI agent that executes real actions, let's talk architecture, not just prompts.
Let's talk