---
name: atomhouse
description: "Build a working web app on atomhouse, a self-hosted data platform: create an app, design tables, query them with DuckDB SQL, add JS functions and scheduled or row-change triggers, store objects, publish a static site, and scope rows and columns per user. Use when the user mentions atomhouse, or asks for a website, backend, form app or admin panel *with accounts and a database*, or wants to create tables, query data or publish a page on this platform. Not for a static page with no data behind it."
---

# atomhouse

> **Hosted AtomHouse Cloud:** every published site is already behind a platform
> gate for login, registration, workspace membership and app access. Do **not**
> build a login or registration form in the page, and do not call `/auth/login` or
> `/auth/register` from it. Use `GET /auth/me` for the current member and spend the
> effort on the app's own approval rules.
>
> If `/auth/me` answers `401`, do not draw a login screen: refresh the page with
> `location.reload()` and let the gate handle it. On logout, call `POST /auth/logout`
> and then `location.reload()`; never leave the app on screen after logout. If an
> existing page already has a login or logout screen, remove it and replace those
> paths with the platform gate. The rest of this document is unchanged.

> First time here? **Read [INSTALL.md](INSTALL.md) first** — it is shorter than
> this file and gets you connected.

## Credential

Every call needs `Authorization: Bearer <token>`. **Check what you already have before asking for anything**:

```bash
curl -s https://atomhouse.cloud/api/v1/auth/me -H "Authorization: Bearer $ATOMHOUSE_TOKEN"
# 200 -> you are signed in; the body names your account and default workspace
# 401 -> no usable token; use the device flow below
```

Store the token at `~/.atomhouse/credentials/atomhouse.token` with mode 600, or in `$ATOMHOUSE_TOKEN`, or in the OS keychain. **One token, not one per workspace**: a token is your account's session, and it reaches every workspace that account belongs to — which is why `workspace` is an argument on each call rather than part of the credential. The file name is your own choice; `<name>` keeps several *accounts* apart, not several workspaces.

**Not beside this document**: a skill directory gets synced, backed up and shared, and this document may not have a local copy at all. Never paste a token into the conversation.

Never send a cookie or an `x-csrf-token` header — those are for browsers, and a script that pretends to be one is a script that breaks when the cookie rotates.

If that probe hangs or answers something that is not JSON, the problem is the path to the instance, not the token: check `https://atomhouse.cloud/healthz` first, then try the same request with another HTTP client. A sandbox that blocks outbound `curl` and a proxy that rewrites the response both look like this, and neither is the instance refusing you — read the response body before concluding the token is wrong.

### A 200 is not an answer to whose token this is

The probe above proves a token is valid. It does not prove it belongs to the person you are working for, and on a machine somebody has used before those are different questions. `GET /auth/me` answers with `user.email`, `user.id`, `user.actor_kind` (`session` for a person, `app` for a machine credential that reads every row of its app) and `is_admin`. Read it before the first real call, and name the account out loud.

**Recognise is the person's judgement, not yours.** Put the address in front of them and ask. Knowing which addresses are theirs is not something you can work out, and a machine used before will have somebody's token on it — often an administrator the instance made for itself, which nobody recognises because nobody has seen it. If it is another account of theirs, that is a legitimate answer: ask which one to use for this work and write it down, rather than silently using whichever was on disk.

**If it is not theirs, stop.** Do not call `bootstrap` to see what is there: that call is already a read of somebody else's workspace, and its output is convincing enough that you will report it as theirs. Deleting the file and running the device flow costs ten seconds; the alternative is a summary of another account's data delivered with confidence.

This is the last row of the finished-app checklist in [access](reference/access.md), applied one step earlier: there it catches a credential scoped to the wrong *app*, here it catches one scoped to the wrong *person*.

### If the probe answers 401

Do not ask for a password: it would sit in the transcript, and the person would have to trust you with it. Three requests, and one thing the person does in a browser:

```bash
# 1. ask for a device code
curl -s -X POST https://atomhouse.cloud/api/v1/auth/device \
  -H 'content-type: application/json' \
  -d '{"client_name":"<your name>"}'
# -> device_code, user_code, verification_uri_complete, open_command

# 2. Show verification_uri_complete to the person, then open it.
#    Put the URL on its own line as a bare link they can click -- not
#    inside a sentence, and not the open_command string: the person
#    may be reading in a client that cannot run it.
#    Check the host is the instance you are talking to before opening.

# 3. poll until approved
curl -s -X POST https://atomhouse.cloud/api/v1/auth/device/token \
  -H 'content-type: application/json' \
  -d '{"device_code":"<device_code>","wait_seconds":25}'
# -> {"status":"approved","access_token":"atomhouse_sess_..."}
#    status "pending": keep polling. "expired"/"denied": start again from 1.
```

The person sees who is asking and approves it themselves. Codes expire in ten minutes. Save the token — on every later request it is `Authorization: Bearer <token>`.

Then read `/auth/me` once on the new token and say the address, exactly as you would for a token found on disk. The person approving in a browser approves as whoever is signed in there, which is not necessarily the account they meant.

If a token you already had answers `401`, it expired or the session was ended. There is no refresh token; run the three requests again.

### Ending a token

A token you no longer want is still a key until you end it. Replacing the file does not end it, and `401` is not required to revoke: `POST /auth/logout` with that token as the bearer deletes the session server-side, and the token answers `401` from the next call on. It does not touch the file, so a retired token needs both — the call, and the file deleted. `200` means it worked; `401` means it was already dead.

Do this whenever you replace a credential, not only when one has leaked: the old one stays live otherwise, and nothing will ever tell you.

## Getting the caller's identity and workspace

**One skill covers every workspace the account can reach** — you install it once, and which workspace you act on is an argument on the call. You do not know who you are or which workspaces exist until you ask:

```
Endpoint: https://atomhouse.cloud/api/v1/mcp
Header:   Authorization: Bearer <token>
```

Call `bootstrap` with no arguments. It returns the account, every workspace you can reach with your role in each, and — when you pass `workspace` — that workspace's apps with their table and row counts.

Then pass `workspace` on every other tool. **If you omit it, the call goes to the person's default workspace** — the one marked as such, which starts out as the first they created. That is a convenience, not an assumption: when the person has said which workspace they mean, name it.

**Without `workspace`, the app list is a union across every workspace you can reach, and it does not say which workspace each app belongs to** — the same slug can exist twice with different tables. Never report a count from that call as `your apps` or `your tables`: pass `workspace` for each one and count there.

**`bootstrap` does not report whether an app is published** — an app appears there whether it has a site or only a schema. For what you have, count from `bootstrap`; for what is live you must call `site_status` once per app, and say so rather than implying the list was complete.

Do not work from any list of workspaces, apps or tables written into a document. `bootstrap` reads the catalog on the call; anything copied here was true when the document was generated, and this document outlives that.

## Two meanings of "app"

The word is overloaded, and getting it wrong produces a half-built result that looks finished.

| Term | What it is | How it is made |
|---|---|---|
| **An app, as the user means it** | their finished software — a page people open, with data behind it | the whole sequence below: `create_app`, tables, then `publish_site` and `upload_site_file` |
| **An app here** (a `create_app` app) | one backend: a schema, its tables, functions, policies. **No page.** | `create_app` |

**When someone asks you to build an application, they mean the first unless they say otherwise.** That means a site, published and reachable — not only the backend. If you stop at `create_app`, they get a database they cannot look at and will ask what happened.

**When the work is only data — analysing what is already here, or building the backend for someone else's frontend — the second is the whole job, and there is no site to publish.**

## Eight ways to be confidently wrong

These share one property: nothing fails. No error, no `4xx`, no console message — the result is
simply wrong in a way you will not see until somebody else uses it. Read this list before you call
anything done; every other section is detail, and these are the ones that cost a delivery.

Five of them are about building an app, one about reading an account, one about waiting for a
person who was never asked, and two about a model that answers nothing. The first of those costs
nothing to get wrong, and what it produces looks exactly like success.

| Symptom | Cause | Fix |
|---|---|---|
| Anyone approved sees every row | `member` can read and write every table by default, and approving a request puts them in it | `set_app_role` on `member` in the session that creates the app |
| The owner's list is empty for everybody | The frontend wrote `undefined` to `owner_id` — `/auth/me` nests the account under `user` | read `me.user.id`, and send it on every insert |
| The token is in the page | A `machine_credential` committed into HTML is a permanent key to the database, readable by any visitor | call REST with the visitor's cookie; a credential belongs on a server |
| The page is unstyled and nothing is logged | External CSS/JS is blocked by CSP before the request is made | upload the library and reference it relatively |
| Reads work, writes answer `403` | An absolute `https://…/api/v1/…` put the page on another origin, so the cookie did not travel | call `/api/v1/…` relatively — `credentials: 'include'` only sends a cookie to the origin the page is on |
| **A signed-in visitor sees a white screen** | The page loads data first and has nothing to draw when the answer is "no access" — and every new workspace member is in exactly that state until an admin gives them an app role | call `…/apps/{app}/access` first, and draw the ask-for-access state from its `capability: null` |
| **You report another account's data with confidence** | The token on disk was live but not theirs, and a `200` was read as "usable" | read `user.email` from `/auth/me` and confirm it before the first real call |
| **You wait forever at a sign-in nobody was asked to complete** | `open_command` was run on a server. There is no browser there, so the link goes into a log and the person never sees it — and the poll answers `pending` until the code expires | show `verification_uri_complete` as text, say the ten-minute deadline, and poll with a `wait_seconds` you chose |
| **The model feature reports working when it is not** | The page caught every error from `/ai` and rendered an empty list, so "no connection configured" and "the model said nothing" looked the same | `503` is a normal first-run state, not a crash: show `error.message` from the body instead of an empty result. In a function the same mistake is catching the task-only throw |
| **A model that reasons returns nothing** | `max_tokens: 1` is spent entirely on reasoning, so the reply has a `thinking` block and no text | give it a real budget — a reasoning model spends tens to hundreds of tokens before its first word |

Everything on this list is invisible to `describe_table`, `site_status` and every other check the
platform offers. They are the reason this document exists.

### The white screen, specifically

An anonymous visitor is the easy case: no session, `401`, show a sign-in form. The case that gets
missed is **signed in, no access** — a person who did exactly what they were told, made an account,
and gets a blank page because the first data request answered `403` and the code had no branch for
it.

One request settles it, before anything else is drawn:

```js
const r = await fetch(`/api/v1/workspaces/${ws}/apps/${app}/access`, { credentials: 'include' })
if (r.status === 401) return showSignIn()          // no session
const access = await r.json()                      // 200 even with no access
if (!access.capability) return showAskForAccess(access.error)
renderApp(access)                                  // read / write / ddl
```

The endpoint answers **200 with `capability: null`** rather than `403`, on purpose: a page can read
the refusal and say something useful. Testing `if (!r.ok)` instead sends every unauthorised visitor
down the error path, which is where the white screen comes from.

`error` in that body is written for the person — show it, and put the ask-for-access button next to
it. Asking needs no privilege, so the button can be offered to anybody.

## Signing in, when you have no credential

You may have been handed a token already. If not, this is the flow, and it is the first thing that
goes wrong because of where the agent runs.

```
POST /api/v1/auth/device          (no credentials)
  -> user_code, device_code, verification_uri_complete, open_command, expires_in: 600
```

**The person opens `verification_uri_complete` in their own browser and approves.** That is the
step; everything else is waiting for it.

**Print the link before you run anything.** `open_command` is a convenience, not the delivery: it
does nothing on a server (a container, a CI job, anything cloud-hosted), it can be swallowed by a
popup blocker on a laptop, and on a headless machine it fails silently. A browser that opened is
also not an approval — the person still has to click, and they have to know where.

So the link goes on screen first, as its own line, before you try to open anything:

```
Open this and approve, you have 10 minutes:
  https://atomhouse.cn/app/#/device?code=ABCD-EFGH

Code, if you are reading this on a phone: ABCD-EFGH
```

Then `open_command`, if it applies. Then poll. In that order, and **never instead of** — an agent
that runs the command and then waits has dropped the one thing the person needs.

1. The link, printed, on its own line, before anything else.
2. The short code too — they may be reading on a phone and approving on a laptop.
3. Say what you are waiting for and that they have **ten minutes**.
4. Poll `POST /api/v1/auth/device/token` with the `device_code`.

Never sit in a silent loop. If nobody has answered after a minute or two, say so — the deadline is
real, and an expired code cannot be revived.

| Status | What it means | What to do |
|---|---|---|
| `pending` | not decided yet | keep polling |
| `approved` | `access_token` is in this response | take it, and it is never shown again |
| `denied` | the person said no | stop; do not re-ask without being told to |
| `expired` | ten minutes passed | start a **new** `POST /auth/device` — polling the old code answers `expired` forever |
| `consumed` | already used | start a new one |

The token is a bearer credential: it has no refresh, so store it where a repository will not pick
it up and do not print it. On a `401`, the token is gone and the way back is another device
authorization.

### Which sign-in this instance actually offers

**Ask before assuming.** `GET /api/v1/auth/config` takes no credentials and answers what this
deployment has switched on:

```json
{ "email_enabled": true, "google_enabled": true, "allow_registration": true, "captcha_required": true }
```

Those answers are not equivalent to you: **one sign-in method ends in a browser you do not
have**, while the rest hand back a token.

| Sign-in | What it is | Can you use it? |
|---|---|---|
| **device** | a code the person approves in their own browser | **Yes — always, and it is the default** |
| **password** | `POST /auth/login` with an address and password | **Yes**, when `email_enabled` — it returns an `access_token` |
| **google** | an OAuth redirect that ends with a cookie and `/app/` | **No.** It never returns a token, and the callback lands in a browser |

So: if you have no credential, use the device flow above. If the person offers a password, use
`POST /auth/login`. **Do not try to drive Google** — there is nothing at the end of that redirect
for you, and asking the person to complete it on your behalf will not produce a token either.

`allow_registration: false` means nobody can make a new account: the person needs one that already
exists, and the device flow still works for it. `captcha_required: true` means sign-up asks for
characters from an image — a step you cannot complete, which is the other reason to let the person
do the signing in.

## Start here

Every MCP call publishes its own arguments — ask `tools/list` rather than guessing. This document is what a schema cannot tell you: what the platform does, and the order to do it in.

Three kinds of work, and they take different paths:

**Building an app.** Seven steps, and step 2 does most of the work:

1. **`bootstrap`** — takes no arguments. Returns your role, every workspace you can reach, and
   what is in the one you are in. Then pass `workspace` on every other tool; if you leave it out,
   the call goes to your **default workspace** — but when the user has named one, name it.
2. **`create_app`** — in **one call**: the schema, its tables with columns and primary keys, and
   any seed rows. Nothing is left half-configured.

   **Answer this before it, because it decides what this call needs:** *does anything have to
   happen while nobody is looking?* A nightly summary, fields extracted from every new photo, a
   total recomputed when a row changes — yes means a function with a trigger, and a trigger needs
   `machine_credential`. Everything else is REST from the page and needs no credential at all.
   See [Functions: what they are for](#functions-what-they-are-for).

   The wrong question is "can the endpoints express this?" — you will always believe they can,
   and what costs later is computing something once, offline, that the next row will need again.

   **Add `machine_credential` only when something server-side will hold it** — a scheduled
   function, a trigger, a backend of the app's own. A page that visitors sign into does not need
   one and must not get one: the secret is shown once, it never expires, and committing it into
   HTML hands every visitor the app's whole database, which is the third trap above. Static page,
   no server-side consumer: leave the argument out. See
   [the app's own identity](reference/access.md#the-apps-own-identity).
3. **Shape it** — `insert_rows` for data, `create_model` to save a query as a view,
   `set_app_role` for who sees which tables and rows.

   **Before anyone can be approved, narrow `member`.** This is the one mistake that produces an
   app which works perfectly in testing and leaks the whole database in use. Every new app's
   `member` role can read **and write every table**, and the access-request flow puts every
   approved visitor into exactly that role. So an app with per-user rows that leaves `member` at
   its default grants each approved friend the entire database — including rows belonging to
   everybody else.

   If the app has an `owner_id`-style column, send the `set_app_role` call for `member` in the same
   session that creates the app, before you tell anyone it is ready:

   ```
   set_app_role { app, name: "member", tables: [
       { table: "books", can_read: true,  can_write: false },
       { table: "loans", can_read: true,  can_write: true, read_filter: "owner_id = {user_id}" } ] }
   ```

   Narrowing `member` is allowed and expected; only `admin` is fixed. If nobody will ever be
   approved through the public page, this does not apply — but "nobody" is not something to assume
   about an app with a sign-in form.

   **`create_app` puts you in the app's own `admin` role**, and that role lists every table — so
   you can open the app you just built. Two things you cannot do to it, and should not try:
   `set_app_role` on `admin` is refused (it cannot be narrowed, or an app could lose the only role
   that administers it), and there is no `PATCH /roles/{id}` (`405`). To change who may do what,
   create a second role and assign people to it.

   If a built-in `admin` ever does not list a table — an app made before roles named their tables —
   the table endpoints answer `403` on a role you hold. The recovery is one call, not a workaround:

   ```
   set_app_role    { app, name: "owner", tables: [{ table: "<the table>", can_read: true, can_write: true }] }
   assign_app_role { app, email: "<your own>", role: "owner" }
   ```

   Opening the app repairs the `admin` list, so this is a bridge, not a permanent second role.

4. **Give every "mine" column an id, not an email.** Any table where a row belongs to somebody —
   `owner_id`, `borrower_id`, `author_id` — stores the caller's **user id**, and the role's filter
   compares `owner_id = {user_id}`. Do not model ownership as an email address. Two reasons, both
   about the future rather than today: an address can be changed or handed to somebody else, and a
   column full of addresses keeps pointing at the old person when it is. An id cannot move.

   **Nothing writes that column for you.** The platform does not know which column means "owner",
   so an insert that leaves it out stores NULL and the row belongs to nobody — it will not appear
   in anybody's filtered list, including the person who just created it. The frontend must send the
   value, and it reads it from `GET /auth/me` once at start-up:

   ```js
   const me = await api('/auth/me')                  // -> { user: { id }, default_workspace }
   const myId = me.user.id                           // NOT me.id — the id is nested
   await api(`/tables/loans/rows`, { method: 'POST',
     body: JSON.stringify({ values: { owner_id: myId, amount: 5 } }) })
   ```

   The role filter is the other half, and it is written differently: `read_filter` says
   `owner_id = {user_id}` — the placeholder, never a resolved id. The filter is stored once and
   runs for every holder of the role, so a literal id there would show one person's rows to
   everybody.

   You do not need a `users` table for any of this.

5. **Write the frontend** — plain HTML/JS calling REST. Before you start, fetch
   `https://atomhouse.cloud/api/v1/workspaces/{ws}/apps/{app}/rest.md` — one app's endpoints, its sign-in flow,
   the CSRF header, and the one mistake that breaks writes on this platform. That document is for
   you to read — the page needs the API, not a markdown file.
6. **Stop and ask.** Publishing puts the app on a public URL. That is the user's decision, not a
   build step — say what will go public and wait for an answer.
7. **Publish it** — `publish_site` with a slug and title, then `upload_site_file` for each file,
   then `site_status` for the URL. It is reversible with `unpublish_site`, which is why asking
   costs one message rather than a decision nobody can undo.

   **End the reply with the URL on its own line, as a bare link.** Not in a sentence, not
   summarised as "your site is published": the address is the thing the person is going to
   click, and the one piece of this work they cannot reconstruct without asking you again.
   `site_status` returns it; `publish_site` returns it too, so a reload of the file list is not
   needed to find it. Plain text, on its own line:

   ```
   https://your-instance/site/<workspace>/<site>/
   ```

   **Before you hand over the link, ask `site_status`.** It returns a `checks` block per site:
   files the page references that you never uploaded, and `fetch()` paths this instance does not
   serve. You cannot render the page, and you do not have to — the two failures that actually
   happen are both visible in the bytes.

   ```json
   "checks": [{ "site": "shop", "ok": false,
                "missing_files": [{ "reference": "img/bg.png", "source": "style.css" }],
                "invalid_api_calls": [{ "reference": "/api/v1/requests" }] }]
   ```

   An `invalid_api_calls` entry usually means a URL was assembled without its workspace and app
   prefix. Fix it and upload again; do not send the person a link to a page that will come back
   empty.

   Anything you write after the link is described in a sentence — so write nothing after it.

**Analysing data that is already here.** Pure MCP, no app and no page:

`bootstrap` → `describe_table` → `query` (or `read_rows`). That is the whole loop. `create_model` saves a query you run more than once.

**`describe_table` before any SQL** — a guessed column name is the most common refused call — and **`tools/list` before guessing an argument**. DuckDB is not Postgres; read [Dates](reference/data.md#dates) and [SQL](reference/data.md#sql) before writing date or grouping logic.

**Letting somebody in.** When the person says "add my colleague", "invite them", or "how do I give
this to someone" — the workspace, not the app, is what they are asking about. One REST call:

```bash
POST /api/v1/workspaces/{ws}/invitations   {"email": "them@example.com", "role": "member"}
```

`role` is a **workspace** role (`member` or `admin`), and it is not the same thing as an app role.
A new member can reach the workspace and sees no data until somebody gives them an app role too.
If the invitation is for the purpose of reading one app, say so in the same call:
`"app": {"app": "notes", "role": "reader"}`.

Three ways to name the person, and one thing that is none of them:

| They gave you | Send |
|---|---|
| an email | `{"email": "them@example.com", "role": "member"}` |
| a phone number | `{"phone": "+1555…", "role": "member"}` |
| an account id | `{"user_id": "…", "role": "member"}` |
| nothing — they want a link to pass around | `{"role": "member"}` |

**Leaving all three out makes a code.** Eight characters, upper case, without `0`/`O`, `1`, `I`
or `L`, single use. **Nothing on this platform sends email**, so the `token` in the response is the only
copy that exists — put it in your reply, on its own line, or the invitation is lost:

```
A3KF9M2P
```

Say that it works once. An admin who thinks it is a reusable link will send it to four people and
three of them will be refused.

**Read the response, do not assume.** An empty `token` means the person already had an account and
is a member right now — there is nothing to pass on, and inventing a code would be a second,
wrong invitation. A non-empty `token` means somebody has to redeem something: `email` is `null`
for a code, and the address for an invitation that is waiting for that person to sign up.

Neither of you needs to be in the console for this, and no MCP tool does it. It is REST with the
same `Authorization: Bearer` header as everything else. Members and their ids:
`GET /workspaces/{ws}/members`. Detail: [adding somebody to the
workspace](reference/access.md#adding-somebody-to-the-workspace).

## How you get an app

`bootstrap` reports your role in this workspace, and that answer is the one to trust — a role
written into this document would be a snapshot, and this document outlives it. With `owner` or
`admin`, you create the app yourself, and one MCP call builds everything. Creating it puts you in
the app's own `admin` role, which is what lets you open it afterwards — the workspace role alone
does not.

```json
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
  "name": "create_app",
  "arguments": {
    "workspace": "<from bootstrap>",
    "slug": "myapp",
    "name": "My App",
    "description": "what it stores",
    "tables": [{
      "name": "items",
      "columns": [
        {"name":"id","type":"BIGINT","nullable":false,"auto_increment":true},
        {"name":"title","type":"VARCHAR","nullable":false},
        {"name":"created_on","type":"DATE","default":"CAST(strftime(now(), '%Y-%m-%d') AS DATE)"}
      ],
      "primary_key": ["id"],
      "rows": []
    }]
  }
}}
```

`create_app` returns the app slug, its schema name and the `skill_url`.

**Seed rows may carry their own `id`.** Reference data is easier to write when ids are explicit — the
next table's rows can point at them. Doing that used to leave the id sequence behind the data, so the
first row a user added afterwards reused id 1 and hit a duplicate key; the platform now moves the
sequence past whatever you seeded. Both styles work: omit the id and let it be generated, or write it
out and reference it.

**If your role is lower than that**, the tools exist and the permission does not. Ask an admin to
create the app, or to grant you access to one that exists, and say what you need it for:

```json
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
  "name": "request_app_access",
  "arguments": {"workspace": "<from bootstrap>", "app": "existing-app",
                "capability": "read", "reason": "why you need it"}
}}
```

Approval is immediate once an admin decides. Until then, every data call on that app returns `403`.
Once you have access, the rest of this document applies.

## Changing a table that already has data

`query` runs DDL, so adding or altering a column is a statement — not a rebuild:

```sql
ALTER TABLE notes ADD COLUMN archived BOOLEAN DEFAULT false;
```

There is no `alter_table` tool, and `drop_table` is not the way to change a shape: it takes the
rows with it. Reach for `drop_table` only when the table is meant to be gone.

`information_schema` is not exposed; `list_tables` and `describe_table` are how you read the
structure.

## Sizes and limits

These are refused with a clear code, not silently truncated:

| Operation | Limit | Code |
|---|---|---|
| `read_rows`, `query` rows returned | `ATOMHOUSE_MAX_ROWS` (1000) | `limit_exceeded` |
| CSV export | same as above; a bigger table is refused outright | `limit_exceeded` |
| Upload (`/objects`, `/import`) | `ATOMHOUSE_MAX_UPLOAD_BYTES` (64 MiB) | `limit_exceeded` |
| Function source | 256 KiB | `validation` |
| Statement runtime | `ATOMHOUSE_SQL_TIMEOUT_MS` (15 s) | `limit_exceeded` or `timeout` |

To dump a table larger than the export limit, aggregate it first or page through it with `offset`; there is no single-call full dump.

## Managing the workspace

`bootstrap` reports your role, and there are four:

| Role | What it means |
|---|---|
| `owner` | Made the workspace. Everything below. |
| `admin` | Administers it: apps, members, access. Everything below. |
| `member` | Uses the apps it holds a role in. Changes data; never changes an app's shape. |
| `disabled` | Kept but shut out. Every call answers `403`, including reads. |

Only `owner` and `admin` get the tools below; a `member` gets `403` and should ask rather than
retry. All MCP, like everything else here.

| To do this | Tool |
|---|---|
| Give a person access to one app | `assign_app_role` |
| See who has access to what | `list_app_roles` |
| Narrow what a role sees in a table | `set_app_role` |
| Answer somebody's request for access | `review_access_request` |
| See the queue | `list_access_requests` |

**Access requests** have two sides, and both are agent work: somebody who cannot reach an app asks with `request_app_access`, and an admin answers with `review_access_request`.

The asker does **not** have to be a member of the workspace. That is the case a published page
creates: a visitor signs in, is not in this workspace, and cannot read a row. The tool records the
request with `join_workspace: true`, and approving it does two things in one transaction — adds
them to the workspace as a **member**, and puts them in the app's `member` role. Two separate
approvals would leave the reviewer thinking they were finished while the visitor reloaded to the
same refusal.

Asking twice is not an error: while one is pending the call returns the existing request with
`duplicate: true`, so a page may call it from a button without tracking state. A request can ask
for `read` or `write`; `ddl` is refused, because schema changes belong to an app `admin` role.

**Limits live on a role, and nothing else.** A role names the tables it may touch and, per table,
a `read_filter`, a `write_filter`, and read/write column lists. That is the only mechanism: there
is no separate per-person policy, and no implicit "sees everything" role — a table a role does not
list is a table its holders cannot reach, `admin` included.

Two consequences worth knowing:

- **`{user_id}`, `{email}` and `{workspace}` resolve to the caller**, so one role with
  `owner_id = {user_id}` gives every holder their own rows. Create one role, not one per person.
  **Prefer `{user_id}`**: it is the account's permanent identity, while an address can be changed
  or reassigned. Store the caller's id in the owning column, not their email.
- **A machine credential is exempt from roles.** It *is* the app, so it reads every row of its own
  app — which is why an app-credential read never proves a filter works.

## Building vs running, and the three identities

Building the app and running the app are different jobs with different credentials. Confusing them —
or confusing any of these three — is the most common mistake.

| Who | Credential | Runs as | Protocol |
|---|---|---|---|
| You, building | your session token (`atomhouse_sess_…`) | you | MCP over `/mcp` |
| A visitor on the page | that app's session cookie, set by signing in | **that visitor** — their grants, their row filters | REST |
| The app's own work, off the request path | a machine credential (`atomhouse_app_…`) | the app; no user, so `{user_id}` filters match nothing | MCP or REST |

You use MCP to create tables and seed data. The app you generate uses REST, with each of its users
signed in separately. **The app must never contain your session token**: it is yours, it is not
scoped to the app, and it outlives the app. A machine credential is the one identity that may travel
to a server — never to a browser. If the app has a server-side consumer, see
[the app's own identity](reference/access.md#the-apps-own-identity).

### The page is REST

**MCP is for you; REST is for the page.** The page you generate does not use MCP and cannot: it is a browser, it has no MCP client, and it must not carry your token.

Every data operation has an MCP tool except **CSV import and export**, which exist only as REST
endpoints — see [data](reference/data.md#csv-bulk-load-and-what-it-will-not-do). A file is the one
thing an MCP argument is the wrong shape for, and it is the reason those two are the exception
rather than an oversight.

The page's own contract is a separate document, generated per app:

```
GET https://atomhouse.cloud/api/v1/workspaces/{ws}/apps/{app}/rest.md
```

Fetch it once, when you start writing the frontend. It carries the endpoints, the sign-in flow, the CSRF header, CORS, and what a caller is allowed to see. It needs the same `Authorization` header as MCP; a `404` means the app slug is wrong or the app does not exist — not that the document is unlisted.

## Testing the sign-in page

You cannot test a sign-in form without an account to sign in with. `test_account` borrows one:

```
test_account { "workspace": "<slug>" }
→ { "email": "test-<workspace-id>@test.invalid",
    "password": "...",
    "expires_at": "2026-11-08T18:52:28+00:00",
    "lease_minutes": 30, "reused": true,
    "cleanup": "..." }
```

**You are borrowing it, not claiming it.** The lease lasts 30 minutes or until you return it with
`return_test_account`. While you hold it, no other session can borrow the same workspace's test
account — a second caller gets a `409` telling it the account is in use. That is deliberate: two
agents sharing one account would invalidate each other's password the moment either called
`test_account` again.

**The password changes every time it is borrowed.** An old credential you copied somewhere stops
working. If you lose it, calling `test_account` again inside your lease gives you the same account
with a fresh password — it does not extend or move the lease.

What it is for:

- signing in with a real email and password, to see the form work
- requesting access to an app, so you can see the pending state and approve it
- being a second user in an app whose policies differ by role

The account is deleted automatically after three days and owns no workspace, so nothing it did
outlives it. **Do not put real data in it.**

### Clean up, then return it

Two separate things, and both matter:

**1. Remove what the test account was given.** If you approved it into an app, added it to a
workspace, or granted it an app role, undo that:

```
remove_member { "workspace": "<slug>", "user": "test-...@test.invalid" }
```

or revoke the grant through the app's access tools. An approved account left in place is a real
member of the app with real permissions — the automatic cleanup removes the *account* after three
days, not the decisions you made with it. And because the account is reused, **a membership you
leave behind is a membership the next agent inherits**: their test starts with permissions they
never granted, and the failure looks like a policy bug rather than leftover state.

**2. Return the account.**

```
return_test_account { "workspace": "<slug>" }
→ { "released": true }
```

This ends your lease immediately so the next session does not wait out the remaining minutes. If
you skip it, the lease expires on its own and the account is reclaimed — so the cost of forgetting
is a delay for the next caller, not a leak. Returning twice, or after expiry, is not an error.

The same applies to any row the test account created. Test data in a production app is still
production data — and unlike a membership, a row written to a shared table does not disappear when
the account does.

## Working with data — over MCP

This section is about you changing data. A page calls REST instead, and has its own document — see [The page is REST](#the-page-is-rest).

| Tool | Does |
|---|---|
| `list_tables` | tables and views in an app |
| `describe_table` | columns, types, nullability, primary key |
| `query` | SQL, scoped to one app |
| `read_rows` | paged rows with filters and sort |
| `insert_rows` | one or more rows |
| `update_rows` | by primary key |
| `delete_rows` | by primary key |

**`describe_table` first, every time.** It returns the columns and their types as text, so that one call is all you need before writing SQL — there is no reason to follow it with a `SELECT *` to discover the shape. A guessed column name is the most common refused call, and one `describe_table` costs less than the error plus the retry.

`query` runs DuckDB, which is not Postgres: see [Dates](reference/data.md#dates) and [SQL](reference/data.md#sql) before writing anything with a date or a `GROUP BY`.

## Functions: what they are for

A function is JavaScript the platform runs. Its whole reason to exist is **work that happens when
nobody clicks** — a schedule, or a row changing. That is the one thing no page and no REST call can
do.

| A function can | A function cannot |
|---|---|
| `atomhouse.query(sql)` — read, policed by the caller | span two tables in one transaction |
| `insert` / `insertMany` — one row, or a batch in one transaction | reach the network except through `atomhouse.ai` |
| `update` / `delete` — one row, by full primary key | run longer than 5 seconds outside a task |
| `atomhouse.ai.chat` / `.agent` — a model, in a task | |

**Before you build one, ask one question: does this need to happen while nobody is looking?** Yes →
a function with a trigger. No → do it from the page with REST. That question is decidable, and
"the endpoints cannot express it" is not — you will always believe they can.

The second reason is closeness: a rule you would rather not ship to the browser — how a total is
computed, what counts as overdue — belongs in a function, not in the page's JavaScript.

A function gets `timeout_ms`: **2000 by default, 5000 at most**. Work that needs longer — a model
call, a batch backfill — is a task: `POST …/fn/{name}/tasks`, five minutes.

Full reference, including the API and the trigger shapes: [reference/functions.md](reference/functions.md).

**A model belongs here when the same question would otherwise be asked again.** Extracting fields
from every new photo is a trigger on insert; extracting them once by hand and writing the answer
into a column means asking again next week. See
[reference/functions.md#calling-a-model](reference/functions.md#calling-a-model).

## A model, from a function

A workspace owner configures a model connection once in Settings → AI models. After that a page or a
function can use it, on the workspace's key and against its quota.

**One decision, and it is decididable.** Ask where the result goes:

- **The user is waiting, nothing is written, one question at a time** → call
  `POST /workspaces/{ws}/apps/{app}/ai` from the page. No function, no task, one request.
- **The result is written to a table, or batched over rows, or reused by more than one page** →
  put it in a function and start a task. The row lands once, every reader sees it, and the cost is
  paid once.

Anything else is the first case. "It might be slow" is not a reason for the second: a page waiting
three seconds is what the first case is for.

**The body of `/ai` does not name a model.** The workspace's default answers, and the reply does not
say which — a generated frontend uses the capability without being able to read or change the
configuration. Inside a function, `atomhouse.ai.chat` and `.agent` name one or accept the default.

**In a function it only works in a task.** A function gets 2 seconds by default and 5 at most; a
model takes that long to start. Called in a request, `atomhouse.ai` throws and names the task endpoint. A page calling `/ai`
is a normal request and never sees that error.

Full reference — parameters, the agent's tools, the error codes, and what to do when a reasoning
model answers with nothing: [reference/functions.md#calling-a-model](reference/functions.md#calling-a-model).

### The two things that actually go wrong

**A reasoning model given `max_tokens: 1`** spends it all thinking and returns no text. Give it a
real budget; see the parameter table in the reference.

**A write the model chose.** `agent` checks the caller's permissions, but the model picks the
arguments, and a prompt injected through data it reads can pick the wrong ones. If the agent only
needs to read, set `readonly: true` — do not rely on the prompt.

## What this platform does not do

**Not provided:** durable multi-step workflows with retries and state, background job queues, email
delivery, webhooks. A trigger is not a job queue. If the app needs one of these, say so.

## Every tool, in one list

Every MCP tool, by name. Deleting an app, a model or a site is **not** here — those are REST, see
[Cleaning up](reference/access.md#cleaning-up).

Each tool carries its own schema; ask the server for the arguments rather than guessing:

```bash
curl -s https://atomhouse.cloud/api/v1/mcp \
  -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

That costs one call and returns the real parameter names, which is cheaper than a validation error per guess.

| Tool | Does |
|---|---|
| `bootstrap` | **start here** — your role, the apps, their tables and row counts, in one call |
| `create_app` | a new app, its tables, and optionally a credential |
| `create_table` / `drop_table` | create and remove tables; **`ALTER TABLE` goes through `query`** |
| `list_tables` / `describe_table` | what exists |
| `create_model` / `list_models` | save a SELECT as a named view, and see them |
| `read_rows` / `query` | read |
| `insert_rows` / `update_rows` / `delete_rows` | write |
| `deploy_function` / `test_function` / `list_functions` | JS endpoints |
| `create_trigger` / `list_triggers` / `delete_trigger` | run a function on an event |
| `assign_app_role` / `list_app_roles` | who may use an app, and as what |
| `set_app_role` / `list_app_roles` | row and column limits per role |
| `put_object` / `get_object` / `list_objects` / `delete_object` | files, stored privately |
| `publish_site` / `upload_site_file` / `site_status` / `unpublish_site` | host the app here |
| `request_app_access` / `list_access_requests` / `review_access_request` | access requests |
| `test_account` / `return_test_account` | borrow a throwaway account for 30 minutes, and give it back |

`set_app_role` is how you build per-user visibility: a role whose `read_filter` is `owner_id = {user_id}` gives every holder their own rows, and a `read_columns` list hides the rest. One role serves everybody — do not create one role per person. Use `{user_id}` rather than `{email}`: the id cannot change, and an owning column holding ids keeps working when somebody's address does.

## Where the rest is

This file is what you need before the first call. The detail is in four documents beside it, each
readable on its own:

| Document | Read it when |
|---|---|
| [reference/data.md](reference/data.md) | writing SQL, dates, models, or importing and exporting CSV |
| [reference/functions.md](reference/functions.md) | the app needs server logic, a schedule, or file storage |
| [reference/publishing.md](reference/publishing.md) | you are about to put the page on the web, or a visitor is involved |
| [reference/access.md](reference/access.md) | the app's own identity, scoping who sees what, adding somebody to the workspace or handing out an invitation code, deleting something, or reading an error |

Open one only when its question comes up. They carry the same `workspace` and credential rules as
this file — one skill, split for size, not four documents with four conventions.
