# API Reference Overview

> Three isolated HTTP planes (single-port vs split-plane listeners), plane authentication, keyset cursor pagination, query filter operators, sorting, expansion, and headers.

OvertCMS Core organizes all HTTP traffic into **three strictly isolated HTTP planes**—Delivery, Agent, and Admin—plus an asynchronous `worker` plane. Each plane has its own route namespace, authentication contract, and failure boundary.

---

## Base URLs: Single-Port vs Split-Plane Listeners

You can run all planes inside one Go binary on a single port for development or small deployments, or bind each plane to a separate listener/network interface in production.

### Single-Port Combined Mode (Default)

By default, `OVERTCMS_PLANES=delivery,agent,admin,worker` and `OVERTCMS_BIND=:8080` serve all three HTTP planes on one listener:

| Plane | Base Path(s) on `:8080` | Purpose |
| --- | --- | --- |
| **Delivery** | `/delivery/v1/*` | Read-only public (or API-key-gated) content, media streaming, redirects, sitemap |
| **Agent** | `/.well-known/agent-cms.json`, `/llms.txt`, `/mcp`, `/agent/v1/*` | Scoped API key programmatic CRUD, batch, media upload, prompt, native MCP |
| **Admin** | `/admin-api/v1/*` | Human user sessions, RBAC, MFA/WebAuthn/OIDC, schema studio, API keys, audit logs |
| **Health** | `/healthz`, `/readyz` | Liveness and database readiness probes (mounted on every active HTTP plane) |

### Split-Plane Isolated Mode (Production)

Assign dedicated bind addresses—or deploy separate processes with `--planes`—so the Admin Plane stays private behind a VPN/Tailscale interface while the Delivery Plane sits behind your public CDN:

```bash
# Single process with 3 isolated listeners
OVERTCMS_DELIVERY_BIND=":8081" \
OVERTCMS_AGENT_BIND=":8082" \
OVERTCMS_ADMIN_BIND="127.0.0.1:8083" \
./overtcms

# Or separate dedicated processes
./overtcms --planes=delivery --delivery-bind=":8081"
./overtcms --planes=agent    --agent-bind=":8082"
./overtcms --planes=admin    --admin-bind="127.0.0.1:8083"
./overtcms --planes=worker
```

<Note>
  Each isolated listener mounts **only** its own plane's routes plus `/healthz` and `/readyz`. Requesting an `/admin-api/v1/*` route on the Delivery or Agent listener returns `404 not_found`.
</Note>

---

## Authentication Per Plane

Authentication credentials **never cross plane boundaries**:

| Plane | Accepted Credential | Explicitly Rejected | Enforcement Details |
| --- | --- | --- | --- |
| **Delivery** | None (public read-only by default). When `OVERTCMS_DELIVERY_REQUIRE_API_KEY=true`: `Authorization: Bearer ocms_...` (`delivery:read` scope). Draft previews: `X-Preview-Token: pv_...`. | Non-`ocms_` tokens when Delivery API key is enabled. | Serves `publishedData` only (except valid single-entry `X-Preview-Token`). Respects `allowedPostTypes` when API key auth is enabled. |
| **Agent** | `Authorization: Bearer ocms_<live\|test>_<16hex>_<64hex>` (scoped API key). `/.well-known/agent-cms.json` is always public. | Human JWTs and browser cookies (`401 invalid_api_key`). | Enforces preset/custom scopes (`public_read`, `agent_drafter`, `agent_publisher`, `schema_admin`), `allowedPostTypes`, IP/CIDR allowlist, per-key RPM & daily quotas, and `agentWritesPaused` kill switch. |
| **Admin** | `HttpOnly`, `SameSite=Lax` cookies (`overtcms_access` on `/admin-api`, `overtcms_refresh` on `/admin-api/v1/auth`) **or** `Authorization: Bearer <access-jwt>`. | API keys (`ocms_...`) are unconditionally rejected (`401 invalid_token`). | Cookie-authenticated mutations require CSRF checks (`Sec-Fetch-Site: cross-site` rejected; `Origin` must match canonical `scheme://host` or `OVERTCMS_WEBAUTHN_RP_ORIGIN`). 5-role RBAC (`owner`, `admin`, `editor`, `writer`, `viewer`) + Step-Up MFA (`OVERTCMS_STEP_UP_MFA_TTL`, default `15m`) via TOTP or WebAuthn for privileged actions. |

---

## Keyset Cursor Pagination

All collection list endpoints (`/delivery/v1/{postType}`, `/agent/v1/collections/{postType}/entries`, `/admin-api/v1/sites/{siteSlug}/collections/{postType}/entries`, and reference `/options`) use **opaque keyset cursor pagination**—never offset pagination—for stable O(1) deep paging:

- **`limit`:** Positive integer; defaults to **`20`**, clamped to a maximum of **`100`**.
- **`cursor`:** Pass the opaque URL-safe base64 `nextCursor` returned by the previous response.
- **`hasMore`:** Boolean indicating whether another page exists.
- **Sort binding:** Cursors encode the active `sort` field and direction. Changing `sort` while reusing an old cursor returns **`400 invalid_cursor`**.

```json
{
  "items": [ ... ],
  "nextCursor": "eyJmIjoicHVibGlzaGVkQXQiLCJkIjp0cnVlLCJ0cyI6IjIwMjYtMTEtMjVUMTQ6MDA6MDAuMDAwMDAwMDAwWiIsImlkIjoiMDE5NWM4YTItMDAwMS03MDAwLTgwMDAtMDAwMDAwMDAwMDAxIn0",
  "hasMore": true
}
```

---

## Query Filter Syntax

Filter collection listings using bracketed query parameters:

```text
filter[<field>][<op>]=<value>
```

(Shorthand `filter[<field>]=<value>` defaults to `op=eq`. On MCP `cms_query_entries`, pass the equivalent nested JSON object `filters: { "<field>": { "<op>": "<value>" } }`.)

### Supported Filter Operators

| Operator | Syntax Example | Description | Supported Types |
| --- | --- | --- | --- |
| `eq` | `filter[category][eq]=guides` (or `filter[category]=guides`) | Exact equality match. | All filterable fields & system fields |
| `in` | `filter[category][in]=guides,tutorials` | Matches any value in a comma-separated list (1 to **100** values). | All filterable fields & system fields |
| `contains` | `filter[title][contains]=mcp` | Substring match. | Text-indexed fields (`string`, `text`, `slug`, `url`, `date`, `time`, `select`, primitive string `list`) and text system fields. **Rejected** on `number`, `boolean`, `datetime`, `reference`. |
| `gte` | `filter[priceUsd][gte]=10` | Greater than or equal to. | Text, `number`, `date`, `datetime`, `time`, timestamp system fields. **Rejected** on `boolean` and `reference`. |
| `lte` | `filter[publishedAt][lte]=2026-12-31T23:59:59Z` | Less than or equal to. | Text, `number`, `date`, `datetime`, `time`, timestamp system fields. **Rejected** on `boolean` and `reference`. |
| `is_null` | Triggered via `?parent=root` (or `?tree=true`) on Delivery | Matches entries with no outgoing reference on a self-referencing field. | Used internally by self-reference hierarchy queries (`parent=root` / `tree=true`). |

### System Filterable Fields & Strict Index Enforcement

- **Always filterable system fields:** `locale`, `slug`, `publishedAt`, `createdAt`, `updatedAt` (plus `status` on Agent and Admin planes).
- **Schema fields:** Only fields declared with `filterable: true` in the post-type schema can be queried. Filtering on any other field fails fast with **`400 field_not_filterable`**.
- **Malformed syntax** (such as `filter=foo`, `filter[]=bar`, or unknown operators) returns **`400 invalid_filter`** / **`400 invalid_filter_operator`**.

---

## Sorting, Projection, Expansion & Tree Parameters

### Complete Query Parameter Matrix

| Parameter | Delivery Collection | Delivery Single / Singleton | Agent Collection | Description |
| --- | --- | --- | --- | --- |
| `locale` | Yes | Yes | Yes | Filter or resolve entry by locale code (e.g., `en`, `de`). |
| `filter[f][op]` | Yes | — | Yes | Typed field and system filters (`eq`, `in`, `contains`, `gte`, `lte`). |
| `sort` | Yes | — | Yes | Prefix `-` for descending or `+`/none for ascending. System fields: `publishedAt`, `createdAt`, `updatedAt`, `slug`, plus any `sortable: true` schema field. Default: **`-publishedAt`** (Delivery), **`-createdAt`** (Agent/Admin). |
| `limit` | Yes | — | Yes | Page size (`1`–`100`, default `20`). |
| `cursor` | Yes | — | Yes | Opaque keyset pagination cursor. |
| `fields` | Yes | Yes | — | Comma-separated list of `data` field keys to keep in the Delivery response (expanded fields are preserved). |
| `expand` | Yes | Yes | — | Comma-separated top-level `reference` field keys to hydrate inline via zero-N+1 batched lookups. |
| `depth` | Yes | Yes | — | Expansion depth when `expand` is set: `1` (default) or `2` (max). Negative/non-integer returns `400 invalid_depth`. |
| `include` | Yes | Yes | — | Comma-separated derived HTML projections for `rich_html` fields: `plainText`, `wordCount`, `headings`, `readingTime`. Invalid values return `400 invalid_include`. |
| `parent` | Yes | — | — | Self-referencing hierarchy filter: `parent=root` (top-level entries) or `parent=<entryId>` (direct children). |
| `tree` | Yes | — | — | `tree=true` assembles nested published `children[]` breadth-first (max depth **5**, max **1,000** nodes). Requires a self-referencing field on the post type. |
| `q` | — | — | Yes | Accent/case-folded search across display label, slug, and text fields. |
| `status` | — | — | Yes | Comma-separated entry statuses (`draft,scheduled,published,archived,trashed`). |
| `includeTrashed` | — | — | Yes | Boolean (`true` includes `trashed` entries when `status` is omitted). |
| `dryRun` | — | — | `POST` only | `dryRun=true` validates a create request without writing to the database. |

### Example Combined Delivery Query

```http
GET /delivery/v1/posts?locale=en&filter[featured][eq]=true&sort=-publishedAt&fields=title,slug,author,body&expand=author&depth=1&include=wordCount,readingTime,headings&limit=10
```

---

## Canonical Error Envelope

Every error response across all three planes uses a single JSON envelope:

```json
{
  "error": {
    "code": "validation_error",
    "message": "entry validation failed",
    "retryable": false,
    "applied": false,
    "issues": [
      {
        "field": "heroImage.alt",
        "label": "Hero Image (Alt text)",
        "code": "image_alt_required",
        "message": "Hero Image requires non-empty alt text before publishing",
        "constraint": { "requireAlt": true },
        "instruction": "Describe the image clearly for screen readers."
      }
    ]
  }
}
```

- **`applied`:** Always `false` on `4xx` rejections so agents know with certainty no state changed.
- **`retryable`:** Indicates whether retrying the operation later may succeed (e.g., `429` rate limit or `503` service unavailable).
- **`issues[]`:** Field-level diagnostics including the field's `instruction` and, for `reference` fields, `searchEndpoint`.

---

## Request & Response Headers Reference

### Request Headers

| Header | Plane(s) | Description |
| --- | --- | --- |
| `Authorization` | Agent, Admin, Delivery (optional) | `Bearer ocms_...` on Agent/Delivery; `Bearer <access-jwt>` on Admin. |
| `X-Request-ID` | All | Optional correlation ID (1–128 printable ASCII chars); auto-generated UUID if absent or invalid. |
| `Idempotency-Key` | Agent, Admin | Unique actor-scoped deduplication key (max 128 chars) on `POST`, `PATCH`, `PUT`, `DELETE`. |
| `If-Schema-Fingerprint` | Agent | Cached site or post-type schema fingerprint for drift detection (`409 schema_drift_detected` on breaking drift). |
| `If-Match` | Agent, Admin | Entry `ETag` for optimistic locking (alternative to `expectedVersion` in JSON body). |
| `If-None-Match` | Delivery | Cached response `ETag` for conditional `304 Not Modified` responses. |
| `X-Null-Semantics` | Agent, Admin | Set to `clear` on `PATCH` to treat explicit `null` values in `data` as field clears instead of no-ops. |
| `X-Preview-Token` | Delivery | Single-entry signed preview token (`pv_...`) to read unpublished `draftData` on Delivery (bypasses L2 cache). |
| `Origin` | Admin | Required on cookie-authenticated mutations for CSRF verification. |

### Response Headers

| Header | Plane(s) | Description |
| --- | --- | --- |
| `X-Request-ID` | All | Echoed or server-generated request correlation ID. |
| `ETag` | Delivery, Agent, Admin | Content hash (`"sha256:..."`) on Delivery responses and entry mutations. |
| `Cache-Control` | Delivery, Admin | Public Delivery JSON: `public, max-age=60, stale-while-revalidate=300`; API-key Delivery: `private, max-age=60`; Delivery media (public): `public, max-age=31536000, immutable`; Draft previews: `private, no-store`; Admin auth: `no-store`. |
| `Surrogate-Key` | Delivery (public only) | Space-delimited cache invalidation tags (`site:<slug>`, `type:<slug>`, `entry:<id>`, `media:<id>`, `redirects`, `sitemap`). Suppressed on private API-key responses and draft previews. |
| `X-OvertCMS-Cache` | Delivery | L2 Delivery cache status: `HIT` or `MISS` (omitted on draft previews). |
| `Vary` | Delivery | Includes `X-Preview-Token` on entry/singleton routes and `Authorization` when `OVERTCMS_DELIVERY_REQUIRE_API_KEY=true`. |
| `X-Schema-Fingerprint` | Agent | Current active schema fingerprint on `/agent/v1/prompt`, `/agent/v1/schema*`, and capability-gain responses. |
| `X-Schema-Warning` | Agent | Set to `schema_capability_gain` when `If-Schema-Fingerprint` trails only by non-breaking changes. |
| `Idempotency-Replayed` | Agent, Admin | Set to `true` when returning a cached response for a replayed `Idempotency-Key`. |
| `Retry-After` | All | Seconds to wait before retrying on `429` rate limits or `409 operation_in_progress`. |
| `X-Content-Type-Options` / `Content-Security-Policy` / `Content-Disposition` | Delivery Media | `nosniff`, `sandbox; default-src 'none'; script-src 'none'; style-src 'none'`, and `attachment` for documents/PDFs/text files. |
