# Agent onboarding

Go from nothing to an MCP token with plain HTTP calls - create an account, sign in, create an organization and mint a token - and see which steps an agent finishes alone and which need a person.

An agent can reach a working [MCP token](/api/mcp) with five HTTP calls and no
dashboard. This page gives each call as `curl`, the response you get, and
what to do when the server answers with a block that only a person can lift.

Every example reads the server address from an environment variable. Use the
address of the server you are connecting to:

```bash
export COHORLY_URL="https://<your-cohorly-server>"
export COHORLY_DASHBOARD_ORIGIN="https://<the-dashboard-that-serves-it>"
```

`COHORLY_DASHBOARD_ORIGIN` is the origin of the dashboard in front of that
server (the value the server runs with as `COHORLY_DASHBOARD_ORIGIN`). The
sign-in endpoints refuse a request that carries a session cookie but no
trusted `Origin` header (`403`, `MISSING_OR_NULL_ORIGIN`), so every call below
sends one.

## What an agent can do alone

| Step                           | Self-hosted server                                                                    | Cohorly Cloud                                        |
| ------------------------------ | ------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Create the account and sign in | Alone                                                                                 | Alone                                                |
| Create the organization        | Alone. The first account on a new server becomes the owner **without an invite code** | Needs a human: an **invite code** is always required |
| E-mail verification            | Needed only if the server sends e-mail. The link in the e-mail needs a human          | Same                                                 |
| Two-factor authentication      | Alone if you hold the authenticator secret. Otherwise a human                         | Same                                                 |
| Choose the token's scopes      | A human decides which scopes the agent may hold                                       | Same                                                 |

Only an **owner** of the organization can mint an MCP token, and only with an
account credential: nothing an MCP token or a project token holds can mint
another one.

Before you start, one unauthenticated call tells you which of these apply:

```bash
curl -s "$COHORLY_URL/api/auth-methods"
```

```json
{
  "emailPassword": true,
  "google": false,
  "mode": "self-host",
  "inviteRequired": false,
  "emailVerificationRequired": false
}
```

`mode` is `cloud` or `self-host`. `inviteRequired: true` means step 4 needs an
invite code. `emailVerificationRequired: true` means a person must open a
link before step 4 works.

## The sequence

Five calls, in this order. Steps 1 to 3 are the account, 4 is the
organization, 5 is the token.

### 1. Create the account

```bash
curl -s "$COHORLY_URL/api/auth/sign-up/email" \
  -H "Content-Type: application/json" \
  -H "Origin: $COHORLY_DASHBOARD_ORIGIN" \
  -d '{"name":"Agent","email":"agent@example.com","password":"<a long random password>"}'
```

```json
{
  "token": "<session id>",
  "user": {
    "name": "Agent",
    "email": "agent@example.com",
    "emailVerified": false,
    "twoFactorEnabled": false,
    "id": "<user id>"
  }
}
```

The response also sets a `better-auth.session_token` cookie. The account
exists now, but it belongs to no organization yet.

### 2. Sign in

Keep the session in a cookie jar:

```bash
curl -s -c cookies.txt "$COHORLY_URL/api/auth/sign-in/email" \
  -H "Content-Type: application/json" \
  -H "Origin: $COHORLY_DASHBOARD_ORIGIN" \
  -d '{"email":"agent@example.com","password":"<a long random password>"}'
```

```json
{
  "redirect": false,
  "token": "<session id>",
  "user": { "email": "agent@example.com", "emailVerified": false, "twoFactorEnabled": false }
}
```

If the account has two-factor authentication on, this call answers
`{"twoFactorRedirect":true,"twoFactorMethods":["totp"]}` and sets no session.
See [Two-factor authentication](#two-factor-authentication).

### 3. Get the account token

The account token is a short-lived JWT that every `/api/*` route accepts as
`Authorization: Bearer`:

```bash
curl -s -b cookies.txt "$COHORLY_URL/api/auth/token"
```

```json
{ "token": "<account token>" }
```

```bash
export COHORLY_ACCOUNT_TOKEN="<account token>"
```

The account token lives **15 minutes**. The session cookie lasts 7 days, so
when the token expires, call this endpoint again. After a person verifies the
e-mail, fetch a new account token too: the old one still says the address is
not verified, and step 4 keeps refusing it.

Check where you stand:

```bash
curl -s "$COHORLY_URL/api/me" -H "Authorization: Bearer $COHORLY_ACCOUNT_TOKEN"
```

A new account answers with `"org": null, "role": null`: signed in, in no
organization yet.

### 4. Create the organization

```bash
curl -s "$COHORLY_URL/api/onboard" \
  -H "Authorization: Bearer $COHORLY_ACCOUNT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"orgName":"Acme","projectName":"Web"}'
```

```json
{
  "org": { "id": 1, "name": "Acme", "plan": "free", "require_two_factor": false },
  "project": { "id": 1, "name": "Web", "token": "<project token>", "timezone": null }
}
```

Status `201`. The account is now the **owner** of the organization.
`projectName` is optional; without it `project` is `null`. The project token
in this response is for [ingestion](/api/ingestion), not for MCP.

On a self-hosted server whose first account has not onboarded yet, leave out
`inviteCode`. Every later account, and every account on Cohorly Cloud, sends
the code it was given: `"inviteCode":"<code>"`.

### 5. Mint an MCP token

```bash
curl -s "$COHORLY_URL/api/mcp/tokens" \
  -H "Authorization: Bearer $COHORLY_ACCOUNT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"my agent","scopes":["read"]}'
```

```json
{
  "token": "chrly_mcp_<43 characters>",
  "row": {
    "id": 1,
    "name": "my agent",
    "prefix": "<8 characters>",
    "scopes": ["read"],
    "projectId": null,
    "expiresAt": 1000000000000,
    "revokedAt": null
  }
}
```

Status `201`. The token is shown **once**: the server keeps only its hash.
Keep it for the next call:

```bash
export COHORLY_MCP_TOKEN="chrly_mcp_<43 characters>"
```

Fields:

- `scopes`: any of `read`, `write`, `governance`. Defaults to `["read"]`.
  Pick the narrowest set the agent needs.
- `projectId`: pin the token to one project of the organization.
- `expiresInDays`: `1` to `365`, default `90`. A token always expires.

An organization holds at most 20 live tokens (`409`, `token limit reached`).
See [MCP Server](/api/mcp) for what each scope allows.

### Check the token

Call the `list_projects` tool over [MCP](/api/mcp):

```bash
curl -s -N "$COHORLY_URL/mcp" \
  -H "Authorization: Bearer $COHORLY_MCP_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_projects","arguments":{}}}'
```

```text
event: message
data: {"result":{"content":[{"type":"text","text":"1 project(s): Web (id 1)"}, ...],"structuredContent":{"projects":[{"id":1,"name":"Web","eventCount":0,"timezone":null}]}},"jsonrpc":"2.0","id":1}
```

## When a step needs a human

These are the answers the server gives when a step is blocked, with the
real status, code and message. All bodies are JSON.

### An invite code is missing or wrong (step 4)

Without a code on a server that requires one, or without `orgName`:

```json
{ "error": "inviteCode, orgName required" }
```

Status `400`. With a code the server does not know:

```json
{ "error": "invalid invite" }
```

Status `400`. On Cohorly Cloud the code comes from a person: ask for it. On a
self-hosted server, `inviteRequired` in `GET /api/auth-methods` is `false`
only until the instance has its first owner; after that, accounts need a
code or an invite from an owner. A server started with a bootstrap admin
e-mail never skips the code.

A second call to `POST /api/onboard` from an account that is already in an
organization answers `409`, `{"error":"already onboarded"}`.

### The e-mail is not verified (step 4)

A server that can send e-mail (or is set to demand verification) refuses
`POST /api/onboard` until the address is verified:

```json
{
  "error": "email verification required",
  "code": "email_verification_required",
  "message": "Verify your email address before you continue.",
  "resolution": "Open the link in the verification email, or request a new one, then try again."
}
```

Status `403`. Opening the link is a human step. To send a new e-mail:

```bash
curl -s -b cookies.txt "$COHORLY_URL/api/auth/send-verification-email" \
  -H "Content-Type: application/json" \
  -H "Origin: $COHORLY_DASHBOARD_ORIGIN" \
  -d "{\"email\":\"agent@example.com\",\"callbackURL\":\"$COHORLY_DASHBOARD_ORIGIN/\"}"
```

Once the link was opened, go back to step 3 for a new account token, then
repeat step 4.

### Only an owner can mint a token (step 5)

A member of the organization, not an owner, gets:

```json
{ "error": "forbidden" }
```

Status `403`. Ask an owner of the organization to mint the token, or to make
the account an owner. An unknown scope answers `400`, `{"error":"invalid scopes"}`,
and an expiry outside 1 to 365 days answers `400`,
`{"error":"expiresInDays must be 1..365"}`.

### Choosing the scopes

Which scopes an agent holds is a decision for a person. `write` lets it
create and change cohorts, reports and boards, and `governance` the data
dictionary. Deletes and other irreversible changes always wait for a person
to approve them, whatever the scopes.

## Two-factor authentication

Two-factor authentication changes steps 2 and 3, and an organization can
require it of every member.

### An account with two-factor on

Step 2 answers `200` with no session:

```json
{ "twoFactorRedirect": true, "twoFactorMethods": ["totp"] }
```

Finish the sign-in with a current code from the authenticator (the cookie jar
keeps the pending sign-in; send the same one):

```bash
curl -s -b cookies.txt -c cookies.txt "$COHORLY_URL/api/auth/two-factor/verify-totp" \
  -H "Content-Type: application/json" \
  -H "Origin: $COHORLY_DASHBOARD_ORIGIN" \
  -d '{"code":"<6 digits>"}'
```

A wrong code answers `401`, `{"message":"Invalid code","code":"INVALID_CODE"}`.
A backup code goes to `/api/auth/two-factor/verify-backup-code`. Then
continue with step 3. An agent can only do this if a person gave it the TOTP
secret or a backup code.

### An organization that requires two-factor

When the organization requires it, a member who signs in with a password and
has no second factor gets, from every `/api/*` route except `GET /api/me`:

```json
{
  "error": "two factor required",
  "code": "two_factor_required",
  "message": "Your organization requires two-factor authentication.",
  "resolution": "Turn on two-factor authentication for your account, then try again."
}
```

Status `403`. `GET /api/me` still works and shows it in
`twoFactor.setupRequired: true`. Turning on the factor is done in the
dashboard, or through `/api/auth/two-factor/enable` followed by
`/api/auth/two-factor/verify-totp`, which keep working while the account is
blocked.

The `/mcp` endpoint does not use this body. A credential whose owner is
blocked by the requirement answers `401`:

```json
{
  "error": "invalid_token",
  "error_description": "Missing or invalid MCP credential. See docs/MCP.md section 5."
}
```

The same `401` answers a missing, revoked or expired token, so check
`GET /api/me` to tell the cases apart. What each of the four credentials
`/mcp` accepts gets, and what the agent does next, is in
[MCP server: Two-factor authentication](/api/mcp#two-factor-authentication).
