# Onttle: Get Started (for AI agents)

You are an AI coding agent. Your user wants to use **Onttle** in their project. Follow this guide to set it up end to end, and ask the user only for the things you cannot do yourself (marked **👤 User action**).

Onttle is a headless CMS with a REST API. The user designs Tables in the Onttle dashboard, edits Contents there, and their application reads (and optionally writes) that data through the API.

- Dashboard: https://app.onttle.com
- REST API base URL: `https://api.onttle.com/v1`
- MCP server: `https://api.onttle.com/mcp` (see "MCP server" below)
- Human docs: https://onttle.com/docs

---

## 0. Core concepts

```text
Workspace  (team, billing)
  └─ Project  (one app/service; API Keys and data are scoped here)
       └─ Table  (content schema: Columns)
            └─ Contents  (rows; DRAFT or PUBLISHED)
```

- **Column types:** `TEXT`, `NUMBER`, `DATE`, `BOOLEAN`, `CATEGORY`, `FILE`, `EDITOR` (rich text), `JSON`, `REFERENCE` (link to another Table's Contents).
- **Localization:** a Project has a primary language and optional extra languages. `TEXT`/`EDITOR` columns with localization store one value per language.
- **Publishing:** the API only returns Contents that have been published. Drafts are invisible to API reads.
- **Table options:** `slug` support (fetch by slug), SEO fields (`seo_title`, `seo_description`, `seo_image`), and read-only (API-managed data such as logs).
- **Project resources:** Categories (option lists for `CATEGORY` columns), Variables (`{{templates}}` replaced in API responses), Translations (UI string key/values), Files.
- **Members (optional):** email sign-up and login for the app's own end users, with per-Table permission rules (public / signed-in member / owner / role). Not to be confused with Workspace and Project members, who are dashboard users. See step 7.

---

## MCP server (use it when it is connected)

Onttle has an MCP server at `https://api.onttle.com/mcp`. If your tool list has tools whose names start with `onttle_`, it is connected: use them for the steps below instead of asking the user to work in the dashboard.

| Step | Without MCP | With MCP |
| ---- | ----------- | -------- |
| Find the Project and its Tables | Ask the user for the Project ID and table names | `onttle_list_workspaces`, `onttle_list_projects`, `onttle_get_schema` |
| Create or change Tables (step 2) | Hand the design to the user | `onttle_create_table`, `onttle_update_table` (account connection, Project `OWNER` or `ADMIN`) |
| Add sample Contents and publish | Ask the user | `onttle_create_contents`, `onttle_set_contents_status` |
| Types and OpenAPI (step 9) | Ask the user to enable the OpenAPI URL | `onttle_get_openapi_spec`, `onttle_get_api_reference`, resource `onttle://projects/{projectId}/openapi.json` |
| Member sign-up settings (step 7) | Ask the user | `onttle_get_member_settings`, `onttle_update_member_settings`, `onttle_set_table_rules` |
| Manage members (step 7) | Ask the user (dashboard) | `onttle_list_members`, `onttle_update_member`, `onttle_create_member` (account connection) |
| Debug a failing call (step 10) | Read the response | `onttle_analyze_api_logs`, `onttle_get_webhook_logs` |
| Look something up in the docs | Fetch https://onttle.com/docs | `onttle_search_docs` |

How the tools behave:

- **Changes take two calls.** A tool that changes data first returns a preview and a `confirm_token` and changes nothing. Show the preview to the user; after they agree, call the tool again with exactly the same arguments plus `confirm_token` (valid for 10 minutes).
- **Previews validate.** Content previews list rows that would fail in `invalid_rows`; fix them before confirming.
- **Values are keyed by column name**, in results and in `data` alike.
- **`EDITOR` columns take Markdown text or a TipTap document**, the same as the REST API (step 6). Prefer Markdown.
- **Updates and rollbacks follow the dashboard's logic**: an updated row is saved as DRAFT unless `publish: true` is passed, and a rolled-back row takes the values and the status of the revision.
- **`project_id`** is needed on every Project tool with an account connection, and not with an API key connection (the key is its Project).
- **Access follows the connection.** An account acts with the user's role in each Project; a publishable key only reads what the public API serves; a secret key reads drafts and writes Contents. Tables, permission rules, API keys and members need an account connection.

MCP manages the Project. **The application still calls the REST API at runtime**, so steps 3 to 6 (env vars, API client, reads, writes) are the same either way:

- `onttle_create_api_key` issues a **publishable** key and returns the full value once, in the result of the confirmed call. Ask the user to put it in the env file.
- **Secret** keys are issued in the dashboard only (👤 User action).

If the MCP server is not connected, tell the user they can connect it and continue with the dashboard steps meanwhile:

```bash
claude mcp add --transport http onttle https://api.onttle.com/mcp
```

Other clients (Claude apps, Cursor) and API-key connections: https://onttle.com/docs/ai/mcp

---

## 1. Set up the account and Project (👤 User action)

Onttle accounts, Workspaces and Projects are created in the dashboard. With the MCP server connected you can do items 4 and 6 yourself, and item 5 for a publishable key. Ask the user to:

1. Sign up / log in at https://app.onttle.com.
2. Create a **Workspace** (or use an existing one).
3. Create a **Project** for this app. In the project creation screen the AI panel can generate a table structure; otherwise choose **Create manually**.
4. Create the **Tables** this app needs (see step 2), add a few Contents and set them to **PUBLISHED**.
5. Open **API Keys** in the Project and create a key:
   - **Publishable** (`pk-proj_…`): GET only, plus the member endpoints (`/auth/*`, `/me`) and content writes that a Table's permission rule allows (step 7). Safe in browsers; restrict it with allowed hosts.
   - **Secret** (`sk-proj_…`): also create/update/delete, file upload, chat and embeddings. **Server-side only.**
   - The full key is shown once. Ask the user to paste it into the env file themselves; do not ask them to paste it into the chat if you can avoid it.
6. Give you the **Project ID** (shown in the Project settings / API page URL) and the table names or slugs.

While the user does this, inspect the codebase and propose the Table design.

---

## 2. Propose a Table design

Read the codebase to find the content the app needs to manage (pages, posts, products, FAQs, banners, settings, UI strings…). For each, propose a Table:

| Table (slug) | Column   | Type     | Options                |
| ------------ | -------- | -------- | ---------------------- |
| `posts`      | `title`  | TEXT     | required, localization |
|              | `body`   | EDITOR   | localization           |
|              | `cover`  | FILE     |                        |
|              | `tags`   | CATEGORY | multiple               |
|              | `author` | REFERENCE| → `authors`            |

Guidelines:

- Use lowercase `snake_case` column names; the API returns data keyed by column name.
- Enable the Table's **slug** option if pages are addressed by URL.
- Enable **SEO** for Tables that render as public pages.
- Use **Translations** for short UI strings and **Variables** for values reused across contents (phone numbers, prices, links).
- Do not store secrets in Onttle Contents.

Hand the design to the user to create in the dashboard — or, with the MCP server connected through the user's account, create the Tables yourself with `onttle_create_table` after the user approves the preview.

---

## 3. Configure environment variables

```bash
# .env.local (never commit)
ONTTLE_API_URL=https://api.onttle.com/v1
ONTTLE_PROJECT_ID=your_project_id
ONTTLE_API_KEY=pk-proj_or_sk-proj_key
```

- Make sure the env file is in `.gitignore`.
- A secret key must never be exposed to the client bundle (no `NEXT_PUBLIC_`, `VITE_`, `EXPO_PUBLIC_` prefix etc.). If the browser needs data, either use a publishable key or proxy through a server route.

---

## 4. Create an API client

Every request needs `Authorization: Bearer <API_KEY>`. Paths are `/{projectId}/tables/{tableIdOrSlug}`. The key may also be sent as `X-Onttle-Key: <API_KEY>`; that form is required once member tokens are involved (step 7), because `Authorization` then carries the member's access token.

```typescript
// lib/onttle.ts
const API_URL = process.env.ONTTLE_API_URL ?? 'https://api.onttle.com/v1'
const PROJECT_ID = process.env.ONTTLE_PROJECT_ID!
const API_KEY = process.env.ONTTLE_API_KEY!

export async function onttle<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API_URL}/${PROJECT_ID}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
      ...init?.headers,
    },
  })

  if (!res.ok) {
    throw new Error(`Onttle ${res.status}: ${await res.text()}`)
  }

  return (res.status === 204 ? undefined : await res.json()) as T
}
```

---

## 5. Read contents

### List

```http
GET /v1/{projectId}/tables/{tableIdOrSlug}?page=1&size=20&lang=en
```

| Query   | Description |
| ------- | ----------- |
| `page`  | Page number, default `1` |
| `size`  | One of `1, 10, 20, 30, 40, 50` (other values fall back to `50`) |
| `lang`  | Language code for localized columns; defaults to the Project's primary language |
| `sort`  | JSON array, e.g. `[{"i":"created_at","o":"desc"}]`. `i` is a column name or `created_at`, `updated_at`, `slug`; add `"l":"en"` for a localized TEXT column |
| `filters` | JSON array, e.g. `[{"i":"title","w":"contains","v":"hello"}]`. `w` operators include `equals`, `not`, `contains`, `not_contains`, `starts_with`, `ends_with`, `null`, `not_null`; dates use `is`, `before`, `after`, `between` |
| `op`    | `AND` (default) or `OR` between filters |

Response:

```json
{
  "list": [
    {
      "id": "…",
      "created_at": "2026-08-30T09:00:00.000Z",
      "updated_at": "2026-08-30T09:00:00.000Z",
      "published_at": "2026-08-30T09:00:00.000Z",
      "owner_member_id": null,
      "data": {
        "title": "Hello Onttle",
        "body": "…"
      },
      "slug": "hello-onttle"
    }
  ],
  "pagination": { "page": 1, "size": 20, "total": 1, "totalPages": 1 }
}
```

Column values are under `data`, keyed by column name. `slug` is present only when the Table has slug support, and `seo_title` / `seo_description` / `seo_image` only when it has SEO support. `seo_title` and `seo_description` are one text per project language (`{ "ko": "…", "en": "…" }`), or that language's string when the request has `language=`. `owner_member_id` is always present: the ID of the member that owns the row, or `null`. URL-encode `sort` and `filters` (e.g. with `URLSearchParams`).

### Single item

```http
GET /v1/{projectId}/tables/{tableIdOrSlug}/{contentsIdOrSlug}?lang=en
```

Returns `404` if the item does not exist or is not published.

### Project resources

```http
GET /v1/{projectId}/categories
GET /v1/{projectId}/variables
GET /v1/{projectId}/translations
```

### Caching

Contents change when editors publish. On frameworks with data caching (e.g. Next.js), use time-based revalidation (`next: { revalidate: 60 }`) or tag-based revalidation triggered by a Webhook configured in the Project.

---

## 6. Write contents (secret key, server-side only)

```http
POST   /v1/{projectId}/tables/{tableIdOrSlug}                     # create
PUT    /v1/{projectId}/tables/{tableIdOrSlug}/{contentsIdOrSlug}  # update
DELETE /v1/{projectId}/tables/{tableIdOrSlug}/{contentsIdOrSlug}  # delete one
DELETE /v1/{projectId}/tables/{tableIdOrSlug}                     # bulk delete, body: { "ids": ["…"] }
```

Unlike read responses, the write body is a flat JSON object keyed by column name (no `data` wrapper), plus optional system keys `slug`, `seo_title`, `seo_description`, `seo_image`, and `is_publish`:

```json
{
  "title": "New Post",
  "body": "…",
  "is_publish": true
}
```

- Unknown keys are rejected.
- `seo_title` / `seo_description` take `{ "ko": "…", "en": "…" }` (languages left out keep their text) or a plain string, stored as the primary language's text.
- An `EDITOR` column takes **Markdown text** (`"body": "# Title\n\nText in **bold**"`) or a **TipTap document** (the `{ "type": "doc", "content": […] }` object, or that object as a JSON string). Prefer Markdown. Reads return it as `{ json, html, markdown, plain }`.
- `is_publish: true` publishes; omitting it saves a **draft**.
- `PUT` replaces the row: send every column you want to keep, and send `is_publish: true` again to keep it published.

### File upload

```http
POST /v1/{projectId}/files
Content-Type: multipart/form-data   (fields: file, name)
```

---

## 7. End-user sign-up and login (optional)

Use this when the app needs its own users to sign up and log in. Onttle handles sign-up, email verification, login, token refresh, password reset and withdrawal; do not build a separate auth server or user table.

### Enable it (👤 User action)

Ask the user to open **End users → Auth settings** in the Project and:

1. Switch **Enable the member feature** on and agree to the personal data processing notice.
2. Add the app's origins to **Allowed origins** (e.g. `https://www.example.com`, and `http://localhost:3000` for development).
3. Set the **email verification redirect URL** and the **password reset redirect URL** to pages of the app (you will build them below). Both must be inside an allowed origin.
   - Optional: a **Sender name** for the auth emails (defaults to the Project name), and **File upload permission** if members should upload files (see "Member file uploads" below).
4. Create a **publishable** key for the browser if they have not yet.

Each sign-up that completes email verification consumes credits; logins, refreshes and emails are free.

### Headers

```http
X-Onttle-Key: pk-proj_…                    # always (the API key)
Authorization: Bearer <accessToken>        # only for a signed-in member
```

### Endpoints

All under `https://api.onttle.com/v1/{projectId}`.

| Method & path | Body | Result |
| ------------- | ---- | ------ |
| `POST /auth/signup` | `{ email, password, profile?, consents? }` | `201 { member }` (status `pending`); a verification email is sent |
| `POST /auth/email/check` | `{ email }` | `{ exists, available }`: whether the email is already a member's, and whether it can sign up (30 per hour per IP) |
| `POST /auth/email/verify` | `{ token }` | `{ member }` (status `active`) |
| `POST /auth/email/resend` | `{ email }` | `{ success: true }` (1 per minute, 5 per day) |
| `POST /auth/login` | `{ email, password }` | `{ accessToken, refreshToken, expiresIn, member }` |
| `POST /auth/token/refresh` | `{ refreshToken }` | same as login, with a **new** refresh token |
| `POST /auth/logout` | `{ refreshToken }` or `{ all: true }` | `{ success: true }` (member token required) |
| `POST /auth/password/reset-request` | `{ email }` | `{ success: true }` (always) |
| `POST /auth/password/reset` | `{ token, password }` | `{ success: true }`; all sessions end |
| `GET /me` | — | `{ member }` |
| `PATCH /me` | `{ profile?, currentPassword?, newPassword? }` | `{ member }` |
| `DELETE /me` | — | `{ success: true }`; the account is deleted at once |
| `GET /me/consents`, `PUT /me/consents` | `{ consents: [{ type, version, agreed }] }` | `{ consents }` |

`member` is `{ id, email, role, status, emailVerified, profile, createdAt, lastLoginAt }`. `profile` is a free-form object for app-defined fields. Consent `type` is `terms`, `privacy` or `marketing`. Passwords are 8–128 characters.

### What to build

1. **Sign-up page:** call `/auth/signup`, then tell the user to check their email. State on this page that an email withdrawn within the last 90 days cannot sign up again.
2. **Verification page** (the verification redirect URL): read `token` from the query string, call `/auth/email/verify`, then send the user to login.
3. **Login:** store `accessToken` and `refreshToken`. Prefer keeping them on the server (e.g. an httpOnly cookie set by the app's own server route) over `localStorage`.
4. **Refresh:** when a request fails with `401 AUTH_TOKEN_EXPIRED`, call `/auth/token/refresh` and retry once. Refresh tokens are **single use**: always replace the stored one with the new one. Never run two refreshes in parallel with the same token; a reused token ends the whole login.
5. **Password reset pages:** a request form (`/auth/password/reset-request`) and the reset redirect URL page (read `token`, call `/auth/password/reset`).
6. **Account page:** `GET /me`, `PATCH /me`, and withdrawal with `DELETE /me` behind a confirmation that explains the 90-day rule.

```typescript
// lib/onttleAuth.ts (browser-safe: publishable key only)
const API = `https://api.onttle.com/v1/${process.env.NEXT_PUBLIC_ONTTLE_PROJECT_ID}`
const KEY = process.env.NEXT_PUBLIC_ONTTLE_PUBLISHABLE_KEY!

export async function onttleAuth<T>(
  path: string,
  init: RequestInit & { accessToken?: string } = {},
): Promise<T> {
  const { accessToken, ...rest } = init
  const res = await fetch(`${API}${path}`, {
    ...rest,
    headers: {
      'X-Onttle-Key': KEY,
      'Content-Type': 'application/json',
      ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      ...rest.headers,
    },
  })
  const body = await res.json().catch(() => ({}))
  // Member errors are { code, message }, e.g. AUTH_INVALID_CREDENTIALS
  if (!res.ok) throw Object.assign(new Error(body.message ?? res.statusText), { code: body.code, status: res.status })
  return body as T
}
```

### Table permission rules

In the dashboard, the table form (create / edit Table) has **Permission rules** below the **API endpoints** switches: one rule per operation — read, create, update, delete. With a publishable key:

| Rule | Allowed for | Otherwise |
| ---- | ----------- | --------- |
| `public` | anyone with the key | — |
| `member` | any signed-in member | `401` |
| `owner` | the member who created the row; lists return only that member's rows | `403 AUTH_FORBIDDEN` |
| `role:<name>` | members with that role | `403 AUTH_FORBIDDEN` |
| `none` | nobody (secret key only) | `403` |

- Defaults: read `public`, writes `none`. Nothing changes for Tables whose rules are untouched.
- A **secret key skips the rules** (server-side only).
- Rows created by a member are owned by that member; the server sets the owner from the member token. Never send `owner_member_id` in a request body: it is rejected as an unknown key, and a row created with a secret key has no owner.
- Every row returns `owner_member_id` at the top level of read and write responses, whatever the Table's rules: the owning member's ID, or `null` when there is no owner. Compare it with `member.id` from `GET /me` to tell the signed-in member's own rows apart. It is always returned, like `id`, even when `fields` is used.
- Member-created rows still need `"is_publish": true` to show up in reads.
- Propose the rules together with the Table design (step 2), e.g. a board: read `public`, create `member`, update and delete `owner`. The user sets them in the dashboard.
- `role:<name>` can only use roles the user defined under **End users → Auth settings → Member roles** (default: just `member`). If the design needs more roles (e.g. `seller`), ask the user to add them there first. Every member signs up as `member`; roles are assigned in the dashboard.

```typescript
// Create a row as the signed-in member (Table rule: create = member)
await onttleAuth('/tables/posts', {
  method: 'POST',
  accessToken,
  body: JSON.stringify({ title: 'Hello', body: '…', is_publish: true }),
})
```

### Member file uploads

`POST /files` is secret key only unless the user sets **File upload permission** (End users → Auth settings) to "Signed-in members" or "A role". Then a signed-in member can upload with the publishable key:

```typescript
const form = new FormData()
form.append('file', file)

const res = await fetch(`${API}/files`, {
  method: 'POST',
  headers: { 'X-Onttle-Key': KEY, Authorization: `Bearer ${accessToken}` }, // no Content-Type: the browser sets the multipart boundary
  body: form,
})
const uploaded = await res.json() // use uploaded.id as the value of a FILE column
```

- Uploads without a signed-in member are never allowed with a publishable key.
- A per-file size cap applies to member uploads (default 10 MB, set by the user); a larger file gets `400 AUTH_INVALID_REQUEST`. Validate the size in the UI first.
- `is_ocr` / `is_generate` are ignored on member uploads.
- Files uploaded by a member are deleted when that member withdraws.

### Notes

- Login and password-reset responses never reveal whether an email is registered. Do not add UI that does.
- `402 AUTH_SIGNUP_PAUSED` means the Workspace is out of credits or hit its monthly sign-up cap; existing members can still log in.
- The REST API has no member management endpoints. Members are managed in the dashboard (**End users**) or, with the MCP server connected through the user's account, with MCP tools:
  - `onttle_list_members`, `onttle_get_member_stats`: list members (emails are masked unless asked for) and sign-up figures. Project `EDITOR` or above.
  - `onttle_update_member`: change a role, suspend or reactivate a member, lift the 90-day re-sign-up block of a withdrawn email. Project `EDITOR` or above.
  - `onttle_create_member`: add a member directly (no verification email; billed as one sign-up). Project `OWNER` or `ADMIN`.
  - Forced withdrawal is done in the dashboard only. An API key connection cannot call these tools.
- Cookie mode (tokens in httpOnly cookies set by Onttle) exists but requires a custom domain connected to the Workspace; default to Bearer mode unless the user asks for it. Details: https://onttle.com/docs/core-features/members

---

## 8. AI features (optional, secret key)

- **Semantic search:** `POST /v1/{projectId}/tables/{tableIdOrSlug}/embeddings` with `{ "query": "…", "threshold": 0.7, "count": 5 }`. Requires Vector/Embeddings to be enabled for the Table in the dashboard.
- **Chat with an Agent:** create an Agent in the dashboard, then `POST /v1/{projectId}/chats` with `{ "agent_id": "…", "message": "…" }` to start a chat and `POST /v1/{projectId}/chats/{chatId}/messages` to continue it. `GET /v1/{projectId}/chats/{chatId}/messages` returns the history.

---

## 9. Types and OpenAPI

Each Project can publish an OpenAPI 3 spec generated from its Tables. With the MCP server connected, read it with `onttle_get_openapi_spec` (no setting needed). Otherwise ask the user to enable the OpenAPI URL on the Project's **API** page, then use:

```text
https://app.onttle.com/workspaces/{workspaceId}/projects/{projectId}/api/openapi.json
```

Prefer generating types from this spec (e.g. `openapi-typescript`) over hand-writing them; it is the source of truth for column names and types. When the member feature is on, the spec also contains the member endpoints, their error codes, and each Table operation's permission rule (`x-onttle-rule`).

---

## 10. Verify

1. Call the list endpoint for one Table with `curl` and confirm `list` is not empty:

   ```bash
   curl "https://api.onttle.com/v1/$ONTTLE_PROJECT_ID/tables/posts?size=10" \
     -H "Authorization: Bearer $ONTTLE_API_KEY"
   ```

2. Run the app and check the page that renders Onttle data.
3. Report to the user what you set up, which env vars they must fill in, and which Tables they still need to create or publish.

### Troubleshooting

| Status | Check |
| ------ | ----- |
| `401` | `Authorization: Bearer` header present; key copied correctly and not deleted/disabled |
| `403` | Publishable key used for a write the Table's permission rule does not allow, allowed hosts mismatch, or the endpoint is disabled |
| `401 AUTH_TOKEN_EXPIRED` / `AUTH_TOKEN_INVALID` | Member access token expired (refresh it) or missing / reused (log in again); the API key must be in `X-Onttle-Key` when `Authorization` carries a member token |
| `403 AUTH_NOT_ENABLED` | The member feature is off for the Project (👤 User action: End users → Auth settings) |
| `409 AUTH_EMAIL_WITHDRAWN` | The email was withdrawn less than 90 days ago |
| `404` | Project ID, table id/slug, or contents id/slug; the item may still be a draft |
| `400` Insufficient Credit | The Workspace is out of credits for this billing cycle; the user must check billing in the dashboard |
| Empty `list` | No Contents are published yet |

---

## More

- Quick Start: https://onttle.com/docs/getting-started/quick-start
- MCP server: https://onttle.com/docs/ai/mcp
- Concepts: https://onttle.com/docs/getting-started/concepts
- Column types: https://onttle.com/docs/developers/column-types
- Authentication: https://onttle.com/docs/rest-api/authentication
- Members (sign-up & login): https://onttle.com/docs/core-features/members
- Members API: https://onttle.com/docs/rest-api/members-api
