# Admin API

> The dashboard's own JSON REST API — auth, SSO, projects, search, sources, members, MCP tokens, webhooks, metrics, the audit log and the error shapes every endpoint shares.

- Updated: 2026-11-04
- Source: https://contextator.com/en/docs/admin-api/
- Language: en-US
- Author: Muhammet Şafak

---
Everything the dashboard can do is a JSON REST call — the dashboard is just a client of this API. Use it
for scripted setup, scheduled re-indexing, or monitoring.

**Base URL** `http://localhost:3444/api`

## Authentication

Every request carries one of three credentials:

| | What it is | Who uses it |
|---|---|---|
| **A session cookie** | `contextator_session`, set by `POST /api/auth/login` | The dashboard, and anything driving a browser |
| **`Authorization: Bearer ctxk_…`** | An account's own **API token** — named, scoped to a subset of routes and, optionally, one project, revocable on its own | Scripts and CI jobs that should carry only *some* of an account's authority — see [API tokens](#api-tokens) below |
| **`Authorization: Bearer $ADMIN_TOKEN`** | Machine access with `root` permissions | Scripts, CI, cron that need the whole instance |

```bash
export API=http://localhost:3444/api
export TOKEN=your-admin-token
curl -s $API/projects -H "Authorization: Bearer $TOKEN" | jq
```

Five things follow from that split:

- **What you may do depends on who you are.** A session is bound to an account, so its instance role
  and its per-project memberships decide every call — see
  [Accounts and Permissions](/en/docs/accounts-and-permissions/). `ADMIN_TOKEN` always acts as `root`.
- **An API token can never do more than the account that minted it.** Its scope is checked *after*
  that account's own role and membership, so narrowing it — to one project, or to a handful of
  routes — can only take authority away, never add it.
- **A cookie request that changes something must come from this site.** The server checks
  `Sec-Fetch-Site`, falling back to `Origin` and `Referer`, and answers `403 csrf_blocked` otherwise.
  Bearer requests are exempt: they carry no ambient credential, which is why `curl` and CI — sending
  neither header — work unchanged.
- **Neither bearer token counts as a signed-in account, as far as these routes are concerned.** The
  endpoints that are about *your* account (`/api/auth/password`, `/api/auth/sessions`) require a
  session — that check refuses `ADMIN_TOKEN` and a scoped API token alike with `403 token_has_no_account`,
  even a token scoped to allow the exact route. Only a browser holding a session cookie can reach them.
- **A project you cannot reach answers `404`, not `403`**, the same as a project that does not exist,
  so ids cannot be probed. A route you may reach but not use in that way answers `403`.

`GET /api/health`, `GET /api/setup/status`, `POST /api/setup`, `POST /api/auth/login`,
`GET /api/auth/oidc/login` and `GET /api/auth/oidc/callback` are the only endpoints reachable with no
credential at all — the last two because the browser has no session yet when it asks for the redirect,
and the provider sends the **browser** back to the callback with the code, by redirect — not a
server-to-server call from the provider itself. Linking an already signed-in account to that same
provider (`POST /api/auth/oidc/link`, `DELETE /api/auth/oidc/link` — see
[Single Sign-On](/en/docs/sso/#linking-or-unlinking-your-own-account)) is different: it needs the
caller's own session, same as any other self-service account endpoint.

---

## Health

```bash
curl -s $API/health | jq
```

```json
{
  "ok": true,
  "version": "1.0.0",
  "uptimeSec": 3610,
  "db": "up",
  "database": { "mode": "embedded" },
  "embeddings": {
    "id": "local:Xenova/multilingual-e5-small:fp32:\"query: \"+\"passage: \"",
    "provider": "local", "model": "Xenova/multilingual-e5-small",
    "dimensions": 384, "dtype": "fp32", "ready": true
  },
  "chunkBudget": { "checked": true, "ok": true, "chunkMaxTokens": 96, "suggestedChunkMaxTokens": null },
  "sessions": { "total": 2, "streamable": 2, "sse": 0 },
  "allowedDocRoots": ["/docs"],
  "dataDir": "/data",
  "secretKeyConfigured": true,
  "uploads": { "maxFileBytes": 52428800, "maxFilesPerRequest": 500, "maxArchiveBytes": 268435456 }
}
```

Good liveness probe: `ok === true && db === "up"`. Good readiness probe: also `embeddings.ready`. The
response answers `503` with the same body while the database is unreachable, `200` otherwise — a monitor
does not need a second check for that.

`embeddings` carries the model's input window — `maxInputTokens` (what the model reads usefully), `truncatesAtTokens` (where the runtime cuts) and `windowSource` — together with `queryPrefix` and `passagePrefix` (empty strings for a symmetric model), and `chunkBudget` says whether `CHUNK_MAX_TOKENS` fits inside it (`checked` is `false` until the model has loaded), so a
misconfiguration that would silently truncate chunks shows up here before it shows up in search quality —
see [Configuration](/en/docs/configuration/#applying-changes).

An anonymous caller gets a shorter answer — `ok`, `version`, `db`, `authRequired` and `needsSetup` —
because the rest describes the machine. Past `uptimeSec`, `database`, `embeddings`, `chunkBudget` and `sessions` (shown above), a signed-in answer also carries `disk` — `{ freeBytes, totalBytes, minFreeBytes, ok }` for `DATA_DIR`, or `null` when the file system cannot be read; it informs and does not move `ok` or the status code — and `sync`, the band the source dialog works in: `{ defaultIntervalMinutes, minIntervalMinutes, maxIntervalMinutes, webhookMinIntervalMinutes, webhookVerificationWindowMinutes }`.

A signed-in `member` gets the middle shape: everything except `allowedDocRoots`, `dataDir`, `secretKeyConfigured` and the database target, which wait for an administrator. The fields a monitor watches are in both shapes.

## Setup and sign-in

| Method & path | Description |
|---------------|-------------|
| `GET /api/setup/status` | `{ needsSetup, oidc }` — `needsSetup` is `true` while this instance has no account; `oidc` is `{ enabled, buttonLabel }` when single sign-on is configured and `{ enabled: false }` otherwise. Public |
| `POST /api/setup` | `{ code, username, displayName?, email?, password }` → `201 { user }`, and the session cookie. Creates the first `root` account. `403 invalid_setup_code`, `409` once an account exists. Public |
| `POST /api/auth/login` | `{ username, password }` → `{ user, mustChangePassword }` and the cookie. `401 invalid_credentials` for both a wrong password and an unknown username, `403 account_disabled`, `429` with `Retry-After` when rate-limited. Public |
| `POST /api/auth/logout` | Revokes this session and clears the cookie → `204`. Idempotent |
| `GET /api/auth/me` | The signed-in account, its role, `authKind` (`session`\|`token`\|`apiToken` — a dashboard session, `ADMIN_TOKEN`, or an API token), and — for a `member` — its per-project roles in `projects`. Also `oidc` (`{ enabled, buttonLabel }`), `canLinkOidc` (`false` for root) and `federatedProviders` — see [Single sign-on](#single-sign-on) below |
| `POST /api/auth/password` | `{ currentPassword, newPassword }` → `204`. Clears `mustChangePassword`, revokes this account's **other** sessions and ends its MCP connector credentials. `401 invalid_credentials` when `currentPassword` is wrong |
| `GET /api/auth/sessions` | Your own live sessions: when each started, when it was last seen, its user agent and IP, and which one is `current` |
| `DELETE /api/auth/sessions?scope=others\|all` | End them → `204`. `others` is the default; `all` signs you out too |

```bash
# sign in and keep the cookie in a jar, then use it like a browser would
curl -s -c jar -X POST $API/auth/login -H 'content-type: application/json' \
  -d '{"username":"alice","password":"…"}' | jq
curl -s -b jar $API/auth/me | jq
```

## Single sign-on

Only present when this instance has an OIDC provider configured — see [Single Sign-On](/en/docs/sso/)
for who can link and why root cannot.

| Method & path | Description |
|---------------|-------------|
| `GET /api/auth/oidc/login` | Redirects to the identity provider to sign in. Public — the browser has no session yet |
| `GET /api/auth/oidc/callback` | The identity provider sends the **browser** back here with the code, by redirect — not a server-to-server call from the provider. Public because a sign-in arrives with no session yet; a link arrives with the session that started it, carried by the browser's own cookie on the redirect. Refuses to sign a `root` account in (`root_local_only`), even one whose link was made before a promotion to `root` — the role is re-read off the account at callback time, not assumed from when the link was made |
| `POST /api/auth/oidc/link` | Self-service, for an already signed-in account: starts the same redirect, but to *connect* the provider to this account rather than sign in fresh. A `POST`, so the same-site check applies. → `200 { url }` to navigate to. Refused for root (`403 root_local_only`) — root never signs in over SSO |
| `DELETE /api/auth/oidc/link` | Removes the caller's own linked identity → `204`. Scoped to your own account; there is no admin surface over another account's link. Not refused for root — a link made before a promotion to root stays in place until removed, and this is how. Also revokes every session and API token the account holds, including the one making this call, and — in the same transaction — every MCP OAuth access and refresh token the account was issued, so an MCP client signed in as it gets `401` until it authorizes again; other accounts are untouched. The unlink's audit event records the count as `detail.revokedMcpCredentials`. **`409 last_sign_in_method`** — nothing removed, nothing revoked — when the account has no local password and this link is its only way to sign in; an admin sets a password first with `POST /api/users/:id/password`, and the unlink then succeeds |

## Accounts

`/api/users/*` needs `admin` or `root`. Only a `root` account may create, change or delete another
`root` account. `PATCH /api/users/:id` refuses `409 root_requires_unlink` when asked to set
`role: "root"` on an account that still has a linked SSO identity — unlink it first with
`DELETE /api/auth/oidc/link` above.

| Method & path | Description |
|---------------|-------------|
| `GET /api/users` | Every account: role, active flag, `mustChangePassword`, project count, last sign-in, and `activeSessionCount` |
| `POST /api/users` | `{ username, displayName?, email?, role?, password?, mustChangePassword? }` → `201 { user, temporaryPassword }`. `role` defaults to `member` and `mustChangePassword` to `true`; omit `password` and one is generated and returned **once** |
| `GET /api/users/:id` | `{ user, activeSessionCount }` |
| `PATCH /api/users/:id` | `{ displayName?, email?, role?, isActive? }` → the updated account. A demotion or a disable also ends that account's sessions |
| `POST /api/users/:id/password` | `{ password? }` → `{ temporaryPassword }`. Forces a change at the next sign-in and ends that account's sessions and MCP connector credentials |
| `DELETE /api/users/:id` | Delete the account, its sessions and its memberships → `204` |
| `DELETE /api/users/:id/sessions` | Sign that account out everywhere → `204` |

`409` guards the last active root account against deletion, demotion and being disabled; `403` guards
an admin reaching for a root one, and anyone reaching for their own role, active flag or deletion.

```bash
# hand someone a new temporary password without touching the dashboard
ID=$(curl -s $API/users -H "Authorization: Bearer $TOKEN" | jq -r '.[] | select(.username=="alice") | .id')
curl -s -X POST $API/users/$ID/password -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' -d '{}' | jq -r .temporaryPassword
```

## API tokens

`/api/tokens*` needs only a session — any account manages its **own** tokens, and there is no admin
view over anyone else's. This is how a script or a CI job gets a credential narrower than
`ADMIN_TOKEN`: name it, optionally pin it to one project and an expiry date, and list exactly which
routes it may call. A token pinned to a project can call only that project's `/api/projects/:id/*` routes: an instance-level route such as `GET /api/projects` or `GET /api/audit` answers `403` even when the token's scope lists it. The dashboard's own **Account menu → API tokens** page is a client of exactly
these endpoints — mint, list and revoke there without touching `curl` at all.

| Method & path | Description |
|---------------|-------------|
| `GET /api/tokens` | Your own tokens: `id`, `name`, `prefix`, `scope`, `projectId`, `createdAt`, `lastUsedAt`, `revokedAt`, `expiresAt`. Never the secret |
| `POST /api/tokens` | `{ name?, scope, projectId?, expiresAt? }` → `201 { token, secret }`. `scope` is one or more `"<METHOD> <route template>"` strings, such as `"POST /api/projects/:id/reindex"`. Mint only checks that shape and, if given, that `expiresAt` is in the future — it does not check an entry against your own role, nor `projectId` against your own projects. What keeps the token bounded is that every request re-checks your *live* role and project access at call time. `secret` is returned this once and never again. `401 session_revoked` if your session was revoked before the mint could run. An `expiresAt` that is not in the future answers the standard `400 validation_failed`, with an entry in `issues` whose `path` is `["expiresAt"]` and whose `message` is `must be in the future` |
| `DELETE /api/tokens/:tokenId` | Revoke one of your own tokens → `204`. Takes effect on the very next request |

```bash
# mint a token that can only reindex one project — /api/tokens needs a session, not
# ADMIN_TOKEN, so sign in first (see "Setup and sign-in" above) and reuse the cookie jar.
# a cookie-authenticated request that changes something needs Sec-Fetch-Site too — see the
# CSRF rule above — curl never sends it on its own, unlike a real page's fetch would
curl -s -X POST $API/tokens -b jar \
  -H 'content-type: application/json' -H 'Sec-Fetch-Site: same-origin' \
  -d '{"name":"ci-reindex","scope":["POST /api/projects/:id/reindex"],"projectId":"'"$P"'"}' | jq
```

Deleting the project named in `projectId` deletes the token with it, rather than widening its reach.

## SSO group mappings

| Method & path | Description |
|---------------|-------------|
| `GET /api/oidc/group-mappings` | The mappings from an identity-provider group to a project and a role (`viewer` or `editor`). `admin` |
| `POST /api/oidc/group-mappings` | Add one; `409 mapping_exists` when that group already maps that project. `admin` |
| `DELETE /api/oidc/group-mappings/:id` | Remove one; the memberships that rested on it are recomputed in the same request. `admin` |

How the mappings are used at sign-in: [Single Sign-On](/en/docs/sso/#groups-grant-project-memberships).
`GET /api/projects/:id/members` returns `origin` (`manual` or `oidc_group`) and `groups` for each member, and while
`OIDC_GROUPS_CLAIM` is set the members API answers `409 membership_managed_by_group` for a group-granted row.
`GET /api/auth/me` carries `oidc.groups`.

## Project members

Who reaches one project. `root`, `admin` and `ADMIN_TOKEN` reach every project without a membership,
so only `member` accounts appear here.

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/members` | The project's members and their roles. Any member of the project may read it |
| `PUT /api/projects/:id/members/:userId` | `{ "role": "viewer" \| "editor" }` → the member. Creates or changes the membership (root/admin) |
| `DELETE /api/projects/:id/members/:userId` | Revoke access → `204` (root/admin) |

Adding a member to a project a `member` account can then see:

```bash
curl -s -X PUT $API/projects/$P/members/$ID -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' -d '{"role":"editor"}' | jq
```

`400` if the target is an `admin` or `root` account — they already have access, so a membership row
would say something untrue.

## Projects

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects` | All projects with counts, `mcpUrl` and the live indexing `job` |
| `POST /api/projects` | `{ "name": "demo", "rootPath": "/docs/demo", "index": true }` → `201`. `rootPath` is optional and creates a first local source. The response also carries `mcpToken` — `{ token, secret }` for the first MCP token a new project is born with, readable this once — or `null` |
| `GET /api/projects/:id` | One project in the list's shape, plus `quotas: { documents, chunks, uploadBytes }`, each `{ limit, used, inherited }`. `limit` is the effective limit (`0` is unlimited); `used` is the project's document count, chunk count and stored upload bytes (`null` when the disk could not be measured); `inherited` is `true` when the limit is the instance's `PROJECT_MAX_*` because the project has none of its own. A `viewer`'s |
| `GET /api/projects/:id/status` | One project plus its job |
| `POST /api/projects/:id/reindex?force=true` | Queue a run → `202 { job }`. `force` is `true`, `false`, `1` or `0`; a forced run writes a second index generation beside the live one, so it answers `507 insufficient_disk` when the embedded database's data directory is too full to hold it |
| `GET /api/projects/:id/runs` | Recent index runs, newest first |
| `GET /api/projects/:id/search?q=…&limit=…&source=…&path_prefix=…&version=…` | The same search the project's `search_docs` tool runs, as JSON: `{ query, limit, source, pathPrefix, version, belowFloor, scoreFloor, scoreFloorOverridden, hits: [{ score, fusedScore, denseRank, lexicalRank, path, title, headingPath, chunkIndex, content, contextBefore, contextAfter }] }`. `score` is the cosine similarity and is shown rather than ranked on; `fusedScore` is what ordered the list, and the two ranks say which half of search found the excerpt (`null` for the half that did not). `belowFloor` is whether an agent would have been told *no good match* — the hits come back either way, so the dashboard can show what was withheld. `scoreFloor` is the floor that decided it and `scoreFloorOverridden` says whether it is the project's own rather than the instance's. `limit` is 1–20 (default 5); `source`, `path_prefix` and `version` are optional. `400 invalid_request` for a source or a version this project does not have (the message names the ones it does), `409 not_indexed` when the project has no chunks, `409 model_mismatch` when they were embedded with another model |
| `GET /api/projects/:id/export` | The whole project — documents, chunks, source settings — as one `.tar.gz` (a project `manager`'s) |
| `POST /api/projects/import` | Multipart: the archive as a file part and an optional `name` field → `201` with a report of what was imported (an instance `admin`'s). `507 insufficient_disk` when `DATA_DIR`, and with the embedded database its data directory, cannot hold `DATA_DIR_MIN_FREE_BYTES` plus four times the archive's size; the check runs before the upload is read and again before it is unpacked, so a refusal leaves no project row or file behind |
| `DELETE /api/projects/:id` | Delete the project → `204` (`409` while indexing) |

### Quotas

| Method & path | Description |
|---------------|-------------|
| `PATCH /api/projects/:id/quotas` | `{ maxDocuments?, maxChunks?, maxUploadBytes? }`, each a whole number of `0` or more, or `null`: a number sets the project's own limit (`0` exempts it from the instance default), `null` hands it back to the instance's `PROJECT_MAX_DOCUMENTS`, `PROJECT_MAX_CHUNKS` or `PROJECT_MAX_UPLOAD_BYTES`, and a key left out stays as it was → `{ quotas }`, shaped as above. An unknown key or an empty body answers `400`, an unknown project `404`. A project `manager`'s, which only an instance `admin`, `root` or `ADMIN_TOKEN` is, so a project member never sets a limit. Audited |

An upload that would take the project past `maxUploadBytes` answers `413 quota_exceeded` with the limit, the bytes used and the bytes requested; an index run that crosses the document or chunk quota ends with the error code `quota_exceeded` instead of answering a request. If the stored upload bytes cannot be measured, the upload is refused with `503 quota_usage_unavailable` rather than let through.

### Secrets and personal data

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/findings` | The PII scan's findings for the project, for an `editor` and above (a `viewer` gets `403`): the document path, the rule, the position, a masked preview and a short group id. It never returns a value. See [Configuration](/en/docs/configuration/#scanning-documents-for-secrets-and-personal-numbers) |

### Query log and score floor

What agents asked of a project, and the relevance floor that decides when they are told *no good match*. Reading is a `viewer`'s; changing either is a project `manager`'s.

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/queries/summary?days=…&actor=…&model=…&generation=…&floor=…&limit=…` | A summary of the logged searches in a window. `days` is 1–90 (default 7); `actor` is `mcp` (default), `dashboard` or `all`; `limit` is 1–100 (default 20). `model` and `generation` are given together or not at all and name one retrieval configuration; `floor` (a number from 0 to 1, or `none`) narrows a named configuration and needs both. The answer also carries `reportedGaps`: what agents sent with `report_gap` in the window, grouped by question |
| `GET /api/projects/:id/queries/export?…` | The repeated questions as `application/x-ndjson` (a `….jsonl` file download), for the evaluation harness. Takes the same filters; `limit` is 1–500 (default 100). A `viewer`'s, as it reads the same log the summary does |
| `PATCH /api/projects/:id/query-log` | `{ "enabled": true \| false }` → `{ queryLogEnabled }`. Whether this project records what agents ask; takes effect on the next search and deletes nothing |
| `DELETE /api/projects/:id/query-log` | Delete this project's logged queries → `{ deleted, reportedGapsDeleted, dumpsUnaffected: true }` — the `report_gap` reports go with the queries; a dump already taken still holds the rows |
| `GET /api/projects/:id/score-floor/preview?floor=…&days=…&actor=…` | What a floor would cost before it is set: of the searches in the window, how many the proposed floor would answer that the current one refused, and the reverse, with a few of each. `floor` is a number from 0 to 1 or `instance`; every count is an upper bound (`atMost: true`) |
| `PATCH /api/projects/:id/score-floor` | `{ "floor": 0.5 }` or `{ "floor": null }` → `{ scoreFloor, instanceScoreFloor, effectiveScoreFloor }`. `null` hands the project back to the instance's `SEARCH_SCORE_FLOOR`; the next search reads the new value |

A floor does not have to be guessed. The server can measure the project with the floor off and propose one:

| Method & path | Description |
|---------------|-------------|
| `POST /api/projects/:id/score-floor/suggestions` | A project `manager`'s. Measures the live index with up to 100 probes — each the last eight words of a sentence taken from one of its chunks — and stores the highest floor that refuses none of them → `201 { suggestion }` (`id`, `createdAt`, `trigger`, `embeddingModel`, `liveGeneration`, `suggestedFloor`, `previousFloor`, `basis`, `appliedAt`). `200 { suggestion: null, reason: "insufficient_data" \| "no_fit" }` when fewer than 20 probes can be made or no floor fits. `409` when the project is not indexed, was indexed with another model, a measurement of it is already running or queued, or two other projects are already being measured. It never changes the project's floor. The server also makes one after a re-index caused by a model change (`trigger: model_change`). Audited |
| `GET /api/projects/:id/score-floor/suggestions` | A `viewer`'s. `{ current: { project, embeddingModel, liveGeneration }, suggestions }`, newest first; the newest ten are kept |
| `POST /api/projects/:id/score-floor/suggestions/:suggestionId/apply` | A project `manager`'s. Sets the project's floor to the suggestion's → `{ suggestion, scoreFloor, instanceScoreFloor, effectiveScoreFloor }`. `409` when it was already applied or when the project's model or live generation differs from the one measured; `404` for an unknown suggestion. Audited |

A probe is a fragment of the text it should find, so it usually scores higher than a real question: treat the suggestion as an upper bound and check it with `score-floor/preview` in both directions before applying it.

```bash
# create and index
curl -s -X POST $API/projects -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' \
  -d '{"name":"handbook","rootPath":"/docs/handbook","index":true}' | jq

# re-index everything, every night
for id in $(curl -s $API/projects -H "Authorization: Bearer $TOKEN" | jq -r '.[].id'); do
  curl -s -X POST "$API/projects/$id/reindex" -H "Authorization: Bearer $TOKEN" > /dev/null
done
```

### Golden questions

A project's own evaluation set: questions with the file (and optionally the heading) that should answer them. Reading is a `viewer`'s; changing the set is an `editor`'s. Refusal questions are not kept here.

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/golden-questions` | The set ordered by `key` → `{ questions: [{ id, key, lang, query, expectFile, expectHeading, tags, note, createdAt, updatedAt }] }`. `key` is the question's name (`^[a-z0-9][a-z0-9-]*$`, at most 100 characters, unique in the project); `expectHeading` and `note` are `null` when absent |
| `POST /api/projects/:id/golden-questions` | `{ key, lang: "en" \| "tr", query, expectFile, expectHeading?, tags?, note? }` → `201` with the view. `query` is 1–4000 characters; `expectFile` is a document path with the source name as its prefix (`<source>/<path>`). Unknown fields are refused. `409` for a key the project already has, `400 validation_failed` otherwise, `400` once the project holds 1000 questions. Audited |
| `PUT /api/projects/:id/golden-questions` | `{ questions: [...] }` (each as in `POST`, at most 1000) replaces the whole set in one transaction → `{ questions }`. A duplicate key or an invalid row changes nothing (`400`); `[]` clears the set. Audited |
| `GET /api/projects/:id/golden-questions/export` | The set as `application/x-ndjson`, downloaded as `golden.jsonl`, one question per line in the shape the repository's `eval/golden.jsonl` has |
| `GET /api/projects/:id/golden-questions/:questionId` | One question; `404` for an unknown project or question |
| `PATCH /api/projects/:id/golden-questions/:questionId` | Any of `lang`, `query`, `expectFile`, `expectHeading` (`null` clears), `tags`, `note` (`null` clears) → the view. `key` cannot change, and neither can an empty body (`400`). Audited |
| `DELETE /api/projects/:id/golden-questions/:questionId` | → `204`; `404` for an unknown project or question. Audited. The set also goes with its project |

### Golden-set eval runs

A project's golden questions (above) are asked of its live index by the server
itself, and each run is kept, so a regression is visible without running anything. A run is started by a swap
(a force or model-change re-index), by an incremental run that wrote chunks, removed files or recorded document
changes, by a change to the set (after 60 seconds without another), and by a manager. A project with no golden
questions does nothing and records nothing.

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/eval-runs?limit=` | A `viewer`'s. The runs, newest first (`limit` 1 to 100, default 30), without per-question ranks |
| `GET /api/projects/:id/eval-runs/:runId` | A `viewer`'s. One run, with `results`: `{ key, fp, rank }` per question asked (the 0-based rank of the right file in a page of ten, so `rank: 4` is fifth place; `null` when absent). Question text is never in a run |
| `POST /api/projects/:id/eval-runs` | A `manager`'s, audited. Starts a run now → `202 { runId }`; the run goes on in the background and is read back from the two routes above. The row is not guaranteed: a project deleted while it ran, a shutdown, or a failed write leave `runId` unwritten for good, so poll with a limit. A golden set emptied after the request is accepted records an `error` run. `409` when this project already has a run going or waiting, when the server is already running one (one at a time across the instance), or when the project has no golden questions |

A run carries `trigger` (`index_rebuild`, `index_incremental`, `golden_set`, `manual`), `status` (`ok` or `error`,
with `error` saying why and no figures), `generation`, `embeddingModel`, `questionCount`, `scoredCount`, `recall5`,
`mrr`, `regressed`, `comparedTo` and three lists of question keys: `lostKeys`, `skippedKeys` and `newlySkippedKeys`.

- **Scored as `npm run eval -- --project` scores**: the same search with the floor off and no reranker, and the
  same scoring module, so the two figures are one number.
- **A question whose `expectFile` is not in the live index is skipped.** It leaves the denominator and is listed
  in `skippedKeys`; one that the previous good run did ask is also in `newlySkippedKeys`, which is a warning and
  not a regression. A run with nothing left to ask is an `error`.
- **`regressed` is true when at least one question was lost** against the project's last `ok` run: it was in the
  top five then, is asked now with the same text, expected file and heading, and is not in the top five now. The
  count is gross, so a question gained elsewhere does not cancel a lost one. A question that was edited since is
  not compared. The first run has nothing to be compared with.
- **An index that changed during the run** (a swap) makes the run an `error`; the swap has already queued its own.
- The last 100 runs per project are kept, and runs are not part of a project export.

### Watching a job

`GET /api/projects` includes a `job` for any project with a live run:

```json
{ "phase": "embedding", "filesTotal": 84, "filesDone": 31, "filesSkipped": 22,
  "filesRemoved": 0, "chunksDone": 96,
  "sources": [{ "name": "handbook", "type": "local", "status": "synced" }],
  "queue": null }
```

`phase` is one of `queued`, `syncing`, `scanning`, `embedding`, `finalizing`, `done`, `error`. A queued
job carries `queue`: `{ position, aheadProjectName }` — its place in the queue and the name of the project that is running ahead of it (`null` when none is named). `queue` is `null` for a job that is not queued.

## MCP access

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/mcp-tokens` | The project's live tokens: `id`, `name`, `prefix`, `createdAt`, `lastUsedAt`, `expiresAt` (`null` for a token that never expires). The secret itself is never returned. An expired token stays in the list until it is revoked |
| `POST /api/projects/:id/mcp-tokens` | `{ "name": "claude-code", "expiresInDays": 90 }` → `201 { token, secret }`. `expiresInDays` is `30`, `90`, `365` or `null` (the default — no expiry). **`secret` is the only time the token is readable** |
| `DELETE /api/projects/:id/mcp-tokens/:tokenId` | Revoke it → `204`, closing the project's open MCP sessions |
| `PATCH /api/projects/:id/mcp-tokens/:tokenId` | `{ allowedCidrs: string[] \| null }` → the token's view, never the secret. Replaces the network allowlist of one live static token; `null` or `[]` removes the limit. It takes effect on the token's next MCP request. `400` as for `POST`, `404` for an unknown, revoked or OAuth-issued token, or one of another project. Audited under the route template, and the audit detail never contains the list. An `editor`'s |
| `PATCH /api/projects/:id/mcp-auth` | `{ "mode": "open" \| "token" \| "account" }` → `{ "mcpAuth" }`. Switching away from `open` also closes the project's open sessions. `account` requires the caller to be a member of the project through OAuth 2.1 on `/mcp/*`; a static `ctxm_…` token is refused in that mode |

`GET /api/projects` reports the current mode as `mcpAuth`. Closing an endpoint and minting a token:

```bash
curl -s -X PATCH $API/projects/$P/mcp-auth -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' -d '{"mode":"token"}' | jq

curl -s -X POST $API/projects/$P/mcp-tokens -H "Authorization: Bearer $TOKEN" \
  -H 'content-type: application/json' -d '{"name":"claude-code"}' | jq -r .secret
```

The client then sends that secret as `Authorization: Bearer ctxm_…` on `/mcp/<project-name>` — see
[Connecting AI Clients](/en/docs/connecting-ai-clients/).

A static token can also be bound to some of the project's sources (token scope, new in 0.6.0; see
[Connecting AI Clients](/en/docs/connecting-ai-clients/#limiting-a-token-to-some-sources)).
`POST /api/projects/:id/mcp-tokens` takes `sources`, a list of source **names** (absent or `null`: the whole project);
`PATCH /api/projects/:id/mcp-tokens/:tokenId/sources` (`editor`) takes `{ "sources": ["handbook"] }` to replace the scope
or `{ "sources": null }` to remove it. Refusals carry their code in `error`: `400 empty_scope` for `[]`,
`400 unknown_source` for a name the project does not have, `409 not_static` for an OAuth credential. `GET
/api/projects/:id/mcp-tokens` returns `sources` (`string[]` or `null`) and `scopeEmpty` on every token, and both writes are audited
with the names.

## Sources

| Method & path | Description |
|---------------|-------------|
| `GET /api/projects/:id/sources` | The project's sources. A source's credential (`secret`) is never returned — only `hasSecret`. The webhook secret of a `git`, `notion` or `confluence` source is returned in `webhookSecret` to an `editor` or above, and as `null` to a `viewer`; `hasWebhookSecret` says whether one is set |
| `POST /api/projects/:id/sources` `{ type, name, label?, flavor?, config?, secret?, syncIntervalMinutes?, index? }` | Add a source. `type` is `local`, `git`, `upload`, `notion`, `confluence`, `web`, `s3`, `gdrive` or `github`; `config` is type-specific — see the table below. `secret` is taken only by the types that use a credential (`git`, `notion`, `confluence`, `s3`, `gdrive`, `github`; for `s3` it is the JSON string `{"v":1,"accessKeyId":"…","secretAccessKey":"…"}`, for `gdrive` the service account's key file as Google issued it, and for `github` the bare token, which is optional); on `local`, `upload` or `web` it answers `400 invalid_request` naming the type, and `secret: null` (meaning "no secret") is accepted on every type. `syncIntervalMinutes` is 5–43200 or `null`; omitted takes the instance default |
| `PATCH /api/projects/:id/sources/:sid` | Change label, content type (`flavor`), config or token (`"secret": null` removes it), `syncIntervalMinutes` (`null` switches scheduling off) and `webhookMinIntervalMinutes` (0–43200; `null` returns the source to the instance's `WEBHOOK_MIN_INTERVAL_MINUTES`). Type and name are immutable. The webhook minimum is an API-only setting; the dashboard does not show it |
| `DELETE /api/projects/:id/sources/:sid` | Remove it, its documents and its files (`409` while indexing) |
| `POST /api/projects/:id/sources/notion/oauth` | Not an API-token route: starts the **Connect with Notion** flow and needs a dashboard session of a project editor. `GET /api/sources/notion/oauth` says whether the flow is configured; `GET /api/sources/notion/oauth/callback` is where Notion sends the browser back — see [Notion](/en/docs/notion/#connect-with-notion-oauth) |
| `POST /api/projects/:id/sources/:sid/sync` | Queue a run → `202 { job }` |
| `POST /api/projects/:id/sources/:sid/test` | Connectivity check → `{ ok, message }` |
| `POST /api/projects/:id/sources/:sid/webhook-verification` | Notion only: open the 15-minute, one-shot window in which the source's webhook accepts the `verification_token` Notion sends → `202 { webhookVerificationExpiresAt }`. `400` on a source that is not a Notion source |
| `POST /api/projects/:id/sources/:sid/webhook-secret` | Generate a new webhook secret: rotates it on a git source, and on a Confluence source turns the webhook on (or regenerates it) — see [Push Webhooks](/en/docs/push-webhooks/#confluence-data-center) |
| `DELETE /api/projects/:id/sources/:sid/webhook-secret` | Confluence only: turn the webhook off. Deliveries are then refused with `not_enabled` again |

Since 0.6.0, an edit that moves the host of a source's address — a Confluence `baseUrl`, a git `url`, an S3 `endpoint`, a
GitHub `apiBaseUrl` — while a credential is stored is refused with `400 invalid_request` unless the same request supplies
the credential again (the new value, or `"secret": null` to remove it). A Notion `secret` that starts with `{` is refused
the same way, because that is the shape of an OAuth connection, which only the dashboard flow creates.

Adding a git source:

```bash
curl -s -X POST $API/projects/$PROJECT_ID/sources \
  -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{
        "type": "git",
        "name": "api-docs",
        "label": "API reference",
        "config": { "url": "https://github.com/org/repo.git", "branch": "main", "subdir": "docs" },
        "secret": "ghp_…",
        "index": true
      }' | jq
```

`config` by type:

| Type | Keys |
|------|------|
| every type | `language` (the text-search configuration), `version` (what the `version=` search filter matches) |
| `local` | `path`, `extensions` |
| `git` | `url`, `branch`, `subdir`, `username`, `provider`, `extensions` |
| `upload` | `extensions` |
| `notion` | `rootIds`, `extensions` |
| `confluence` | `baseUrl` (required), `deployment` (`cloud` \| `datacenter`), `email` (Cloud only), `spaceKeys`, `extensions` — see [Confluence](/en/docs/confluence/) |
| `web` | `entryUrl`, `entryKind` (`auto` \| `sitemap` \| `llms` \| `crawl`, default `auto`), `extensions` — public pages only, no credential |
| `s3` | `bucket` (required), `endpoint` (empty for AWS), `region`, `prefix`, `pathStyle`, `extensions` — see [Document Sources](/en/docs/document-sources/#s3-buckets) |
| `gdrive` | `folderIds` (required, 1 to 50), `extensions`; `serviceAccountEmail` is written by the server — see [Document Sources](/en/docs/document-sources/#google-drive) |
| `github` | `owner` and `repo` (required), `apiBaseUrl`, `includeClosed`, `includeDiscussions` (needs a token, else `400 invalid_request`), `includeBots`, `extensions` — see [Document Sources](/en/docs/document-sources/#github-issues-and-discussions) |

## Uploads

| Method & path | Description |
|---------------|-------------|
| `POST /api/projects/:id/sources/:sid/uploads` | Open a session → `{ session }`. `507 insufficient_disk` when `DATA_DIR` has less than `DATA_DIR_MIN_FREE_BYTES` free |
| `POST /api/projects/:id/sources/:sid/uploads/:session/files` | `multipart/form-data`; each part's `filename` is the path inside the source. Archives are unpacked server-side. The disk check runs on every request, so a folder upload can get `507 insufficient_disk` part-way through; a refused request writes nothing |
| `POST /api/projects/:id/sources/:sid/uploads/:session/commit?mode=add\|replace` | Move the staged files in and queue a run → `202` |
| `DELETE /api/projects/:id/sources/:sid/uploads/:session` | Discard the staged upload |
| `GET /api/projects/:id/sources/:sid/files` | List an upload source's files |
| `DELETE /api/projects/:id/sources/:sid/files?path=…` | Delete one and re-index |

```bash
SESSION=$(curl -s -X POST $API/projects/$P/sources/$S/uploads -H "Authorization: Bearer $TOKEN" | jq -r .session)
curl -s -X POST "$API/projects/$P/sources/$S/uploads/$SESSION/files" \
     -H "Authorization: Bearer $TOKEN" -F 'file=@guide.md;filename=guides/guide.md'
curl -s -X POST "$API/projects/$P/sources/$S/uploads/$SESSION/commit?mode=add" \
     -H "Authorization: Bearer $TOKEN"
```

## Webhooks

| Method & path | Description |
|---------------|-------------|
| `POST /api/webhooks/git/:sourceId` | Push webhook for a git source, authenticated by the per-source secret — **not** by an account or `ADMIN_TOKEN` |
| `POST /api/webhooks/confluence/:sourceId` | Confluence Data Center webhook, signed with `X-Hub-Signature` over the per-source secret. `401 not_enabled` until the source's webhook is turned on |
| `POST /api/webhooks/notion/:sourceId` | Notion webhook. An unsigned `verification_token` is stored only while a verification window is open (see `webhook-verification` above); after that each delivery is signed with `X-Notion-Signature`. `401 verification_not_open`, `invalid_signature` or `not_verified` otherwise |

See [Push Webhooks](/en/docs/push-webhooks/).

## Metrics

```bash
curl -s http://localhost:3444/metrics -H "Authorization: Bearer $METRICS_TOKEN"
```

`GET /metrics` is a separate, Prometheus-shaped endpoint (`text/plain; version=0.0.4`) with its own
credential rules — it is **not** part of `/api/*` and is **not public** by default. It reports the
indexing queue by lane, whether one is running, the last index run and whether it worked, searches by
actor, the database connection pool, and whether the database itself answers.

Beyond those, `/metrics` carries what tells you when one process is no longer enough:
`contextator_search_request_duration_seconds{indexing}` and
`contextator_search_duration_seconds{phase,indexing}` for every MCP and dashboard search,
`contextator_embedding_batch_duration_seconds` and `contextator_embedding_batch_size` for indexing, and
`contextator_index_run_wait_seconds{lane}` for the queue. `contextator_mcp_requests_total{method,tool,era}` counts MCP
messages by protocol era (a tool name the server does not know is counted as `other`), and
`contextator_mcp_tool_duration_seconds{tool}` times each tool call. `contextator_mcp_gap_reports_total{outcome}`
counts `report_gap` calls by outcome (`accepted`, `limited`, `disabled` or `failed`), and golden-set eval runs are
counted without any label by `contextator_eval_runs_total`, `contextator_eval_run_errors_total` and
`contextator_eval_regressions_total`; a project's score is never a metric. No label carries a project, a document or a query.
Contextator runs one process with one indexer queue on purpose; revisit that when, sustained over a week, the search
p95 while indexing is above 1 s and twice the idle p95, the interactive queue wait p95 is above 5 minutes, or the
interactive backlog stays above zero for 15 minutes at a time.

It accepts a signed-in session, `ADMIN_TOKEN`, a `METRICS_TOKEN` bearer, or no credential at all when
`METRICS_PUBLIC=1` — see [Configuration](/en/docs/configuration/#observability). It answers `200` even
while the database is down, with `contextator_db_up 0` and the rows that need a database left out, so a
scrape gap is never how an outage gets reported. **While the database is down only the three credentials
that need no database read still work** — `ADMIN_TOKEN`, `METRICS_TOKEN`, `METRICS_PUBLIC` — a session
cookie is a database row and cannot be confirmed, so a browser presenting one gets `401` rather than
`500` during an outage. That is the reason to configure `METRICS_TOKEN` before an outage, not during one.

## Audit log

`/api/audit` needs `root` or `admin` — the log is instance-wide, and a project membership is not
standing to read who was given the root role.

| Method & path | Description |
|---------------|-------------|
| `GET /api/audit?actor&actorUser&action&project&from&to&limit&cursor` | The audit log, newest first. Every filter is applied in SQL: `actor` is the label as it was recorded at the time; `actorUser` is an account id matched **exactly** against the acting account — it returns that account's own sessions **and** every API token it owns, whatever the tokens are named; a value that is not a UUID answers `400 validation_failed`. `action` is `<METHOD> <route template>`; `project` is a project id or `none`. `from`/`to` are **UTC days**, and `to` is inclusive of the named day. `limit` is 1–200 (default 50). `cursor` is the previous page's `nextCursor` — a **row id**, never an encoded instant, so two events inside the same millisecond cannot lose one of themselves at a page boundary; a cursor naming no row answers `400`. Answers `{ events, nextCursor, filters, retentionDays }` — `nextCursor` is `null` on the last page, and `filters` (distinct actors, actions, projects, and the accounts with events, for the pickers) comes back on the first page only |

```bash
curl -s "$API/audit?action=DELETE%20/api/projects/:id&limit=50" \
  -H "Authorization: Bearer $TOKEN" | jq
```

### How it is written

Every state-changing request above leaves a row in `audit_events` naming the account that made it — what
was done, to which project, source, token, membership or account, and when. A sign-in and the creation
of the first account are recorded too, and so is `POST /oauth/authorize`, a person granting a connector
lasting read access to one project.

It is written by the **policy layer**, not by each handler, so there is no route that can be added
without being covered — and none that can opt out. The exceptions are **eight** — a source's test route, the
file-bytes route of an upload session, the three webhook deliveries (git, Notion, Confluence) and the three OAuth
protocol routes (`register`, `token`, `revoke`) — each named with its reason in
`src/auth/policy.ts`.

A route that *creates* something names nothing in its own path, so the new object's id is read back out
of the response, through a table of fixed paths in that same file, and kept only when the value found
there is a UUID — "who minted this token" is therefore a question the log answers, and it lines up
against the revocation that names the same id.

### What it does not hold

The rows carry no user content: a question, a document and an excerpt never reach a column of this
table. The only body fields any action may record are named in that same policy file, each restricted to
a closed set of values (`mode` is one of `open`/`token`/`account`, and so on). That keeps it a different
record from the query log, which holds what agents asked, is governed by its own retention, and has its
own per-project switch — the two are deliberately not one table.

Two things beyond that are deliberately not recorded. **Refused requests** — a refusal is the permission
matrix working, and logging every probe would turn the table into a scan log; the one exception is a
person refusing a connector at `/oauth/authorize`, which is somebody deciding rather than the matrix
declining. And **an action that changed something and then answered `5xx`**: the row is written only for
a response under 400, so a handler that commits and then fails afterwards leaves none. No handler in this
API is currently shaped that way, and `SECURITY.md` names it as the limit it is.

### Reading it

`GET /api/audit` and the dashboard's **Audit log** panel (account menu, beside Users) are both root/admin
only. Each row renders as a sentence ("dana deleted a source from handbook") rather than as the columns
it is stored in. "Who" is two pickers: **Actor** is the label as it was recorded, and **Account** is the
account id — which finds that account's own actions together with those of every API token it owns, since
a token's label is only its name and owner and cannot gather them on its own. A project that has since
been deleted still has its rows: `project_id` carries no foreign key, so the panel cannot look its *name*
up, and says so on the row rather than leaving it blank.

The two columns the panel filters on — `actor_label`, because it outlives the account, and `action` — are
indexed by migration `0011`. At 200,004 rows a selective actor filter runs in 0.07 ms against 9.7 ms
without the index, a page turn is 3 ms, and a first page is 19–52 ms because it also fills the filter
dropdowns with three `DISTINCT` scans no index can help — paid once per filter change, never per page
turn.

The log is **not tamper-evident** — anyone with database access can remove a row and nothing here would
show it (`SECURITY.md`) — and rows older than `AUDIT_LOG_RETENTION_DAYS` are swept on the same
quarter-hourly timer as expired sessions.

## Errors

| Status | Meaning |
|--------|---------|
| `400` | `validation_failed` — the body or query did not match its schema; `issues` lists each problem. Or `invalid_request` — a bad path, a missing `SECRET_KEY`, a password the policy refuses; `message` explains |
| `401` | No credential, or a wrong one. `setup_required` means this instance has no account yet |
| `403` | Signed in, but not allowed: `forbidden`, `csrf_blocked`, `password_change_required`, `account_disabled`, `token_has_no_account`, `invalid_setup_code`, `root_local_only` |
| `404` | Unknown project, source or session — **and** any project this account has no access to |
| `409` | Duplicate name, the project is indexing, setup is already complete, the last root account, or a refusal that carries its own code (`root_requires_unlink`, `not_indexed`, `model_mismatch`, and the codes of a refused project import). `DELETE /api/auth/oidc/link` answers `409 last_sign_in_method` instead when the account has no local password — unlinking would leave it no way to sign in, so nothing is removed until an admin sets one |
| other `4xx` | `request_error` — a rejection by the framework itself, before any route-specific check: malformed JSON, a body over the size limit, an unsupported content type. `message` is Fastify's own |
| `429` | Too many sign-in attempts. `Retry-After` and `retryAfterSec` say how long |
| `507` | `insufficient_disk` — a forced re-index, an import, or an upload (opening a session or sending files) was refused because the disk cannot hold it; nothing was written |
| `500` | Internal error — the response says only that; the details are in the logs |

Errors are JSON: `{ "error": "conflict", "message": "…" }`, with `issues` on `validation_failed` and `retryAfterSec` on `429`. The codes named in the table are the ones this page mentions, not a closed list.

## Notes

- A source's credential and an account's password are never returned: a source only reports `hasSecret`, and a password is shown only the one time a temporary one is generated. A webhook secret is different — it is returned to an `editor` or above (see Sources), because an operator needs to paste it into the sender.
- `POST /api/projects/:id/reindex` is safe to call often: indexing is incremental.
- Authorization is decided server-side from one policy table covering routes by method and shape, so a
  new endpoint is protected the moment it exists. What the dashboard hides is cosmetic.
- The API is bound to the same port as the dashboard and the MCP endpoints, so anything that can reach
  one can reach the others ([Security](/en/docs/security/)).
