@centerfy/sdk
v1.2.0
Published
Official TypeScript SDK for the Centerfy AI API.
Maintainers
Readme
Centerfy TypeScript SDK
The official TypeScript SDK for the Centerfy AI API. @centerfy/sdk gives you fully typed access to your Centerfy sub-account — CRM contacts, omnichannel messaging (email, SMS, WhatsApp, Facebook, Instagram), AI voice agents, knowledge bases, appointments, phone numbers, conversations, and call history — from Node.js or any JavaScript runtime with fetch. Every method, parameter, and response is typed, and every failure throws a typed error you can branch on with instanceof.
Installation
npm install @centerfy/sdk
# or
yarn add @centerfy/sdk
# or
pnpm add @centerfy/sdkRequires Node.js 18+ (which ships fetch natively). The SDK also works in any runtime that provides fetch — Deno, Bun, Cloudflare Workers, modern browsers — or you can supply your own implementation via the fetch option.
Quickstart
Create an API key in Centerfy → Settings → API & Webhooks, then:
import { CenterfyClient } from "@centerfy/sdk";
const centerfy = new CenterfyClient({ apiKey: "cfy_..." });
// List contacts
const { contacts, has_more } = await centerfy.contacts.list({ limit: 25 });
// Create a contact (or update an existing one matched by email/phone)
const created = await centerfy.contacts.create({
first_name: "Ada",
last_name: "Lovelace",
email: "[email protected]",
phone: "+14155550123",
});
// Have an AI agent write and send a message to that contact
const reply = await centerfy.messages.sendAi({
channel: "sms",
contact_id: created.contact_id,
agent_id: "AGENT_UUID",
prompt: "Welcome them and offer to book an intro call this week.",
});
console.log(reply.generated_message);Prefer the command line? The
@centerfy/clipackage provides an interactivecenterfyshell built on this SDK —npm i -g @centerfy/cli.
Configuration
new CenterfyClient(options) accepts:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| apiKey | string | — (required) | Your sub-account API key (cfy_...), sent as the x-api-key header on every request. Create and manage keys in Settings → API & Webhooks. |
| baseUrl | string | https://api.centerfy.ai | Override the API origin. |
| timeoutMs | number | 30000 | Per-attempt request timeout in milliseconds. |
| maxRetries | number | 0 | Automatic retries for 429 / 5xx responses and network failures. Retry-After is honored on 429; otherwise exponential backoff with jitter. |
| fetch | typeof fetch | global fetch | Custom fetch implementation (useful for testing or older runtimes). |
| defaultHeaders | Record<string, string> | {} | Extra headers to send with every request. |
Every SDK method also accepts an optional final options argument ({ signal?: AbortSignal, headers?: Record<string, string> }) for per-request cancellation and headers.
Error handling
Every failed API call throws a subclass of CenterfyError, so you can branch on the failure mode without string-matching messages:
import {
CenterfyError,
CenterfyNotFoundError,
CenterfyRateLimitError,
CenterfyValidationError,
} from "@centerfy/sdk";
try {
await centerfy.contacts.get("missing-id");
} catch (err) {
if (err instanceof CenterfyNotFoundError) {
console.log("Contact does not exist");
} else if (err instanceof CenterfyRateLimitError) {
console.log(`Rate limited — retry in ${err.retryAfterSeconds}s`);
} else if (err instanceof CenterfyValidationError) {
console.log("Bad request:", err.message, err.body);
} else if (err instanceof CenterfyError) {
console.log(`API error ${err.status} on ${err.request?.method} ${err.request?.path}`);
} else {
throw err;
}
}| Error class | Status | When |
| --- | --- | --- |
| CenterfyAuthError | 401 | The API key is missing, malformed, or revoked. |
| CenterfyForbiddenError | 403 | The key is valid but the account is not entitled to API access (plan gate). |
| CenterfyNotFoundError | 404 | The requested resource does not exist. |
| CenterfyValidationError | 400 / 422 | The request payload failed validation. |
| CenterfyRateLimitError | 429 | Rate limit exceeded. Exposes retryAfterSeconds from the Retry-After header. |
| CenterfyServerError | 5xx | The API encountered an unexpected server-side error. |
| CenterfyConnectionError | — | Network/transport failure (DNS, TLS, timeout, abort) — no HTTP response received. |
All errors carry status (0 for transport failures), the parsed JSON error body when available, and the request ({ method, path }) that failed.
Rate limits. The API allows 50 requests per minute per sub-account. On 429 the response includes a Retry-After header; set maxRetries on the client to have the SDK automatically retry 429 and 5xx responses, honoring Retry-After:
const centerfy = new CenterfyClient({ apiKey: "cfy_...", maxRetries: 3 });Pagination
List endpoints that page (contacts.list, conversations.list, calls.list) use limit/offset parameters and return total and has_more:
const all = [];
let offset = 0;
while (true) {
const page = await centerfy.contacts.list({ limit: 100, offset });
all.push(...page.contacts);
if (!page.has_more) break;
offset += page.limit;
}limit is 1–100 (default 50; values above 100 are capped) and offset defaults to 0.
API reference
Every method returns a Promise of a fully typed response and accepts an optional trailing RequestOptions argument (omitted below for brevity).
client.contacts
| Method | Description |
| --- | --- |
| list(params?) | List contacts, newest first, paginated (limit 1–100, default 50; offset default 0). |
| get(contactId) | Get a single contact by id. |
| create(params) | Create a contact — or update in place if one matches by email or phone (created: false). Requires email or an E.164 phone. |
| update(contactId, params) | Partial update; only the fields present are changed. tags replaces the entire tag set. |
| delete(contactId) | Permanently delete a contact (409 if still referenced by related records). |
| addTags(contactId, params) | Add (merge) one or more tags; values are lowercased, trimmed and de-duped. |
| removeTags(contactId, params) | Remove one or more tags; matching is case-insensitive, missing tags are ignored. |
| createNote(contactId, params) | Create a note on a contact (content 1–5000 characters). |
| listNotes(contactId) | List a contact's active notes, newest first. |
| deleteNote(contactId, noteId) | Delete a contact's note (soft delete). |
| makeAiCall(contactId, params) | Place an outbound AI phone call to the contact's phone on file. Requires agent_id; optional pool_id round-robins the caller-ID. |
client.tags
| Method | Description |
| --- | --- |
| list() | List the distinct contact tags in your sub-account, sorted A→Z, each with a usage count. |
client.phoneNumbers
| Method | Description |
| --- | --- |
| list() | List your owned phone numbers (active only), each with its assigned agent if any. |
| get(phoneNumberId) | Get a single owned phone number by id. |
| assignAgent(phoneNumberId, params) | Assign a number to an agent so its inbound calls route there. Idempotent for the same agent; 409 if assigned to a different agent. |
| unassignAgent(phoneNumberId) | Remove the agent from a number. Idempotent; the number stays active. |
client.numberPools
| Method | Description |
| --- | --- |
| list() | List your number pools with member numbers resolved, newest first. |
| create(params) | Create an empty number pool (name required). |
| get(poolId) | Get a single pool by id, including its member numbers. |
| update(poolId, params) | Rename a pool and/or replace its complete member set (phone_number_ids uses set semantics; [] clears). |
| delete(poolId) | Delete a pool; its number assignments are removed but the numbers stay in your inventory. |
| addNumber(poolId, params) | Add an owned number to a pool. Idempotent (already_in_pool: true). |
| removeNumber(poolId, numberId) | Remove a number from a pool; the number stays in your inventory. |
client.voices
| Method | Description |
| --- | --- |
| list(params?) | List the AI voices available for agents, optionally filtered by gender. Each voice's name is the identifier to use as an agent's voice_id. |
| preview(params) | Generate a spoken preview of a voice. Resolves with raw MP3 bytes (ArrayBuffer) rather than JSON. |
client.agents
| Method | Description |
| --- | --- |
| create(params) | Create an AI agent. Core configuration fields are required; conditional fields apply when their toggles are true. |
| list(params?) | List your AI agents, newest first. Pass active to filter active/paused. |
| get(agentId) | Get a single AI agent by id — the list fields plus system_prompt, inbound_greeting and outbound_greeting. |
| update(agentId, params) | Partial update — send at least one field; omitted fields keep their values. Includes system_prompt, inbound_greeting and outbound_greeting (""/null clears a greeting); the response echoes what was saved. |
| duplicate(agentId) | Duplicate an agent — full configuration, fresh id, "(copy)" appended to the name. |
| archive(agentId) | Archive (soft-delete) an agent — deactivated so it stops taking calls; phone and call history remain. Idempotent. |
| listCustomTools(agentId) | List the custom tools assigned to an agent (secrets are never included). |
| assignCustomTool(agentId, params) | Assign a custom tool to an agent. Idempotent (already_assigned: true). |
| removeCustomTool(agentId, toolId) | Remove a custom tool from an agent; the tool itself is untouched. |
| assignKnowledgeBase(agentId, params) | Connect a knowledge base to an agent (an agent has at most one — any existing connection is replaced). Optional max_results (default 5) and similarity_threshold (default 0.30). |
| removeKnowledgeBase(agentId, knowledgeBaseId) | Disconnect a knowledge base from an agent; only the link is removed. |
| testChat(agentId, params) | Text playground: send the conversation so far (messages, last one from the user) and get the agent's next reply, produced like the live chat channels. Nothing is saved. Tools are simulated by default (mock_tools, per-tool tool_results); pass mock_tools: false to run them for real. |
client.agentFolders
| Method | Description |
| --- | --- |
| create(params) | Create an agent folder (name required; optional hex color, default #3b82f6). |
| list() | List your agent folders, oldest first. |
| update(folderId, params) | Partial update — name and/or color, at least one required. |
| addAgent(folderId, params) | Assign an agent to a folder. An agent belongs to at most one folder, so this re-homes it. |
| removeAgent(folderId, agentId) | Remove an agent from a folder, moving it back to the root. |
| delete(folderId) | Delete a folder. The folder must be empty (409 otherwise). |
client.customTools
| Method | Description |
| --- | --- |
| create(params) | Create a custom tool (name, description, url, method required). Created unassigned — attach to an agent separately. |
| get(toolId) | Fetch a custom tool by id. The stored API-key secret is never returned (has_api_key indicates whether one is set). |
| update(toolId, params) | Partial update — only the fields you send change; at least one required. |
| delete(toolId) | Delete a custom tool, unlinking it from every agent first (409 for tools registered on the voice engine). |
client.knowledgeBases
| Method | Description |
| --- | --- |
| list() | List your knowledge bases, newest first, each with source counts. |
| create(params) | Create a knowledge base (name required and unique). Optional chunk_size (default 1000) and chunk_overlap (default 200). |
| delete(knowledgeBaseId) | Delete a knowledge base including its documents and text entries. |
| enable(knowledgeBaseId) | Enable a knowledge base so its agents can retrieve from it. Idempotent. |
| disable(knowledgeBaseId) | Disable a knowledge base; its data is kept. Idempotent. |
| addText(knowledgeBaseId, params) | Add a plain-text source (title, content; entry_type "text" or "snippet"). Embedded asynchronously. |
| addFaq(knowledgeBaseId, params) | Add an FAQ source (title plus non-empty faq_pairs); pairs are combined into one entry and embedded asynchronously. |
| addUrl(knowledgeBaseId, params) | Add a URL source; the page is fetched, chunked, and embedded asynchronously. |
| addFile(knowledgeBaseId, file, filename?) | Add a file source via multipart upload (.pdf, .docx, .xlsx, .txt, .csv). xlsx is queued (processed: false); the rest process inline. |
| deleteSource(knowledgeBaseId, sourceId) | Delete any source — file/URL or text/FAQ — including its vectors. |
| get(knowledgeBaseId) | One knowledge base with every source in it (files, URLs, text, FAQ), newest first; text sources are previewed. |
| listSources(knowledgeBaseId, params?) | Sources with optional type / status filters and limit / offset pagination. |
| getSource(knowledgeBaseId, sourceId, params?) | One source with its full text (content, FAQ faq_pairs); include_chunks returns the embedded chunks — the only stored text for file and URL sources — paged by chunk_offset / next_chunk_offset. |
client.appointments
| Method | Description |
| --- | --- |
| list(params) | List appointments in a date range (from and to required, ISO 8601), ascending, each with its linked contact. Optional status and timezone; limit default 100, max 500. |
| get(appointmentId) | Fetch a single appointment by id, including its linked contact. |
| create(params) | Create an appointment (title, appointment_date, calendar_id required). The contact is resolved by contact_id or by email/phone (created if missing). |
| update(appointmentId, params) | Partial update — only the fields present change. |
| delete(appointmentId) | Permanently delete an appointment (409 if related records prevent deletion). |
client.messages
| Method | Description |
| --- | --- |
| send(params) | Send a message you wrote to a contact on a channel (email, sms, whatsapp, facebook, instagram). Email requires subject plus message or html. |
| sendAi(params) | Have an AI agent write and send a message to a contact, optionally steered by prompt. Returns the generated_message. |
| listForContact(contactId, params?) | Fetch a contact's most recent messages across every channel, oldest → newest. Optional channel filter; limit default 100, max 500. |
client.conversations
| Method | Description |
| --- | --- |
| list(params?) | List conversations (the inbox), newest first. Optional channel and status filters; offset paginated. |
| get(conversationId) | Fetch a single conversation by id. |
| listMessages(conversationId, params?) | List a conversation's most recent messages, oldest → newest. Optional channel filter; limit default 100, max 500. |
client.calls
| Method | Description |
| --- | --- |
| list(params?) | List call history, newest first, with resolved agent and contact names. Optional from/to, status, direction, and agent_id filters; offset paginated. |
| stats(params?) | Aggregate call metrics over an optional date range (default: last 30 days) — totals by direction and status, recordings, talk time. |
| get(callId) | Fetch a single call with full detail, including the transcript and AI summary. |
Examples
Make an AI call to a contact
const result = await centerfy.contacts.makeAiCall("CONTACT_UUID", {
agent_id: "AGENT_UUID",
pool_id: "POOL_UUID", // optional — round-robins the caller-ID
});
console.log(result.status, result.call_id); // e.g. "queued" / "initiated"Upload a knowledge-base file
Node.js:
import { readFile } from "node:fs/promises";
const bytes = await readFile("./pricing.pdf");
const upload = await centerfy.knowledgeBases.addFile(
"KB_UUID",
new Blob([bytes], { type: "application/pdf" }),
"pricing.pdf",
);
console.log(upload.processed, upload.document.total_chunks);Browser:
const file = document.querySelector<HTMLInputElement>("#file")!.files![0];
const upload = await centerfy.knowledgeBases.addFile("KB_UUID", file, file.name);Save a voice preview MP3
voices.preview resolves with the raw audio bytes as an ArrayBuffer:
import { writeFile } from "node:fs/promises";
const audio = await centerfy.voices.preview({
name: "Marissa",
text: "Hi! Thanks for calling — how can I help today?",
});
await writeFile("preview.mp3", Buffer.from(audio));Templated vs AI-generated messages
// You write the message
await centerfy.messages.send({
channel: "email",
contact_id: "CONTACT_UUID",
subject: "Your appointment is confirmed",
message: "Hi Ada — see you Thursday at 2pm.",
});
// The agent writes the message
const ai = await centerfy.messages.sendAi({
channel: "whatsapp",
contact_id: "CONTACT_UUID",
agent_id: "AGENT_UUID",
prompt: "Confirm Thursday's appointment and ask if they have questions.",
});
console.log(ai.generated_message);Project structure
The SDK source lives under src/. Each API resource is its own module, and the
client wires them together.
src/
├── index.ts Public entry point — exports the client, errors, and all types
├── client.ts CenterfyClient — groups every operation under a resource namespace
├── http.ts Fetch transport — auth header, timeouts, retries, query/body handling
├── errors.ts Typed error hierarchy (CenterfyError and subclasses)
├── resource.ts Base class shared by every resource (the _get/_post/… helpers)
├── types.ts Shared types (pagination, message channels, …)
└── resources/ One module per API resource — params + response types + methods
├── contacts.ts
├── tags.ts
├── phone-numbers.ts
├── number-pools.ts
├── voices.ts
├── agents.ts
├── agent-folders.ts
├── custom-tools.ts
├── knowledge-bases.ts
├── appointments.ts
├── messages.ts
├── conversations.ts
└── calls.tsA companion command-line interface is published as @centerfy/cli.
License
MIT
