# Overview (/docs/sdk)

`coss` is the official TypeScript SDK. It has zero dependencies, is fully typed and runs on
Node.js 22+, Bun, Deno and Cloudflare Workers.

```package-install
coss
```

## The client [#the-client]

One client covers every product. Create it once and reuse it. Each endpoint's page in the
[API reference](/docs/api-reference) shows its SDK call in the **TypeScript** tab; these pages cover
how the client itself behaves.

```ts twoslash
import { Coss } from "coss";

const coss = new Coss({ apiKey: process.env.COSS_API_KEY });
//    ^?
```

Hover any identifier in these examples to see its type.

## Products [#products]

The same client reaches every product. A short example of each, with its guide:

### Email [#email]

[Sending](/docs/email/sending), and [broadcasts](/docs/email/broadcasts) to a whole audience or segment:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
await coss.email.send({
  from: "Acme <hello@acme.com>",
  to: "ada@example.com",
  subject: "Welcome",
  html: "<p>It works!</p>",
});

const { data: broadcast } = await coss.email.broadcasts.create({
  name: "October newsletter",
  segment_id: "seg_01k7c8m4q2f3e9v6t5r1n0p8yz",
  from: "Acme <news@acme.com>",
  subject: "What's new",
  html: "<p>Hi {{{contact.first_name|there}}}</p>",
});
await coss.email.broadcasts.send(broadcast!.id);
```

### SMS [#sms]

[Text messages](/docs/sms) from your organization's numbers:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: sms } = await coss.sms.send({
  from: "+14155550123",
  to: "+14155550199",
  body: "Your order has shipped.",
});
```

### Verify [#verify]

[One-time codes](/docs/verify) by SMS or email:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
await coss.verify.start({ to: "+14155550123" });
const { data: check } = await coss.verify.check({ to: "+14155550123", code: "482913" });
console.log(check?.valid);
```

### Sign [#sign]

[E-signatures](/docs/sign) on your PDFs, embedded or by email:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const pdfBase64: string;
// ---cut---
const { data: request } = await coss.sign.requests.create({
  title: "Services agreement",
  documents: [{ filename: "agreement.pdf", content: pdfBase64 }],
  signers: [
    {
      name: "Ada Lovelace",
      email: "ada@example.com",
      fields: [{ type: "signature", anchor: "{{signature:signer_1}}" }],
    },
  ],
});
```

### Forms [#forms]

[Form endpoints](/docs/forms) for your site, with spam filtering and delivery built in:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: form } = await coss.forms.create({
  name: "Contact us",
  notifications: { recipients: ["support@example.com"] },
});
console.log(form?.endpoint);
```

### Scheduling [#scheduling]

[Bookings](/docs/scheduling) with your users' calendars and double-booking handled:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const eventTypeId: string;
// ---cut---
const { data: slots } = await coss.scheduling.slots.list(eventTypeId, {
  start: "2027-01-04T00:00:00Z",
  end: "2027-01-11T00:00:00Z",
});

const { data: booking } = await coss.scheduling.bookings.create({
  event_type: eventTypeId,
  start: slots!.data[0]!.start,
  attendee: { name: "Sam Lee", email: "sam@example.com", time_zone: "America/Chicago" },
});
```

### Inboxes [#inboxes]

[Email addresses for AI agents](/docs/inboxes), with threads and replies:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const messageId: string;
// ---cut---
const { data: inbox } = await coss.inboxes.create({ username: "support-agent" });

await coss.inboxes.messages.reply(inbox!.id, messageId, { text: "On it." });
```

### Hooks [#hooks]

[Webhooks as a service](/docs/hooks), delivered to your customers' endpoints:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: message } = await coss.hooks.messages.send({
  application: "customer_8812",
  event_type: "invoice.paid",
  payload: { invoice_id: "in_1042", amount: 4200 },
});
```

### Risk [#risk]

[Risk assessments](/docs/risk) of sign-ups, logins and other events:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: assessment } = await coss.risk.assess({
  event: "signup",
  user: { email: "ada@example.com" },
  ip: "203.0.113.7",
});
console.log(assessment?.decision, assessment?.reasons);
```

## Options [#options]

```ts twoslash
import { Coss } from "coss";
// ---cut---
const coss = new Coss({
  apiKey: "coss_test_...",
  baseUrl: "https://api.coss.com",
  timeout: 30_000,
  maxRetries: 2,
  dangerouslyAllowBrowser: false,
});
```

| Option                    | Default                                         | Description                                                |
| ------------------------- | ----------------------------------------------- | ---------------------------------------------------------- |
| `apiKey`                  | `COSS_API_KEY`                                  | A `coss_live_…` or `coss_test_…` key                       |
| `baseUrl`                 | `COSS_BASE_URL`, then `https://api.coss.com`    | The API origin                                             |
| `timeout`                 | `30000`                                         | Per-attempt timeout in milliseconds                        |
| `maxRetries`              | `2`                                             | Retries for network errors, timeouts, 409, 429 and 5xx     |
| `fetch`                   | global `fetch`                                  | A custom `fetch` implementation                            |
| `dangerouslyAllowBrowser` | `false`                                         | Allow running where `document` exists (exposes your key)   |
| `tracing`                 | `true`                                          | An OpenTelemetry span per call, when `@opentelemetry/api` is installed ([Tracing](/docs/api-reference/tracing)) |

The constructor throws only for programmer errors: a missing API key, or running in a browser
without `dangerouslyAllowBrowser`.

## Results, not exceptions [#results-not-exceptions]

Every method returns `{ data, error }`. API and network failures come back as `error`; they are
never thrown. Checking `error` narrows `data`:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const result = await coss.email.get("email_01k7c8m4q2f3e9v6t5r1n0p8yz");

if (result.error) {
  console.error(result.error.message);
} else {
  console.log(result.data.subject);
  //                 ^?
}
```

## Per-request options [#per-request-options]

Methods take an optional last argument. Every method accepts an `AbortSignal`; `send` also takes an
idempotency key.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
const params = { from: "a@acme.com", to: "b@example.com", subject: "Hi", text: "Hi" };
// ---cut---
const controller = new AbortController();

await coss.email.send(params, { idempotencyKey: "welcome-user-123", signal: controller.signal });
await coss.email.get("email_01k7c8m4q2f3e9v6t5r1n0p8yz", { signal: controller.signal });
```

## Any endpoint [#any-endpoint]

`coss.request()` calls an endpoint by its path, for one the SDK has no method for yet. It takes
the client's key, version, timeout and retries, and returns the response's JSON as `{ data, error }`,
unchecked (pass a type to describe it):

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data, error } = await coss.request<{ data: { id: string }[] }>("GET", "/v1/domains", {
  query: { limit: 5 },
});

await coss.request("POST", "/v1/domains/dom_01k7c8m4q2f3e9v6t5r1n0p8yz/verify");
```

GET and DELETE are retried like every other call; POST, PUT and PATCH only with `retry: true`,
since not every endpoint deduplicates them (saving a template's draft counts every attempt as a
revision). `responseType: "text"` or
`"bytes"` reads a body that isn't JSON (a CSV export, a received email's raw message).

## Diagnose a delivery [#diagnose-a-delivery]

`coss/diagnose` explains what happened to an email: a verdict, what each recipient's status means
(a bounce with the receiving server's reason, a suppression with its entry, a delay, a failure and
its cause), account problems that affect it and what to do next. `diagnose` reads the email, its
events and the account context it needs; `diagnoseEmail` is the pure part, for data you already
have. The CLI's `coss emails diagnose` and the MCP server's `diagnose_email` use it too.

The other products have the same: `fetchSmsDiagnosis`, `fetchVerificationDiagnosis`,
`fetchSignRequestDiagnosis`, `fetchFormSubmissionDiagnosis`, `fetchHookDeliveryDiagnosis` and
`fetchSchedulingSlotsDiagnosis` read what they need and answer with a verdict, a summary and next
steps, and `diagnoseSms`, `diagnoseVerification`, `diagnoseSignRequest`, `diagnoseFormSubmission`,
`diagnoseHookDelivery` and `diagnoseSchedulingSlots` are their pure parts.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
import { diagnose } from "coss/diagnose";

const { data, error } = await diagnose(coss, "email_01k7c8m4q2f3e9v6t5r1n0p8yz");
if (data) {
  console.log(data.verdict, data.summary);
  //               ^?
  for (const recipient of data.recipients) console.log(recipient.address, recipient.explanation);
}
```

## Runtimes [#runtimes]

The package is ESM-only and uses nothing but `fetch`, `AbortSignal` and `crypto.randomUUID`.
Environment fallbacks read `process.env` where it exists; on Workers or Deno without env access,
pass `apiKey` (and `baseUrl`) explicitly.
