# 🔗 Uplink Integration Guide

Complete guide for embedding Uplink Studio into client websites and managing multi-tenant content.

---

## Table of Contents

1. [Overview](#overview)
2. [Quick Start](#quick-start)
3. [Adding a New Client](#adding-a-new-client)
4. [Integration Methods](#integration-methods)
5. [Webhooks & On-Demand Revalidation](#webhooks--on-demand-revalidation)
6. [MCP Server](#mcp-server)
7. [Online / Offline: Testing Fallbacks](#online--offline-testing-fallbacks)
8. [API Reference](#api-reference)
9. [Environment Variables](#environment-variables)
10. [Troubleshooting](#troubleshooting)

---

## Overview

Uplink is a **multi-tenant CMS** designed to be embedded into client websites via a `/uplink` route. Each client gets isolated access to their content, documents, and media through a single shared platform.

### Key Concepts

- **Multi-Tenant**: One CMS instance serves multiple clients with strict data isolation
- **Embedded Studio**: CMS UI is embedded into the client's website at `/uplink` via an `<iframe>`
- **Role-Based Access**: Four roles — `admin`, `client_admin`, `editor`, `viewer` — with granular permissions
- **Client Scoping**: All data is automatically filtered by the current client context via Row-Level Security

---

## Quick Start

### Starting a new site

No project yet — only an idea, wireframes or mockups, or code another AI made? Start from the **Uplink starter**: a bare Next.js App Router site with Uplink built in from the first commit. It holds everything the installer below writes, repository backups, and a home page, legal pages (at `/{slug}`), header and footer that read Business info, Legal, the theme and Search & sharing — and nothing hard-coded that Uplink holds. Its `AGENTS.md` tells every later agent the same.

- **Agents:** call `get_starter_setup` and write the files it returns into a new, empty folder. Its `instructions` cover filling Uplink from what the person has (asking, never inventing) and the path to a live site.
- **By hand:** run the install command below with `--starter --target my-site` instead of `--target .`, in the folder that should hold the new project. It refuses a folder that already has a `package.json`.

Then follow **Launch** in Uplink, which takes you through GitHub, Vercel, the site's key and instant updates one step at a time. The starter needs Node.js 20 or later.

### Prerequisites

- Node.js 18+ installed
- An API key generated for the client in the Uplink studio: with the client open in the header, **Developer → API keys → Generate key**. Leave **Let this key write content** off — the site only reads

> The REST API (`/api/v1/*`) is **framework-agnostic** and can be consumed from any server-side environment. The `/uplink` studio embed is too: it is just a full-page `<iframe>` whose `src` is `UPLINK_HOST`, so any framework (or a plain HTML page) can host it. The installer below is one option — the Next.js App Router path, which also writes a typed API helper and the webhook receiver. On any other stack, skip the installer, serve a `/uplink` page containing that iframe (marked `noindex, nofollow`), and consume the API directly.

### Installation Steps

**Step 1: Run the installer in the client's Next.js project root**

> **Agents:** if you are connected to the Uplink MCP server, call `get_install_setup` (with `app_dir`: `app` or `src/app`) and write the files it returns with your own tools, instead of running the command below. It returns exactly what the installer writes, with instructions — and it avoids the "download a script and run it" step that agent permission checks refuse. Never put the MCP connection's own key in `UPLINK_API_KEY`; ask the person for the site's key.

```bash
node -e "const u=new URL('https://www.uplinkcms.com/api/install-uplink'),h=require(u.protocol==='http:'?'http':'https'),{writeFileSync:w}=require('fs'),{join:j}=require('path'),{tmpdir:t}=require('os'),{execFileSync:x}=require('child_process');h.get(u,r=>{let d='';r.on('data',c=>d+=c);r.on('end',()=>{const f=j(t(),'install-uplink.js');w(f,d);x(process.execPath,[f,...process.argv.slice(1)],{stdio:'inherit'})})}).on('error',e=>{console.error(e.message);process.exit(1)})" -- --target . --host https://www.uplinkcms.com --api-key upl_<key>
```

The installer creates:

- `app/uplink/page.tsx` — iframe embedding the CMS
- `app/uplink/layout.tsx` — applies `noindex, nofollow` metadata
- `lib/uplink.ts` — server-only HTTP helper **and shared TypeScript types** for API calls
- `app/api/revalidate/route.ts` — the webhook receiver (see *Webhooks & On-Demand Revalidation*)
- `lib/uplink-image.tsx` — `<UplinkImage>`, the standard way to show an Uplink image: sized for each screen, with its blur placeholder (see *Render every Uplink image with `<UplinkImage>`*); and `<UplinkVideo>`, the same for a background or hero video (see *Video*)
- `app/api/media/[id]/route.ts` — serves Uplink images and videos from the site's own origin, cached by the site's CDN
- `lib/uplink-theme.tsx`, `app/uplink-theme.css` and `app/api/uplink-fonts/[file]/route.ts` — `<UplinkTheme />`, which puts the theme set in Uplink → Your site → Theme (colours, fonts, text sizes, spacing) on every page as CSS variables, the Tailwind v4 mapping onto them, and the route that serves the theme's fonts from the site's own domain (see [GET /api/v1/theme](#get-apiv1theme))
- `lib/uplink-theme-preview.tsx` and `app/api/uplink-theme-preview/route.ts` — let a person see a theme on the real site before it is published, in their browser only (see *Previewing a theme on the site* under [GET /api/v1/theme](#get-apiv1theme))
- `lib/uplink-integrations.tsx`, `lib/uplink-consent.tsx`, `app/api/uplink-region/route.ts` and `app/api/uplink-consent/route.ts` — `<UplinkIntegrations />`, which renders the Google Analytics and cookie banner set up in Uplink → Your site → Integrations, `<CookieSettingsLink />` for the footer, the route that tells the banner which country a visitor is in (see [GET /api/v1/integrations](#get-apiv1integrations)), and the route that passes each choice to Uplink's consent records ([POST /api/v1/consent](#post-apiv1consent)). The installer adds their one dependency, `vanilla-cookieconsent`, to `package.json` — run `npm install` afterwards
- `lib/uplink-seo.tsx`, `app/sitemap.ts`, `app/robots.ts`, `app/llms.txt/route.ts` and `app/llms/[...path]/route.ts` — Search & sharing: `uplinkMetadata()` for each page's title, description and share card, `<UplinkPageSeo>` for its JSON-LD, `<UplinkPageQA>` — the Q&A spot every page gets — and the sitemap, robots.txt and AI index Uplink builds (see [GET /api/v1/seo](#get-apiv1seo)). A route whose `public/` file already exists is skipped

In a project with a `src/app` directory (or a `src/` folder and no `app/`), every one of these goes under `src/` instead: `src/app/uplink/page.tsx`, `src/lib/uplink.ts`, `src/app/api/media/[id]/route.ts`, and so on.

It also upserts `UPLINK_HOST` and `UPLINK_API_KEY` into the project's `.env.local` and adds safe placeholder entries to `.env.example`.

> **Route shape**: The installer creates a _flat_ `app/uplink/page.tsx`, not a catch-all (`app/uplink/[[...tool]]/page.tsx`). All studio navigation happens inside the `<iframe>` at the CMS origin — there are no Next.js sub-routes to handle on the client side. If your project already has a catch-all route at that path, flatten it to `app/uplink/page.tsx`.

> **TypeScript types**: `lib/uplink.ts` exports `ContentItem`, `SchemaItem`, and `FieldDef` — the TypeScript shapes that match the API responses. Import them wherever you consume the API:
>
> ```typescript
> import type { ContentItem, SchemaItem, FieldDef } from '@/lib/uplink';
> ```

**Step 2: Verify `.env.local`**

```dotenv
UPLINK_HOST=https://www.uplinkcms.com
UPLINK_API_KEY=upl_<your_client_api_key>
```

For local development, change `UPLINK_HOST` to `http://localhost:3000` (or whatever port the CMS dev server runs on).

**Pointing a site at a protected preview** (such as `https://preview.uplinkcms.com`)? Vercel refuses requests there before Uplink sees the key. Set `UPLINK_PROTECTION_BYPASS` in `.env.local` to the bypass secret (an Uplink admin has it) and `lib/uplink.ts` sends it as `x-vercel-protection-bypass`; so does the backup script. Leave it unset for production. The installer adds it, empty, to `.env.example`.

**Step 3: Access the studio**

Start the client's dev server and open `/uplink`. You will be prompted to log in with your Uplink credentials.

**Step 4: Analytics and the cookie banner**

Put `<UplinkIntegrations />` once at the end of `<body>` in the root layout and `<CookieSettingsLink />` in the footer. They render nothing until someone sets up Google Analytics or the cookie banner in Uplink → **Integrations**, so they are safe to add now. If the site already hard-codes a Google Analytics tag or a cookie banner, move it into Uplink and remove the hard-coded one in the same change, or visits are counted twice.

**Step 5: The theme**

Put `<UplinkTheme />` in the root layout's `<head>`, and `@import "./uplink-theme.css";` after Tailwind in your global stylesheet. Nothing changes until classes use the theme (`bg-primary`, `font-heading`, `text-h1`, `px-gutter` …) or Uplink sends a value; a site that already has a design should capture it into the theme first so nothing visibly changes — see [GET /api/v1/theme](#get-apiv1theme).

**Optional: repository backups**

Add `--with-backups` to the installer command to make the site's repository a backup of its Uplink data. Backups are free; private images and scheduled runs are **Backup extras**, a Pro feature (see [GET /api/v1/backup](#get-apiv1backup)). It additionally writes:

- `lib/uplink-fallback.ts` — reads the backup with the same visibility rules as the API
- `lib/uplink-backup.ts` — a drop-in for `lib/uplink.ts`: its `getUplinkJson` calls Uplink first and, only when Uplink is unreachable, answers 5xx, or the client is switched **OFFLINE**, answers from the backup. A wrong key or host, a 404 and a 400 are thrown as before. `getUplinkJsonWithSource` also says whether the answer is `live` or `backup`, with `dataAsOf`
- `scripts/uplink-backup.mjs` and an `uplink:backup` script in `package.json`
- a line in `.gitattributes` (`uplink-backup/*.json text eol=lf`), so on Windows a backup never shows line-ending-only changes and the JSON keeps matching its checksums in `manifest.json`
- an empty backup under `uplink-backup/`, so the site builds before the first real one (it is never answered from)

Then:

```bash
npm run uplink:backup        # writes uplink-backup/ and public/uplink-backup/
```

and import `getUplinkJson` from `@/lib/uplink-backup` instead of `@/lib/uplink`. Review the diff and commit both folders — the repository is the backup; Uplink keeps no copy. Re-run `npm run uplink:backup` to refresh it; an unchanged workspace produces no diff. The script writes everything to a staging folder first and replaces the previous backup only once every file has arrived at its exact size, so a failed run leaves the old backup whole. `-- --dry-run` shows what a backup would hold without writing anything; `-- --no-files` backs up the JSON only. On a protected preview it sends `UPLINK_PROTECTION_BYPASS` as the bypass header.

The backup is bundled into the build, so a deploy serves the backup committed with it.

**Images from the backup while Uplink is up (opt-in).** Off by default: while Uplink answers, every image comes through Uplink's image route, sized for each screen. With **Serve images from the backup** on in Uplink → Developer → Backups, `getUplinkJson` from `@/lib/uplink-backup` also points each image the backup holds **at the same version** at its static copy under `/uplink-backup/media/` — the `url` of a media asset, and the `url` and `image_url` of a media field — so it loads from the site's own CDN instead of through Uplink's image route. Everything else comes from the live response, so what is shown and its alt text never go stale. It is skipped for an image replaced since the backup (its version changed), for an image that is private or not published/unlisted **live** (visibility changes without a new version), and for an original wider than 2000 px that Uplink would send optimized — unless **Serve large images from the backup** is on as well. The paths are the ones a backup answer already uses, so a site that renders during an outage needs no change. The static copy is the **full-size original**: `<UplinkImage>` sends it through Next.js's own optimizer, so it is still sized for each screen — turn the preference on only when every Uplink image renders that way and `next.config` has neither `images.unoptimized` nor `output: 'export'`. Otherwise every phone downloads the original instead of Uplink's sized copy, and the page gets slower. A site with its own Uplink reader gets the same by passing each live response through `preferBackupMedia(body, snapshot)` from `lib/uplink-fallback.ts`; it changes nothing unless the backup's manifest says `"imagesFromBackup": true`.

**Private images.** `npm run uplink:backup -- --include-private` also backs up private images, into `uplink-backup/private-media/` — never web-served — fetched with the site's key. Put the flag in the `uplink:backup` script in `package.json` so every refresh keeps it. A site that serves images through its own route (a proxy that adds the API key) answers from `readUplinkBackupMedia(id)` in `@/lib/uplink-backup` when Uplink fails; on Vercel, add `outputFileTracingIncludes: { '<that route>': ['./uplink-backup/private-media/**'] }` to `next.config` so the files are in its bundle. Only include private images in a private repository.

**Back up to GitHub (simplest).** On the Backups page (**Developer → Backups**), a client admin presses **Back up to GitHub → Connect GitHub** and installs Uplink's GitHub App on the site's repository. Uplink then makes each backup itself and opens or updates one "Refresh Uplink backup" pull request, both on **Back up now** and on the **Backup frequency** schedule. There is no API key, secret, variable or workflow to add, and CI runs on its pull requests. An agent cannot connect it; tell the person. The workflow below is for a site that cannot use it.

**Scheduled backups with a workflow.** `--with-backup-workflow` (which implies `--with-backups`) also writes `.github/workflows/uplink-backup.yml`. It wakes every day and runs `npm run uplink:backup -- --scheduled`, which asks Uplink whether a backup is due by the **Backup frequency** set on the Backups page — daily, weekly, monthly, annually, or off. Only when one is due does it back up, and only when something changed does it open or update one "Refresh Uplink backup" pull request; changing the frequency in Uplink needs no change to the repository. Running it by hand from the Actions tab backs up right away. Nothing is merged automatically. It needs, in GitHub → Settings: the `UPLINK_API_KEY` secret (plus `UPLINK_PROTECTION_BYPASS` for a protected preview host), the `UPLINK_HOST` variable, and *Actions → General → Allow GitHub Actions to create and approve pull requests*. Pull requests opened by the built-in token do not start other workflows; close and reopen one if your CI must run on it.

---

## Adding a New Client

There are three methods to add clients to the Uplink platform:

### Method 1: Admin UI (Recommended)

This is the easiest method for non-technical team members.

1. **Sign in as an Uplink admin** (or an agency admin) and open **All clients → Clients**

2. **Add a new client**
   - Click **Add client**
   - Fill in the client details:
     - **Client name**: Display name (e.g., "Acme Corporation")
     - **Production domain**: Client's website domain (e.g., "acme.com"). No site yet? Leave it and **Vercel address** empty: Launch fills in the Vercel address
     - **Serve published media publicly** (optional, off by default): lets image URLs work without an API key. Images marked **Private** in Media are never served this way
   - Click **Add client**
   - The new client starts **ONLINE**. **Online / Offline** in its menu on **Clients** can pause its delivery for fallback testing — see [Online / Offline](#online--offline-testing-fallbacks)

3. **Generate an API Key**
   - With the client open in the header, go to **Developer → API keys → Generate key** — the path every client admin and agency admin has. Platform admins can also choose **API keys** in the client's menu on **Clients**, then **Generate**
   - Name it, then generate. Leave **Let this key write content** off unless an agent will set up content over MCP
   - Copy the raw key immediately — it is shown **once only**
   - Optionally click **Copy install command** to get a pre-filled installer command for the client project

4. **Give people access to the client**
   - Choose **Invite** in the client's menu on **Clients**, or open the client and go to **Your business → Users → Invite people**
   - Enter their email, or pick someone from the client open in the header (people who already have access to the client you are inviting into are left out), and choose a role. The dialog names the client being granted: access is to that client only
   - Uplink admins invite `client_admin`, `editor` or `viewer`; client admins invite `editor` or `viewer`
   - A client not yet set up in Astrion Portal asks an Uplink admin to **Set up** first, which creates its Astrion organisation
   - Astrion Portal emails the invitation; the dialog also shows a single-use link to share if the email does not arrive. It works only for the invited address and expires in 7 days; a new account is finished from the invitee's own inbox
   - The invitee signs in, or creates an Astrion account, with that address, accepts, and lands in Uplink on the client at the invited role. An existing account keeps everything it already has
   - Change a role or remove access in Astrion Portal. Pending invitations are listed under **Users**, where they can be sent again (**Resend** — the earlier link stops working) or revoked

### Agencies

An agency (a web or marketing agency that looks after several client sites) can manage all of its clients without being an Uplink admin.

1. An Uplink admin opens **Platform → Agencies → New agency**. Leave the Portal organisation ID blank to create the agency's organisation in Astrion Portal.
2. On the agency's card, press **Invite an admin** to invite the agency's people as **agency admins**: pick a client to choose from its people, or type a new person's email, then **Send invitation**. An agency admin is a client admin at every client the agency manages: they see those clients under **Clients**, invite each client's own people (editors and viewers), set a client up in Portal, and **Add client** — always under their own agency.
3. Optionally click the agency's logo (its initials until there is one) to upload, change or remove it (PNG, JPEG, WebP, GIF or SVG, up to 1 MB; an SVG containing scripts or links is refused). The card lists the clients the agency manages, each with its own mark; click one to open its **Business info**.
4. Optionally fill in **Agency info** on the card — the agency's public name, tagline, website, footer credit wording, phone, email, address and social profiles. Every client site the agency manages can show it, for example as a "Website by …" link in the footer, from [`GET /api/v1/agency`](#get-apiv1agency). Saving is live on all of those sites at once, so it is confirmed first.
5. Put an existing client under the agency from the client's **Edit** dialog (**Agency**). A client belongs to at most one agency; only Uplink admins change it. Saving also links the client's Astrion Portal organisation to the agency's, which is what lets the agency's admins invite the client's people. Portal makes that link only for someone who administers both organisations; if you don't, the dialog says so and the agency's admins can't invite until it is linked. A client an agency admin sets up in Portal is linked from the start.

Access follows the agency: take a client out of the agency, or remove someone's agency admin role in Portal, and their access to its clients ends at their next sign-in (within about ten minutes). Agency admins cannot delete clients. **Users** shows people who reach a client through its agency as "via <agency>".

5. **Switch to the new client**
   - Use the client selector in the top navigation bar to select the newly created client and begin adding content, documents, and media

### Moving a Client Between Instances

**Export**, in a client's menu on **Clients**, produces a portable snapshot of one workspace, and **Import client** on the same page applies it to another instance. This is how a client is migrated between deployments, cloned into staging, or archived. The bundle format is shared with Insanity CMS, so a workspace exported there can be imported here.

**Export** — choose which sections travel: content items (including list items and pending drafts), media, documents, site settings (with their current values) and business info, schema templates, users and memberships, API keys, and activity log history. Two output formats:

| Format           | Contents                                                            | Use when                                                                   |
| ---------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `.json` manifest | Records plus signed download links for every file, valid **7 days** | The usual case. Small file, no size ceiling on the media it can carry.      |
| `.zip` archive   | Records plus the actual file bytes                                  | Offline archival, or when the source instance will not be reachable later.  |

**Import** — pick the bundle, then review before anything is written. The preflight report names every collision, and each section has its own toggle, so a bundle can be applied in part (for example: content and media, but not activity history). Records that already exist are either left alone or replaced, your choice. Activity log entries are append-only and are never overwritten. A site setting whose key is already used by a *different* setting in the target workspace is always skipped, since site code matches on the key. Bundles exported before site settings existed import as having none.

**Record ids are preserved.** Media references inside content store a storage path by value, and every path is prefixed with the client UUID, so the client and all its records keep their original ids. A workspace can therefore only be imported into an instance that does not already hold different records under those ids.

**Users are the exception.** A profile id is a foreign key into that Supabase project's `auth.users` table and cannot move between instances. Each exported user is matched by email, and for every one you choose: link to the existing account here, invite them into this instance, attribute their records to yourself, or skip them. Platform admins are never created or modified by an import.

**API keys** transfer as hashes, so a client site keeps working with the key it already has — no re-issue and no `.env` change. Only platform admins can export or import them.

---

## Integration Methods

### Integrating into Next.js Projects

Uplink Studio can be embedded into any site — the `/uplink` page is a full-page `<iframe>` whose `src` is `UPLINK_HOST`. The options below are the Next.js paths (App Router or Pages Router).

#### Option 1: Next.js App Router (App Router, recommended)

**Step 1: Run the installer**

Run this one-line command in the client's Next.js project directory:

```bash
node -e "const u=new URL('https://www.uplinkcms.com/api/install-uplink'),h=require(u.protocol==='http:'?'http':'https'),{writeFileSync:w}=require('fs'),{join:j}=require('path'),{tmpdir:t}=require('os'),{execFileSync:x}=require('child_process');h.get(u,r=>{let d='';r.on('data',c=>d+=c);r.on('end',()=>{const f=j(t(),'install-uplink.js');w(f,d);x(process.execPath,[f,...process.argv.slice(1)],{stdio:'inherit'})})}).on('error',e=>{console.error(e.message);process.exit(1)})" -- --target . --host https://www.uplinkcms.com
```

If you already have the client's API key, include it and the installer will append it to the client's `.env.local`:

```bash
node -e "const u=new URL('https://www.uplinkcms.com/api/install-uplink'),h=require(u.protocol==='http:'?'http':'https'),{writeFileSync:w}=require('fs'),{join:j}=require('path'),{tmpdir:t}=require('os'),{execFileSync:x}=require('child_process');h.get(u,r=>{let d='';r.on('data',c=>d+=c);r.on('end',()=>{const f=j(t(),'install-uplink.js');w(f,d);x(process.execPath,[f,...process.argv.slice(1)],{stdio:'inherit'})})}).on('error',e=>{console.error(e.message);process.exit(1)})" -- --target . --host https://www.uplinkcms.com --api-key upl_<key>
```

Optional local command (from this CMS repo):

```bash
npm run scaffold:uplink -- --target /path/to/client-site --host https://www.uplinkcms.com
```

The installer creates these files inside the client app:

- `app/uplink/page.tsx`
- `app/uplink/layout.tsx`
- `lib/uplink.ts`
- `app/api/revalidate/route.ts`
- `lib/uplink-image.tsx` (`<UplinkImage>`)
- `app/api/media/[id]/route.ts`

In a project with a `src/app` directory (or a `src/` folder and no `app/`), every one of these goes under `src/` instead: `src/app/uplink/page.tsx`, `src/lib/uplink.ts`, `src/app/api/media/[id]/route.ts`, and so on. It also writes `UPLINK_HOST` (and `UPLINK_API_KEY`, when given) to `.env.local` and placeholders to `.env.example`. `--with-backups` and `--with-backup-workflow` add the backup files described under *Optional: repository backups* in the Quick Start.

Environment note:

- For local development, use `UPLINK_HOST=http://localhost:3000` (or your local port).
- For production, set `UPLINK_HOST` to exactly `https://www.uplinkcms.com` — with `www`, over `https`. For a preview key, use the preview host it was issued on (`https://preview.uplinkcms.com`). The API-key dialog shows the exact value next to the key, with a copy button.

**Why the exact host matters.** A host that redirects — `http://…`, or a host the platform sends on to another — makes `fetch` drop the `Authorization` header when it follows the redirect to a different origin. The request then arrives with no key and gets `401`. The generated `lib/uplink.ts` passes `redirect: 'manual'` and throws an `UplinkError` naming the host to use instead, rather than following it.

**Fail the build on configuration errors; don't hide sections.** `getUplinkJson` throws `UplinkError`, which carries `status`, `kind` and Uplink's `code`. `kind` is `config` (3xx / 401 / 403 / missing env var), `not_found` (404), `offline` (423 — the client was switched Offline to test fallbacks), `server` or `network`. Render a fallback for `not_found` and `offline`, and rethrow `config` — during `next build` that fails the deploy with the fix in the message, instead of shipping a site with every CMS section silently empty:

```ts
import { getUplinkJson, isUplinkConfigError, UplinkError } from '@/lib/uplink';

export async function getTeam() {
  try {
    return await getUplinkJson<ContentItem[]>('/api/v1/content', { searchParams: { type: 'list', slug: 'team' } });
  } catch (error) {
    if (isUplinkConfigError(error)) throw error; // wrong host or key: fail loudly
    if (error instanceof UplinkError) return null; // not published, offline, or Uplink down: fall back
    throw error;
  }
}
```

Sites installed before this change keep their old `lib/uplink.ts`; re-run the installer with `--force` to get the new one.

`app/uplink/layout.tsx` applies `noindex, nofollow` metadata so the client's `/uplink` route is not indexed by search engines.

---

## Webhooks & On-Demand Revalidation

### The problem this solves

The Uplink API never serves stale data — every content endpoint returns `Cache-Control: no-store`. The delay a client notices comes entirely from **their own** Next.js cache. A site fetching with `next: { revalidate: 300 }` shows an edit up to 5 minutes late, and longer on low-traffic pages, because the first visitor after expiry still receives the stale copy while the refresh happens behind them.

Webhooks close that gap. Uplink POSTs to an endpoint on the client's site the moment published content changes, and that endpoint calls `revalidateTag`. Edits appear in **seconds**, with the ISR window left in place as a fallback.

### Setting one up

**1. Scaffold the receiver.** The installer creates `app/api/revalidate/route.ts` and adds cache tags to every fetch in `lib/uplink.ts`. On an existing install, re-run it with `--force` so those files are rewritten:

```bash
npm run scaffold:uplink -- --target /path/to/client-site --host https://www.uplinkcms.com --force
```

**2. Register the endpoint.** In Uplink, with the client open: **Developer → API keys → Webhooks → Connect {domain}** (platform admins also have **Webhooks** in the client's menu on **Clients**). Uplink already knows the client's domain and where the installer put the receiver, so it registers `https://{domain}/api/revalidate` — e.g. `https://acme.com/api/revalidate` — in one click. Use **Use a different address** only for a staging deployment or a site that answers on another host: delivery never follows redirects, so if `acme.com` redirects to `www.acme.com`, register the `www` URL. The test ping names the redirect target when this happens. A custom URL must be `https`.

**3. Save the signing secret.** It is shown **once**, immediately after you add the endpoint. Add it to the environment variables of wherever the site is hosted (Vercel, Netlify, …) and redeploy. It is not needed in `.env.local`: webhooks reach only the deployed site, never a dev server on your machine.

```bash
UPLINK_WEBHOOK_SECRET=whsec_<the secret shown in Uplink>
```

**4. Prove it works.** Click **Send test ping**. The endpoint's response is reported back in the studio and recorded on the row, so a wrong secret or a missing route is visible immediately rather than the next time someone publishes.

### What fires a webhook

Only changes to the **published** surface. Draft workflow is deliberately silent — nothing a visitor could see has changed:

| Action | Fires? |
| ------ | ------ |
| Publish a page, post or list item | ✅ |
| Edit published content and publish the changes | ✅ |
| Reorder a published list | ✅ (once for the whole reorder) |
| Unpublish, unlist or archive published content | ✅ |
| Delete published or unlisted content | ✅ |
| Upload a new media asset | ✅ |
| Replace a media file, or change its title, alt text, status, privacy or folders | ✅ |
| Delete a media asset | ✅ |
| Publish or unlist a document, or return it to draft | ✅ |
| Replace, edit or delete a published or unlisted document | ✅ |
| Change a site setting's value, define a setting, or delete one | ✅ |
| Set up, change, pause or remove an integration (Google Analytics, the cookie banner) | ✅ |
| Publish or restore the theme | ✅ |
| Change Search & sharing — a page, the site defaults, the AI tools switch, or a share image in use | ✅ |
| Approve, change, hide or delete an approved review | ✅ (`review.updated`) |
| Add or edit a review that is waiting for approval | ❌ |
| **Save a draft** on a published page | ❌ |
| **Discard a draft** | ❌ |
| Create or edit a draft that was never published | ❌ |
| Upload a document (it starts as draft) | ❌ |

Bursts are coalesced: a 20-item drag-reorder produces one delivery, not twenty.

### Payload

```json
{
  "id": "9f1c…",
  "event": "content.published",
  "clientId": "…",
  "occurredAt": "2026-09-02T12:00:00.000Z",
  "tags": ["uplink", "uplink:content", "uplink:content:about-us"],
  "resources": [
    { "type": "content_item", "id": "…", "slug": "about-us", "parentId": null }
  ]
}
```

`tags` is the actionable field — pass each entry to `revalidateTag`. On Next.js 16 call `revalidateTag(tag, { expire: 0 })`, Next's documented choice for a webhook: the recommended `'max'` profile marks the data stale but serves the next visitor the old page while it refreshes, which defeats instant updates. Next.js 15 takes one argument and already expires at once; the scaffolded receiver casts `revalidateTag` so the same file type-checks on both. `resources` is there for receivers that want finer control; each entry's `type` is `content_item`, `media_asset`, `document`, `site_setting` (whose `slug` is the setting key), `business_info`, `integration` (whose `slug` is the provider), `agency` (whose `id` is the agency's), `uplink_credit` or `theme`.

`event` is the most significant change in the batch, one of `content.published`, `content.unpublished`, `content.deleted`, `content.updated`, `document.published`, `document.unpublished`, `document.deleted`, `document.updated`, `media.created`, `media.updated`, `setting.created`, `setting.updated`, `setting.deleted`, `business_info.updated`, `integration.created`, `integration.updated`, `integration.deleted`, `agency.updated`, `uplink_credit.updated`, `theme.updated`, or `test.ping`. Route on `tags`, not on `event` — new event names may be added.

| Header | Meaning |
| ------ | ------- |
| `X-Uplink-Signature` | `v1=<hex>` — HMAC-SHA256 over `` `${timestamp}.${rawBody}` `` |
| `X-Uplink-Timestamp` | Unix seconds; must be within 5 minutes of your clock |
| `X-Uplink-Delivery`  | Unique per delivery — usable as an idempotency key |
| `X-Uplink-Event`     | The most significant event in the batch |

### Tag scheme

| Tag | Invalidates |
| --- | ----------- |
| `uplink` | Every Uplink-backed fetch |
| `uplink:content` | Any `/api/v1/content`, `/api/v1/schemas` or `/api/v1/legal` fetch (legal pages are content items) |
| `uplink:content:<slug>` | One item fetched by slug |
| `uplink:list:<parent_id>` | The children of one list |
| `uplink:media` | Any `/api/v1/media` fetch |
| `uplink:documents` | Any `/api/v1/documents` fetch, including document files |
| `uplink:settings` | Any `/api/v1/settings` fetch |
| `uplink:business-info` | Any `/api/v1/business-info` fetch |
| `uplink:integrations` | Any `/api/v1/integrations` fetch (including the Uplink credit) |
| `uplink:agency` | Any `/api/v1/agency` fetch |
| `uplink:theme` | Any `/api/v1/theme` fetch |
| `uplink:seo` | Any `/api/v1/seo` fetch (which the helper also tags `uplink:content` and `uplink:business-info`: it is built from posts, legal pages and the business name) |
| `uplink:forms` | Any `/api/v1/forms` fetch |
| `uplink:reviews` | Any `/api/v1/reviews` fetch |

The scaffolded `getUplinkJson` attaches these automatically, so a fetch made through it is already invalidatable. If you fetch the API by hand, tag it yourself to the same scheme or the webhook will have nothing to act on.

### Verifying the signature

The scaffolded route does this for you. If you are writing your own receiver, two details matter:

- **Read the raw body before parsing it.** Re-serialising parsed JSON does not round-trip, and the MAC will not match.
- **Compare in constant time**, and reject timestamps outside a ~5 minute window — the timestamp is inside the signed material specifically so a captured delivery cannot be replayed later.

### Delivery guarantees

- **At-least-once.** Retries and multi-endpoint fan-out can deliver the same change twice. `revalidateTag` is idempotent, so this is harmless — but do not treat a delivery as a counter.
- **Retried on failure.** A failed delivery is retried with backoff (30s, 2m, 10m, 30m) and abandoned after 5 attempts. `4xx` responses are treated as permanent and fail fast, since a bad secret or missing route will not fix itself.
- **Never lost to a missed notification.** A cron sweep re-drains anything the live path failed to deliver.
- **Never blocks publishing.** If the webhook system is misconfigured or down, the CMS write still succeeds and the client site falls back to its ISR window.
- **Nothing is sent while the client is OFFLINE.** Changes made while a client is switched offline are suppressed, not queued, and are not replayed when it comes back online. See [Online / Offline](#online--offline-testing-fallbacks).

### Security

- Endpoints must be `https`, and requests to loopback, private, link-local and cloud-metadata addresses are refused — the URL is attacker-controllable input from Uplink's point of view.
- Redirects are not followed, so a `3xx` cannot be used to reach an internal address.
- Signing secrets are stored server-side only and are unreachable from the browser and from PostgREST.

---

## MCP Server

Uplink hosts a [Model Context Protocol](https://modelcontextprotocol.io) server at **`/api/mcp`**, giving AI agents (Claude Code, Claude Desktop, Cursor, Windsurf, VS Code) read access to your CMS content, schemas, media, and documents — and, with a `content:write` key, the ability to set up lists and upload files as drafts.

It is part of the deployed app. There is nothing to clone, build, or keep up to date — connecting is a URL and a key, or a URL and a sign-in.

### Connect the Claude app (connectors)

For claude.ai, Claude Desktop and Claude on mobile.

Claude's connectors take a URL and sign you in, so there is no key to copy:

1. In Claude, open **Settings → Connectors → Add custom connector**.
2. Name it after the client and paste the workspace's own address, `https://www.uplinkcms.com/api/mcp/w/<workspace id>` — copy it from **Developer → API keys → Connect an agent**, under *Claude app*.
3. Sign in to Uplink when asked. Choose whether the agent may **write** (off unless you turn it on; never deletes published content, every write in the activity log), then **Allow**.

Only a platform admin or a client admin of the workspace can connect it, as with **Connect an agent**. The connector gets its own key, listed under **Developer → API keys** with a **Connector** badge; revoke it there to disconnect at once. A connector reaches one workspace. Claude allows one connector per URL, so each workspace has its own address: add one connector per client and turn on the one you need in each chat. A workspace's address serves only that workspace — it refuses a key from any other, and its sign-in offers only that workspace. `https://www.uplinkcms.com/api/mcp` still works as a connector too; its sign-in lets you pick any workspace you can connect. A connector signed in there may reach several workspaces, so every call says which project it comes from (`project_site`) and every change names the workspace; to skip that on each call, the agent calls `pin_workspace` once with both and passes the `pin` it returns (it starts with the workspace's name, lasts 12 hours and works only on that connection) instead. A workspace's own address needs no pin.

**A connector follows your Claude account into every project and chat**, including other clients' sites — Claude Code loads it too. So the server names its workspace and site in its instructions and at the end of every tool result, and every write tool asks for `project_site` (see *Write tools*). For work on one client's site in code, prefer **Connect an agent** in that project: its key lives in the project's own config.

Any MCP client that supports OAuth sign-in can connect the same way. Uplink is the authorization server: `/.well-known/oauth-protected-resource/api/mcp` (and `…/api/mcp/w/<workspace id>` for a workspace's own address, which the client names as its `resource` when signing in) points at `/.well-known/oauth-authorization-server`, with dynamic client registration and PKCE (S256). The access token is an ordinary Uplink key, sent in the `Authorization` header, so it follows every rule a key from **Connect an agent** does. It does not expire and there is no refresh token: it lasts until it is revoked.

### Connect in one click

1. Open **Developer → API keys**.
2. Under **Connect an agent**, leave **Allow the agent to write content** on (the default) or turn it off for read-only access, then click **Connect an agent**.
3. Pick your tool: copy the Claude Code command and run it **in your project folder**, or click **Add to Cursor** / **Add to VS Code**. A read-only key also gets a plain URL for clients that accept only a URL.

Install Uplink in **one place per tool**. The Claude Code extension in VS Code reads the same `.mcp.json` as the terminal, so don't also add it to VS Code's own `mcp.json` unless you use Copilot — two entries means two places to update when the key changes. If a client that holds a key offers **Authenticate**, the key is missing or revoked: fix it and use **Reconnect**, or let it sign in instead (see *Connect the Claude app* above).

The button mints a key dedicated to MCP. It is:

- **able to write by default** — a `content:write` key, so the agent gets the write tools below with no second key. Everything it creates is a draft, it can delete only drafts that never went live, and every write is logged. Turn the switch off for a **read-only** key
- **one per workspace** — renewing replaces it, so there is never a second live key you forgot about
- **revocable** — **Disconnect** kills it immediately; **Renew key** issues a fresh one and invalidates the old

The raw key is shown **once**, at the moment it is issued, and the ready-made connection commands can only be built while it is on screen. If you lose it, renew — it cannot be recovered.

### Connecting by hand

If you already have a key, the endpoint takes it in an `Authorization` header. Run this in your project folder:

```bash
claude mcp add --scope project --transport http uplink https://www.uplinkcms.com/api/mcp \
  --header "Authorization: Bearer upl_your_key"
```

- **Use `--scope project`.** It writes `.mcp.json` in the project folder, so there is exactly one `uplink` entry for that repo. The default *local* scope keys entries by the project's path string; on Windows the VS Code extension and a terminal report that path with different drive-letter case, so the same repo can end up with two entries — one of them silently holding an old key.
- **It writes your key to `.mcp.json`.** Add `.mcp.json` to `.gitignore`, or use the environment-variable form below.
- **Replacing a key** (after **Renew key**): `claude mcp add` refuses a name that already exists, so remove it first. `;` works in bash, zsh and PowerShell, and removing a missing entry is harmless:
  ```bash
  claude mcp remove uplink --scope project ; claude mcp add --scope project --transport http uplink https://www.uplinkcms.com/api/mcp --header "Authorization: Bearer upl_new_key"
  ```
  If you installed with an older command (no `--scope`), also run `claude mcp remove uplink --scope local` so the old entry can't shadow the new one.
- **Approve it for the folder.** Claude Code asks you to approve a project server, but stores that approval per path string — so on Windows an approval in the VS Code extension doesn't carry over to a terminal. Instead, create `.claude/settings.local.json` in the project (or add `"uplink"` to the list if the file exists) and gitignore it:
  ```json
  { "enabledMcpjsonServers": ["uplink"] }
  ```
  `claude mcp list` may still show "Pending approval" afterwards; sessions load the server regardless. Check with `/mcp` in a session.

**Environment-variable form**, for teams that commit `.mcp.json`. Claude Code substitutes `${VAR}` in `.mcp.json` from the environment it is **launched** in — not from `.env.local`. The single quotes keep `${VAR}` literal in bash, zsh and PowerShell:

```bash
claude mcp add --scope project --transport http uplink https://www.uplinkcms.com/api/mcp \
  --header 'Authorization: Bearer ${UPLINK_MCP_KEY}'
```

Then set `UPLINK_MCP_KEY` in your shell profile or system environment.

**Protected preview deployments.** A deployment behind Vercel Deployment Protection (such as a preview) is guarded by Vercel before any request reaches Uplink. Without an `x-vercel-protection-bypass` header, Vercel answers with its own 401 and SSO redirect — no key is ever checked. Add the header to every client:

```bash
claude mcp add --scope project --transport http uplink https://preview.example.com/api/mcp \
  --header "Authorization: Bearer upl_your_key" \
  --header "x-vercel-protection-bypass: <bypass secret>"
```

On a protected deployment, **Connect an agent** says so, and for platform admins includes the bypass header in every command it generates. Other users need the value from an Uplink admin. The URL-only form cannot work there, because a URL cannot carry the header.

**Other tools — one install per tool, inside the project.** An Uplink key belongs to one client workspace, and you likely work across several client repos, so configure each tool in the repo's own folder rather than a machine-wide config — otherwise every repo talks to whichever workspace was installed last. Each tool reads its own file, so install each tool you use once, and don't install the same tool in two places. **Connect an agent** generates every snippet below with your key (and the bypass header on a protected preview).

For tools that take a JSON config (Cursor, Claude Desktop, Windsurf):

```json
{
  "mcpServers": {
    "uplink": {
      "type": "http",
      "url": "https://www.uplinkcms.com/api/mcp",
      "headers": { "Authorization": "Bearer upl_your_key" }
    }
  }
}
```

| Tool | Project file | Notes |
| ---- | ------------ | ----- |
| Claude Code | `.mcp.json` + `.claude/settings.local.json` | Written by `claude mcp add --scope project`; approval file above |
| VS Code (GitHub Copilot) | `.vscode/mcp.json` | Uses `"servers"` instead of `"mcpServers"`: `{ "servers": { "uplink": { "type": "http", "url": …, "headers": { … } } } }`. VS Code's one-click install writes to your **profile**, shared by every workspace — prefer the project file. The Claude Code extension doesn't need this file |
| Cursor | `.cursor/mcp.json` | The entry above. Prefer the project file to the one-click install |
| Codex | `.codex/config.toml` | Read only for projects Codex **trusts**. Don't use `codex mcp add`, which writes the shared `~/.codex/config.toml` |
| Windsurf | `~/.codeium/windsurf/mcp_config.json` | Machine-wide only — it can point at one Uplink workspace at a time |

Codex's project config:

```toml
[mcp_servers.uplink]
url = "https://www.uplinkcms.com/api/mcp"
http_headers = { "Authorization" = "Bearer upl_your_key" }
```

**Every file containing a real key must be gitignored:** `.mcp.json`, `.claude/settings.local.json`, `.vscode/mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`.

### Clients that accept only a URL

Some "add a connector" dialogs take a URL, offer no way to set a header and cannot sign in. For those, the key goes in the path:

```
https://www.uplinkcms.com/api/mcp/upl_your_key
```

This works only with a **read-only** key — any other key is refused at this URL outright. A URL is recorded in access logs, proxy logs, browser history, and `Referer` headers, so a key that travels in one is treated as more exposed and is capped at reads. To get one, turn off **Allow the agent to write content** under **Connect an agent** and connect (or renew). Prefer the header form wherever the client supports it.

### Early access

A client can opt in to Uplink's preview release for its **agent connections**: **Developer → API keys → Early access**. Platform admins and the client's own client admins can turn it on by typing `EARLY ACCESS`, and anyone who can turn it on can turn it off with no confirmation. While it is on, `https://www.uplinkcms.com/api/mcp` hands the client's MCP requests to the preview release behind the scenes. The agent gets the newest tools and installer files (`get_install_setup`) before everyone else, and they may not work as expected.

- **Nothing changes in the project.** Keep the same URL and key. Do not point an agent at a preview host, and never put a Vercel bypass secret in a site.
- **Only agent connections move.** The live site's `/api/v1` requests are always answered by the stable release, and every URL the tools hand out (media links, `UPLINK_HOST`) still points at `https://www.uplinkcms.com`.
- **Check which release answered.** Every `/api/mcp` response carries `Uplink-Release-Channel: early` or `stable`. If the preview release cannot be reached, the request is answered by `stable`.

### What the MCP provides

**Resources** — documentation the agent can read at any time:

| URI | Contents |
| --- | -------- |
| `uplink://docs/integration` | Full integration guide (this document) |
| `uplink://docs/readme` | Project architecture and database overview |
| `uplink://docs/agents` | Development requirements and contributor guidelines |

**Tools** — live reads, scoped to the workspace the key belongs to:

| Tool | Endpoint | Filters |
| ---- | -------- | ------- |
| `fetch_schemas` | `GET /api/v1/schemas` | `slug` |
| `fetch_content` | `GET /api/v1/content` | `status`, `type`, `slug`, `parent_id`, `featured` |
| `fetch_documents` | `GET /api/v1/documents` | `category`, `status`, `id` |
| `fetch_media` | `GET /api/v1/media` | `id` (one, or a comma-separated batch), `folder`, `mime_type` |
| `resolve_media` | `GET /api/v1/media/resolve` | `reference` |
| `fetch_settings` | `GET /api/v1/settings` | `key` |
| `fetch_business_info` | `GET /api/v1/business-info` | — |
| `fetch_agency` | `GET /api/v1/agency` | — |
| `fetch_legal` | `GET /api/v1/legal` | `kind`, `slug` |
| `fetch_integrations` | `GET /api/v1/integrations` | — |
| `fetch_traffic` | `GET /api/v1/traffic` | `days` (7, 30 or 90), `recent_visits` |
| `fetch_uptime` | `GET /api/v1/uptime` | — |
| `fetch_theme` | `GET /api/v1/theme` | — |
| `fetch_seo` | `GET /api/v1/seo` (with `include=health` when there is no `path` or `format`) | `path`, `format` |
| `find_fonts` | — (Uplink's copy of the Google Fonts catalog: weights, italics, variable range, character sets) | `query`, `category`, `limit` |
| `inspect_backup` | `GET /api/v1/backup?dry_run=true` | `include_files`, `unlisted_document_ids` |
| `get_install_setup` | — (the installer's base files and `.env` entries, as text) | `app_dir` |
| `get_starter_setup` | — (a new Next.js site with Uplink built in, as text: the installer's `--starter` files) | `name` |
| `get_backup_setup` | — (the installer's `--with-backups` files, as text) | `lib_dir` |
| `site_checkup` | — (what Uplink can do for a site, whether this connection can, and the Uplink Score) | — |
| `check_site` | `GET /api/v1/score?check=site` (checks the live site again, then answers the score) | — |
| `whats_new` | — (what changed in Uplink since a date, newest first: the same list as the public page at `https://www.uplinkcms.com/changelog`, also as Markdown at `/changelog.md`; reads no workspace, so it needs no `project_site`) | `since` (YYYY-MM-DD, that day included), `limit` |

Every read tool is annotated `readOnlyHint`, so a client can tell the person up front that connecting cannot change their content.

**Agents offer what a site is missing.** People rarely know everything Uplink can do, so the server tells agents to start with `site_checkup` when a request is broad — "set up Uplink", "back up my site", "what can Uplink do?". It lists each capability (editable content, image placeholders, fast images and video on phones, a first screen that appears at once on phones, instant updates, site settings, business info, the theme, Search & sharing, analytics and the cookie banner, legal pages, repository backup and fallback, error handling, locked images) with what it gives the person, how to check whether the project already has it, and whether this workspace and key can set it up. The agent checks the project, explains what is missing in plain language, and asks before changing anything.

**Backing a site up with an agent.** "Back up my site using Uplink" is enough. The agent calls `inspect_backup`, which explains what a backup is (`about`), what it would hold, and returns `finish` — the steps to write it — and `offer_the_person` — connecting the fallback, testing it, keeping it fresh — which the agent presents before committing, because a backup the site does not read protects nothing. When the feature is not enabled it says what it would give and how to get it. The `finish` steps: if the project does not have `scripts/uplink-backup.mjs` yet, call `get_backup_setup` and write the files it returns with its own file tools — nothing is downloaded or executed, so agent permission checks that rightly stop "download and run a script" are not involved, and every file shows up in the diff — then run `npm run uplink:backup`, switch the site's imports to `@/lib/uplink-backup`, build, and show you the diff before committing. The script — not the agent — fetches and writes the backup, so megabytes of files never pass through the agent, and every file is checked before the previous backup is replaced. Backups are free; private images and a schedule need **Backup extras** (Pro), and `inspect_backup` says so when one is asked for without it. See [GET /api/v1/backup](#get-apiv1backup).

**Write tools** — listed **only** for a key with the `content:write` scope: the key **Connect an agent** issues by default, or a key generated with **Let this key write content** on. Any other key never sees them.

**Every write tool takes `project_site`** (except `fetch_saved_themes`, which only reads): the domain the project the agent is working in is served at, read from the project, or `"none"` when it has none yet. Uplink compares it with the workspace's domain — the same host, ignoring `www.`, or a subdomain of it — and when it is missing, `"none"` or another site, nothing is written: the tool names the workspace and tells the agent to ask the person. Only after the person says yes does the agent call again with `confirmed_by_person: true`. A workspace with no domain on record has nothing to compare and is written to. Every audited write records the outcome as `metadata.workspace_check` (`matched`, `confirmed_by_person` or `no_domain_on_record`). This is not a permission — the key already reaches only its own workspace — it stops a connector that follows the person everywhere from changing one client's site from another client's project.

| Tool | What it does |
| ---- | ------------ |
| `create_schema` | Create a list schema: `{ slug, name, fields }`. Idempotent on `slug` — an existing schema is returned unchanged with `created: false` |
| `create_list` | Create a list from a schema (`schema_slug`, optional `title`, `slug`). Idempotent on the list's slug |
| `add_schema_fields` | Add fields to an existing list (`list_id` or `list_slug`) or to a workspace schema (`schema_slug`): `{ …target, fields }`, same field shape as `create_schema`. Additive only — nothing is removed, renamed or retyped; a key that already exists with the same type is reported in `already_present`. A list keeps its own copy of its schema, so pass the list to change an existing list. On a **published** list the fields become a pending draft of its schema (the live list is unchanged), `upsert_items` accepts them at once, and `set_status` `"published"` on the list makes them live |
| `upsert_items` | Create or update up to 100 items in a list, matched on the field named by `match_on`. Fields are merged; `sort_order` is kept unless given |
| `upsert_post` | Create or update one blog post, found by `slug`: `{ slug, new_slug?, title?, content?, fields? }`. `title` is required to create. `content` is HTML starting at `<h2>`, sanitized on write. `fields` are the post fields in *Blog posts* below, merged; `featured_image` takes a published media id. Refuses unknown fields, a `seo_title` over 70 or `meta_description` over 160 characters, and bad dates or URLs. Returns `missing_for_publish`. `new_slug` renames — the old slug keeps resolving |
| `upsert_legal_page` | Create or update the workspace's legal page of one `kind` (one page per kind): `{ kind, title?, slug?, content?, source_url?, unlink_source?, effective_date?, nav_label? }`. A new page is a draft titled and slugged for its kind (`Terms of Service` → `terms-of-service`, `Privacy Policy` → `privacy-policy`). Pass the text as `content` (HTML, cleaned on write) **or** a policy service's document as `source_url` — an iubenda link, or a Termageddon embed code or policy URL — and Uplink pulls the text now and daily. `effective_date` is read from the text's "Last updated" line when it has one. Returns `missing_for_publish`. See *GET /api/v1/legal* |
| `sync_legal_page` | Pull a linked legal page's text from its provider now: `{ kind }`. A change on a published page becomes a pending draft; `outcome: "unchanged"` when nothing changed |
| `upload_media` | Upload an image from an https `url` Uplink can download (up to 20 MB) or `base64` bytes the agent holds (up to 3 MB) — never for an image attached to a chat, which reaches the agent as a picture and not as bytes: that is `create_upload_link` — with `title`, `alt_text`, `tags`, `folder` and optional `is_private`, `serve_original`, and `locked` (which needs `lock_reason`). Created as `draft`. The stored filename is derived from the title — "Jordan Rivers" in folder Team becomes `Team/jordan-rivers.png` — so use the `storage_path` it returns. Returns the `fetch_media` shape |
| `set_serve_original` | Turn Serve original on or off for an image or video (`id`, `serve_original`). Off lets Uplink optimize the image or make the video's phone copy (`mobile_url`). Works on locked assets. Returns the `fetch_media` shape |
| `create_upload_link` | Make a short-lived link to a page (`/share/upload/<token>`, no sign-in) where the person drops images straight into Media at full size — up to 50 MB each, 30 per link, JPG, PNG, WebP, GIF or SVG: `{ folder?, note?, expires_in_hours? }` (default folder `Uploads`, 24 hours, at most 168). For images attached to a chat or on the person's device, which no tool call can carry. Nothing is stored for the link: its token is signed, and it works only while the connector key that made it is live and the workspace is online. Returns `url`, `link_id`, `tell_the_person`, `next_step` and `for_agents_with_a_shell` (the same upload with curl, for agents that run commands). Each image arrives as a `draft` and goes through the same steps as a studio upload, shown on the page the same way (reading its details, saving, alt text from Uplink's generator, sized copies for phones and desktops); it is attributed to whoever connected the connector |
| `fetch_upload_link` | List the images a link has taken (`link_id`), drafts included, in the `fetch_media` shape, with `alt_text` from Uplink's alt text generator, written a few seconds after each image arrives (`null` until then, or if it failed), plus a small preview picture of each (up to 12 per call, each file's `preview` naming its picture) so the agent can see which image is which |
| `lock_media` | Lock a media asset (`id`, `reason`) so its file cannot be replaced and it cannot be deleted, drafted or archived — see *Locked images*. There is no unlock tool |
| `rename_media` | Rename a media asset: `{ id, title }` (up to 200 characters). Changes the name shown in Media and returned by `fetch_media`; the file, `filename` and every URL stay the same. Works on locked assets. Returns the asset in the `fetch_media` shape |
| `upload_document` | Upload a document from an https `url` (up to 25 MB) or `base64` (up to 3 MB), with `title`, `category` and `tags`. Returns the document with `download_url` |
| `delete_draft` | Delete a list, list item or schema made by mistake that **was never published**: `{ resource_type: "content_item" \| "schema", id? or slug?, include_items? }`. Refused, with the reason, for anything that has ever been published or unlisted (kept in `content_items.first_published_at`), anything another item or list still points at, a list with items unless `include_items: true` (then every item must be a never-published draft too), a schema any list was made from, a built-in schema, and pages, posts, legal pages, media, documents and settings. Deleting is for good; the activity log entry keeps a copy of what was deleted |
| `set_status` | Move a content item, document or media asset between `draft`, `published` and `unlisted`. A locked image cannot be moved to `draft`. A blog post is refused until it has an `excerpt`, `featured_image` and `published_at`; a legal page until it has its text, an `effective_date` and no `[[prompt]]` left from an outline. Publishing a list whose pending schema change renames, removes or retypes a field is refused — publish its changes in the studio. Pass `id` for one, or `ids` (same `resource_type`, at most 200) for many; `include_items: true` with a list id gives the list and every item in it the same status in one call. Each id is applied on its own, so one refusal does not stop the rest: a many-id call returns `results` with each id's outcome or `error`. `warnings` says when something just changed is still not shown because its list is not published, when a published list still has unpublished items, or when taking a list off the site hides its live items |
| `define_setting` | Define a site setting: `{ key, label, description?, type, default_value, options? }`. `type` is `boolean`, `text`, `number` or `select`; a `select` needs `options` (strings, or `{ value, label }`). A new setting takes `default_value` as its live value. On an existing key only `label`, `description`, `default_value` and `options` change — never the current value, the key or the type, and options can never drop the live value. See *GET /api/v1/settings* |
| `set_setting` | Change a site setting's **live** value: `{ key, value }`. There is no draft; the site sees it on its next fetch. Setting the current value returns `changed: false` |
| `set_business_info` | Change the **live** business info: `{ name?, legal_name?, tagline?, phone?, phone_country?, email?, address?: { unit?, street?, locality?, region?, postal_code?, country? }, service_area?, cta?: { url?, label? }, social?: [{ platform, url, label? }] }`. `phone` is the number as typed (or starting with `+`); `phone_country` its two-letter country, needed unless the number starts with `+` (defaults to the stored one, then the address country). `cta` is the call to action. `logo?`, `logomark?` and `favicon?` are media ids — the image must be in this workspace, not private, and published or unlisted (upload with `upload_media`, then `set_status` it published); agents set only the files the person names as their brand images. A partial update: a field left out keeps its value, `null` clears it; `social` replaces the whole list (`url` may be a handle where the platform has one). Values are checked and links built exactly as in the studio — anything unusable is refused with the reason and nothing is saved. Returns the fields changed and the new business info. See *GET /api/v1/business-info* |

| `set_integration` | Add, change, pause or resume an integration, **live** at once: `{ provider, id?, banner?, enabled?, consent_mode?, returning_visitors? }`. `provider` is `uplink_analytics` (no `id`: Uplink makes one; `returning_visitors: true` recognises visitors who accept analytics in the banner; see [Uplink Analytics](#uplink-analytics)), `google_analytics_4` (`id` = the `G-` measurement ID, or the Google tag that holds it), `uplink_cookie_banner` (`banner`: `position`, `theme`, `accent`, `floating_button`, `show`, `policy_links`, `text`, merged over what is stored), `cookieyes` (`id` = the installation code or its key), `cookiebot` (`id` = the script or its `data-cbid`) or `adobe_fonts` (`id` = the Adobe Fonts web project's embed code or its ID; its fonts are then named with `set_theme` `source: "adobe"`). A second cookie banner is refused, and so is `consent_mode: "none"` while a banner is on. There is no remove tool. See *GET /api/v1/integrations* |
| `register_pages` | Add the site's pages to Search & sharing in one call: `{ pages: [{ path, label? }] }` (up to 500). Paths already there are untouched. Not for blog posts or legal pages — they are found by their path patterns |
| `set_page_seo` | Write how pages appear in search, AI answers and share cards, **live** at once: `{ pages: [{ path, label?, title?, description?, summary?, faq?, faq_display?, page_type?, share_image_media_id?, share_title?, share_description?, canonical_path?, noindex?, in_sitemap? }] }` (up to 50; a partial update per page, `null` clears a field, `faq` replaces the list). Every page is checked before any is written. Marked as written by an agent — the person sees *not reviewed yet* in the studio, which blocks nothing. Returns each page resolved, its `issues`, and `review_url` / `tell_the_person`, which the agent passes on. See *GET /api/v1/seo* |
| `set_seo` | Change the Search & sharing defaults, **live** at once: `{ title_template?, home_title?, default_description?, default_share_image_media_id?, google_site_verification?, bing_site_verification?, allow_ai_crawlers?, post_path_pattern?, legal_path_pattern? }`. A verification value may be the whole `<meta>` tag. The path patterns describe the site's routes, and only an agent sets them |
| `set_theme` | Change the theme, **live** at once: `{ tokens, base_updated_at? }`. `tokens` is merged over the stored theme (objects key by key; a font, a `{ mobile, desktop }` pair or any other value replaces what was there; `null` clears a token) in the shape `fetch_theme` returns. Fonts are checked against the Google Fonts catalog (`find_fonts`) and fetched once by Uplink before saving. `base_updated_at` refuses the write if someone published since. `color_roles` assigns the site's colour roles (`{ "cta": "secondary" }`; `null` puts one back to its default) — only roles defined with `define_color_role`. Returns the fields changed, `contrast_warnings` and the new theme. There is no reset or delete tool. To let the person see a theme first, use `save_theme`. See *GET /api/v1/theme* |
| `define_color_role` | Define a **colour role** — the site's own name for what one kind of element is painted with — **live** at its default at once: `{ key, label, description?, default_value }`. `key` is snake_case (`cta`, `card_arrow`), at most 40 characters, never ending in `_on` or `_hover`, and never changes; `default_value` is what the element shows today — a palette colour or shade to follow (`primary`, `primary_subtle`, `secondary_hover`, `on_primary`, `surface`, …) or `#rrggbb` — so switching the site code to the role changes nothing visibly. Calling it again updates the label, description and default. At most 24 per workspace; no delete. Returns the role as the theme resolves it and `site_code`: the plain CSS, the three lines for `app/uplink-theme.css` and the Tailwind classes. See *Colour roles* under *GET /api/v1/theme* |
| `save_theme` | Save a theme **without publishing it** — the theme's draft: `{ name, tokens }`. It becomes a saved theme in **Your site → Theme**, where the person picks it under **Switch theme** (*Your saved themes*), checks the preview and publishes it; the site does not change. A name that already exists (ignoring case) updates that saved theme, `tokens` merged over it; a new name starts from the live theme. `tokens` takes the `set_theme` shape and is checked the same way, so it can always be published. Names are plain text up to 60 characters; a workspace keeps at most 50. Returns `differs_from_live`, `contrast_warnings`, `review_url` and `tell_the_person`. There is no delete tool |
| `create_onboarding_link` | Make a link to this workspace's client onboarding form, exactly as Business info → Onboarding form does: `{ expires_in_days?, label?, send_to_email? }` (with `send_to_email`, Uplink emails the link to the client) (7, 30 — the default — or 90 days). The client fills it in once, with no sign-in, and what they send goes straight into the workspace. Returns url (the only copy: Uplink keeps a hash), link, notifies (the person who connected the connector is the link's maker and gets an email and a push when it is sent), check_status, review_url and tell_the_person. Agency admins of the agency that manages the workspace, and Uplink admins, only (not the client's own client admins). There is no tool to turn a link off |
| `resend_onboarding_link` | Send a live onboarding link again: `{ id, send_to_email? }`. Uplink never keeps the url, so it makes a new one for the same link; the one sent before stops working, and label, expiry, views and uploads stay. Emails it when `send_to_email` is given. At most 10 times per link. Returns url (the only copy), link, emailed_to or email_error and tell_the_person. Same people as `create_onboarding_link` |
| `fetch_onboarding_links` | List the workspace's onboarding form links, newest first (at most 50), or one by id: state (active, submitted, expired or revoked), views, last_viewed_at, submitted_at, submitted_by, saved (where what the client sent went, in words), not_saved and saved_ids. state submitted means the client finished. Never a link's url. Read-only, but listed for write keys only (it holds client contact details); agency and Uplink admins only |
| `fetch_saved_themes` | List the saved themes, newest first: `id`, `name`, `updated_at`, `differs_from_live` and `tokens` in the `set_theme` shape. Read-only, but listed for write keys only: saved themes never reach a site or `/api/v1` |

The safeguards are enforced on the server, whatever the agent asks for:

- **Everything an agent creates starts as `draft`.** Nothing is visible to the site until an explicit `set_status` call publishes it. Publish the list as well as its items — a list item is only served while its list is published.
- **Published items are never overwritten in place.** `upsert_items` or `upsert_post` on a published item saves a pending draft, exactly like an edit in the studio; the live item is unchanged until `set_status` publishes it again, which promotes the draft (Publish changes).
- **Every write is recorded in the activity log**, attributed to the person who created the key, with the key's id in the entry's metadata.
- **Published content is never deleted.** The one delete tool, `delete_draft`, deletes only a list, list item or schema that was never published and that nothing points at; everything else is refused. To take something off the site, set it to `draft` or `unlisted`.
- **Site settings are the one thing with no draft.** A setting is live the moment it is defined (at its default), so define it with the same default the site code falls back to. Changing a live value is always its own `set_setting` call — only make it when a person has asked.
- **Business info has no draft either.** `set_business_info` is live at once, so only enter facts the person gave or confirmed — for example the values hard-coded in their current site — and leave `cta.label` unset unless they chose one.
- **Integrations have no draft either.** `set_integration` is live on the site's next page load, so agents use only IDs the person gave or the site already hard-codes, remove any hard-coded copy in the same change, and keep the banner's default wording unless the person gives their own.
- **The live theme has no draft, but a saved theme is one.** `set_theme` restyles every page on the next load, so agents show the person the change and get a yes first — or save it with `save_theme`, which changes nothing on the site, for the person to preview and publish in **Your site → Theme**. On a site that already has a design they capture its current values first, so nothing visibly changes, and never "improve" the look on their own. When a design gives one kind of element a colour of its own, they define a colour role for it with today's colour as the default — live, but changing nothing — and recolour it in a saved theme, never by swapping palette colours. Contrast warnings are reported, never enforced.
- **Search & sharing has no draft either.** `register_pages`, `set_page_seo` and `set_seo` are live at once, so agents say what they will write first, read each page's content, and never state a fact the business has not (a price, an hour, a guarantee) — a question's answer may come from anywhere the business has said it. Each page an agent writes is marked *not reviewed yet* in the studio, and the result hands the agent a `review_url` to give the person. The label blocks nothing.
- **An agent never writes legal text.** `upsert_legal_page` stores the business's own terms or policy — text the person gave, text the site already shows, or their iubenda or Termageddon document — and agents are told to say it is a legal document to have reviewed by a qualified lawyer, and to publish only once the person confirms.
- **An agent can lock an image but never unlock one.** Unlocking is done by an admin in the studio.
- Uploaded media is `draft` too: it is not served, and a media field pointing at it is not expanded, until `set_status` publishes it with `resource_type: "media_asset"`. Media fields take `{ "path": "<storage_path>", "altText": "…" }` using the `storage_path` that `upload_media` returns.
- An `upload_*` `url` must be public https; private and internal addresses are refused, and each redirect is re-checked.
- **`base64` is for small files only (3 MB).** The whole MCP request has to fit the hosting platform's ~4.5 MB request-body limit, and base64 adds a third to the file's size. A larger base64 upload is rejected by the platform with a bare `413 Request Entity Too Large` before it reaches Uplink — pass the file as a `url` Uplink can download instead.
- **An image attached to a chat is not a file the agent can send.** The model sees the picture, but its bytes never reach a tool call, and writing them out as base64 is far beyond what a model can produce for any real photo. So `upload_media` cannot take it at any size. The agent calls `create_upload_link` and gives the person the link: they drop the images on the page, the bytes go from their browser straight to Storage (so neither limit applies), and the agent picks them up with `fetch_upload_link`.

**Connect an agent** issues a write key by default. To make one by hand instead, open **Developer → API keys** (or, for platform admins, **API keys** in the client's menu on **Clients**) and turn on **Let this key write content** before generating. Connect it with the header form above. A `content:write` key is refused in the URL-path form, like any key that is not read-only.

### Verifying the connection

Restart the agent after adding the server (Claude Code loads MCP servers at startup), then run `/mcp` in Claude Code, or check the MCP panel in Cursor or VS Code. A connected server lists the six read tools above, plus the nine write tools for a `content:write` key. A tool added to Uplink appears only after the agent reconnects — restart it, or reconnect the server from `/mcp`.

If the server appears but every call returns 401, the key has been revoked or renewed — issue a new one from **Connect an agent**.

### The legacy stdio server

The `mcp/` directory still holds the original stdio server, which ran locally and required a clone, a build, and an absolute path in every agent config. It remains only for local development against a CMS running on `localhost`. For every other use the hosted `/api/mcp` endpoint above replaces it, and it needs no maintenance from the people connecting to it.

---

## Online / Offline: Testing Fallbacks

On the **Clients** page, **Online / Offline** in a client's menu opens its switch: an LED showing **ONLINE** (green) or **OFFLINE** (red) and a vertical lever beside it. An offline client shows **OFFLINE** beside its name. Switching a client OFFLINE deliberately pauses everything Uplink delivers for that one client, so you can check that a site built on Uplink stays usable when live data is not there. It is a setting a person chooses — not a health check. ONLINE means delivery is enabled; it does not mean the site is reachable.

### Switching a client

- **Who:** platform admins — the same people who can edit the client.
- **Going offline:** pull the lever down (or click it, or press **Arrow Down** / **Space** when it has focus). A dialog asks you to type `OFFLINE` exactly, then press **Take offline**. Cancelling, pressing Escape or closing the dialog leaves the client online.
- **Going online:** push the lever up. No confirmation is needed.
- The LED and lever change only after the server confirms. The change is recorded in the activity log as **Took offline** / **Brought online**, with who did it and when.
- New clients start online, and existing clients were online when this was introduced. Going offline deletes nothing — content, keys, webhooks and settings are all kept.

### What an offline client's integrations receive

Every `/api/v1/*` request made with the client's key — and every keyless image request for its assets — gets this and nothing else, **after** the key has been checked (an invalid key still gets `401`):

```
HTTP/1.1 423 Locked
Cache-Control: no-store
Uplink-Client-Delivery-Status: offline
```

```json
{
  "error": "Data delivery for this client has been intentionally disabled by a user in Uplink. Switch this client to ONLINE to resume delivery.",
  "service": "uplink",
  "present": true,
  "client_delivery_status": "offline",
  "reason": "user_selected",
  "code": "UPLINK_CLIENT_OFFLINE_BY_USER",
  "message": "Data delivery for this client has been intentionally disabled by a user in Uplink. Switch this client to ONLINE to resume delivery."
}
```

It describes the one client's delivery setting and says nothing about Uplink as a whole. It is a `4xx`, not a `5xx`, on purpose: a platform outage looks different (a `5xx`, a timeout, or no connection at all), and this response is not worth retrying — it will not change until a person switches the client back.

While a client is offline Uplink also:

- **sends no webhooks**, including **Send test ping** (which answers `409` with an explanation). Changes made while offline are recorded as suppressed and are **not replayed** when the client comes back online — the site simply reads current data again on its next fetch.
- **restyles the site to its fallbacks**: `GET /api/v1/theme` answers `423` too, so `<UplinkTheme />` renders nothing and the values in `app/uplink-theme.css` apply (or the repository backup's theme, with `load={getUplinkJson}` from `@/lib/uplink-backup`). That is the point of the switch — it shows what visitors would see.
- **answers MCP read tools** with the same payload, as a tool error. MCP write tools keep working: they change content in Uplink, and nothing reaches the site until the client is online again.

### Handling it in a site

Branch on `code` (or `reason`), never on the message text, and return your fallback instead of throwing:

```ts
const UPLINK_CLIENT_OFFLINE = 'UPLINK_CLIENT_OFFLINE_BY_USER';

export async function getContent(slug: string) {
  try {
    const res = await fetch(`${process.env.UPLINK_HOST}/api/v1/content?slug=${slug}`, {
      headers: { Authorization: `Bearer ${process.env.UPLINK_API_KEY}` },
      next: { tags: ['uplink', `uplink:content:${slug}`] },
    });

    if (res.status === 423) {
      const body = await res.json().catch(() => null);
      if (body?.code === UPLINK_CLIENT_OFFLINE) return FALLBACK_CONTENT; // deliberate pause: no retry
    }
    if (!res.ok) throw new Error(`Uplink responded ${res.status}`);
    return (await res.json()).data;
  } catch (error) {
    // Real failures — timeouts, DNS, 5xx — are a different condition. Log them,
    // then fall back as well (retrying with backoff if that suits the page).
    console.error('Uplink unavailable', error);
    return FALLBACK_CONTENT;
  }
}
```

Returning a fallback matters under ISR: if a revalidation **throws**, Next.js keeps serving the last good page, so the fallback never appears. Do not retry a `423` automatically.

### Testing the fallback

1. Switch the client **OFFLINE** on the Clients page.
2. Load the site with its cache out of the way — `next dev`, a fresh deployment, or a page whose revalidate window has passed. Pages and images already cached by the site, a CDN in front of it, or a browser were delivered before the switch and keep showing until those caches expire; Uplink cannot recall them.
3. Confirm every page still renders and is usable with the fallback content, and that nothing retries in a loop.
4. Switch the client **ONLINE**, load the site again (same cache caveat), and confirm live content returns.
5. Test real connection failures **separately** — for example, point `UPLINK_HOST` at an unreachable address, or block it, and watch for timeouts. An intentional pause answers instantly with a clear status; it does not simulate a timeout, DNS failure or an unreachable service.

### Where the switch takes effect

The server commits the new state before the Clients page shows it, and every API request and webhook dispatch reads it fresh — nothing caches it. Two limits are worth knowing:

- **Already delivered is delivered.** Responses sent before the switch, and anything the site or a CDN cached from them, cannot be recalled.
- **A webhook already in flight may land.** The dispatcher re-checks the switch immediately before sending, but a delivery that has already started (including its one quick retry about a second later) completes. Everything after that is suppressed.

---

## API Reference

All endpoints are under `/api/v1` and require an API key. Two key types are accepted — both start with `upl_` and use the same `Authorization: Bearer` header, but they have different scopes and lifetimes.

**Authentication header** (all requests):

```
Authorization: Bearer upl_<your_key>
```

**Host:** call `https://www.uplinkcms.com` (production) or the host the key was issued on. The API is also served on the bare `uplinkcms.com` without a redirect, but `www` is canonical. Don't let your HTTP client follow redirects to Uplink: a redirect to another origin (including `http://` → `https://`) strips `Authorization`.

**401 responses** say which of three things went wrong, so a site or agent can act without parsing prose:

```json
{
  "error": "Missing Authorization header. … Set UPLINK_HOST to exactly https://www.uplinkcms.com and do not follow redirects.",
  "code": "missing_authorization",
  "canonical_host": "https://www.uplinkcms.com"
}
```

| `code` | Meaning |
| ------ | ------- |
| `missing_authorization` | No `Authorization` header arrived. If your code sends one, a redirect dropped it — fix `UPLINK_HOST`. |
| `malformed_authorization` | A header arrived but is not `Bearer upl_<key>`. |
| `invalid_api_key` | The key is not recognised by this host: mistyped, revoked, or issued by a different environment. Production keys work only on `https://www.uplinkcms.com`, preview keys only on `https://preview.uplinkcms.com`. |

**Offline clients:** when the key's client has been switched **OFFLINE** on the Clients page, every endpoint below answers `423` with `code: "UPLINK_CLIENT_OFFLINE_BY_USER"` and no data. See [Online / Offline: Testing Fallbacks](#online--offline-testing-fallbacks).

### Key types

| Type | Where to create | Scoped to | Survives user removal? |
|------|----------------|-----------|----------------------|
| **Production API Key** | Developer → API keys → Generate key (or, for platform admins, Clients → the client's menu → API keys → Generate) | The client workspace | ✅ Yes — workspace credential |
| **Development API Token** | Developer → Developer docs → Dev tokens (developer accounts only) | The user's account → resolves to their assigned client | ❌ No — invalidated immediately |

**Key scopes** — a Production API Key has one of three scopes:

| Scope | Issued by | Can |
| ----- | --------- | --- |
| `read_only` | **Connect an agent** with **Allow the agent to write content** off | Read. The only scope accepted in an MCP URL path |
| `full` | **Generate key** (default) | Read every `/api/v1` endpoint. Sees no MCP write tools |
| `content:write` | **Connect an agent** (default), or **Generate key** with **Let this key write content** on | Everything `full` can, plus the MCP write tools |

**Use Production API Keys for all production and staging deployments.** Development tokens are suitable for local development and scripting, but because they are tied to a specific user account, they stop working the moment that account is removed from the workspace. If you set up a client integration while logged in as a developer user and used a development token, replace it with a Production API Key before offboarding that user.

> **Warning:** If a user with active development tokens is removed via the Users admin panel, the CMS will alert the admin and offer to generate a replacement Production API Key before completing the removal.

---

### GET /api/v1/schemas

Returns all structured list schemas defined for your client. Use this endpoint first to understand what content types and fields exist so you can dynamically render them.

**Query params**

| Param  | Type   | Description                        |
| ------ | ------ | ---------------------------------- |
| `slug` | string | Return a single schema by its slug |

**Response**

```json
{
  "data": [
    {
      "id": "uuid",
      "title": "Blog Posts",
      "slug": "blog-posts",
      "status": "published",
      "schema": [
        { "key": "image", "label": "Featured Image", "type": "media", "required": true },
        { "key": "excerpt", "label": "Excerpt", "type": "textarea" },
        { "key": "featured", "label": "Featured post?", "type": "boolean" }
      ],
      "item_count": 12,
      "created_at": "2026-05-01T00:00:00Z",
      "updated_at": "2026-05-20T00:00:00Z"
    }
  ]
}
```

`item_count` is the number of **published** items in the list — the ones
`GET /api/v1/content?parent_id=<id>` returns. Draft, unlisted and archived items are not counted.

Each `schema` entry is a field definition:

| Property      | Type     | Description                                         |
| ------------- | -------- | --------------------------------------------------- |
| `key`         | string   | Unique field key (matches keys in `fields` objects) |
| `label`       | string   | Human-readable label                                |
| `type`        | string   | Field type — see table below                        |
| `description` | string?  | Optional helper text                                |
| `required`    | boolean? | Whether a value is required                         |
| `options`     | string[] | Values for `select` / `radio` fields                |
| `fields`      | array?   | Nested field definitions for `object` type fields   |

**Supported field types**

| Type                | Description                                       |
| ------------------- | ------------------------------------------------- |
| `text`              | Single-line text                                  |
| `textarea`          | Multi-line text                                   |
| `url`               | URL string                                        |
| `boolean`           | True / false toggle                               |
| `number`            | Numeric value                                     |
| `select`            | Dropdown (one of `options`)                       |
| `radio`             | Radio group (one of `options`)                    |
| `image`             | Image URL string, for images hosted outside Uplink only — an image Uplink holds is a `media` field |
| `media`             | Uploaded media asset — expanded in `/api/v1/content` responses (see below) |
| `json`              | Arbitrary JSON / GeoJSON                          |
| `object`            | Nested object with sub-fields                     |
| `icon`              | Lucide icon name string (e.g. `"CircleArrowRight"`) |
| `offer`             | Something to buy: a Stripe or Square payment link with price and currency — expanded in `/api/v1/content` (see below) |

**Rendering `offer` fields**

An offer is stored as `{ url, price, currency, availability? }`: `url` is an https Stripe Payment Link (`buy.stripe.com`, `donate.stripe.com`) or Square checkout link (`square.link`, `checkout.square.site`), `price` a number with at most two decimals, `currency` an ISO 4217 code and `availability` one of `in_stock`, `out_of_stock`, `sold_out`, `preorder`, `limited`. Anything else is refused when it is saved. Uplink takes no payment itself: the buy button links to `url`, and Stripe or Square handle the checkout. An offer is always a top-level field of its item, never inside an `object` or `array`.

`GET /api/v1/content` adds three keys to each offer:

```json
"ticket": {
  "url": "https://buy.stripe.com/abc123",
  "price": 25,
  "currency": "CAD",
  "availability": "in_stock",
  "provider": "stripe",
  "price_display": "CA$25.00",
  "json_ld": {
    "@context": "https://schema.org",
    "@type": "Product",
    "name": "Saturday workshop",
    "offers": { "@type": "Offer", "url": "https://buy.stripe.com/abc123", "price": "25.00", "priceCurrency": "CAD", "availability": "https://schema.org/InStock" }
  }
}
```

Show `price_display` next to a button linking to `url`, and put `json_ld` in a `<script type="application/ld+json">` in the same render, so search engines and AI tools see the price only where a visitor does. `json_ld` is named by the item's title. The installer's `lib/uplink-seo.tsx` has `<UplinkJsonLd data={item.fields.ticket?.json_ld} />` for this. An offer that is not usable (for example one saved before these rules) comes back as stored, without these keys, so render a buy button only when `json_ld` is present.

When the item has them, `json_ld` also carries the item's `description` field (as plain text) and the public images in its `media` fields and arrays of `media` (in schema order) as `image`, which Google needs to show it as a product.

**Products: a list with Buy buttons**

Uplink has one built-in list schema, `products` (Content → New content → Products in the studio; `create_list` with `schema_slug: "products"` over MCP). It is for selling packages, services, tickets, classes, gift cards or digital items through Stripe or Square payment links. Each item has:

| Key | Type | What it is |
| --- | --- | --- |
| `name` | text | The product's name (required; the item title defaults to it) |
| `offer` | offer | Payment link, price, currency and availability, as above. Empty = shown without a Buy button |
| `image` | media | The main photo |
| `gallery` | array of media | More photos |
| `description` | textarea | A sentence or two |
| `button_label` | text | What the button says ("Book now"); empty means "Buy" |

The installer's `lib/uplink-products.tsx` renders it:

```tsx
import UplinkProducts from '@/lib/uplink-products';

<UplinkProducts list="products" />
```

It draws a grid of cards (photos, name, price, availability, description, Buy button) in the site's Uplink theme, with each product's `json_ld` beside its price. The Buy button is a plain link to the payment page; an item marked `sold_out` or `out_of_stock` shows that instead of the button. Pass `render` to draw the products with the site's own components, or use `getUplinkProducts('products')` for a page of your own. A list that does not exist, or Uplink being unreachable, renders `fallback` (nothing by default).

Uplink is not a store: there is no cart, stock count, tax or shipping logic, and Uplink never sees the payment. For something that ships, turn on address collection (shipping) and add a flat shipping rate on the Stripe payment link, or turn on shipping for the Square checkout link.


**Rendering `icon` fields on the client**

The value is a PascalCase string matching a [Lucide](https://lucide.dev) component name. Import it dynamically:

```typescript
import * as LucideIcons from 'lucide-react';

// item.fields.icon === "CircleArrowRight"
const Icon = LucideIcons[item.fields.icon as keyof typeof LucideIcons] as
  React.ComponentType<{ size?: number; className?: string }> | undefined;

// Then render:
{Icon && <Icon size={24} />}
```

**Example — fetch a single schema and render its fields**

```typescript
import { getUplinkJson } from '@/lib/uplink';
import type { SchemaItem } from '@/lib/uplink';

const { data: schema } = await getUplinkJson<{ data: SchemaItem }>('api/v1/schemas', {
  searchParams: { slug: 'blog-posts' },
});

// schema.schema is the array of FieldDef objects
// Use it to dynamically render a form or typed component
```

---

### GET /api/v1/content

Returns content items. Includes `schema` (field definitions) and `fields` (field values) for list containers and their children.

**Query params**

| Param       | Type   | Description                                                     |
| ----------- | ------ | --------------------------------------------------------------- |
| `status`    | string | `draft`, `published` or `unlisted`. **Omitted: published only** (see below). Any other value is a `400` |
| `type`      | string | Filter by type: `page`, `post`, `custom`, `list` or `legal` (legal pages — read them with [GET /api/v1/legal](#get-apiv1legal), which shapes them the same way) |
| `slug`      | string | Return a single item by slug                                    |
| `parent_id` | string | Return all list items belonging to a specific list (by list ID) |
| `featured`  | string | `true`: only items whose `fields.featured` is `true` (featured blog posts). Any other value is a `400` |

**Default visibility — drafts are never served unless you ask for them**

When `status` is omitted, `/api/v1/content` follows the same rule as documents and media:

| Request | Without `status` returns |
| ------- | ------------------------ |
| A collection (`type`, `parent_id`, or nothing) | `published` only |
| A `slug` lookup — the direct-link path | `published` or `unlisted` |

To read drafts — for a preview page, say — pass `status=draft` explicitly. `archived` is never served.

> **Changed:** `status` used to default to *every* non-archived status, so a site that left the filter out showed drafts publicly. Sites that already pass `status: 'published'` see no difference. Anything that relied on getting drafts without asking must now pass `status=draft`.

**Response shape — one rule for every `type`**

- **With `slug`** the request addresses one item: `{ "data": { … } }` — an **object** — or `404` with `{ "error": "Not found", "code": "not_found" }` if nothing matches. Adding `type` or `status` narrows the lookup but never changes the shape.
- **Without `slug`** the request is a collection query (any mix of `type`, `status`, `parent_id`): always `200` with `{ "data": [ … ] }` — an **array** — and `{ "data": [] }` when nothing matches. A collection query never returns `404`.

So "this list has no items yet" is `200` with an empty array, while a `404` carrying `code: "not_found"` means a slug that doesn't exist (or isn't servable). A `404` **without** that code — typically HTML — means the URL itself is wrong. `/api/v1/schemas?slug=` follows the same rule.

**Media fields are expanded inline**

A `media` field is stored as `{ path, altText }`. In every response it is expanded (each entry of an `array` of `media` too) so it can be rendered with correct dimensions and a blur placeholder without fetching the media library:

```json
"photo": {
  "path": "client-id/team/jane.jpg",
  "altText": "Jane smiling",
  "url": "https://…supabase.co/storage/v1/object/sign/…",
  "id": "…",
  "version": 3,
  "width": 1200,
  "height": 800,
  "alt_text": "Jane Doe, CTO",
  "mime_type": "image/jpeg",
  "blur_data_url": "data:image/jpeg;base64,…",
  "image_url": "https://www.uplinkcms.com/api/v1/media/…/image?v=3"
}
```

| Field | Meaning |
| ----- | ------- |
| `path`, `altText` | The stored value. `altText` is the alt text chosen for this field, and wins over the asset's own |
| `url` | A signed storage URL, valid for **1 hour**, to the **uploaded original** (not optimized). Renderable directly; do not cache it in ISR/static pages |
| `id`, `version`, `width`, `height`, `alt_text`, `mime_type`, `blur_data_url` | The asset, exactly as `/api/v1/media` returns it |
| `image_url` | The asset's versioned `/api/v1/media/{id}/image?v={version}` URL — what `/api/v1/media` calls `url`. **Optimized** (see *Image optimization*); prefer it over `url`. Safe to cache indefinitely; needs the API key unless public media is on |
| `status`, `is_private` | The asset's visibility — see *Media status and privacy* below |
| `serve_original` | `true` when `image_url` sends the stored file unoptimized |
| `mobile_url` | **Video fields only**: the phone copy's versioned URL (see *Video*), or `null`. Image fields do not carry it |
| `desktop_url` | **Video fields only**: the desktop copy's versioned URL (see *Video*), or `null`. Image fields do not carry it |
| `poster_url` | **Video fields only**: the video's poster still (see *Video*), or `null`. Image fields do not carry it |

What is added depends on the asset's visibility:

| Asset | Media field contains |
| ----- | -------------------- |
| `published` or `unlisted`, not private | Everything above |
| **Private** | Everything above **except `url`** — a signed URL works without a key, which private rules out. Fetch `image_url` server-side with your key |
| `draft` or `archived` | Only the stored `path` and `altText` — nothing to render |
| Deleted asset | `path`, `altText` and `url` |

`image` fields are plain external URLs and are not expanded.

**Render every Uplink image with its blur placeholder.** This is the standard, not an option: every component that shows an image from Uplink — cards, grids, team photos and carousels as well as the hero — passes the asset's `blur_data_url` and its `width`/`height`, so the image fades in from a blurred preview in its reserved space instead of popping in from a blank box. With `next/image`:

```tsx
<Image
  src={src}
  alt={alt}
  width={photo.width}
  height={photo.height}
  placeholder={photo.blur_data_url ? 'blur' : 'empty'}
  blurDataURL={photo.blur_data_url ?? undefined}
/>
```

Carry the three fields through whatever helper maps the asset to your image props, so no component can drop them. `<UplinkImage>` (below) does it for you.

**Render every Uplink image with `<UplinkImage>`.** This is the standard too. A page that feels instant on a desktop that has seen it before can take seconds on a phone opening it for the first time, and the image is almost always why. `lib/uplink-image.tsx` (written by the installer and `get_install_setup`) fixes each cause:

- **Sized for the screen.** Every `srcset` entry is a real file of that width, so a phone showing a team photo 200 px wide downloads a ~600 px file, not the 2000 px copy a desktop hero needs. `sizes` is required: say how wide the image is really shown. A two-column grid on a phone is about `50vw`, not `100vw`.
- **Cached at the site's edge.** Uplink image URLs are loaded through the site's `app/api/media/[id]/route.ts`, which the site's CDN keeps. Uplink's own CDN never stores an image (see *Stable image proxy*), so without a site-side cache every new visitor waits on Uplink for every image.
- **Never the original.** A media field's `url` is the uploaded original, often a 5–10 MB phone photo. `<UplinkImage>` uses `image_url` and ignores it.
- **The blur placeholder,** from `blur_data_url`.

```tsx
import { UplinkImage } from '@/lib/uplink-image';

// A hero: the one image the page opens on gets priority.
<UplinkImage asset={hero.fields.image} sizes="100vw" priority className="object-cover" fill />

// A two-column team grid on phones, four columns from 1024 px up.
<UplinkImage asset={member.fields.photo} sizes="(max-width: 1023px) 50vw, 25vw" />
```

Give `priority` only to the image the page opens on. Everything else loads lazily as it scrolls into view. Without both `width` and `height` on the asset (or passed as props), the image fills its parent, which must be sized and `position: relative`. SVG and GIF are sent as uploaded, because resizing would rasterize one and stop the other moving. A private image is not rendered: the site's proxy works without a key, so show private images only from a route of your own that checks who is signed in.

**Ordering**

When `parent_id` is provided, items are returned in the order set in Uplink via drag-and-drop (`sort_order ASC`, with unordered items at the end falling back to `created_at ASC`). No client-side sorting is needed — just render the array as-is.

Top-level items (no `parent_id`) are ordered by `updated_at DESC`, except blog posts (`type=post`), which are ordered by `fields.published_at DESC`, then `created_at DESC`.

**Blog posts**

`type: "post"` is a blog article. Its fields are built into Uplink rather than defined per list, so every site's blog reads the same contract, and editors get an article editor in the studio (**Content → New content → Post**) with a rich-text body, the fields below, and a *Search & sharing* panel with character counters and a search-result preview.

```json
{
  "id": "…", "type": "post", "title": "Why Wellness Programs Pay Off", "slug": "why-wellness-programs-pay-off",
  "previous_slugs": [],
  "content": "<h2>…</h2><p>…</p>",
  "status": "published",
  "created_at": "…", "updated_at": "…",
  "word_count": 1180, "reading_minutes": 5,
  "fields": {
    "excerpt": "One or two sentences that answer the article's question.",
    "featured_image": { "id": "…", "width": 1600, "height": 900, "alt_text": "…", "blur_data_url": "…", "image_url": "…" },
    "published_at": "2026-09-01",
    "featured": true,
    "author": "Sterling Brokers",
    "category": "Wellness at Work",
    "tags": ["benefits"],
    "key_takeaways": ["…"],
    "faq": [{ "question": "…", "answer": "…" }],
    "sources": [{ "label": "…", "url": "https://…" }],
    "seo_title": null,
    "meta_description": null,
    "canonical_url": null,
    "noindex": false
  }
}
```

| Field | Type | Use it for |
| ----- | ---- | ---------- |
| `excerpt` | string | Cards, the meta description when `meta_description` is empty, and the answer summary. **Required to publish** |
| `featured_image` | media | Cards, the article header, `og:image`. Expanded like any media field. **Required to publish** |
| `published_at` | `YYYY-MM-DD` | The date shown, the sort order, `datePublished`. **Required to publish**. Use `updated_at` for `dateModified` |
| `featured` | boolean | Show the post in the site's blog preview (`featured=true`) |
| `author`, `category` | string or null | Byline and grouping |
| `tags`, `key_takeaways` | string[] | Tags; a short "Key takeaways" box at the top of the article |
| `faq` | `{ question, answer }[]` | An FAQ section on the page and `FAQPage` JSON-LD |
| `sources` | `{ label, url }[]` | Citations at the end of the article (`url` may be null) |
| `seo_title` | string or null (≤ 70) | The `<title>` when set; otherwise use `title` |
| `meta_description` | string or null (≤ 160) | The meta description when set; otherwise use `excerpt` |
| `canonical_url` | URL or null | Only when the article was first published elsewhere |
| `noindex` | boolean | Add `<meta name="robots" content="noindex">` and leave it out of the sitemap |

`word_count` and `reading_minutes` sit beside `created_at`, not in `fields`: Uplink computes them from the body every time a post is served (words of the sanitized body text only — not the title, excerpt or FAQ — and `reading_minutes` = `round(word_count / 225)`, at least 1), so they are always current and nobody sets them. Show "N min read" from `reading_minutes` rather than counting words in the site; `upsert_post` ignores both if sent, and the studio shows the same figure to the editor.

Every field is always present — `false`, `[]` or `null` when unset. `content` is sanitized HTML (`h2`–`h4`, `p`, lists, `strong`/`em`, links, `blockquote`, `code`, `figure`/`img`); any `<h1>` is served as `<h2>` because the page's `<h1>` is the post title. Render it with `dangerouslySetInnerHTML`.

**Contents list — part of the standard.** Every Uplink blog shows an "In this article" list on an article with **two or more** `<h2>` sections: one entry per `<h2>`, in order, each linking to its section. `<h3>` is for points within a section and is not listed. The studio counts the Headings as the editor writes and tells them this, so a site without the list breaks that promise. Give each `<h2>` an `id` from its text (lowercase, words joined by hyphens, a number added to repeats) when rendering, and link to `#id`. It also gives AI answer engines and search results jump links into the article.

**Renamed posts keep their links.** When a live item's slug changes, the old slug is added to `previous_slugs`, and a `slug` lookup that matches no current slug finds the item by an old one. The response carries the **current** `slug`, so answer a mismatch with a permanent redirect:

```typescript
const { data: post } = await getUplinkJson<{ data: ContentItem }>('api/v1/content', {
  searchParams: { type: 'post', slug: params.slug },
});
if (post.slug !== params.slug) permanentRedirect(`/blog/${post.slug}`);
```

**New posts appear on their own.** Publishing, unpublishing or editing a post fires the webhook with `uplink`, `uplink:content` and `uplink:content:<slug>`, so a blog index fetched with the `uplink:content` tag picks up a new post the moment it is published — build the index from `type=post`, never from a hard-coded list. The installer's `app/sitemap.ts` lists every published post for you (see [GET /api/v1/seo](#get-apiv1seo)), and a post's metadata comes from `uplinkMetadata('/blog/<slug>')` with the site's title pattern and default share image applied.

**Typical pattern — fetch a list's schema then its items**

```typescript
import { getUplinkJson } from '@/lib/uplink';
import type { SchemaItem, ContentItem } from '@/lib/uplink';

// 1. Get the list container (has the schema field definitions)
const schemaRes = await getUplinkJson<{ data: SchemaItem }>('api/v1/schemas', {
  searchParams: { slug: 'blog-posts' },
});
const schema = schemaRes.data;

// 2. Get all published items in that list — already sorted by CMS order
const itemsRes = await getUplinkJson<{ data: ContentItem[] }>('api/v1/content', {
  searchParams: { parent_id: schema.id, status: 'published' },
});
const items = itemsRes.data;

// Each item in `items` has a `fields` object whose keys match schema.schema[n].key
// Items arrive in the order set via drag-and-drop in Uplink — no re-sorting needed
```

---

### GET /api/v1/documents

Returns the **published** documents for the client.

**Query params**

| Param      | Type   | Description                                                                          |
| ---------- | ------ | ------------------------------------------------------------------------------------ |
| `category` | string | Filter by document category                                                          |
| `status`   | string | `published` or `unlisted`. Any other value is a `400`; `draft` and `archived` are never served |
| `id`       | string | Return a single document by id. Responds `404` if it isn't servable                  |

**Status semantics** — documents use the same four states as content items:

| Status      | In the listing | By `?id=` |
| ----------- | -------------- | --------- |
| `published` | Yes            | Yes       |
| `unlisted`  | No             | Yes       |
| `draft`     | No             | No        |
| `archived`  | No             | No        |

A document uploaded through the CMS starts as `draft`, so it is invisible here until
someone publishes it. Documents that existed before status was introduced were
backfilled to `published` and are unaffected.

**Response fields**

| Field          | Description                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------- |
| `id`           | Document UUID                                                                                     |
| `title`        | Display title, editable independently of the filename                                             |
| `filename`     | The current file's name. Changes when the file is replaced                                        |
| `status`       | `published` or `unlisted`                                                                         |
| `version`      | Increments every time the underlying file is replaced. Earlier versions are archived, not deleted |
| `uploaded_at`  | When the document was first created. Never changes                                                |
| `updated_at`   | Last metadata edit or file replacement. Poll this to detect a replaced file                       |
| `download_url` | `/api/v1/documents/{id}/file?v={version}` — **host-relative**; join it to `UPLINK_HOST`. Serves the file itself (below) |
| `storage_path` | Internal storage key, **stable across replacements**. Do not construct public URLs from it        |
| `file_size`, `mime_type`, `category`, `tags` | Metadata, all editable in the CMS                               |

> Replacing a file keeps `storage_path` and `id` unchanged and bumps `version`, so a
> cached reference keeps resolving to the newest bytes. Compare `version` or
> `updated_at` to decide when to re-fetch.

---

### GET /api/v1/settings

Returns the client's **site settings**: values the site reads at runtime and a client admin can change in the studio under **Your site → Site settings** — "show the animated map", "the holiday banner text", "items per page" — without a deploy.

A developer defines each setting with the MCP `define_setting` tool: a stable `key` the site code matches on, a label, a description, a type and a default. In the studio, platform admins and client admins change the **value** (with a confirmation, recorded in the activity log); editors and viewers see settings read-only. Nobody in the studio can create, rename or retype a setting, and a key and type never change once created. Platform admins can delete a setting that is no longer used.

**There is no draft.** What this endpoint returns is live, and a change reaches the site on its next fetch — within seconds with a webhook (tag `uplink:settings`).

**Types**

| `type`    | `value` is                                   | Studio control      |
| --------- | -------------------------------------------- | ------------------- |
| `boolean` | `true` or `false`                            | Switch              |
| `text`    | A string, at most 2000 characters (may be `""`) | Edit dialog      |
| `number`  | A finite number (integer or decimal)         | Edit dialog         |
| `select`  | One of the setting's `options[].value`       | Dropdown of labels  |

**Query params**

| Param | Type   | Description                                                      |
| ----- | ------ | ---------------------------------------------------------------- |
| `key` | string | Return one setting by key. Responds `404` if it is not defined   |

**Response**

```json
{
  "values": { "animated-locations-map": true, "hero-variant": "summer" },
  "data": [
    {
      "key": "animated-locations-map",
      "label": "Animated locations map",
      "description": "Animate the map on the contact page. Off shows a static image.",
      "type": "boolean",
      "options": null,
      "value": true,
      "default_value": true,
      "updated_at": "2026-09-26T10:00:00.000Z"
    },
    {
      "key": "hero-variant",
      "label": "Hero variant",
      "description": "Which seasonal hero the home page shows.",
      "type": "select",
      "options": [
        { "value": "spring", "label": "Spring campaign" },
        { "value": "summer", "label": "Summer campaign" }
      ],
      "value": "summer",
      "default_value": "spring",
      "updated_at": "2026-09-27T09:00:00.000Z"
    }
  ]
}
```

`values` is a `{ key: value }` convenience map. With `?key=` the response is `{ "data": { … } }` for that one setting.

| Field           | Description                                                                          |
| --------------- | ------------------------------------------------------------------------------------ |
| `key`           | Lowercase, hyphenated, at most 64 characters. The contract with your code; never changes |
| `type`          | `boolean`, `text`, `number` or `select` (above). Never changes. Treat any type you do not recognise as absent — more may be added |
| `options`       | For `select`, the allowed choices as `{ value, label }`; `null` for every other type. Options can be added later, but the live value and the default are always among them |
| `value`         | The live value                                                                       |
| `default_value` | What the setting was defined with; the studio offers a reset to it                   |
| `updated_at`    | Last change to the value or the definition                                           |

**Reading it in a site.** Always keep a default in code, and use it whenever the key is missing, its type is not the one you expect, or the request fails (including `423` while the client is offline). Check the type before trusting the value:

```ts
type UplinkSetting = { key: string; type: string; value: unknown };

async function readSettings(): Promise<UplinkSetting[]> {
  try {
    const { data } = await getUplinkJson<{ data: UplinkSetting[] }>('/api/v1/settings');
    return data;
  } catch (error) {
    // A wrong host or key is a bug to fix, not a reason to quietly use defaults.
    if (isUplinkConfigError(error)) throw error;
    return [];
  }
}

function setting<T>(settings: UplinkSetting[], key: string, type: string, fallback: T): T {
  const found = settings.find((s) => s.key === key && s.type === type);
  const ok =
    found &&
    (type === 'boolean' ? typeof found.value === 'boolean'
      : type === 'number' ? typeof found.value === 'number'
      : typeof found.value === 'string');
  return ok ? (found!.value as T) : fallback;
}

const settings = await readSettings();
const mapOn = setting(settings, 'animated-locations-map', 'boolean', true);
const banner = setting(settings, 'banner-message', 'text', '');
const hero = setting(settings, 'hero-variant', 'select', 'spring');
// For a select, also guard against a value your code does not know how to render:
const heroVariant = ['spring', 'summer'].includes(hero) ? hero : 'spring';
```

`getUplinkJson` tags the fetch `uplink` + `uplink:settings`, so a settings webhook revalidates it.

---

### GET /api/v1/business-info

Returns what the client's site shows about the **business** — name, logo, logomark, favicon, tagline, phone, email, address, service area, call to action and social profiles, with an icon for each — so none of it is hard-coded in the site. Client admins edit it in the studio under **Your business → Business info**; platform admins and agency admins can also open any client they manage from **Business info** in the client's menu on **Clients** (or **Edit** on the client); a change is confirmed and recorded in the activity log. Agents read it with `fetch_business_info` and, with a write key, change it with `set_business_info`.

**Uplink builds every link.** Render `display`, link to `href`, and never build a `tel:`, `mailto:`, maps or profile URL in the site. An editor picks the phone number's country (by flag) and types the digits; Uplink validates it, stores it in E.164 and formats it for display (libphonenumber), and builds the `tel:` link, emails become `mailto:`, a social handle becomes the platform's profile URL, and every web link is stored as `https`. A social link must point at the platform it is filed under.

**The logo, logomark and favicon are images from the client's Media.** The editor picks each one from Media (an image that is public and published or unlisted); this endpoint expands it exactly like a media field in `/api/v1/content`, so `<UplinkImage>` renders it and a backup can serve it. Once an image is picked — in the studio or with `set_business_info` — Uplink **locks** it in Media, so it cannot be replaced, deleted or unpublished by accident, and files it in the client's **Brand** folder (alongside any folder it was already in; the folder appears with the first brand image). To change the logo, pick or upload a new image in Business info; the old one is unlocked when a person makes the change in the studio, and stays locked after a change over MCP (a key never unlocks) until a person unlocks it in Media. Any change to a brand image that does reach the site — its alt text, or its file once a person has unlocked it — fires `business_info.updated`. An image that has since been made private comes back `null`, never as a link.

**Business info is the source of truth.** A site reads its name, logo, logomark, favicon and contact details from here and keeps its own copies only as the fallback for a `null`. Do not add a new logo or favicon file to the site's repository, or hard-code a contact detail: change it in Uplink, and every page follows.

**Nothing is defaulted.** A field nobody has entered is `null` — `cta.label` included — so the site keeps its own wording for it. **There is no draft:** what this endpoint returns is live, and a change reaches the site on its next fetch — within seconds with a webhook (event `business_info.updated`, tag `uplink:business-info`).

**Response** — always `200` for a valid key; a workspace that has entered nothing gets every field `null` and `"social": []`.

```json
{
  "data": {
    "name": "Acme Plumbing",
    "legal_name": null,
    "tagline": "Fixing leaks since 1998.",
    "logo": {
      "id": "2f1c0a7e-5b8d-4c3a-9e61-0d4b7a2c9f10",
      "version": 3,
      "width": 600,
      "height": 160,
      "alt_text": "Acme Plumbing",
      "mime_type": "image/svg+xml",
      "blur_data_url": null,
      "image_url": "https://www.uplinkcms.com/api/v1/media/2f1c0a7e-5b8d-4c3a-9e61-0d4b7a2c9f10/image?v=3",
      "status": "published",
      "is_private": false,
      "serve_original": false
    },
    "logomark": null,
    "favicon": {
      "id": "8a0e6c2d-1f4b-4e7a-b3c5-6d9f2a1e0b47",
      "version": 1,
      "width": 512,
      "height": 512,
      "alt_text": null,
      "mime_type": "image/png",
      "blur_data_url": "data:image/webp;base64,…",
      "image_url": "https://www.uplinkcms.com/api/v1/media/8a0e6c2d-1f4b-4e7a-b3c5-6d9f2a1e0b47/image?v=1",
      "status": "published",
      "is_private": false,
      "serve_original": false
    },
    "phone": {
      "display": "(613) 555-0123",
      "international": "+1 613 555 0123",
      "e164": "+16135550123",
      "href": "tel:+16135550123",
      "country": "CA"
    },
    "email": { "display": "hello@acmeplumbing.example", "href": "mailto:hello@acmeplumbing.example" },
    "address": {
      "lines": ["4B-123 Main Street", "Springfield, ON A1A 1A1"],
      "unit": "4B",
      "street": "123 Main Street",
      "locality": "Springfield",
      "region": "ON",
      "postal_code": "A1A 1A1",
      "country": "CA",
      "maps_href": "https://www.google.com/maps/search/?api=1&query=4B-123%20Main%20Street%2C%20Springfield%2C%20ON%20A1A%201A1%2C%20CA"
    },
    "service_area": "Springfield and area",
    "cta": { "label": null, "href": "https://acmeplumbing.example/book" },
    "social": [
      { "platform": "linkedin", "label": "LinkedIn", "href": "https://www.linkedin.com/company/acme-plumbing", "icon_svg": "<svg …>…</svg>" },
      { "platform": "facebook", "label": "Facebook", "href": "https://www.facebook.com/acmeplumbing", "icon_svg": "<svg …>…</svg>" }
    ],
    "json_ld": {
      "@context": "https://schema.org",
      "@type": "LocalBusiness",
      "name": "Acme Plumbing",
      "slogan": "Fixing leaks since 1998.",
      "url": "https://acmeplumbing.example",
      "logo": "https://www.uplinkcms.com/api/v1/media/2f1c0a7e-5b8d-4c3a-9e61-0d4b7a2c9f10/image?v=3",
      "telephone": "+16135550123",
      "email": "hello@acmeplumbing.example",
      "address": { "@type": "PostalAddress", "streetAddress": "4B-123 Main Street", "addressLocality": "Springfield", "addressRegion": "ON", "postalCode": "A1A 1A1", "addressCountry": "CA" },
      "areaServed": "Springfield and area",
      "sameAs": ["https://www.linkedin.com/company/acme-plumbing", "https://www.facebook.com/acmeplumbing"]
    },
    "updated_at": "2026-10-01T10:00:00.000Z"
  }
}
```

| Field          | Description |
| -------------- | ----------- |
| `logo`         | The full logo (wordmark / lockup) for the header and footer, or `null`. The same keys as an expanded media field: `id`, `version`, `width`, `height`, `alt_text`, `mime_type`, `blur_data_url`, `image_url` (the versioned image URL — optimized unless `serve_original`), `status`, `is_private`. Render it with `<UplinkImage asset={info.logo} sizes="…" priority />`; there is no `url` (a media field's signed original), and you never need one |
| `logomark`     | The symbol on its own, for tight spaces and square avatars, or `null`. Same shape as `logo` |
| `favicon`      | The browser-tab icon, or `null`. Same shape as `logo`; served at `/favicon.ico` by the installed `app/favicon.ico/route.ts` and linked from the root layout (below) |
| `phone`        | `{ display, international, e164, href, country }`. `display` is the national format (`(613) 555-0123`); `international` carries the calling code (`+1 613 555 0123`) — use whichever the design shows. Every number saved is valid; only a number stored before validation existed could come back with just `display` and the rest `null` — show it without a link |
| `email`        | `{ display, href }` with a `mailto:` href |
| `address`      | `null` when no street, city, region or postal code is set. `lines` is ready to render one per line (the country is left out); the parts are there for layouts that need them. `country` is ISO 3166-1 alpha-2 |
| `cta`          | The site's main call to action — book a call, get a quote, contact us. `null` without a link. `label` is `null` unless the editor set one — keep your own button text then |
| `social`       | In the editor's order. `platform` is one of `linkedin`, `facebook`, `instagram`, `youtube`, `x`, `tiktok`, `pinterest`, `threads`, `bluesky`, `github`, `google_business`, `other`; pick icons by it, and treat a platform you do not recognise as `other` — more may be added. `label` is the platform's name, or the editor's name for an `other` link. `icon_svg` is the platform's icon as an inline SVG string — monochrome (`fill="currentColor"`, so it takes your text colour), `viewBox="0 0 256 256"`, `aria-hidden`; size it with CSS. It comes from Uplink's fixed icon set (Phosphor, MIT), never from what an editor typed, so it is safe to inline. Use it, or your own icons — your choice |
| `json_ld`      | schema.org `LocalBusiness` (with a street address) or `Organization`, built from the fields above and the client's domain — `logo` is the logo's (else the logomark's) absolute image URL. Put it in the root layout as-is in a `<script type="application/ld+json">`. `null` until a name is set |
| `updated_at`   | Last change; `null` until something has been saved |

**Reading it in a site.** Keep the current values in code as a fallback, and use them field by field for anything `null` and for any response that is not a `200` (including `423` while the client is offline):

```ts
import { site } from '@/content/site'; // the values the site shipped with

type BusinessInfo = {
  name: string | null;
  phone: { display: string; international: string | null; href: string | null } | null;
  cta: { label: string | null; href: string } | null;
  social: { platform: string; label: string; href: string }[];
  json_ld: Record<string, unknown> | null;
  // …the other fields above
};

export async function getBusinessInfo() {
  let live: BusinessInfo | null = null;
  try {
    live = (await getUplinkJson<{ data: BusinessInfo }>('/api/v1/business-info')).data;
  } catch (error) {
    // A wrong host or key is a bug to fix, not a reason to quietly use defaults.
    if (isUplinkConfigError(error)) throw error;
  }
  return {
    name: live?.name ?? site.name,
    phone: live?.phone ?? site.phone, // display "(613) 555-0123", or international "+1 613 555 0123"
    ctaHref: live?.cta?.href ?? site.ctaUrl,
    ctaLabel: live?.cta?.label ?? 'FREE Consult', // the site's own wording
    social: live && live.social.length > 0 ? live.social : site.social,
    jsonLd: live?.json_ld ?? null,
  };
}
```

`getUplinkJson` tags the fetch `uplink` + `uplink:business-info`, so a business-info webhook revalidates it.

**The logo and favicon.** Render the logo through the site's own image route with `<UplinkImage>` (from `lib/uplink-image.tsx`), keeping the site's own file for `null`. The favicon is served at `/favicon.ico` by `app/favicon.ico/route.ts` (the installer and `get_install_setup` write it), because the Vercel dashboard, Google and many other readers only ever ask that address; link it from the root layout's metadata with its id and version:

```tsx
import Image from 'next/image';
import type { Metadata } from 'next';
import { UplinkImage, type UplinkImageAsset } from '@/lib/uplink-image';
import siteLogo from '@/public/logo.svg'; // the file the site shipped with

export function Logo({ info }: { info: { name: string | null; logo: UplinkImageAsset | null } }) {
  return info.logo ? (
    <UplinkImage asset={info.logo} alt={info.name ?? 'Home'} sizes="160px" priority />
  ) : (
    <Image src={siteLogo} alt="Home" priority />
  );
}

export async function generateMetadata(): Promise<Metadata> {
  const info = await getBusinessInfo(); // returns the live favicon, or null
  // The id and version make browsers fetch the new icon when it changes in Uplink.
  const favicon = info.favicon ? `/favicon.ico?media=${info.favicon.id}&v=${info.favicon.version}` : null;
  return { icons: { icon: favicon ?? '/icon.png' } }; // the site's own icon, in public/, for null
}
```

The route sends the favicon as a 128 px PNG inside an .ico (it asks Uplink for `?w=128&format=png`; an uploaded .ico is sent as it is) and is revalidated with business info. A static `app/favicon.ico` or `public/favicon.ico` takes that address instead: delete it once Business info has a favicon. **Never point the icon at `/api/media/…` alone** (`uplinkImageSrc(info.favicon)`): browsers show it, but `/favicon.ico` stays a 404 and Google's results show a grey globe. The Uplink Score checks `/favicon.ico` as well as the link.

The best favicon to upload is a square PNG, 512 × 512 (at least 48 × 48). An .ico works too; avoid an SVG, which Safari and most readers of `/favicon.ico` cannot show.

**In a repository backup.** A backup holds it as `uplink-backup/business-info.json` — exactly this response's `data` — so a site using `getUplinkJson` from `@/lib/uplink-backup` keeps showing its logo, phone, address and links while Uplink is unavailable. The logo, logomark and favicon point at their backed-up files (`/uplink-backup/media/…`), like any media field. A backup made before business info was backed up has no such file: re-running the installer (or `get_backup_setup`) adds a `null` placeholder so the site builds, and the reader then leaves this request to the site's own fallback until the next `npm run uplink:backup`.

---

### GET /api/v1/agency

Returns the **agency** that builds and looks after this client's site — for a "Website by …" link in the footer, or a credits page — so the agency's details are never hard-coded in each site. The agency enters them once under **Platform → Agencies → Agency info**, and every client it manages serves the same record. Agents read it with `fetch_agency`.

```json
{
  "data": {
    "id": "a9e00000-0000-4000-8000-0000000000b1",
    "name": "Northwind Agency",
    "tagline": "Websites for local businesses.",
    "logo_url": "https://….supabase.co/storage/v1/object/public/agency-logos/…/logo-….png",
    "website": { "display": "northwind.example", "href": "https://www.northwind.example/" },
    "credit_label": "Website by",
    "phone": { "display": "(613) 555-0123", "international": "+1 613 555 0123", "e164": "+16135550123", "href": "tel:+16135550123", "country": "CA" },
    "email": { "display": "hello@northwind.example", "href": "mailto:hello@northwind.example" },
    "address": { "lines": ["1 Main Street", "Springfield, ON A1A 1A1"], "…": "same shape as business info" },
    "social": [{ "platform": "instagram", "label": "Instagram", "href": "https://www.instagram.com/northwind", "icon_svg": "<svg …>" }],
    "updated_at": "2026-10-06T10:00:00Z"
  }
}
```

**`data` is `null` when no agency manages the client** — render no credit. `name` is never null: it is what the agency entered, else its name in Uplink. Every other field may be `null` (`social` is `[]`), and nothing is defaulted — `credit_label` above all, so the site keeps its own wording. `phone`, `email`, `address` and `social` have exactly the shapes of [`/api/v1/business-info`](#get-apiv1business-info): render `display`, link to `href`, never build a link. `logo_url` is a small public image; draw it with a plain `<img>`.

**There is no draft.** A change is live on every site the agency manages, and reaches each on its next fetch — within seconds with a webhook (event `agency.updated`, tag `uplink:agency`), sent when the agency info, the agency's name or its logo changes, and when a client joins or leaves an agency.

```tsx
// components/AgencyCredit.tsx — a server component, in the footer
import { getUplinkJson } from '@/lib/uplink';

export async function AgencyCredit() {
  const agency = await getUplinkJson<{ data: AgencyInfo | null }>('/api/v1/agency')
    .then((r) => r.data)
    .catch(() => null);
  if (!agency) return null;
  const label = `${agency.credit_label ?? 'Website by'} ${agency.name}`;
  return agency.website ? (
    <a href={agency.website.href} rel="noopener">{label}</a>
  ) : (
    <span>{label}</span>
  );
}
```

`getUplinkJson` tags the fetch `uplink` + `uplink:agency`, so an agency webhook revalidates it.

The credit is decoration: keep the `.catch(() => null)`, so a failed fetch drops the credit and never the page.

**In a repository backup.** A backup holds this whole response as `uplink-backup/agency.json` — `{ "data": … }`, so a client with no agency is kept as `data: null` — and the fallback reader answers this path from it. A backup made before the agency was backed up has a `null` placeholder: the reader does not answer, the fetch fails, and the credit is left out while Uplink is unavailable. `logo_url` stays Uplink's URL; the logo file is not copied.

---

### GET /api/v1/legal

Returns the client's **legal pages** — terms of service, privacy policy, cookie policy and any other kind — ready to render. Every site should have a terms of service and a privacy policy; with Uplink the person keeps them in the studio under **Your business → Legal**, where they paste the ones they have, fill in an outline, or link their **iubenda** or **Termageddon** documents, which Uplink then keeps up to date. Agents read them with `fetch_legal` and, with a write key, set them with `upsert_legal_page`.

**Uplink does not write legal text.** It stores and serves what the business provides. The studio's outlines are headings and prompts only, a page with a `[[prompt]]` left in it cannot be published, and every publish in the studio asks the person to confirm the text is theirs and reviewed. Tell the people you build for to have their policies reviewed by a qualified lawyer.

A legal page is a content item (`type: "legal"`), so it has the usual statuses, and its edits wait to be published: changing a published page — by hand, by an agent, or by a provider update — waits as **changes not published** until someone publishes them, and only the live text is ever served.

**Query params** — at most one:

| Param  | Description |
| ------ | ----------- |
| `kind` | One page by kind: `terms`, `privacy`, `cookies`, `disclaimer`, `accessibility`, or any other lowercase-dash kind a workspace adds (one page per kind) |
| `slug` | One page by slug — for a single `[slug]` route that serves every legal page. Also matches a slug the page was live at before; the page comes back under its current `slug`, so answer with a permanent redirect when they differ |

**Response** — without `kind` or `slug`, the **published** pages in footer order (terms, privacy, cookies, disclaimer, accessibility, then any other kind): `{ "data": [ … ] }`, possibly empty. With `kind` or `slug`, one page that is published or **unlisted** (the direct link): `{ "data": { … } }`, or `404` `{ "error": "Not found", "code": "not_found" }`. Drafts are never served. `kind` and `slug` together, or a malformed `kind`, is a `400`.

```json
{
  "data": {
    "id": "6f1c…",
    "kind": "privacy",
    "title": "Privacy Policy",
    "slug": "privacy-policy",
    "nav_label": "Privacy",
    "status": "published",
    "effective_date": "2026-04-09",
    "updated_at": "2026-10-01T10:00:00.000Z",
    "body_html": "<p>This Website collects some Personal Data from its Users.</p><h2 id=\"owner-and-data-controller\">Owner and Data Controller</h2><p>Acme Plumbing<br />123 Main Street</p>…",
    "toc": [
      { "id": "owner-and-data-controller", "text": "Owner and Data Controller", "level": 2 },
      { "id": "methods-of-processing", "text": "Methods of processing", "level": 3 }
    ],
    "source": { "provider": "iubenda", "url": "https://www.iubenda.com/privacy-policy/12345678", "fetched_at": "2026-10-01T09:17:00.000Z" }
  }
}
```

| Field            | Description |
| ---------------- | ----------- |
| `title`          | Render it as the page's `<h1>`. |
| `body_html`      | Sanitized HTML: `h2`–`h4`, paragraphs, lists, links, emphasis, tables. No scripts, styles, classes or inline handlers. **The leading `<h1>` is removed** (providers open with their own, e.g. "Privacy Policy of example.com"); any later `h1` becomes `h2`. Every `h2` and `h3` carries an `id`, and new-tab links carry `rel="noopener noreferrer"`. Render it as HTML. |
| `toc`            | One entry per `h2`/`h3` in `body_html`, in order, with the `id` already on the heading — render an "On this page" list with no parsing. |
| `effective_date` | `YYYY-MM-DD`, when this text took effect; show it as "Effective …" or "Last updated …". Required before a page can be published. For pasted or provider text it is read from the document's "Last updated" line, and the editor can change it. |
| `nav_label`      | Short footer link text. `null` unless the editor set one — use `title` then. |
| `kind`           | Known kinds are `terms`, `privacy`, `cookies`, `disclaimer` and `accessibility`; a workspace can add others. Treat a kind you do not know as a page like any other. |
| `source`         | `null` for text written or pasted in Uplink. For a page linked to a policy service: `provider` (`iubenda` or `termageddon`; treat one you do not know as a link to show), `url` — the service's public copy, which you may link as "View the original" — and `fetched_at`, when Uplink last pulled a change. Provider text is served verbatim apart from cleaning: nothing is substituted into it. |
| `status`         | `published`, or `unlisted` when fetched by `kind`/`slug`. |

**Reading it in a site.** One route per page (or one `app/[slug]/page.tsx` using `slug`), with the page the site has today kept as the fallback for a `404` or any non-`200`; footer links come from the listing:

```ts
type LegalPage = {
  kind: string;
  title: string;
  slug: string;
  nav_label: string | null;
  effective_date: string | null;
  body_html: string;
  toc: { id: string; text: string; level: 2 | 3 }[];
  source: { provider: string; url: string } | null;
};

export async function getLegalPage(kind: 'terms' | 'privacy'): Promise<LegalPage | null> {
  try {
    return (await getUplinkJson<{ data: LegalPage }>('/api/v1/legal', { searchParams: { kind } })).data;
  } catch (error) {
    if (isUplinkConfigError(error)) throw error;
    return null; // render the site's own page
  }
}

// Footer: (await getUplinkJson<{ data: LegalPage[] }>('/api/v1/legal')).data
//   .map((page) => ({ href: `/${page.slug}`, label: page.nav_label ?? page.title }))
```

`getUplinkJson` tags the fetch `uplink` + `uplink:content`; publishing a legal page, publishing its changes or unpublishing it fires the content webhook, so the page and the footer update within seconds.

**Linked to a policy service.** Uplink can keep a page in sync with **iubenda** or **Termageddon**:

- **iubenda** — paste the document's link (`https://www.iubenda.com/privacy-policy/12345678`, `…/terms-and-conditions/12345678`, `…/privacy-policy/12345678/cookie-policy`).
- **Termageddon** — paste the policy's embed code from **Embed Codes → Copy Code** (or its `https://policies.termageddon.com/api/policy/<id>` URL, or the embed id itself). One embed code per policy; a Termageddon embed does not say which policy it is, so add it to the matching page.

Uplink reads the text from the service at a URL it builds from that document id, cleans it, and checks for changes every day. A change to a live page never goes live by itself: it waits as changes not published, for a person to review and publish.

**In a repository backup.** A backup holds `uplink-backup/legal.json` — what this endpoint serves for every published and unlisted page — and the fallback reader answers `/api/v1/legal` from it with the same rules (the listing still returns published pages only). A backup made before legal pages were backed up has no such file: re-running the installer (or `get_backup_setup`) adds a `null` placeholder so the site builds, and the reader leaves these requests to the site's own fallback until the next `npm run uplink:backup`.

---

### POST /api/v1/consent

One choice a visitor made in the Uplink cookie banner, for its consent records. The site's own `app/api/uplink-consent/route.ts` (from the installer) sends it with the site key, so the key never reaches a browser, and passes the visitor's IP address and browser as `Uplink-Visitor-IP` / `Uplink-Visitor-UA` for the rate limit only (a daily hash; neither is kept).

```json
{
  "consent_id": "5f0c1e2a-9b7d-4c3e-8a61-0d2f4b6c8e10",
  "revision": 18342771,
  "accepted": ["necessary", "analytics"],
  "rejected": ["marketing"],
  "method": "asked",
  "action": "custom",
  "language": "en-ca",
  "path": "/contact"
}
```

`method` is `asked` (by the banner), `told` (the opt-out notice) or `gpc` (Global Privacy Control); `action` is `accept_all`, `reject_all`, `custom` or `withdrawal`. Answers `204` (also for a bot or over the rate limit of 30 an hour per visitor, so the site never waits), `400 UPLINK_CONSENT_INVALID` for a choice it cannot read, and the usual `401` and offline answers. Records are kept 12 months. Any key scope.

### GET /api/v1/integrations

Returns the **integrations** the client's site runs — Google Analytics 4, the cookie banner and font services — with every script and stylesheet already built. People set them up in the studio under **Your site → Integrations**: they paste a GA4 measurement ID, turn on the free **Uplink cookie banner**, connect the **CookieYes** or **Cookiebot** account they already pay for, or add their **Adobe Fonts** web project. Platform admins, client admins and editors can change them; viewers can look. Every change is confirmed and recorded in the activity log. Agents read them with `fetch_integrations` and, with a write key, change them with `set_integration`.

**Render it with `<UplinkIntegrations />`, never by hand.** The installer writes `lib/uplink-integrations.tsx` (a server component) and `lib/uplink-consent.tsx` (its browser half, plus `<CookieSettingsLink />`) and adds `vanilla-cookieconsent` to `package.json`. Put the component once in the root layout and the link in the footer:

```tsx
// app/layout.tsx
import UplinkIntegrations from '@/lib/uplink-integrations';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <UplinkIntegrations />
      </body>
    </html>
  );
}

// in the footer
import { CookieSettingsLink } from '@/lib/uplink-consent';
<CookieSettingsLink className="footer-link" />
```

It renders nothing until something is set up, and nothing on `/uplink`. A change in Uplink reaches the site without a deploy — within seconds with a webhook (events `integration.created`, `integration.updated`, `integration.deleted`; tag `uplink:integrations`). With repository backups, pass the backup reader so tags keep working while Uplink is away: `<UplinkIntegrations load={getUplinkJson} />` with `getUplinkJson` from `@/lib/uplink-backup`.

**Response** — always `200` for a valid key; nothing set up is `{ "consent_default": null, "integrations": [], "credit": { … } }`. Paused integrations are left out.

```json
{
  "data": {
    "consent_default": {
      "id": "uplink-consent-default",
      "strategy": "beforeInteractive",
      "inline": "window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('consent','default',{…});"
    },
    "integrations": [
      {
        "provider": "uplink_cookie_banner",
        "category": "consent",
        "consent_category": "necessary",
        "requires_consent": false,
        "config": { "theme": "light" },
        "scripts": [],
        "consent": {
          "adapter": "uplink",
          "revision": 1898161890,
          "position": "bottom-bar",
          "theme": "light",
          "accent": "#1f2937",
          "floating_button": false,
          "show": "where_required",
          "ask_first_in": ["AT", "BE", "…", "GB", "CH", "CA-QC"],
          "reject_on_first_layer_in": ["AT", "BE", "…", "GB", "CH", "CA-QC"],
          "text": { "title": "We use cookies", "description": "…", "accept_all": "Accept all", "reject_all": "Reject all", "choose": "Choose", "save": "Save choices" },
          "links": { "privacy_policy": null, "cookie_policy": null },
          "categories": [
            { "key": "necessary", "label": "Necessary", "read_only": true, "services": [ … ] },
            { "key": "analytics", "label": "Analytics", "read_only": false,
              "services": [ { "provider": "google_analytics_4", "label": "Google Analytics 4",
                              "cookies": [ { "name": "_ga", "purpose": "…", "duration": "2 years" } ] } ] }
          ],
          "notice": { "key": "1x9k2p", "label": "Cookie notice", "before": "We use cookies for analytics (Google). You can turn them off at any time in ", "link": "Cookie settings", "after": ".", "close": "Close",
                      "purposes": [ { "category": "analytics", "purpose": "analytics", "companies": ["Google"] } ] },
          "languages": ["en", "fr"],
          "translations": { "fr": { "text": { "title": "Nous utilisons des témoins", "…": "…" },
                                    "categories": [ "…the same categories, in French…" ],
                                    "notice": { "key": "1x9k2p", "label": "Avis sur les témoins", "…": "…" } } }
        },
        "styles": [],
        "csp": { "script": [], "connect": [], "img": [], "frame": [], "style": [], "font": [] }
      },
      {
        "provider": "google_analytics_4",
        "category": "analytics",
        "consent_category": "analytics",
        "requires_consent": false,
        "config": { "measurement_id": "G-ABC123XYZ" },
        "scripts": [
          { "id": "uplink-ga4-src", "strategy": "afterInteractive", "src": "https://www.googletagmanager.com/gtag/js?id=G-ABC123XYZ" },
          { "id": "uplink-ga4-config", "strategy": "afterInteractive", "inline": "…gtag('config','G-ABC123XYZ');" }
        ],
        "consent": null,
        "csp": { "script": ["https://www.googletagmanager.com"], "connect": ["https://*.google-analytics.com", "…"], "img": ["…"], "frame": [], "style": [] }
      }
    ],
    "credit": {
      "name": "Uplink",
      "url": "https://www.uplinkcms.com/why-uplink?ref=site-credit",
      "message": "This site's content is managed with Uplink — …"
    }
  }
}
```

| Field | Description |
| ----- | ----------- |
| `consent_default` | Google Consent Mode v2's default (everything denied until the visitor accepts). Present when Google Analytics asks visitors first — the default for every client. It is the only consent default on the page; render it before everything else |
| `integrations` | In render order: the cookie banner (at most one) first, then the tags |
| `provider` | `google_analytics_4`, `uplink_cookie_banner`, `cookieyes`, `cookiebot`, `adobe_fonts`, or a declared embed (`google_maps`, `youtube`, `vimeo`, `calendly`, `cloudflare_turnstile`: category `embeds`, no scripts, listed under Necessary in the banner with its cookies, and its hosts in `csp` — the site's own code renders it). More will be added — render a provider you do not recognise from its `scripts` as usual, and ignore fields you do not know |
| `scripts` | Built by Uplink from fixed templates and validated IDs — never from free text. `src` is always `https`; `attributes` holds `data-*` attributes only. Inject them in order |
| `styles` | Stylesheets to load, `[{ id, href, preconnect }]` — today only an Adobe Fonts web project (`https://use.typekit.net/<id>.css`). `<UplinkIntegrations />` renders them as `<link rel="stylesheet">` React hoists into `<head>`, and renders no other URL. `[]` for every other provider |
| `requires_consent` | `true` for a tag that does not follow Consent Mode itself: load it only once its `consent_category` is granted. Google tags are `false` — they wait for consent through Consent Mode |
| `consent` | On the banner row only. `adapter` says which banner gives consent: `uplink` (the config CookieConsent receives — every string must be HTML-escaped, which the installer's component does), `cookieyes` or `cookiebot`. An adapter you do not know means "not granted" |
| `consent.revision` | A hash of the providers and their categories: changes when a provider is added, removed or changes category, so returning visitors are asked again |
| `consent.languages`, `consent.translations` | The languages the banner speaks (`en`, and `fr` unless the person switched French off) and, for each other language, everything a visitor reads: `text` (the person's own French, else Uplink's French defaults), `categories` (same keys, French names, cookie purposes and durations) and `notice` (same `key`). Quebec visitors and browsers whose first language is French get French first; everyone else English |
| `consent.notice` | What a visitor the banner does not ask is shown instead: `before` + a Cookie settings button labelled `link` + `after`, a `close` button that records nothing, and `label` for the region. Show it again when `key` changes. `purposes` lists what it names. `null` when nothing is optional |
| `consent.links` | Site paths of the **published** privacy policy and cookie policy (Your business → Legal), or `null` |
| `csp` | Hosts a `Content-Security-Policy` must allow for this integration: `script`, `connect`, `img`, `frame`, `style` and `font` |
| `credit` | The Uplink credit for developers, or `null` when the site hides it. Render it only when present — a missing or `null` field shows nothing |
| `footer_credit` | The visible "Powered by Uplink" credit, `{ required, text, href, label }`, or `null` when it is not shown. `required` is `true` on the Free plan. Render it with `<UplinkPoweredBy />` |

**The cookie banner.** The Uplink cookie banner is free, built on the open-source [CookieConsent](https://github.com/orestbida/cookieconsent) library (MIT), loads from the site itself and matches the site (position, and light, dark with a button colour, or `theme: 'site'`: the site's own Uplink theme — its `--uplink-*` colours, fonts and button shape, falling back to light for any it leaves unset). It offers only the categories that have a tag turned on, lists exactly the cookies those tags set (Uplink knows them — no scan is needed), and shows **Accept all** and **Choose** on one line; Choose opens the choices, where a visitor turns each category on or off or rejects them all. Visitors in the EU and EEA, the UK, Switzerland and Quebec (`reject_on_first_layer_in`) also get **Reject all** beside Accept all, with the same weight. On phones it stays small. It **speaks English and French** (`languages`): visitors in Quebec and browsers whose first language is French see it in French (`translations.fr`, Uplink's French defaults unless the person wrote their own), everyone else in English; the person can switch French off. It **never takes keyboard focus** when it appears: it is announced politely to screen readers and reached with Tab, and the button's words are black or white by WCAG contrast. **Who is asked** is the person's choice in Uplink → Your site → Integrations (`show`): `always` (every visitor, the default), `where_required` (only visitors where the law asks first, listed in `ask_first_in` — the EU and EEA, the UK, Switzerland and Quebec) or `never` (no one). A visitor who is not asked is **told instead**: a small notice (`notice`) names the purposes and companies (“We use cookies for analytics (Google). You can turn them off at any time in Cookie settings.”), its Cookie settings opens the choices with everything on, and its Close records nothing. It shows again when `notice.key` changes (a new purpose or company). Their tags run, except under **Global Privacy Control**, which counts as “no” to Analytics and Marketing with no notice; where visitors are asked, a GPC visitor is still asked. A choice a visitor made always wins, and a visitor who is not asked keeps an earlier refusal even after the banner changes. Switching a category off **erases its cookies and reloads the page** once (site code can listen for the `uplink:consent-withdrawn` window event first). `revision` is a hash of the providers and their categories, so visitors are asked again when a provider is added, not only a category. Sites written before this (`data-uplink-integrations="1"`) keep counting visitors who are not asked as having accepted, with no notice, until their `lib/uplink-consent.tsx` and `lib/uplink-integrations.tsx` are rewritten from the installer; Check site says so. The site learns where a visitor is from its own `app/api/uplink-region/route.ts`, which reads only the country and region the host puts on the request (Vercel, Cloudflare or Netlify), keeps nothing and never sends it to Uplink; a visitor whose place it cannot tell is asked, and gets Reject all by their time zone. Treat an unknown `show` as `always`. It shows only once a tag needs consent. Its wording starts neutral and is the person's to change; it is interface text, not legal text. A workspace has **at most one** banner, and while one is on every integration asks visitors first. Visitors reopen their choices with `<CookieSettingsLink />`, or a floating button the person can turn on. The banner links no policies by default — put the privacy policy in the site footer (`GET /api/v1/legal`). `links` holds the published privacy and cookie policy paths only when the person turns on **Policy links on the banner** (`policy_links`); otherwise both are `null`. **Consent records:** each choice a visitor makes (accept all, reject all, a custom choice, or a withdrawal; not a page load, and not Close on the notice) goes through the site's own `app/api/uplink-consent/route.ts` to [`POST /api/v1/consent`](#post-apiv1consent), and Uplink keeps one anonymous row for 12 months: the banner's random consent id (from `cc_cookie`, shown to the visitor in Cookie settings so they can quote it), the revision, the categories accepted and rejected, how they were asked (`asked`, `told` by the notice, or `gpc`), the language, the page path and the time. No IP address, user agent or cookie value is kept. Client admins (an agency's admins included) see, look up and export them in Uplink → Your site → Integrations → Uplink cookie banner → Consent records, and agents read them with `fetch_consent_records`. Sites written before this (`data-uplink-integrations` below `3`) keep no records until the installer's files are added; Check site says so. CookieYes and Cookiebot are the choice for a business that wants automatic cookie scanning; they have their own plans, and their free plans have limits.

**The Uplink credit.** `<UplinkIntegrations />` also tells developers that the site is built on Uplink: a `<meta name="generator" content="Uplink">` tag, which technology detectors such as Wappalyzer and BuiltWith read, and one message in the browser console linking to [why developers use Uplink](https://www.uplinkcms.com/why-uplink). Nothing appears on the page, and nothing is logged on `/uplink`. Hiding it is **White label** — on the Pro plan for one workspace, or an agency's Agency plan for every client it manages — and is set under **Your site → Integrations → Uplink credit** (an agency's default on its card under **Platform → Agencies**). For now a platform admin sets both the plan and the choice; everyone else sees them locked. A client's own choice beats its agency's, and Hidden applies only while White label is active: if it lapses, the credit comes back and the choice is kept. A change reaches the site within seconds with a webhook (event `uplink_credit.updated`, tag `uplink:integrations`). Leave it to Uplink — do not strip the tag or the message from the site's code.

**The footer credit ("Powered by Uplink").** `<UplinkPoweredBy />` from `lib/uplink-credit.tsx` (an install file) renders the words "Powered by" and the Uplink logo, linking to the site's own `/uplink` page. Put it in the site's footer on every page and leave it there: it renders only while this response's `footer_credit` is set. On the Free plan the terms require it, visible to visitors; Uplink checks the live home page for it every day and on every Check site / `check_site`, and while it is missing every connector tool result carries a notice that the site is in breach of the terms. On a paid plan it stays until a client admin switches it off under **Site settings → Powered by Uplink**. It takes the footer's text colour and size (the logo draws in `currentColor`); never hide it, shrink it to nothing or move it off screen. A backup holds it too, so the credit stays while the site is served from the backup.

**Check site.** The Integrations page checks the site each time it opens, and again on **Check again**: it fetches the site's home page and reports whether `<UplinkIntegrations />` is there, whether a Google Analytics tag is also hard-coded (every page view counted twice), and whether a second cookie banner is hard-coded.

**In a repository backup.** A backup holds it as `uplink-backup/integrations.json` — exactly this response's `data` — and the fallback reader answers this path from it. A backup made before integrations were backed up has a `null` placeholder (written by the installer or `get_backup_setup`), and the site then renders no integrations while Uplink is unavailable. A backup made before the Uplink credit existed has no `credit`, so the site shows none while it is served from that backup.

---

### Uplink Analytics

**Uplink Analytics** is Uplink's own visitor statistics. When it is on, `GET /api/v1/integrations` includes a `uplink_analytics` entry whose one inline script (`id: "uplink-analytics"`) sends each page view to `POST /api/v1/collect` on the Uplink that served the response. `<UplinkIntegrations />` renders it like any other integration, so a site that already renders the component needs no code change.

- **No cookies, nothing stored in the browser.** `requires_consent` is `false` and the cookie banner lists nothing for it (unless the site recognises returning visitors, below). Uplink stores no IP address: a visitor is a hash of that day's random salt, the workspace, the IP and the user agent, and each day's salt is deleted when the day ends, so a visitor cannot be followed from one day to the next.
- **What is sent:** the path (never the query string or `#hash`), the landing page's referrer (Uplink keeps only its host), `utm_source`, `utm_medium` and `utm_campaign`, and the window width. Uplink adds the country (from the request) and phone, tablet or desktop, browser and OS (from the user agent).
- **What counts:** a page view whose `Origin` is one of the workspace's site addresses (production or Vercel, with or without `www`) and whose user agent is not a bot. The `/uplink` page, pages shown inside a frame (the studio preview) and automated browsers are skipped. Client-side navigation is counted once per new path. A visit is the same visitor with no more than 30 minutes between pages.
- **Content-Security-Policy:** allow `https://www.uplinkcms.com` in `connect-src` (`csp.connect`).
- **Returning visitors (opt-in, needs a cookie banner):** with `returning_visitors: true` in its config (Integrations → Uplink Analytics → *Recognise returning visitors*, or `set_integration` with `returning_visitors: true` after the person asks), the response carries a **second** `uplink_analytics` entry with `consent_category: "analytics"`, `requires_consent: true` and one script, `id: "uplink-analytics-visitor"`, so the banner holds it back until the visitor accepts analytics. It keeps a random id (32 hex characters) in the first-party cookie `uplink_vid` for 13 months, renewed on each visit, and the tracking script sends it as `v`. Uplink keeps only `sha256(workspace | id)`, never the id, and forgets a visitor 13 months after their last visit. The Uplink cookie banner lists `uplink_vid` under Analytics (and asks visitors who already chose again); with CookieYes or Cookiebot, list it in that service's dashboard. Without a banner the entry is left out, and visitors who decline are counted the cookieless way. `fetch_traffic` then has `returning` (`{ days, from, visitors, returning_visitors, visits, returning_visits }`, the range's last 30 days at most, only visitors who accepted), and each recent visit by a recognised visitor has `visitor: { key, visits, first_seen }`.
- **Turning it on:** agents use `set_integration` with `provider: "uplink_analytics"` (no `id`) after the person says yes. Raw page views are kept 30 days.
- **AI tools:** ChatGPT, Claude, Perplexity and other AI tools fetch pages themselves and never run the script. `lib/uplink-ai-visits.ts` (installer) exports `reportAiVisit(request)`: call it from the site's `proxy.ts` (Next.js 16; `middleware.ts` on 15) and pass what it returns to `event.waitUntil()`. For a request whose user agent looks like an AI tool it sends `POST /api/v1/ai-visits` with the site key, `{ "path", "user_agent" }`, after the page is answered; for everyone else it does nothing. Uplink names the tool and why it came — `live` (fetched while answering someone: ChatGPT-User, Claude-User, Perplexity-User), `search` (indexing for AI search) or `training` — keeps only that and the path for 30 days, and summarises it per day for good. The starter ships the proxy. It counts only while Uplink Analytics is on; the endpoint answers `204` to any valid key and `401` without one. The report's `ai` section also has `answers` (the questions each fetched page answers in Search & sharing, since AI tools never send the person's question), `referrals` (people who clicked a link in an AI answer, by assistant and landing page) and `new_pages` (pages fetched for the first time in the last 7 days).
- **Reading it:** people see it in **Visitors → Traffic**. Agents use `fetch_traffic` (`GET /api/v1/traffic?days=7|30|90`, any key, never cached): totals against the same length of time just before, a daily series, top, landing and exit pages, sources named and grouped (`direct`, `search`, `ai`, `social`, `email`, `other`; `ai` is a click from an AI answer such as ChatGPT or Perplexity), UTM tags, countries, devices, browsers, and journeys from source → landing page and page → next page. `visitors` over more than one day is a sum of each day's visitors. Today is included, summarised every hour. `recent_visits=1` (`recent_visits: true` in the tool) adds the newest 10 visits of the last 30 days, each with its pages in order, where it came from, country, device and how long it lasted, with nothing that says who the visitor was. Visitors → Traffic lists them as **Recent visits**, on its Visits tab.

### Forms

**Forms** are contact forms a site shows and Uplink delivers. People build them in the studio under **Content → Forms** (start from Contact, Request a quote or Request a call back, then change the fields), and agents with `set_form`. A visitor's message is checked by Uplink, emailed through Resend to the people the form sends to, and **not kept**: Uplink stores only counts (seen, started, sent, failed, blocked) per form, page and day. Clicking **Reply** in the email answers the visitor, because the email's `Reply-To` is the address they typed (the form's first `email` field).

- **Who it goes to:** the workspace's Business info email by default, or up to 5 people chosen in the form, each of whom must be the Business info email or a member of the workspace. A form cannot send to anyone else, so it cannot be used to send mail to strangers. A member who leaves is dropped from delivery on the next message.
- **Fields:** 1–20 of `text`, `email`, `phone`, `textarea`, `select` (1–20 `options`), `checkbox` and `hidden`, each `{ key, label, type, required?, placeholder?, help?, options?, width? }` (`width: "half"` puts two side by side). Labels and text are plain text: no HTML.
- **Hidden fields** carry what an order form holds quietly: a package, a plan, an order code. They are never shown. The site fills each one from, first to last, the page (`<UplinkForm form="order" values={{ package: 'launch' }} />`), the page's URL (`?package=launch`, or `?<param>=` when the field sets `param`), then the field's fixed `value`. A field with `reference: true` gets a fresh order code from Uplink for every message (like `K7QX-3M9P`), and whatever the browser sends for it is ignored. Hidden answers appear first in the email, under **Details**. A visitor can edit a URL, so a hidden value says what they chose, never what they paid.
- **Subject:** the form's `subject` may name any answer as `{field_key}`, e.g. `New order {order_code}: {package}`; the sender's name is added after it.
- **Sending visitors on:** a form's `redirect` replaces the thank-you message with a link, for example a Stripe payment link: `{ "url": "https://buy.stripe.com/default" | null, "rules": [{ "field": "package", "equals": "launch", "url": "https://buy.stripe.com/launch?client_reference_id={order_code}&prefilled_email={email}" }] }`. The first rule whose field's answer matches (trimmed, ignoring case) wins, else `url`; with `url: null` everyone else sees the thank-you message. Links are `https://` only, up to 20 rules, and `{field_key}` placeholders (URL-encoded answers) are allowed only in the query or fragment. Uplink works the link out for each message and keeps no record of it; the email says where the visitor was sent.
- **Spam:** a hidden field (`uplink_website`), a minimum time to fill in the form (2.5 seconds), known bots and messages with more than 5 links are answered exactly like a real message (`200`) and counted as `blocked`, so a script learns nothing. Each visitor can send 5 messages an hour and each workspace 200 a day; the limit uses a hash of that day's random salt, the IP and the user agent, and no IP address is stored.
- **On the site:** the installer (and `get_install_setup`) writes `lib/uplink-form.tsx` (`<UplinkForm form="contact" />`, a server component), `lib/uplink-form-client.tsx` (the form itself, styled from the theme's `--uplink-*` variables; pass `unstyled` or a `className` to style it yourself) and `app/api/uplink-forms/route.ts`, the site's own route the browser posts to. That route accepts only same-origin requests, adds the site key and the visitor's IP and user agent (`Uplink-Visitor-IP`, `Uplink-Visitor-UA`), and forwards to Uplink, so the key never reaches the browser.
- **A change is live at once.** Saving a form emits `form.updated` (tag `uplink:forms`); recipients and subject never reach the site and emit nothing.
- **Reading the numbers:** **Visitors → Traffic** has a Forms card on its Overview tab, and `fetch_traffic` has `forms` (`{ days, totals, forms: [{ key, name, views, starts, submissions, failed, blocked, conversion_rate }], pages }`).
- **Not in a backup yet:** forms are not part of a repository backup in this version; while Uplink is unavailable the site shows its `fallback`.

#### GET /api/v1/forms

Returns the workspace's enabled forms, or one with `?key=contact`: `{ data: [{ key, name, fields, submit_label, success_message, reply_to_field, redirect }] }` (with `key`, `data` is the one form). `submit_label` and `success_message` are `null` when the person set none, and the site keeps its own wording. Never cached (`no-store`). Who it sends to is never included. An unknown or paused key is `404 UPLINK_FORM_NOT_FOUND`. Any key scope. Agents read it with `fetch_forms`.

#### POST /api/v1/forms/submit

Sends one message. Body (at most 64 KB): `{ "form": "contact", "path": "/contact", "values": { "name": "…", "email": "…" }, "uplink_website": "", "elapsed_ms": 8200 }`. Called by the site's `app/api/uplink-forms/route.ts`, never from the browser.

| Status | `code` | Meaning |
| --- | --- | --- |
| `200` | — | `{ ok: true, redirect_url? }`: sent (or quietly blocked as spam). `redirect_url` is where to send the visitor when the form has a redirect |
| `404` | `UPLINK_FORM_NOT_FOUND` | No enabled form with that key |
| `422` | `UPLINK_FORM_INVALID` | `fields` maps each field key to what is wrong |
| `429` | `UPLINK_FORM_LIMITED` | The visitor's hourly or the workspace's daily limit |
| `502` | `UPLINK_FORM_NOT_SENT` | Resend refused it; the visitor can try again |
| `503` | `UPLINK_FORM_NO_RECIPIENT` | The form has nobody to send to (no Business info email) |
| `503` | `UPLINK_FORM_EMAIL_OFF` | Email is not configured on this Uplink (`RESEND_API_KEY`) |
| `503` | `UPLINK_FORM_FULL` | The plan's form submissions for this month are used, plus 10%. `error` gives the visitor the business's email and phone instead. Starts again on the 1st (UTC) |

#### POST /api/v1/forms/events

`{ "form": "contact", "path": "/contact", "event": "view" | "start" }` counts a form seen or started. Always `204`; bots are not counted.

#### set_form (MCP)

`set_form { key, name?, preset?, fields?, recipients?, subject?, submit_label?, success_message?, redirect?, enabled? }` creates a form (from `preset` `contact`, `quote` or `callback` when no fields are given) or changes one by key. A form's key never changes. It returns the form, who it sends to, the code to put on the page and where the person reviews it. There is no delete tool: a person deletes a form in the studio.

### Reviews

**Reviews** are what customers said about the business, published on its site as content. People add them in the studio under **Content → Reviews**, and agents with `set_review`. Uplink is not a CRM: a review holds only what the site shows (the name it is shown under, the words, optional stars, headline and date, where it came from and a link to it there) and never a customer's email, phone or anything else about them.

- **Nothing shows until it is approved.** A new review waits for approval. Platform admins, client admins and editors approve, hide, feature, edit and delete reviews in the studio. An agent may approve only a review that links to where the customer posted it publicly (`source` google, facebook, yelp, tripadvisor or other, with `source_url`), so its words can be checked; any other is saved waiting and the result says so (`approval_refused`). An agent that changes the words of such an approved review sends it back to waiting. There is no delete tool.
- **Fields:** `author_name` (one line, at most 80), `body` (at most 2,000, newlines kept), `rating` (whole stars 1–5, or `null` for a testimonial), `title` (one line, at most 120), `reviewed_on` (`YYYY-MM-DD`, not in the future), `source` (`google`, `facebook`, `yelp`, `tripadvisor`, `direct` — sent to the business, the default — or `other`), `source_url` (`https://`), `featured`. Text is plain text: render it escaped. At most 500 reviews per workspace.

`GET /api/v1/reviews[?featured=true][&limit=6]` returns the **approved** reviews, featured first and then newest:

```json
{
  "data": [
    { "id": "…", "author_name": "Sarah K.", "rating": 5, "title": null, "body": "Best coffee in town.",
      "reviewed_on": "2026-10-02", "source": "google", "source_label": "Google",
      "source_url": "https://g.page/r/…", "featured": true }
  ],
  "summary": { "count": 1, "rated_count": 1, "average": 5 },
  "json_ld": {
    "@context": "https://schema.org", "@type": "LocalBusiness", "name": "Acme Coffee", "url": "https://acme.com",
    "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5.0", "reviewCount": 1, "bestRating": 5, "worstRating": 1 },
    "review": [{ "@type": "Review", "author": { "@type": "Person", "name": "Sarah K." }, "reviewBody": "Best coffee in town.",
      "datePublished": "2026-10-02", "reviewRating": { "@type": "Rating", "ratingValue": 5, "bestRating": 5, "worstRating": 1 },
      "publisher": { "@type": "Organization", "name": "Google" } }]
  }
}
```

`summary` and `json_ld` describe exactly the reviews returned, so put `json_ld` on the page that shows them and nowhere else. The business is named from Business info (else the workspace name); it is a `LocalBusiness` when it has a street address, otherwise an `Organization`, as Business info's own `json_ld`. `aggregateRating` is left out when no review has stars, and `json_ld` is `null` with no reviews. Google seldom shows review stars in search for reviews a business publishes about itself, so say plainly that the markup is for search engines and AI tools to read, not a promise of stars. `status=pending | hidden | all` is for agents (`fetch_reviews`), like content's `status=draft`; it adds `status`, `added_via` and `approved_at` and returns no `json_ld`. Cache tag `uplink:reviews`.

- **On the site:** the installer (and `get_install_setup`) writes `lib/uplink-reviews.tsx`: `<UplinkReviews />` renders every approved review, `<UplinkReviews featured limit={3} />` the featured ones, with stars, the words, name, date and a link to the original, styled from the theme's `--uplink-*` variables (`unstyled` or `className` to style it yourself), and the JSON-LD. `getUplinkReviews()` reads the same data for a layout of your own; render `<UplinkJsonLd data={reviews.json_ld} />` (lib/uplink-seo) beside it. With no approved reviews, or while Uplink is unavailable, it shows its `fallback`.
- **The review link:** **Content → Reviews → Ask for reviews** (or `set_review_link`, client admins only) turns the business's own review page into a short link, `https://www.uplinkcms.com/review/<token>`, and a QR code (download PNG or SVG in the studio, or `GET /review/<token>/qr?size=512` as SVG). The link redirects (302) to the review page, which must be on Google (`g.page`, `search.google.com`, `www.google.com`, `maps.app.goo.gl` …), Facebook, Yelp or Tripadvisor; no other site, so the address can never send people anywhere else. The token never changes, so a printed code keeps working when the review page changes. Uplink keeps nothing about the people who use it, and does not count them.
- **Not in a backup yet:** reviews are not part of a repository backup in this version.

### Announcement bars

An **announcement bar** is a short message across the top or bottom of the site — *"**Beacon West Development** Survey closes November 30. [Have your say →]"*. People set them up in the studio under **Content → Announcements** (with a live preview in the site's theme) and agents with `set_announcement`. Uplink provides the bar: never build one by hand or keep its words in a site setting.

- **What a bar holds:** an optional bold lead-in (`title`, 60 characters), the `message` (200), an optional link (`https://…` or a page on the site such as `/events`, with its words and "open in a new tab"), a `style` taken from the theme (`brand` = the primary colour, `secondary`, `accent`, `soft`, `dark`, or the lightly tinted status colours `info`, `success`, `warning`, `urgent`), an `icon` (`dot`, `pulse`, `megaphone`, `info`, `alert`, `calendar`, `gift`, `sparkle` or `none`), `placement` (`top` or `bottom`), `sticky`, `scrolling` (a sideways ticker that pauses on hover and stays still under `prefers-reduced-motion`), `dismissible`, the pages it shows on (`include`, empty = every page, and `exclude`, which wins: `/` is the home page, `/events` one page, `/events/*` it and everything under it), `starts_at` and `ends_at`, `priority` (0–100) and an on/off switch. Plain text only.
- **Which one shows:** at each placement, the highest-priority bar that is switched on, inside its dates, meant for the page and not closed by this visitor. Closing it shows the next.
- **Never covers the header.** At the top the bar sits in the page's flow, above the header. While it shows it sets `--uplink-announcement-offset` on `<html>` (how much of the bar is in view) and `--uplink-announcement-height`; a header that is `position: sticky` or `fixed` at `top: 0` (a `<header>`, or any element marked `data-uplink-header`) is moved down by that much automatically. A sticky bottom bar sits in the flow at the end of the page, so it never covers the footer either.
- **Dates and closing are decided in the visitor's browser,** before the page paints, from what the site fetched. So a cached page starts and ends a bar on time, an open page changes when a date passes, and nothing jumps. A closed bar is remembered in that browser (`localStorage` key `uplink-announcements-closed`, never a cookie) and shows again when its wording or link changes (`version`).
- **Counts, cookie-free:** the browser tells Uplink when a bar was shown (once per page), its link clicked or the bar closed, with `navigator.sendBeacon` to `POST /api/v1/announcements/events`. Uplink keeps a daily count per bar and nothing about the visitor. The studio shows the last 30 days. **Content-Security-Policy:** allow `https://www.uplinkcms.com` in `connect-src`.
- **On the site:** the installer (and `get_install_setup`) writes `lib/uplink-announcement.tsx` (`<UplinkAnnouncement />`, a server component) and `lib/uplink-announcement-client.tsx` (the bar, styled from the theme's `--uplink-*` variables; pass `className`, or `unstyled` to style `.uplink-announcement` yourself; `headerSelector` names a header that is neither `<header>` nor `[data-uplink-header]`). Render it once, as the first thing in `<body>` in the root layout. The starter does. Existing sites adopt it by writing the two files and that one line.
- **A change is live at once.** Saving emits `announcement.updated` (tag `uplink:announcements`; sites installed before the tag existed still refresh through the broad `uplink` tag). Not part of a repository backup: while Uplink is unavailable no bar shows.

#### GET /api/v1/announcements

`{ data: [{ id, key, version, title, message, link: { url, label, new_tab } | null, style, icon, placement, sticky, scrolling, dismissible, pages: { include, exclude }, starts_at, ends_at, priority }], now }` — every bar that is switched on and has not ended, scheduled ones included, highest priority first, at most 10. `?all=true` returns every bar whatever its state, each with `enabled`, `state` (`live` | `scheduled` | `off` | `ended`), `updated_at` and `last_30_days { views, clicks, dismissals }`; `?key=` one bar the same way, or `404 UPLINK_ANNOUNCEMENT_NOT_FOUND`. Never cached (`no-store`). Any key scope. Agents read it with `fetch_announcements`.

#### POST /api/v1/announcements/events

`{ "a": "<announcement id>", "e": "view" | "click" | "dismiss" }`, sent by the browser with no key. Counted only when the bar exists, the `Origin` is one of the workspace's site addresses and the user agent is not a bot. Always `204`.

#### set_announcement (MCP)

`set_announcement { key?, title?, message?, link?: { url, label, new_tab? } | null, style?, icon?, placement?, sticky?, scrolling?, dismissible?, pages?: { include?, exclude? } | null, starts_at?, ends_at?, priority?, enabled? }` creates a bar (a new key, or no key: one is made from the wording) or changes only what is passed. Dates are ISO 8601 with a time zone. Live at once when switched on and inside its dates. It returns the bar with its `state`, the code for the site, where the person reviews it and a sentence to pass on. There is no delete tool: switch it off with `enabled: false`; a person deletes it in the studio.

### GET /api/v1/theme

Returns how the client's site **looks** — its colours, fonts, text sizes, spacing and corner radius — as ready-to-inline CSS custom properties. People set it in the studio under **Your site → Theme**: pick a starter preset or start from what the site already has, choose fonts from Google Fonts or the system, set a type scale and density, and see the result at once in a live preview at phone and desktop widths. A theme in progress can be named and saved without publishing, and loaded again later like a preset. **Your site** in the preview shows the real site with the theme being edited, and **Open on your site** opens it in a new tab — only for the person looking (see *Previewing a theme on the site*). Platform admins and client admins publish it; editors and viewers can look. Agents read it with `fetch_theme` and, with a write key, change it with `set_theme` — or save a draft for the person to preview and publish with `save_theme`.

**There is no draft: a publish is live on the site's next page load.** The studio confirms every publish, naming what changes (*"the primary colour, the heading font (Inter → Fraunces)"*) and any text that may be hard to read. Every publish keeps a version: **History** previews or restores any of the last 100, and a restore is itself a new version, so going back never loses anything. A publish from a form someone else has published over since is refused (`409`, "Someone changed the theme while you were editing").

**Render it with `<UplinkTheme />`, never by hand.** The installer writes five files:

- `lib/uplink-theme.tsx` — a server component for the root layout's `<head>`. It reads this endpoint (tag `uplink:theme`) and renders one inline `<style data-uplink-theme>` plus at most two font preloads. It checks the CSS once more (nothing that could leave the `<style>` element is rendered), renders an empty style on any failure, and never throws.
- `app/uplink-theme.css` — the Tailwind v4 mapping onto the theme (below). Import it after Tailwind in your global stylesheet.
- `app/api/uplink-fonts/[file]/route.ts` — serves the font files from your own domain (below).
- `lib/uplink-theme-preview.tsx` and `app/api/uplink-theme-preview/route.ts` — the theme preview (below). `<UplinkTheme />` renders it; it does nothing unless the browser opened a preview link.

**Previewing a theme on the site.** A preview link is `https://<your site>/?uplink_theme_preview=uthp_…`. The studio makes one for **Your site** and **Open on your site** in **Your site → Theme**, and `save_theme` returns one as `site_preview_url`. **Copy link** copies the whole link, to send to someone — whoever opens it sees the theme until it ends, including edits made meanwhile. To try it on another address of the same site — a Vercel preview deployment, say — **Copy for a preview deployment** copies just `?uplink_theme_preview=uthp_…` to add to the end of that address (the site takes it out of the address bar once read, so it cannot be copied from there); the deployment needs the preview files and the site's key like production. The browser that opens it keeps the token for the tab (`sessionStorage`), takes it out of the address bar, asks the site's own `/api/uplink-theme-preview` route — which asks `GET /api/v1/theme?preview=<token>` with the site's key — and lays the CSS over the live theme, with a bar saying it is a preview and **Exit preview**. Every other visitor sees the live theme. A link lasts a day (editing it in the studio extends it) and is answered only for the workspace that made it, so it shows nothing on any other site. A site installed before previews existed shows the live theme: replace `lib/uplink-theme.tsx` and add the two files from the installer or `get_install_setup`. The studio's **Your site** frame needs a site that allows being shown inside another page; otherwise use **Open on your site**.

`?preview=<token>` answers like the live theme plus `preview: { label, expires_at }`, never cached (`Cache-Control: private, no-store`). An unknown, ended or other workspace's token is a `404` with `code: UPLINK_THEME_PREVIEW_NOT_FOUND`. Never cache it or call it from code a visitor did not ask for.

```tsx
// app/layout.tsx
import UplinkTheme from '@/lib/uplink-theme';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <UplinkTheme />
      </head>
      <body>{children}</body>
    </html>
  );
}
```

```css
/* app/globals.css */
@import "tailwindcss";
@import "./uplink-theme.css";
```

A change in Uplink reaches the site without a deploy — within seconds with a webhook (event `theme.updated`, tag `uplink:theme`). `<UplinkTheme base />` also sets element defaults (body, `h1`–`h6`, links, code, the scrollbar) wrapped in `:where()`, so they have zero specificity and your own classes always win; it is off by default so installing changes nothing. With repository backups, pass the backup reader: `<UplinkTheme load={getUplinkJson} />` with `getUplinkJson` from `@/lib/uplink-backup`.

**Response** — always `200` for a valid key. A workspace that never published a theme gets `version: 0`, every token `null`, and empty `css` — the site keeps its own look.

```json
{
  "data": {
    "schema_version": 1,
    "version": 14,
    "updated_at": "2026-10-07T09:12:00Z",
    "tokens": {
      "color": { "primary": "#1f4fd1", "on_primary": null, "background": "#ffffff", "text": "#111827", "…": null },
      "font": {
        "heading": { "source": "google", "family": "Fraunces", "weights": [600, 700], "italic": false, "preload": true },
        "body": { "source": "system", "stack": "sans" },
        "mono": null,
        "subsets": ["latin"]
      },
      "type": {
        "base": { "mobile": 16, "desktop": 18 },
        "ratio": { "mobile": 1.2, "desktop": 1.25 },
        "roles": { "h1": { "size": null, "weight": 700, "line_height": 1.1, "letter_spacing": -0.02, "font": "heading" }, "…": {} }
      },
      "space": { "unit": 4, "steps": { "md": null, "…": null }, "gap": "md", "pad": "lg", "gutter": { "mobile": 16, "desktop": 32 }, "section": { "mobile": 56, "desktop": 112 } },
      "layout": { "container": 1200, "prose": 68 },
      "radius": { "sm": 4, "md": 8, "lg": 16, "button": "md" }
    },
    "resolved": { "color": { "primary": "#1f4fd1", "on_primary": "#ffffff", "primary_hover": "#0a34b6", "…": "" }, "variables": { "--uplink-color-primary": "#1f4fd1", "…": "" } },
    "css": "@font-face{font-family:\"Fraunces\";…}@font-face{font-family:\"Fraunces Fallback\";src:local(\"Times New Roman\");…}:root{--uplink-color-primary:#1f4fd1;…}",
    "base_css": ":where(body){…}:where(h1){…}",
    "fonts": {
      "faces": [{ "family": "Fraunces", "style": "normal", "weight": "600 700", "subset": "latin", "file": "3b1f…e9.woff2", "unicode_range": "U+0000-00FF, …" }],
      "preload": ["3b1f…e9.woff2"],
      "path": "/api/uplink-fonts/",
      "uploaded": [{ "id": "…", "family": "Acme Sans", "category": "sans-serif", "weights": [400, 700], "italic": true, "variable": null, "files": [ … ] }]
    },
    "contrast": [{ "pair": "on_primary/primary", "foreground": "#ffffff", "background": "#1f4fd1", "ratio": 6.78, "needs": 4.5, "passes": "aa", "token": "primary", "fix": null, "message": "Passes AA." }]
  }
}
```

| Field | Description |
| ----- | ----------- |
| `tokens` | What was entered. Every token may be `null` — not set — and is then left out of the CSS, so the site's own value applies. Uplink never invents a value |
| `resolved` | Every value after derivation, for agents and for sites that build their own CSS: `on_*` colours (`null` means automatic — near-black or white, whichever reads better), `*_hover` and `*_subtle` shades of each brand colour, heading sizes from the scale, `color_roles` (every colour role the workspace defined, as this theme shows it — see *Colour roles*), and `variables`, the `--uplink-*` map the CSS is built from |
| `css` | Ready to inline in a `<style>` element: the `@font-face` rules (pointing at `fonts.path`), a metric-adjusted fallback face per family, and one `:root{…}` block with only what is set. Under 8 KB |
| `base_css` | Optional element defaults, zero specificity — `<UplinkTheme base />` adds them |
| `fonts.preload` | At most two files — the body font's and, if different, the heading font's latin, normal-style file — and only for a role whose **Preload** is on |
| `contrast` | WCAG 2.2 AA checks for the pairs a site draws (`text` on `background` and `surface`, `on_primary` on `primary`, links, borders, status colours, and the scrollbar on its track at 3 : 1). `passes` is `aa`, `large_text_only` or `fails`. Warnings never block a publish |

**The variable names are the contract.** A site maps its styles onto these once, and Uplink changes the values for ever after. A name is never renamed or removed; a new one may be added, and a site ignores one it does not know:

```
--uplink-color-{primary|secondary|tertiary}  --uplink-color-on-{…}  --uplink-color-{…}-hover  --uplink-color-{…}-subtle
--uplink-color-{background|surface|text|text-muted|border|success|warning|danger|info}
--uplink-color-{link|link-hover|scrollbar|scrollbar-track}
--uplink-role-{key}  --uplink-role-{key}-on  --uplink-role-{key}-hover   (the site's colour roles; _ in a key becomes -)
--uplink-font-{heading|body|mono}            (the family with its fallbacks)
--uplink-text-{h1…h6|lead|body|small}        (a size or a clamp())
--uplink-leading-{role}  --uplink-weight-{role}  --uplink-tracking-{role}  --uplink-family-{role}
--uplink-space-{xs|sm|md|lg|xl|2xl}  --uplink-space-unit  --uplink-gap  --uplink-pad
--uplink-gutter  --uplink-section  --uplink-container  --uplink-prose
--uplink-radius-{sm|md|lg|button}
```

A site without Tailwind uses them directly: `color: var(--uplink-color-text)`.

**Links and scrollbars.** `color.link`, `color.scrollbar` and `color.scrollbar_track` follow another colour unless set: links and the scrollbar follow `primary`, the track follows `background`. Each may instead hold a colour of its own (`"#rrggbb"`) or the name of a palette colour to follow (`primary`, `secondary`, `tertiary`, `background`, `surface`, `text`, `text_muted`, `border`). Links and the scrollbar may also be `"none"`: Uplink leaves them to the site. They become `--uplink-color-link`, `--uplink-color-link-hover` (the followed brand colour's hover shade, or one step toward more contrast with the page), `--uplink-color-scrollbar` and `--uplink-color-scrollbar-track` (`transparent` when there is no page background to follow). `<UplinkTheme base />` colours `a` and sets `scrollbar-color` on `html`. Browsers that do not support `scrollbar-color` (older Safari) keep their own scrollbar.

**Colour roles.** A design rarely paints every button with the primary colour: the main call to action may be secondary, a service card's arrow red, a feature band dark. A **colour role** is the site's own name for what one kind of element is painted with, so a theme can recolour that kind of element and nothing else. An agent defines each role once with `define_color_role` — a `key` that never changes (`cta`, `card_arrow`), a label, and a default that matches what the element shows today — and the site paints the element with the role instead of a palette colour: `bg-role-card-arrow text-role-card-arrow-on hover:bg-role-card-arrow-hover`, or `background: var(--uplink-role-card-arrow, #cad6e8)`. A theme then assigns roles in `tokens.color_roles` — `{ "card_arrow": "secondary" }` — a palette colour or shade to follow (`primary`, `primary_hover`, `primary_subtle`, `on_primary` and the same for `secondary` and `tertiary`; `background`, `surface`, `text`, `text_muted`, `border`; `success`, `warning`, `danger`, `info`) or a colour of its own (`"#rrggbb"`). A role the theme does not assign shows its default. Each becomes `--uplink-role-{key}` (the fill), `--uplink-role-{key}-on` (the colour on it: the brand colour's own `on_*` for a brand colour or its hover shade, the brand colour itself on its subtle tint when that reads, else near-black or white) and `--uplink-role-{key}-hover`; a role that follows a colour the theme does not set is left out, so the site's fallback applies. `resolved.color_roles` lists every role with its `label`, `value`, `from` (`theme` or `default`), `follows`, `color`, `on` and `hover`, and `contrast` checks text on every role that does not follow a brand colour. Because assignments live in the theme, a saved theme and a preview link carry their own: a redesign that recolours buttons is previewed on the real site and goes live only when it is published. Roles carry colours only — layout differences between designs are site code. A workspace has at most 24; the person sees them in **Your site → Theme → Colour roles**.

**Sizes grow with the screen.** Every phone/desktop pair (type sizes, gutter, section spacing) becomes a `clamp()` that is the phone value at 360 px wide, the desktop value at 1280 px, and grows linearly in between — no breakpoints in the site. Heading sizes left unset come from the scale: `base × ratio^n`, where `h6` and body are on the base, each heading level is one step up (`h1` is five), `lead` is one up and `small` one down. The spacing steps are the unit × 1, 2, 4, 6, 10 and 16 unless set on their own.

**The Tailwind mapping** (`app/uplink-theme.css`, Tailwind v4) gives you utilities that follow Uplink:

| Utilities | From |
| --------- | ---- |
| `bg-primary`, `text-on-primary`, `hover:bg-primary-hover`, `bg-primary-subtle` (and `secondary`, `tertiary`) | brand colours |
| `bg-background`, `bg-surface`, `text-text`, `text-text-muted`, `border-border`, `text-danger` … | neutral and status colours |
| `text-link`, `hover:text-link-hover` | the link colour |
| `bg-role-{key}`, `text-role-{key}-on`, `hover:bg-role-{key}-hover` | the site's colour roles (`card_arrow` → `role-card-arrow`); `get_install_setup` writes the roles that exist, and `define_color_role` returns the three lines for a new one |
| `font-heading`, `font-body`, `font-mono` | fonts |
| `text-h1` … `text-h6`, `text-lead`, `text-body`, `text-small` | size, line height, weight and letter spacing together |
| `gap-items`, `p-card`, `px-gutter`, `py-section`, `p-step-md`, `gap-step-lg` … | spacing |
| `max-w-site`, `max-w-readable` | container width and reading line length |
| `rounded-sm`, `rounded-md`, `rounded-lg`, `rounded-button` | radius |

The second value in each `var()` is the theme as it was when the file was written (`get_install_setup` fills in the site's current theme; the installer uses a neutral default), used only when Uplink sends no value. Tailwind's own `--spacing` is left alone, so `p-4` and friends do not change. Spacing steps are `step-*` so they never shadow Tailwind's container sizes (`max-w-md`).

**Fonts load fast, from your own domain, and tell Google nothing.** When someone picks a Google font, Uplink fetches its files once (keyless, server to server — preferring variable fonts, one file for every weight) and keeps them. Your site serves them through `app/api/uplink-fonts/[file]/route.ts`, which fetches `GET /api/v1/theme/fonts/{sha256}.woff2` with the key and lets your CDN keep each file for a year — the name is the file's hash, so its bytes never change. A visitor's browser talks only to your site: no request to Google, so nothing for the cookie banner to declare. Each family gets a metric-adjusted fallback face (as `next/font` does), so the swap barely moves a line. System fonts are offered too — nothing to download at all.

**Fonts you have a licence for.** In **Your site → Theme → Fonts → Upload a font**, an admin uploads `.woff2`, `.woff`, `.ttf` or `.otf` files (up to 4 MB each — one per weight and style, or one variable file), confirming that the font's licence allows it on this website; the confirmation is recorded. Uplink reads each file (refusing anything that is not one font), converts it to WOFF2, and takes the family, style, weight or variable range and fallback metrics from the file. Uploaded fonts belong to that workspace alone: their files are served only to its key, through the same `GET /api/v1/theme/fonts/{file}` and the site's own font route, and backed up with the theme. A theme names one by id — `{ "source": "custom", "font_id": "…", "weights": [...], "italic": false, "preload": true }` — and `fonts.uploaded` in the response lists them (`id`, `family`, `weights`, `italic`, `variable`). A font the live theme uses cannot be deleted.

**Adobe Fonts.** Adobe's licence does not allow copies, so Uplink never serves those files: the person adds their Adobe Fonts web project under **Your site → Integrations → Fonts** (provider `adobe_fonts`), `<UplinkIntegrations />` loads its stylesheet from `use.typekit.net`, and the theme names a family from it — `{ "source": "adobe", "family": "proxima-nova", "weights": [...], "italic": false, "fallback": "sans" }`. The CSS uses that name with the fallback stack; nothing is preloaded. Add the site's domain to the web project in Adobe Fonts, or the fonts will not show.

**`GET /api/v1/theme/fonts/{file}`** — one font file. Key-authenticated like every v1 route; `404` for a name that is not a SHA-256 or a file Uplink does not hold. `Cache-Control: public, max-age=31536000, immutable` with `Vercel-CDN-Cache-Control: no-store`, so only your site's edge caches it. Never link to it from a page — the key would be needed; use the installer's route.

**Moving an existing site onto the theme.** Capture first: set the theme to the values the site already uses (its Tailwind theme, CSS variables and `next/font` imports), so nothing visibly changes, then switch classes to the mapped utilities and remove `next/font/google` and any `fonts.googleapis.com` link for fonts the theme now serves — in the same change. A connected agent does this with `set_theme` (see `site_checkup` → `theme`).

**In a repository backup.** A backup holds it as `uplink-backup/theme.json` — exactly this response's `data` — and its font files under `public/uplink-backup/fonts/`. The fallback reader answers this path from it, and the font route sends a browser to the backed-up copy when Uplink does not answer, so a site that leaves Uplink keeps its look. A backup made before themes were backed up has a `null` placeholder, and the site then uses the fallbacks in `app/uplink-theme.css` while Uplink is unavailable.

---

### GET /api/v1/seo

Returns how each page of the client's site appears in **search results, AI answers and share cards** — its title, description, canonical, robots tag, Open Graph and X card, schema.org JSON-LD, and the questions it answers — plus the site's sitemap, `robots.txt` and `llms.txt`. People edit it in the studio under **Your business → Search & sharing**; platform admins, client admins **and editors** change it, viewers read. A connected agent can fill all of it in (`register_pages`, `set_page_seo`, `set_seo`), reading each page's content.

**Uplink stores what was entered and builds everything else when this answers** — the title with the site's title pattern, every meta tag, the JSON-LD, the sitemap. When search engines or AI tools start reading something new, Uplink adds it here and every site has it on its next request, with no deploy. Ignore keys you do not know; none is ever renamed or removed.

**There is no draft: a save is live on the site's next page load.** The studio confirms every save. A page an agent wrote is marked *Written by an agent, not reviewed yet* in the studio until a person checks it — a label for the person, nothing more: it changes nothing a site sees and blocks nothing.

**Query params**

| Param | Description |
| ----- | ----------- |
| *(none)* | `{ data: { site, pages } }` — the defaults, and every Search & sharing page, published blog post and published legal page, resolved |
| `path` | `{ data: ResolvedPageSeo }` — one page, every fallback applied. `/about`, `/About/` and `/about/` are the same page. **Never `404`**: a path Uplink knows nothing about answers with the site defaults and `entry: false`. A path with `?`, `#` or spaces is a `400` |
| `format` | `sitemap` → `{ data: [{ path, url, last_modified }] }`; `robots` → `{ data: { rules, sitemap, text } }`; `llms` → `{ data: string \| null }` (`llms.txt`, `null` when AI tools are turned off); `page_md` (with `path`) → `{ data: string \| null }`, the page in plain text for AI tools. Anything else is a `400` |
| `include=health` | Adds `health` to the no-param answer: each page's stored values, who wrote them (`source`: `agent` \| `person`), whether its Q&A spot was found on the live site (`qa_spot`) and `issues` worth fixing. For agents; a site never needs it |

**A resolved page**

```json
{
  "data": {
    "path": "/rooms",
    "kind": "page",
    "entry": true,
    "label": "Rooms",
    "title": "Rooms and suites · Alpine Ridge Lodge",
    "title_template": "%s · Alpine Ridge Lodge",
    "description": "Six rooms with mountain views, breakfast included.",
    "summary": "Our rooms, what each includes, and how to book.",
    "canonical": "https://www.alpineridge.example/rooms",
    "robots": { "index": true, "follow": true },
    "open_graph": {
      "type": "website", "title": "Rooms and suites", "description": "…", "url": "https://www.alpineridge.example/rooms",
      "site_name": "Alpine Ridge Lodge",
      "image": { "id": "…", "version": 3, "width": 2400, "height": 1260, "alt_text": "The lodge at dusk", "mime_type": "image/jpeg", "image_url": "https://www.uplinkcms.com/api/v1/media/…/image?v=3", "…": "" },
      "published_time": null, "modified_time": null
    },
    "x": { "card": "summary_large_image", "site": "@alpineridge", "title": "Rooms and suites", "description": "…", "image": { "…": "" } },
    "faq": {
      "display": "shown",
      "items": [{ "question": "Is breakfast included?", "answer": "Yes, every morning from 7 to 10." }],
      "json_ld": { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [ "…" ] }
    },
    "json_ld": [{ "@type": "CollectionPage", "…": "" }, { "@type": "BreadcrumbList", "…": "" }],
    "verification": { "google": "abc123", "bing": null },
    "updated_at": "2026-10-09T08:00:00Z"
  }
}
```

| Field | Description |
| ----- | ----------- |
| `kind` | `page` (a Search & sharing page), `post` (a blog post, found by the post path pattern), `legal` (a legal page, by the legal path pattern) or `none` (the site defaults). A Search & sharing page wins over a post or legal page at the same path |
| `title` | The whole `<title>`, the site's title pattern already applied (the home page's own title is used as it is). `null`: keep the page's own — and apply `title_template` to it |
| `description` | The meta description: the page's, else its summary, else the site default. A post's is its `meta_description`, else its excerpt |
| `summary` | One to three sentences that answer "what is this page about?" — used in the AI index and as `WebPage.abstract` |
| `canonical` | Absolute. `null` when the client has no domain in Uplink |
| `open_graph.image`, `x.image` | The share image, in the expanded media field shape: the page's, a post's featured image, else the site's default share image. Render it through your own image route at 1200 px (`uplinkShareImageUrl()` does) — share crawlers get the original format |
| `faq` | The page's questions and how the person wants them shown: `shown` (a list), `collapsed` (accordions) or `ai_only` (not on the page; only in the AI index). `json_ld` is the `FAQPage` markup, and is **present only when the questions are on the page** — Google penalises markup for questions a visitor cannot see. Render it only beside the visible questions; `<UplinkPageQA>` does. Treat an unknown `display` as `ai_only` |
| `json_ld` | The page's own schema.org nodes: its type (`WebPage`, `AboutPage`, `ContactPage`, `CollectionPage`, or a page about a `Service`, `Product` or `Place`), breadcrumbs named from the registered pages, and `BlogPosting` for a post. Never the FAQ. Business info's `json_ld` (the organisation) is separate — render both |
| `verification` | The Google Search Console and Bing Webmaster codes, for `<meta>` tags on every page |

**The site name and X handle come from Business info** (`name`, the `x` profile) and are never stored here, so the two cannot disagree.

**Render it with the installer's files, never by hand.** `lib/uplink-seo.tsx` holds:

- `uplinkMetadata(path, ownMetadata)` — returns Next.js `Metadata`. Uplink's values win field by field; the page's own are used for anything Uplink leaves unset and for everything when Uplink can't be reached or the client is Offline.
- `<UplinkPageSeo path>` — the page's JSON-LD.
- `<UplinkPageQA path>` — **the Q&A spot.** Put it on **every** page, where the questions belong (usually just above the footer), even on a page with no questions yet: the person then decides in Uplink whether they are shown, collapsed or for AI tools only, and nobody touches the code again. It renders the questions styled with the Uplink theme's variables (zero specificity: your classes win; pass `className`, `heading`, or `render={(items, display) => …}` to draw them yourself), writes the `FAQPage` markup only beside visible questions, and always leaves an empty `<div data-uplink-qa="/path" hidden>` marker so **Check site** can tell the spot is there.

```tsx
// app/rooms/page.tsx
import { uplinkMetadata, UplinkPageSeo, UplinkPageQA } from '@/lib/uplink-seo';

export const generateMetadata = () => uplinkMetadata('/rooms', { title: 'Rooms' }); // your own values = the fallback

export default function Rooms() {
  return (
    <>
      <UplinkPageSeo path="/rooms" />
      {/* …the page… */}
      <UplinkPageQA path="/rooms" />
    </>
  );
}
```

Put them in each page, or in a shared page wrapper that receives the path — not in the root layout: a Next.js layout does not know the current path on the server, and fetching the questions in the browser would hide them from search engines and AI tools. The fetch is tagged `uplink:seo` (and `uplink:content` and `uplink:business-info`, which it is also built from), so a change reaches the site without a deploy — webhook event `seo.updated`.

**Sitemap, robots.txt and llms.txt.** The installer also writes `app/sitemap.ts`, `app/robots.ts`, `app/llms.txt/route.ts` and `app/llms/[...path]/route.ts`, each keeping your own as the fallback. It skips any whose `public/` file exists (`public/sitemap.xml`, `public/robots.txt`, `public/llms.txt`) — Next.js refuses both — so replace that file only when you mean to.

- **Sitemap:** every page not hidden from search and not pointing its canonical elsewhere, every published post and every published legal page, with `last_modified`. Entries need the client's domain in Uplink.
- **robots.txt:** allows everything except `/uplink`, names the sitemap, and — when the person turns **Let AI tools read this site** off — asks every known AI crawler (GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot and others; Uplink keeps the list current) to stay away. Search crawlers such as Googlebot and Bingbot are never affected. On by default.
- **llms.txt:** the plain-text index AI tools read ([llmstxt.org](https://llmstxt.org)): the site's name and tagline, each page as `- [name](https://…/llms/page.md): summary`, then the blog. Each `/llms/<page>.md` is that page in plain text with **every** question it answers — the only place `ai_only` questions appear. Not served while AI tools are turned off. llms.txt is an emerging convention: harmless where it is not read.

**FAQ, honestly.** Google shows FAQ rich results only for a few authoritative health and government sites, so don't promise dropdowns in search. The questions pay off in AI answers, which quote a page that asks a question and answers it plainly — and on the page itself.

**Blog posts and legal pages** keep their own fields (`seo_title`, `meta_description`, `canonical_url`, `noindex`, `faq` — see *Blog posts* under `GET /api/v1/content`) and are found at the path patterns `post_path_pattern` (default `/blog/{slug}`) and `legal_path_pattern` (default `/{slug}`). These describe the site's routes, so only an agent sets them (`set_seo`); the studio shows them read-only.

**Check site.** In the studio, **Check site** fetches each registered page of the live site and reports which pages don't have the Q&A spot yet (questions set to show there won't appear) and whether the site reads Search & sharing at all (its titles match). Until a site uses `uplinkMetadata()`, changes in Uplink don't reach it.

**In a repository backup.** A backup holds it as `uplink-backup/seo.json` — this response without a path, plus the sitemap, robots, `llms.txt` and each page's plain text — and the fallback reader answers this path from it (an unknown path gets the defaults for that path). A backup made before Search & sharing was backed up has a `null` placeholder, and every page keeps its own metadata while Uplink is unavailable.

---

### GET /api/v1/score

The **Uplink Score**: one number from 0 to 100 for how complete the client's site is, split into ten categories, with every check that is missing and how to fix it. The studio shows the same score on **Score**, and `site_checkup` includes it.

| Category | Points |
| -------- | ------ |
| Images and first screen | 15 |
| Search | 15 |
| AI ready | 10 |
| Theme | 10 |
| Business info | 10 |
| Analytics | 10 |
| Legal | 10 |
| Backup | 10 |
| Consent | 5 |
| Resilience | 5 |

Some checks read Uplink's own records (a published theme, alt text, a privacy policy) and are always current. Others read the **live site**: Uplink fetches the home page, up to 24 more pages from Search & sharing, `/sitemap.xml`, `/robots.txt`, `/llms.txt` and each published legal page from the client's domain, and keeps what it found until the next check. A client with no domain scores 0 on those checks, so it cannot reach 100. While the client is **OFFLINE** no check runs and the last one is kept.

**Query params**

| Param | Description |
| ----- | ----------- |
| `check` | `site` checks the live site again before answering (at most once a minute; a second request within the minute gets that check). Agents call it after a deploy, through the `check_site` tool |

**Response** (abridged):

```json
{
  "data": {
    "score": 82,
    "max": 100,
    "score_version": 1,
    "version_note": null,
    "site_check": "ok",
    "site_check_detail": null,
    "site_checked_at": "2026-10-11T09:30:00.000Z",
    "categories": [
      {
        "id": "images",
        "name": "Images and first screen",
        "points": 11,
        "max": 15,
        "checks": [
          {
            "id": "images_sized",
            "name": "Images and videos are sized for phones",
            "points": 2.5,
            "max": 5,
            "passed": false,
            "evidence": "site",
            "detail": "3 of 6 images on /, /rooms reach every phone at full size.",
            "what_it_gives": "…",
            "fix": { "capability": "fast_images", "tools": ["get_install_setup", "fetch_media"], "ask_person": null, "studio": null }
          }
        ]
      }
    ]
  }
}
```

`site_check` is `ok`, `never` (not checked yet), `no_domain`, `offline` or `failed` (with the reason in `site_check_detail`). A check covering many pages scores in proportion; the categories' whole points always add up to `score`. `fix.capability` is the `site_checkup` capability that sets the check up. Check ids and points are versioned by `score_version`; treat an unknown check or category as information only. The response is never cached.

**What the site sends.** Two checks read things a page does not show:

- `<UplinkImage>` marks the images it draws with `data-uplink-image="<asset id>"`, which is how the score knows an image has its size and blurred preview. Keep the attribute.
- The installer's `lib/uplink.ts` sends `Uplink-Site-Kit: uplink=1` with every request, and `lib/uplink-backup.ts` adds `fallback=1`. Uplink keeps the latest value for the **Resilience** checks. A site that reads Uplink its own way earns the same points by sending the same header — but only when it really fails loudly on a wrong key and falls back to its backup.

---

### GET /api/v1/heartbeat

Answers "this key works, and it belongs to this site", live and never cached. The installer's
`app/api/uplink-status/route.ts` calls it with the site's own `UPLINK_API_KEY` and `UPLINK_HOST`, so Uplink's uptime
checker can tell that Uplink is working on the site, not only that the site answers (a key removed from the hosting
settings, revoked or mistyped is emailed about within minutes).

```json
{ "data": { "ok": true, "sites": ["acme.com", "acme.vercel.app"] } }
```

A wrong key gets the usual `401`, an Offline client the usual `423`.

**A site that reads Uplink its own way** gets the same check by serving `GET /api/uplink-status` itself: call this
endpoint server-side with no cache, then answer `200 { "uplink": "ok", "sites": <data.sites> }`, or
`503 { "uplink": "failing", "reason": "missing_key" | "invalid_key" | "wrong_host" | "unreachable" | "uplink_error" }`.
Never put the key or any content in the answer. Once Uplink has seen the route, a 404 from it counts as Uplink not
working on the site.

### GET /api/v1/backup

Prepares a **repository backup**: everything your site's key can read from `/api/v1` — published content and list items, list schemas, deliverable media and documents, site settings, business info, legal pages, the theme with its font files, and Search & sharing — laid out as files for the site to commit to **its own repository**. The repository is the backup: if Uplink is unreachable, switched offline, or no longer used, the site still has its data. Uplink keeps no copy.

**Free for every client.** Private images (`include_private_media`) and scheduled runs (`scheduled=true`) are **Backup extras**, a Pro feature a platform admin turns on on the **Backups** page (Developer → Backups); asking for either without it answers `403` with `code: UPLINK_FEATURE_NOT_AVAILABLE`. An **Include private images** preference left on after the plan lapses is ignored, so the backup still runs, without private images.

**Backup preferences.** On the same page, platform admins and the client's admins choose how backups are made — no one has to edit the site, and the next backup (scheduled ones included) follows them:

- **Include private images** (Backup extras) — `include_private_media` defaults to this. A request that sets the parameter still decides for itself.
- **Backup frequency** (Backup extras) — off, daily, weekly, monthly or annually. The site's GitHub workflow (below) asks `?scheduled=true` every day and Uplink backs up only when one is due: a whole period after the last backup — a backup run by hand counts too. Uplink cannot add the workflow to a repository, so connected agents read the frequency (through `inspect_backup` and `site_checkup`) and add it when it is missing. The page shows when the next scheduled backup is due.
- **Serve images from the backup** — off by default. While Uplink is up, the site loads images from its backup when the version matches (see *Images from the backup while Uplink is up*). Turn it on only for a site that renders every Uplink image through `<UplinkImage>` or `next/image` with its optimizer on: the backup copy is the full-size original. It is written into the next backup's `manifest.json` as `"imagesFromBackup": true` (absent when off), which the site's reader follows.
- **Serve large images from the backup** — with the one above on, originals wider than 2000 px load from the backup too, instead of through Uplink. It is written into the next backup's `manifest.json` as `"wideImagesFromBackup": true` (absent when off).

Every response reports them as `preferences: { includePrivateMedia, refreshFrequency, imagesFromBackup, wideImagesFromBackup }`, and the schedule as `schedule: { frequency, lastBackupAt, nextDueAt, due }`. Changes are recorded in the activity log. The page also shows when the last backup ran, who ran it and what it held.

Any valid key may call it, read-only keys included — a backup contains nothing the key could not already read. Like every `/api/v1` route it answers `423` while the client is switched **OFFLINE**, so take backups while it is online. Every backup (not a dry run) is recorded in the activity log against the key's creator.

**What it never contains:** drafts, archived items, unsaved draft edits, unlisted documents you did not ask for, users, activity, or keys. **Private media** only when you ask for it (below).

**Query params**

| Param                   | Type               | Description                                                                 |
| ----------------------- | ------------------ | --------------------------------------------------------------------------- |
| `dry_run`               | `true`             | Counts, total file size and what was left out — no files, no links, not logged |
| `scheduled`             | `true`             | A run by the site's schedule: backs up only when one is due by the Backup frequency; otherwise answers `{ data: { scheduled: true, due: false, schedule } }` — nothing prepared, nothing logged |
| `include_files`         | `false`            | JSON only: media and document files are not copied                          |
| `unlisted_document_ids` | comma-separated ids | Unlisted documents to include (they are otherwise left out)                |
| `include_private_media` | `true`             | Also back up private media. Their files go to `uplink-backup/private-media/` — never under `public/` — and are copied **with the key**: their `url` is Uplink's key-protected image route, never a link that works without it (`requiresKey: true`). Only for a private repository: anyone who can read it can read them |

Any other parameter is a `400`.

**Response**

```json
{
  "data": {
    "formatVersion": 1,
    "dataAsOf": "2026-09-27T09:00:00.000Z",
    "counts": { "content": 42, "schemas": 3, "media": 18, "documents": 4, "settings": 6, "files": 22 },
    "fileBytes": 18342112,
    "omitted": { "privateMediaIds": ["…"], "unlistedDocumentIds": [], "unresolvedMediaPaths": [] },
    "manifest": { "formatVersion": 1, "clientId": "…", "host": "https://www.uplinkcms.com", "…": "…" },
    "json": { "encoding": "gzip+base64", "data": "H4sIAAAA…" },
    "files": [
      {
        "path": "public/uplink-backup/media/jordan-rivers-3f2c1a9e-v2.jpg",
        "url": "https://…supabase.co/storage/v1/object/sign/…",
        "size": 482113
      }
    ],
    "filesExpireAt": "2026-09-27T12:15:00.000Z"
  }
}
```

**Writing it into the repository**

1. Decode `json.data` (base64, then gunzip). It is `{ "path": "text" }` for every JSON file under `uplink-backup/`, `manifest.json` included. Write each text **verbatim** — the manifest's `sha256` values are of those exact bytes.
2. Download each entry of `files` from its `url` to its `path` before `filesExpireAt`. A file whose size is not `size` is a failed copy. An entry with `requiresKey: true` (a private image) must be fetched with the `Authorization` header (and the preview bypass header, if any); Uplink redirects it to the original file. Send the key to nothing else.
3. Only when every file has arrived, replace the previous `uplink-backup/` and `public/uplink-backup/` with the new ones. A backup missing a file must never be committed as if it were whole.

Each record in `media.json` also carries `backup_path` — where its file is in the repository (`public/uplink-backup/media/…`, or `uplink-backup/private-media/…` for a private image, whose `url` is `null`).

`dataAsOf` means **the data is current as of this time**: it is the newest change — to content, media, a document or a setting — that the backup contains. It is **not** the time of the request, so it can be hours or days old, and a later backup with no new changes reports the same value. That is deliberate: an unchanged workspace produces an unchanged tree, and no diff to commit. Files are named `<title>-<short-id>-v<version>.<ext>` — for example `jordan-rivers-3f2c1a9e-v2.jpg` — from the title given in Uplink (else the filename), the first 8 characters of the id (the full id if two names would otherwise clash), and the version, so a replaced file gets a new path. Renaming an item in Uplink renames its file in the next backup. The JSON files mirror the `/api/v1` responses, except that media and document URLs point at the local copies (`/uplink-backup/…`).

---

### GET /api/v1/documents/{id}/file

Serves the bytes of one document. This is where every document's `download_url` points.

```
GET /api/v1/documents/{id}/file?v={version}
Authorization: Bearer upl_<key>
```

- **Auth** — the same key as every other v1 route, scoped to its workspace. No key → `401`.
- **Visibility** — identical to `?id=` on the listing: `published` and `unlisted` documents are served. `draft`, `archived`, unknown and malformed ids — and ids from another workspace — all return the same `404`, never `403`, so the endpoint does not reveal which ids exist.
- **`v`** — a cache-buster only. The **current** version is served whatever `v` says, so a consumer holding an old `download_url` still gets a file. (This differs from the media image endpoint, which `404`s a stale version.)
- **Response** — `200` streaming the bytes, with:
  - `Content-Type` — the document's MIME type
  - `Content-Length`
  - `Content-Disposition: attachment; filename="<ASCII fallback>"; filename*=UTF-8''<encoded name>`
  - `ETag: "doc-{id}-v{version}"` — send it back as `If-None-Match` for a `304`
  - `Cache-Control: private, no-cache` — revalidate with the ETag rather than caching blindly

```bash
curl -H "Authorization: Bearer $UPLINK_API_KEY" \
  "$UPLINK_HOST/api/v1/documents/$ID/file?v=1" -o out.pdf
```

Like the media image endpoint, it needs the API key, so serve it to browsers through a same-origin route on your site. Never put the key in client-side code.

---

### GET /api/v1/media

Returns media assets for the client.

**Query params**

| Param            | Type   | Description                             |
| ---------------- | ------ | --------------------------------------- |
| `id`             | string | One asset id, or a comma-separated batch (`?id=a,b,c`, up to 100). Also returns `unlisted` and private assets. Ids that match nothing are simply absent — still `200` |
| `include_private` | `true` | Include private assets in a listing. They are left out otherwise |
| `folder`         | string | Filter by folder name                   |
| `mime_type`      | string | Filter by MIME type (e.g. `image/jpeg`) |
| `updated_since`  | string | ISO 8601 timestamp. Only returns assets with `updated_at` strictly after this value. Persist the newest `updated_at` you've seen and pass it back on the next sync to skip re-fetching/re-signing assets that haven't changed. |

Each asset object includes the following fields relevant to image rendering:

| Field          | Stable? | Description                                                                                                                                 |
| -------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`           | Yes     | Media record UUID. Use this as the identifier for the image proxy                                                                           |
| `url`          | Yes     | `/api/v1/media/{id}/image?v={version}` — this CMS's own versioned image endpoint. Safe to cache or persist indefinitely; see Caching below. |
| `poster_url`   | Yes     | For a **video**: the same URL with `&poster=1` — a still Uplink takes from it, WebP at most 1920 px wide (see *Video*). By default the clearest frame in its first seconds; when an editor chose a frame, the URL also carries `&pt={ms}`, so it changes with the choice. `null` for every image and audio file, and for a video no still could be taken from. |
| `mobile_url`   | Yes     | For a **video**: the same URL with `&w=1280` — Uplink's phone copy (720p H.264, see *Video*). `null` for every image and audio file, and for a video Uplink makes no copy of (Serve original, a format it cannot read, longer than 3 minutes, or not made smaller). |
| `desktop_url`  | Yes     | For a **video**: the same URL with `&w=1920` — Uplink's desktop copy (1080p H.264, see *Video*). `null` for every image and audio file, and for a video Uplink makes no desktop copy of (the same reasons as `mobile_url`). |
| `version`      | Yes     | Increments every time the underlying file is replaced. Embedded in `url`.                                                                    |
| `updated_at`   | Yes     | Timestamp of the last file replacement or metadata edit (distinct from `uploaded_at`, which never changes).                                  |
| `storage_path` | —       | Internal storage key. Do **not** use this to construct URLs.                                                                                |
| `blur_data_url` | Yes    | Small base64 JPEG data URL (e.g. for next/image `blurDataURL`), precomputed server-side on upload/replace. `null` for an image with transparency (a logo on a clear background — `next/image`'s blur would paint its clear areas as a dark square), and always `null` for audio and other non-image files. `null` means **no placeholder**: render `placeholder="empty"` and never make or fetch one. A video's comes from its poster still. |
| `status`       | —       | `published` or `unlisted` — see *Media status and privacy* |
| `is_private`   | —       | `true` for a private asset — see *Media status and privacy* |
| `serve_original` | —     | `true` when an editor turned on **Serve uncompressed original**: `url` then sends the stored file byte for byte (and ends in `&original=1`). See *Image optimization* |
| `is_locked`    | —       | `true` when the file is locked and cannot be replaced — see *Locked images* |
| `lock_reason`, `locked_at` | — | Why and when it was locked; `null` while unlocked |
| `content_hash` | —       | SHA-256 hex digest of the stored file (the original bytes, not an optimized rendition). `null` for files uploaded before hashing was introduced |

**Media status and privacy**

Media uses the same status vocabulary as documents and content, plus an independent **Private** flag. Both are set per image in **Media**.

| Status | In a listing | By `?id=`, `/resolve`, the image endpoint, media fields |
| ------ | ------------ | ------------------------------------------------------ |
| `published` | Yes | Yes |
| `unlisted`  | No  | Yes |
| `draft`, `archived` | No | No |

Every image that existed before status was introduced is `published`, and new uploads in the studio default to `published` too — unlike documents — so an image an editor picks for a page works immediately, exactly as before. Images an agent uploads over MCP start as `draft`.

**Private means an image is never delivered in a form that works without your API key.** Concretely:

- The image endpoint refuses it to a request with no key — even when the workspace serves media publicly.
- A listing leaves it out unless you pass `include_private=true`, so marking an image private removes it from a site's galleries instead of leaving a broken image behind.
- Inside a content field it carries no signed `url`.
- A server holding the key can still fetch it — by `?id=`, `/resolve`, `image_url` or the image endpoint — for example to show it on a members-only page through your own authenticated route. Responses flag it `is_private: true`.

Private is independent of status: a private image can be published (served to key holders) or draft (served to nobody). In the studio, private images also appear in a **Private** folder; it is a view, not a real folder, so an image stays in its own folders too.

**Locked images**

Lock an image when site code depends on that exact file — pins drawn at stored percentages over a map, hotspots over a diagram. Replacing such a file keeps the URL working while every overlay silently lands in the wrong place; a lock makes that impossible.

While an image is locked, for everyone — in the studio, over MCP, and directly against the database:

- Its file cannot be replaced (so `version` and `content_hash` cannot change) and it cannot be deleted.
- It cannot be moved from `published`/`unlisted` to `draft` or `archived`.
- Title, alt text, tags, folders, `published` ↔ `unlisted`, **Private** and **Serve uncompressed original** stay editable — none changes the pixels.
- A refused change fails with an error whose message starts `UPLINK_MEDIA_LOCKED` and includes the reason.

In the studio, open the file in **Content → Media** and press **Lock file…** in its details; it needs a reason. A locked file says **Locked** on its square, its details say why, and **Replace file** and **Delete file…** are disabled. Platform admins and the client's admins can lock and unlock; editors and viewers can do neither. Unlocking asks for a typed `UNLOCK`. Both are recorded in the activity log. Over MCP, `upload_media` with `locked: true` and `lock_reason`, or `lock_media`, locks an image; nothing unlocks one. Locking or unlocking emits `media.updated`.

A site that must render the exact file can assert on it: check `is_locked` and compare `content_hash` with the digest it was built against. Earlier versions are not retained, so a lock — not pinning `?v=` — is what keeps a file from changing.

> **Migration note:** `url` previously returned a raw Supabase signed URL that expired after 1 hour and changed on every request. It is now this CMS's own stable, versioned proxy URL. If you were persisting or diffing the old `url` value, use the `version`/`updated_at` fields instead.

**Stable image proxy**

```
GET /api/v1/media/{id}/image
GET /api/v1/media/{id}/image?v=<version>
Authorization: Bearer upl_<key>
```

- `{id}` is the `id` field from the media record — the UUID returned by `/api/v1/media`. It is **not** the storage path, a folder name, or a filename segment.
- **This endpoint requires the `Authorization` header** and is intended for **server-side fetches only** — unless the workspace serves media publicly (below). A browser `<img src="...">` tag cannot attach that header, so direct client-side use returns `401`. Go through a same-origin proxy or server route (see troubleshooting below).

**Public delivery (per workspace, off by default)**

A platform admin can turn on **Serve published media publicly** under **Edit** in the client's menu on **Clients**. While it is on, this endpoint also answers requests that carry **no** `Authorization` header, for every asset in that workspace, so `url` can go straight into an `<img>` or `next/image` with no proxy. The versioned form keeps its `Cache-Control: public, max-age=31536000, immutable`.

- With the setting off — or for an id that doesn't exist — a keyless request gets the same `401` (`missing_authorization`) as before, so it reveals nothing.
- A request that *does* send an `Authorization` header is always judged on that key; a bad key is never quietly treated as public. So with public delivery on, a keyless request gets `200` while one with a bad key gets `401` — by design: sending a key asks to be judged on it.
- This is the only keyless path in `/api/v1`. Every other endpoint requires a key, so a site whose images load but whose content is empty is usually losing its key to a redirect — see *API returns 401 Unauthorized* in Troubleshooting.
- Only `published` and `unlisted` images that are **not private** are served this way. Mark an image **Private** in Media to keep it off public links while leaving the rest of the workspace public.

**Bare form (no `?v=`)** — `302 Found` redirecting to a freshly generated signed URL for the *current* file, same as before. The response is marked `Cache-Control: no-cache, must-revalidate` so it always resolves to the latest replacement.

**Versioned form (`?v=<version>`)** — this is what the `url` field returned by `/api/v1/media` points at. Behavior depends on whether `<version>` matches the asset's current version:

- **Matches current version:** responds `200` and streams the image bytes directly (not a redirect), optimized as described below, with `Cache-Control: public, max-age=31536000, immutable` and a strong `ETag`. Honors `If-None-Match` with `304 Not Modified`. Because the file behind a given version never changes, it's safe for browsers, your own CDN and `next/image` to cache this URL for a long time. Uplink's own CDN never stores it (`Vercel-CDN-Cache-Control: no-store`), so every request that reaches Uplink is checked afresh — making an image **Private**, unpublishing it, switching **Serve uncompressed original**, or taking the client **Offline** applies to the next request at once. It cannot reach copies your visitors' browsers or your own cache already hold, so mark an image Private before it is first shared. An optimized response also carries `Vary: Accept`, since a browser that accepts AVIF or WebP gets that format.
  - A **private** image is answered `Cache-Control: private, …` instead of `public`, so no shared cache on your side — a proxy, your CDN — stores it and replays it to visitors. The installed `app/api/media/[id]/route.ts` refuses such an image outright.
  - Whenever the stored file is sent untouched — a **video** or audio file, a *Serve uncompressed original* image, SVG, GIF — the response carries `Accept-Ranges: bytes` and honours `Range` with `206 Partial Content`. That lets a phone's `<video>` start playing before the whole file has arrived and seek within it; Safari will not play a video from a server that ignores ranges. An optimized image is always sent whole.
- **Does not match current version** (the file has since been replaced): responds `404` with `{ "error": "...", "currentVersion": <n> }`. Superseded file versions are not retained — fetch the current version via the bare endpoint, or via a fresh `/api/v1/media` response.

**Image optimization**

Editors upload originals — often 5–10 MB phone photos — so the versioned form optimizes by default. With no `w`/`h`/`q` on the request:

- JPEG, PNG, WebP and AVIF images wider than **2000 px** are resized to 2000 px wide; smaller ones keep their size. Both are re-encoded (WebP quality 75, or AVIF at the same look).
- The response is **AVIF** when the request's `Accept` header allows it, else **WebP** — AVIF is usually 20–50% smaller, and several times smaller for images with transparency. A browser sends that header itself; a server-side proxy must forward it, as the installed `app/api/media/[id]/route.ts` does, and every answer carries `Vary: Accept`. Uplink makes the AVIF copy shortly after an upload; until it exists, an AVIF browser gets the WebP with `Cache-Control: public, max-age=3600` (not `immutable`), so a cache asks again and gets the AVIF. A client that accepts neither gets the image **in its own format** (JPEG stays JPEG, PNG stays PNG; AVIF becomes JPEG) at the same width `?w=` asked for — never the full-size original. That includes a server-side `fetch` that sends no `Accept` at all: it gets a PNG or JPEG of the asked width, not WebP.
- SVG, GIF and animated images are sent unchanged (a resize would rasterize an SVG and freeze an animation), as is anything above 50 megapixels.
- Uplink makes these sized copies itself when an image is uploaded and keeps them; an image uploaded before that is sized on its first request (that one request takes a second or two longer). If a copy cannot be made for any reason, the original is sent instead, cached for one hour rather than a year, so the image never breaks.

**Serve uncompressed original.** An editor can turn this on for any image or video in **Media**, with the **Send the original file** switch in its details. **Copy link** in an image's details copies the image's `url`, to check either version in a browser (without a key it opens only when the workspace serves media publicly). That image is then always sent byte for byte: no default resize, and `w`/`h`/`q` are ignored. Its `url` gains `&original=1` so caches holding the optimized version are never consulted again, and the change emits `media.updated`. The response flags it `serve_original: true`.

The bare form (no `?v=`) is not optimized by default: without `w`/`h` it redirects to the original file. With `w`/`h` it redirects to the sized copy.

**Image size query params**

Ask for a specific size instead of the default (combine freely with `?v=`). Sizes come from a fixed set of widths, **128, 256, 320, 384, 640, 750, 828, 1080, 1200, 1600, 1920 and 2000 px** — every width next/image asks for up to 2000 — and a requested width rounds **up** to the next one, so `w=800` returns an 828 px image and `w=96` a 128 px one. An image is never enlarged past its own width.

| Param | Type   | Description                                                      |
| ----- | ------ | ---------------------------------------------------------------- |
| `w`   | number | Width in pixels, rounded up to the next size above (anything above 2000 gives 2000). Height scales proportionally. |
| `h`   | number | Height in pixels. Width scales proportionally. Give both `w` and `h` to crop to a box of that shape (the width rounds up and the height keeps the asked proportions). |
| `q`   | number | **Ignored.** Every copy is WebP quality 75 or AVIF quality 55 (the same look). Accepted so existing URLs keep working. |

On a video, `w` with `poster=1` asks for the poster still at that width (WebP, the same steps; a step as wide as the still or wider is the still itself), so a poster can have a `srcset` like any image. Each size is made from the still the first time it is asked for, then stored.

```
GET /api/v1/media/abc-123/image?v=3                → optimized: at most 2000 px wide, AVIF or WebP where accepted
GET /api/v1/media/abc-123/image?v=3&w=800          → 828 px wide, immutable-cacheable
GET /api/v1/media/abc-123/image?w=128              → smallest copy (redirect, always latest)
GET /api/v1/media/abc-123/image                    → original file, always latest
```

**Responsive images with `next/image`**

Use `<UplinkImage asset={…} sizes="…" />` from `lib/uplink-image.tsx` (see *Render every Uplink image with `<UplinkImage>`*). It passes `next/image` a loader, `uplinkImageLoader`, that turns every `srcset` width into a real file at least that wide (the next size up, at most 2000 px): `/api/media/{id}?v=3&w=640&q=75` through the site's proxy, or Next.js's own optimizer for a static copy from the repository backup. Keep `images.unoptimized` off. A site that renders `next/image` itself can import `uplinkImageLoader` and `uplinkImageSrc` from the same file:

```tsx
'use client';
import Image from 'next/image';
import { uplinkImageLoader, uplinkImageSrc } from '@/lib/uplink-image';

<Image loader={uplinkImageLoader} src={uplinkImageSrc(photo)!} alt={photo.alt_text ?? ''} width={photo.width} height={photo.height} sizes="(max-width: 768px) 100vw, 50vw" />
```

A loader is a function, so this must be in a client component. Every width a loader asks for must reach Uplink as `w`: a proxy that forwards only `v` sends the 2000 px copy for every entry.

**Video**

The full-size video is sent exactly as uploaded. For phones, Uplink also makes a **phone copy** of every MP4, WebM or QuickTime video up to 3 minutes long: H.264, at most 1280 px on its longest edge (720p for a 16:9 loop), "fast start", audio kept. It is made after an upload or replace, and for an older video the first time it is asked for. A video's `mobile_url` is that copy's URL: the versioned URL with `&w=1280` (any `w` up to 1280 asks for it). Until the copy exists, the same URL answers with the original, cached for an hour rather than pinned, so nothing has to change when it arrives. `mobile_url` is `null` when no copy will be made: Serve original, another format, too long, or a copy that would not be smaller. To get a phone copy for a video with Serve original on, turn it off: the **Send the original file** switch in the video's details in **Media**, or the MCP tool `set_serve_original`.

For everyone else Uplink makes a **desktop copy** the same way: H.264, at most 1920 px on its longest edge (1080p for a 16:9 loop), at a bitrate a web page needs (capped at 5 Mbit/s), "fast start", audio kept. A video's `desktop_url` is the versioned URL with `&w=1920` (any `w` from 1281 to 1920 asks for it). It is kept only when it is at least 20% smaller than the original, so an export that is already light has none and `desktop_url` becomes `null`; it is `null` for the same reasons as `mobile_url` too. Until it exists, its URL answers with the original, cached for an hour.

Load them through the site's proxy (`/api/media/{id}?v={version}`), which passes `w` and `Range` through so they stream. For a background or hero video, use `<UplinkVideo>` from `lib/uplink-image.tsx`. It fills its parent (which must be positioned and sized), crops to cover it, and does everything below:

```tsx
import { UplinkVideo } from '@/lib/uplink-image';

<section className="relative min-h-[80vh]">
  <UplinkVideo asset={hero.fields.video} sizes="100vw" priority className="-z-10" />
  …
</section>
```

Its poster is an image under the video with a `srcset` of the poster's sized copies (`&poster=1&w=…`), not `<video poster>`: a `poster` attribute has no `srcset`, so every phone would download the full 1920 px still (PageSpeed's "Properly size images"). The video starts only once the page has loaded and the browser is idle, then covers the image: an autoplaying video started at once competes with the page for the network, and Lighthouse, which stops at load, logs the cut-off download as a console error ("Failed to load resource: net::ERR_CONNECTION_FAILED"). A video without a poster starts at once. It is muted, looping, inline, autoplaying and `aria-hidden` by default; give it an `aria-label` when it carries content, and any `<video>` prop to change the rest.

By hand, for any other video:

```tsx
<video
  poster={video.poster_url ? `/api/media/${video.id}${new URL(video.poster_url).search}` : undefined}
  autoPlay muted loop playsInline
  preload="metadata"
>
  {video.mobile_url && (
    <source media="(max-width: 767px)" src={`/api/media/${video.id}?v=${video.version}&w=1280`} type="video/mp4" />
  )}
  {video.desktop_url && (
    <source src={`/api/media/${video.id}?v=${video.version}&w=1920`} type="video/mp4" />
  )}
  <source src={`/api/media/${video.id}?v=${video.version}`} type={video.mime_type} />
</video>
```

- The phone `<source>` comes first: a browser plays the first one whose `media` matches. The desktop copy is next, and the original last. If a copy fails, the browser moves on to the next one, so an outage of a copy (or a site answering from its backup, which holds only the original) still plays.
- `playsInline` and `muted` are what let a phone autoplay it. Without them iOS waits for a tap or opens it full screen.
- A video's `alt_text` describes what it shows. Uplink writes it from stills across the video when none was typed, and leaves it empty rather than write something generic. A video that carries content takes it as `aria-label`; a background loop that only sets a mood is decoration — give it `aria-hidden="true"` and no label.
- `poster` is the video's own `poster_url`, through the proxy with its query string kept whole: a still Uplink takes from every video (WebP, at most 1920 px wide), so the first thing a phone shows is a picture rather than a blank box, and nobody uploads a separate poster image. By default it is the **smart pick**: the clearest of several frames in the first five seconds, never a black frame or a fade-in. An editor can choose another frame in **Media** (the video's details: pause on the frame, then **Use this frame as poster**); on a locked video only an admin can. A chosen frame adds `&pt={ms}` to `poster_url` and sends `media.updated`, so revalidate and build the URL from `poster_url` rather than by hand. As a `poster` attribute it is the full still on every screen; add `&w=` for a smaller one, or let `<UplinkVideo>` pick one per screen. It is made at upload, or the first time it is asked for. The site's proxy must forward `poster` and `pt` — update an older `app/api/media/[id]/route.ts` from the installer; one that drops `pt` still shows the current poster, cached for an hour instead of a year. Use `preload="none"` for a video below the fold.
- The original is still what the backup holds, and what a desktop gets when there is no desktop copy. Upload an MP4 (H.264, with "fast start" so it can play before it has fully arrived), at most 1080p, and a few MB for a looping background. When a video over 10 MB is chosen in **Media**, the studio offers **Make it lighter**: it re-encodes the video in the browser (1080p at a web bitrate) before it is uploaded, says how long that will take, and lets the person upload it as it is instead. It is offered only when the result would be at least 30% smaller.
- An entrance animation that starts the hero at `opacity: 0` delays what phones measure as the page appearing (Largest Contentful Paint) by the length of the fade. Let the first screen paint at once; agents check for this with `site_checkup` (`fast_first_screen`).

Example versioned flow:

```
Client → GET /api/v1/media/abc-123/image?v=3  (Authorization: Bearer upl_...)
CMS    → 200 image bytes, Cache-Control: public, max-age=31536000, immutable, ETag: "..."
```

The `url` field from `/api/v1/media` already has `?v=` baked in, so you rarely need to construct this yourself. Because it's this CMS's own endpoint, use it via your own same-origin proxy (see below) — never expose the CMS API key to the browser. Unlike the old signed-URL scheme, there's no distinction between "short-lived SSR" and "cached" pages anymore: the versioned URL is safe to cache everywhere.

---

### GET /api/v1/media/resolve

Point lookup for a single media asset by a legacy reference, instead of fetching the entire `/api/v1/media` list and searching client-side. Useful when you're holding onto an old identifier — a raw media id, a storage path, or a fragment that used to appear in a signed `url` — and need to find the asset it points to.

**Query params**

| Param       | Type   | Description                                                             |
| ----------- | ------ | ------------------------------------------------------------------------ |
| `reference` | string | **Required.** The value to resolve — an id, a storage path, or a url fragment. |

**Match order**

The reference is tried against these rules in order, and the first match wins:

1. Exact `id` match
2. Exact `storage_path` match
3. `storage_path` ends with `/<reference>`
4. `storage_path` contains `<reference>` as a substring

This order is kept stable so it stays compatible with references already embedded in existing content.

**Response**

```
200 OK
{ "data": { ...same shape as one item from /api/v1/media's data array... } }
```

```
404 Not Found
{ "error": "No media asset found for reference" }
```

**Caching**

`Cache-Control: no-store`, same as the other content endpoints — this is a single indexed row lookup, cheap enough per-call that no client-side caching guidance is needed beyond what you'd already apply to any other endpoint.

**Example**

```
GET /api/v1/media/resolve?reference=logo.png
Authorization: Bearer upl_<key>

200 { "data": { "id": "abc-123", "url": "/api/v1/media/abc-123/image?v=3", "blur_data_url": "data:image/jpeg;base64,...", ... } }
```

---

## Environment Variables

Add these to the environment variables of wherever the site is hosted (Vercel, Netlify, …) — that is what the live site reads. Put them in `.env.local` as well only to run the site, or `npm run uplink:backup`, on your own machine. **Never commit `.env.local`.**

```bash
# Required — set by the install script
UPLINK_HOST=https://www.uplinkcms.com
UPLINK_API_KEY=upl_<your_client_api_key>
```

`UPLINK_HOST` must be the exact host, not one that redirects: `https://www.uplinkcms.com` for production keys, `https://preview.uplinkcms.com` for preview keys. See *Why the exact host matters* under Integrating into Next.js Projects.

For local development:

```bash
UPLINK_HOST=http://localhost:3000
UPLINK_API_KEY=upl_<your_client_api_key>
```

The `UPLINK_API_KEY` is generated per client in the Uplink studio under **Developer → API keys → Generate key**. The **Agent connection** key listed there belongs to your coding agent and may write — never use it as the site's key. The raw key is shown **once** at creation — save it immediately.

The Uplink CMS deployment itself also requires `AI_GATEWAY_API_KEY` to generate image alt text
after upload. Keep this server-only. Platform admins can choose the current Gateway model under
**Platform → AI settings**; Uplink loads the available model list dynamically and retries fallback
models when the primary model fails.

Forms email visitors' messages through Resend, so the Uplink deployment needs `RESEND_API_KEY`, and a verified sending domain for `forms@uplinkcms.com` (or set `FORMS_EMAIL_FROM` to another verified address). Without it every form answers `503 UPLINK_FORM_EMAIL_OFF` and the studio says so.

---

## Troubleshooting

### AI settings cannot load models

Request failures show a Try again button. If AI settings storage is not installed, apply supabase/migrations/20260904000036_create_ai_settings.sql to the CMS database and reload. Models still load, but saving is disabled until setup is complete. A Gateway failure shows saved/default choices with a warning; check the CMS AI Gateway configuration. Resolve other database or session failures before retrying.


### Common Issues

#### Issue: Studio iframe shows a login prompt

**Cause**: No active Uplink session in the browser for the CMS domain.

**Solution**: Log in directly at the `UPLINK_HOST` URL first, or ensure the CMS session cookie is present. The studio authenticates through the CMS's own auth system — the client site does **not** manage auth for `/uplink`.

#### Issue: A form says it was sent but no email arrives

Check **Content → Forms**: a message counted as **blocked** was taken for spam (filled in in under 2.5 seconds, more than 5 links, or a bot), and one counted as **failed** was refused by Resend or had nobody to go to. Check the form sends to someone (the Business info email or a member) and look in the recipient's spam folder: the email comes from `forms@uplinkcms.com` with the visitor as Reply-To.

#### Issue: API returns 401 Unauthorized

**Cause**: The response body's `code` says which:

- `missing_authorization` — no key arrived. If your code does send one, the request was **redirected** and `fetch` dropped the header. Typical signs: every CMS section is empty, yet images load (they can be served without a key). Check with `curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" -H "Authorization: Bearer $KEY" "$UPLINK_HOST/api/v1/content?type=list"` — anything other than `200` with no redirect URL means `UPLINK_HOST` is wrong.
- `malformed_authorization` — the header isn't `Bearer upl_<key>`.
- `invalid_api_key` — mistyped, revoked, or from another environment (a preview key on production, or the reverse).

**Solution**:

1. Set `UPLINK_HOST` to exactly `https://www.uplinkcms.com` (or the preview host for a preview key) — `https`, with `www`, no trailing path. Copy it from the API-key dialog.
2. Confirm `UPLINK_API_KEY` is set correctly in the host's environment variables (or `.env.local` when running locally), starts with `upl_`, and was issued on that same host.
3. Verify the key has not been revoked: it should be listed under **Keys** on **Developer → API keys**.
4. Check the `Authorization` header is `Bearer upl_<key>` (with a space after `Bearer`).

#### Issue: API returns 423 with `UPLINK_CLIENT_OFFLINE_BY_USER`

**Cause**: Someone switched this client **OFFLINE** on the Clients page. This is deliberate, not an outage, and affects only this client.

**Solution**: If you are testing fallbacks, this is the expected response — your site should render its fallback and not retry. Otherwise, a platform admin switches the client back **ONLINE** on the Clients page (the activity log shows who took it offline and when). Changes made while it was offline are not re-sent as webhooks; the site picks up current data on its next fetch.

#### Issue: API returns 403 with `UPLINK_FEATURE_NOT_AVAILABLE`

**Cause**: The endpoint belongs to a feature this client does not have — the response's `feature` names it (for example `repository_backups` — Backup extras — on `GET /api/v1/backup?include_private_media=true`).

**Solution**: A platform admin turns the feature on for the client on the **Backups** page (Developer → Backups). It takes effect on the next request. The key is fine; do not rotate it.

#### Issue: `claude mcp add` says "MCP server uplink already exists"

**Cause**: Claude Code already has a server named `uplink` — usually the connection made with a key you have since renewed. It will not overwrite an existing name.

**Solution**: Use the **replace** command **Connect an agent** shows after you renew. It removes the project entry, then adds the new one:

```bash
claude mcp remove uplink --scope project ; claude mcp add --scope project … (as copied)
```

If you installed with an older command, also run `claude mcp remove uplink --scope local`. `claude mcp list` shows every `uplink` entry and its scope; there should be exactly one, with scope project.

#### Issue: An MCP client offers "Authenticate"

**Cause**: The client got a 401 from `/api/mcp`: its key is missing or revoked, or — on a protected preview — Vercel blocked the request (below). Uplink's 401 points the client at its OAuth sign-in.

**Solution**: Either fix the key and use **Reconnect**, or choose **Authenticate**, sign in to Uplink and pick the workspace — the client then gets its own key. If it fails with "JSON Parse error: Unrecognized token '<'", the client reached a page instead of JSON: use exactly `https://www.uplinkcms.com/api/mcp`. On a protected preview, sign-in cannot work; use a key and the bypass header.

#### Issue: MCP on a preview deployment returns 401 "Protected deployment"

**Cause**: The deployment is behind Vercel Deployment Protection. Vercel rejects the request before Uplink sees it, so the key is never checked.

**Solution**: Add `x-vercel-protection-bypass: <bypass secret>` alongside the `Authorization` header (see *Protected preview deployments* under MCP Server). A site that reads Uplink from a preview needs it too: set `UPLINK_PROTECTION_BYPASS` in its `.env.local` and the installer's `lib/uplink.ts` and backup script send it (a site installed before this re-runs the installer with `--force`, or adds the header by hand).

#### Issue: MCP tools return 401

**Symptom**: Every MCP tool call fails with a 401, or the agent reports the server as failing to connect.

**Cause**: The MCP key was renewed or revoked. Renewing issues a new key and invalidates the old one immediately, so any agent still holding the previous key stops working within a minute.

**Solution**: Open **Developer → API keys → Connect an agent** and either copy the current connection command (available only right after issuing a key) or click **Renew key** to issue a fresh one, then reconnect the agent with the new command.

#### Issue: MCP connection is refused with 403 at `/api/mcp/upl_...`

**Cause**: The key in the URL is not read-only. Only read-only keys may travel in a URL path, because URLs are recorded in far more places than request headers. **Connect an agent** issues a write key unless its switch is turned off.

**Solution**: Send the key in an `Authorization` header against `/api/mcp` instead, or turn off **Allow the agent to write content** under **Connect an agent** and renew to get a read-only key for the URL form.

#### Issue: API returns HTML instead of JSON

**Cause**: A request to `/api/v1/*` hit the session middleware redirect (307) instead of the API handler.

**Solution**: This should not happen — the CMS middleware explicitly bypasses all `/api/v1/*` routes. If it does, confirm you are hitting the correct `UPLINK_HOST` URL and that the path starts with `/api/v1/`.

#### Issue: Stale content after CMS edits

**Cause**: The client site's own Next.js cache, not Uplink. Every content endpoint returns `Cache-Control: no-store`, so the API itself is never stale — the delay is the site's `revalidate` window.

**Solution**: Work through these in order.

1. **Is a webhook registered?** Without one, the site only updates when its own cache expires. See [Webhooks & On-Demand Revalidation](#webhooks--on-demand-revalidation).
2. **Does the endpoint actually work?** Use **Send test ping** under **Developer → API keys → Webhooks**. The row shows the last delivery status and error — a `401` there means `UPLINK_WEBHOOK_SECRET` on the site does not match the secret Uplink holds.
3. **Are the fetches tagged?** A webhook can only invalidate tags the fetch was made under. Fetches through the scaffolded `getUplinkJson` are tagged automatically; hand-written ones are not. Re-run the installer with `--force` to update `lib/uplink.ts`.
4. **Was the change to a draft?** Saving or discarding a draft deliberately fires nothing. Publish the changes to make them live.
5. **In development**, delete `.next/cache/fetch-cache` and restart the dev server.

#### Issue: Webhooks stopped firing after a deployment or secret rotation

**Cause**: The shared secret between Postgres and the app has drifted. The trigger reads `INTERNAL_WEBHOOK_SECRET` from Supabase Vault; the dispatch route reads it from the app's environment. If they disagree, every nudge is rejected.

**Symptom**: This fails *silently* from a client's perspective — content still updates, just on the slow ISR fallback. Check the Uplink deployment logs for `Rejected internal dispatch request: shared secret mismatch`.

**Solution**: Confirm the two match, and that the value carries no stray whitespace:

```sql
select name, length(decrypted_secret) as len
from vault.decrypted_secrets where name like 'INTERNAL_WEBHOOK%';
```

A secret generated with `randomBytes(32).toString('hex')` is exactly 64 characters. Compare against the `INTERNAL_WEBHOOK_SECRET` environment variable in your hosting provider.

#### Issue: Images not displaying

**Cause**: The `url` field on media objects points at `/api/v1/media/{id}/image`, which **requires an `Authorization` header**. A browser `<img src="...">` tag cannot attach that header, so rendering `url` directly in client-side markup always returns `401`.

(Prior to the versioned-URL change, `url` was also a signed URL that expired after 1 hour — that expiry problem no longer applies, since `url` is now this CMS's own stable, versioned endpoint. The auth-header requirement below is the remaining reason images won't load directly.)

**Recommended fix**: render the image with `<UplinkImage>` from `lib/uplink-image.tsx`. It loads it through the site's own `app/api/media/[id]/route.ts`, which adds the key on the server, so the browser never needs one. Both files come from the installer, or from `get_install_setup` over MCP. If your site has an older route at that path, replace it with the installer's: that is the version that forwards `w`/`h`/`q` (without them every screen gets the 2000 px copy), `Accept` (AVIF and WebP) and `Range` (video). It also lets the site's CDN keep each size (`CDN-Cache-Control`), serves only versioned URLs, and refuses private images. **Never** put the CMS API key in browser code.

To build a URL yourself, use `/api/media/{asset.id}?v={asset.version}`, with `&original=1` added when `serve_original` is `true` (or pass through the query string of the asset's `url` / `image_url`, which already has both). It never changes for a given version, so it is safe to cache indefinitely.

**Public delivery instead**: a platform admin can turn on **Serve published media publicly** (**Edit** in the client's menu on **Clients**). The versioned `url` then loads in an `<img>` without a key for every image not marked Private (see *Public delivery* under the media API reference). It is the quickest way to get an image on screen, but not a fast one. Nothing on the site's side caches it, so every new visitor waits on Uplink, and a plain `<img>` sends every screen the 2000 px copy. Use `<UplinkImage>` for anything a visitor sees.

**Blur-up / progressive image loading (required on every image)**

Every asset already carries a precomputed `blur_data_url`, so the blur needs no extra request, and `<UplinkImage>` passes it on **every** Uplink image, not only the hero (see *Render every Uplink image with its blur placeholder* under the content API). An asset whose `blur_data_url` is `null` has **no placeholder on purpose** — usually an image with transparency, such as a logo — and `<UplinkImage>` renders it with `placeholder="empty"`. Never fetch, generate or substitute one: `next/image` fills a placeholder's clear areas with an opaque colour, so a logo would load behind a dark square.

```tsx
<UplinkImage asset={asset} sizes="(max-width: 768px) 100vw, 1200px" />
```

- `blur_data_url` is a ~20 px JPEG inlined in the page, so the preview shows before any image request is made.

**Why `next/image` remote host allowlisting alone is not enough**

Adding the CDN host to `remotePatterns` only allows Next.js to optimise the image. It does not fix expiry — if the signed URL in the `src` is stale, the image still returns 403 regardless of the allowlist. Use the same-origin proxy pattern above instead.

**Do not render a media field's `url`**

It is a signed link to the **uploaded original**, which expires after an hour and is often a 5–10 MB phone photo. It works, but it is the slowest thing a page can send a phone. Use `<UplinkImage>`, which reads `image_url`.

#### Issue: Images or video load slowly on phones, but fine on a desktop

**Cause**: The desktop has usually seen the page before and has every image in its cache. A phone opening it for the first time downloads each one, and three things make that slow:

1. **Every screen gets the 2000 px copy.** The image has no `srcset`, or a loader whose widths never reach Uplink. An older `app/api/media/[id]/route.ts` that forwards only `v` does this even with a loader.
2. **Nothing caches it near the visitor.** Uplink's CDN never stores images, so a keyless `url` in an `<img>`, or a proxy without `CDN-Cache-Control`, sends every new visitor through Uplink for every image.
3. **The original is rendered.** A media field's `url` is the uploaded file, often 5–10 MB.

A video that shows a blank box first has no `poster`, or is a large file; one that is slow only on phones has no phone `<source>` (`mobile_url`), and one that is slow on a desktop has no desktop `<source>` (`desktop_url`). A headline that fades in delays the page appearing.

**Solution**: Render every Uplink image with `<UplinkImage asset={…} sizes="…" />` and replace `app/api/media/[id]/route.ts` with the current installer's (`get_install_setup` returns both). Give `priority` only to the image the page opens on. For video, follow *Video* under `GET /api/v1/media`. Agents connected over MCP find these gaps with `site_checkup` (`fast_images`, `fast_first_screen`).

#### Issue: An image disappeared from the site, or its field has no `url`

**Cause**: The image was marked **Private**, or set to `draft` or `archived`, in **Media**. Private images are left out of listings, refused without a key, and carry no signed `url` in content fields; draft and archived images are not served at all.

**Solution**: If the image should be public, open it in **Media**, set the status to **Published** and turn **Private** off. If it is meant to be private, fetch it server-side with your API key (`image_url` or `/api/v1/media/{id}/image`) and serve it only on pages that require sign-in.

#### Issue: Document download returns 404

**Cause**: The document is `draft` or `archived`, belongs to another workspace, or the id is wrong. The file endpoint uses the same visibility rule as `GET /api/v1/documents?id=`.

**Solution**: Publish (or unlist) the document in **Documents**. Use the `download_url` returned by the API rather than constructing the path, and join it to `UPLINK_HOST` — it is host-relative.

#### Issue: A legal page says iubenda or Termageddon "has no document" or will not pull

Uplink builds the request from the document id, so check what was pasted: for iubenda, a document link (`https://www.iubenda.com/privacy-policy/<id>`, `…/terms-and-conditions/<id>` or `…/privacy-policy/<id>/cookie-policy`), not the dashboard; for Termageddon, the embed code from **Embed Codes → Copy Code** for that one policy. Check the document is published in the service. A temporary outage leaves the page as it was; the daily pull tries again.

#### Issue: Google Analytics shows no visits, or every visit twice

Open **Your site → Integrations** in the studio: it checks the site as it opens (or press **Check again**). **No visits:** the site must render `<UplinkIntegrations />` once in the root layout (see [GET /api/v1/integrations](#get-apiv1integrations)); a `Content-Security-Policy` must allow the hosts listed under `csp`; and while the cookie banner asks first, only visitors who accept analytics set cookies — the rest are measured without cookies, so reports are thinner. **Every visit twice:** the same GA4 ID is also hard-coded in the site (a `gtag` snippet, `@next/third-parties`, or a Google Tag Manager container that sends GA4). Remove the hard-coded one.

#### Issue: The cookie banner does not appear

The Uplink banner appears only once a tag needs consent (turn on Google Analytics), and only once per visitor until the categories change — clear the `cc_cookie` cookie to see it again. For CookieYes or Cookiebot, the site's domain must be registered in that account, and a free plan that has run out stops showing the banner. A site that hard-codes another banner shows two; Check site reports it.

#### Issue: The theme's fonts do not load (the text shows in a fallback font)

The site has no font route. Add `app/api/uplink-fonts/[file]/route.ts` from the installer (or `get_install_setup`): the theme's CSS points every font at `/api/uplink-fonts/`. Check that `UPLINK_HOST` and `UPLINK_API_KEY` are set where the site runs. Right after a workspace is imported, the first request may answer before Uplink has fetched the font files again; the next one has them.

#### Issue: A theme preview link shows the live theme

The site has no preview files yet: `lib/uplink-theme.tsx` does not render `<UplinkThemePreview />`. Replace it and add `lib/uplink-theme-preview.tsx` and `app/api/uplink-theme-preview/route.ts` from the installer (or `get_install_setup`), then deploy. If the bar says the preview has ended, start a new one in **Your site → Theme**: a link lasts a day.

#### Issue: The site does not change after publishing the theme

The fetch is not tagged `uplink:theme`, or there is no webhook. `<UplinkTheme />` reads through `getUplinkJson`, which tags it; a hand-written fetch must add the tag. Without a webhook the site catches up within an hour (the fallback revalidate). Check that `<UplinkTheme />` is in the root layout's `<head>` — view the page source and look for `<style data-uplink-theme`.

#### Issue: Theme classes such as `bg-primary` or `text-h1` do nothing

`app/uplink-theme.css` is not imported. Add `@import "./uplink-theme.css";` after `@import "tailwindcss";` in the global stylesheet. The mapping is for Tailwind v4; on Tailwind v3, use the `--uplink-*` variables directly until a v3 mapping ships.

#### Issue: An Adobe Fonts family shows in a fallback font

The site's domain is not in the web project, or the family is not in it. In Adobe Fonts → Web Projects, add the domain and the family (with the weights the theme uses), and use the family's CSS name exactly as the project shows it (`font-family: proxima-nova, sans-serif;`). Check that `<UplinkIntegrations />` is in the root layout and that a Content-Security-Policy allows `use.typekit.net` and `p.typekit.net` (`csp` in `fetch_integrations`). The studio preview shows Adobe fonts only when the studio's address is in the project too.

#### Issue: A font upload is refused

Uplink reads every file before keeping it. A `.ttc` collection, an archive, a damaged file, or a file over 4 MB is refused with the reason. Upload one font per file. A face the font already has (the same weight and style) is refused too: delete the old file first.

#### Issue: The site looks different while the client is Offline

Expected: Offline stops every delivery, the theme included, so the site shows the fallbacks written in `app/uplink-theme.css` — or, with repository backups and `load={getUplinkJson}`, the backed-up theme. Switch the client back online, or refresh `app/uplink-theme.css` from `get_install_setup` so its fallbacks match the current theme.

#### Issue: MCP write tools are missing

**Cause**: Write tools are listed only for a `content:write` key. `full` keys, and a **Connect an agent** key issued with writes turned off, never see them.

**Solution**: Under **Connect an agent**, turn **Allow the agent to write content** on and renew, then reconnect with the new command — or generate a key with **Let this key write content** on. Use an `Authorization` header against `/api/mcp`; write keys cannot be used in the `/api/mcp/<key>` URL form. Restart the agent so it re-reads the tool list.

---

## Best Practices

### Security

✅ **DO:**

- Always validate client access server-side
- Use environment variables for sensitive keys
- Implement Row-Level Security in production
- Require authentication for all `/uplink` routes
- Sanitize user input before saving

❌ **DON'T:**

- Store API keys in client-side code
- Trust client-side validation alone
- Allow unauthenticated access to studio
- Commit `.env` files to git

### Performance

✅ **DO:**

- Let the API drive freshness — all content endpoints return `Cache-Control: no-store` so responses are never stale
- Paginate large lists (content, documents, media)
- Use optimistic UI updates
- Implement debouncing for search inputs
- Lazy load images in media library
- Render every Uplink image with `<UplinkImage>` and a `sizes` that matches how wide it is really shown, so a phone downloads only what it displays
- Give `priority` to the one image a page opens on, and a `poster` to every video

❌ **DON'T:**

- Load all data at once
- Make unnecessary API calls
- Skip loading states
- Use inline base64 images

### User Experience

✅ **DO:**

- Show clear error messages
- Provide undo functionality
- Auto-save drafts
- Confirm destructive actions
- Show loading indicators

❌ **DON'T:**

- Delete without confirmation
- Leave users in error states
- Hide system status
- Make users repeat work

---

_Last updated: June 2026_
