---
name: kanorio-headless-skill
description: "Connect any custom or AI-built frontend (Next.js, Astro, React, Lovable, v0) to Kanorio Headless for structured collections, blog, anti-abuse forms, responsive media CDN, automated SEO/LLMs.txt, and edge cache invalidation."
canonical_url: "https://kanorio.com/headless/skill.md"
mcp_server: "https://app.kanorio.com/api/mcp"
openapi_spec: "https://app.kanorio.com/api/v1/openapi.json"
capabilities_matrix: "https://kanorio.com/developers/capabilities"
---

# Kanorio Headless — AI Agent & Developer Playbook

You are a coding agent building or connecting a custom frontend powered by **Kanorio Headless**. Follow the phases below in order. Read this file whole so you do not miss authentication boundaries or response shapes.

## Section 0 — Situation Router (Choose Your Starting Path)

| Your Environment | What To Do First |
| --- | --- |
| **A. Kanorio MCP is already connected** (`sites_list`, `collections_create`, `posts_create` are in your tool list) | Proceed directly to **Phase 1**: select an existing site or create a new Headless site and retrieve its permanent `systemHost` (`https://s-<12chars>.kanorio.com`). |
| **B. Local IDE / CLI (Cursor, Claude Code, Codex, Windsurf) without MCP connected yet** | Connect Kanorio MCP via OAuth 2.1 (no manual API key required; a browser window will prompt the user to sign in or sign up and approve):<br/>Claude Code: `claude mcp add --transport http kanorio https://app.kanorio.com/api/mcp`<br/>Cursor (`.cursor/mcp.json`): `{ "mcpServers": { "kanorio": { "url": "https://app.kanorio.com/api/mcp" } } }`<br/>Then proceed to **Phase 1**. |
| **C. Cloud sandbox or frontend-only generator without MCP (Lovable, v0, Bolt)** | Read **Phase 2 & Phase 3** below and wire the frontend against `process.env.NEXT_PUBLIC_KANORIO_SITE_URL` (fallback `"https://s-xxxxxxxxxxxx.kanorio.com"`). Once the user creates a site at `https://app.kanorio.com`, they only need to set that single environment variable. |

---

## Phase 1 — Provision & Model Backend via Kanorio MCP / Management API

1. **Create or switch the site to Headless mode**:
   - To create a new site: call `sites.create` (`name`, `locale`), then call `site.update_developer_settings` with `{ websiteId, frontendMode: "HEADLESS" }`.
   - To use an existing site: call `sites.list`, pick the target `websiteId`, and call `site.update_developer_settings` with `{ websiteId, frontendMode: "HEADLESS" }`.
   - Call `sites.get({ websiteId })` to read the site's permanent, unguessable `systemHost` (e.g. `s-abc123456789.kanorio.com`). In `HEADLESS` mode, all public APIs are immediately serviceable without publishing the hosted template site.
2. **Model structured Collections (`/data` workbench)**:
   - Call `collections.create` to define custom tables (e.g. `projects`, `team`, `faqs`, `services`).
   - Supported 18 field types + `json`: `text`, `rich_text`, `email`, `phone`, `url`, `video_url`, `number`, `boolean`, `date`, `datetime`, `select`, `multi_select`, `color`, `image`, `gallery`, `file`, `reference`, `multi_reference`, `json`.
   - Optional field-level gating (`accessPolicy`): pass `{ gatedFields: ["body"], requires: { kind: "customer" } }` (or `{ kind: "entitlement", featureKey: "pro_member" }`) on any collection including `blog` to strip protected fields for anonymous readers while keeping edge caching.
   - Populate initial published records with `items.bulk_create({ websiteId, collectionKey, publish: true, items: [...] })`.
3. **Blog & Online Forms**:
   - Blog posts live in the `blog` system collection (plus `blog_categories`, `blog_tags`, `blog_authors`). Create and publish posts via `posts.create` and `posts.publish`, or let non-technical teammates write in the Notion-style `/posts` editor.
   - Inspect lead-capture forms via `forms.list({ websiteId })` to obtain the `formId` for `<KanorioForm />`.

---

## Phase 2 — Install SDK, Generate TypeScript Types & Read Content

### 1. Install packages & generate types

```bash
pnpm add @kanorio/sdk @kanorio/elements
npx @kanorio/cli types --site https://s-xxxxxxxxxxxx.kanorio.com --out src/kanorio.d.ts
```

### 2. Three Credential Boundaries (Strict Security Rule)

- **Content Delivery API (`https://{systemHost}/api/v1/*`)**: **100% anonymous, no API key required.** Safe to call from both server components and browser `fetch`. `http://localhost:*` and `http://127.0.0.1:*` are automatically allowed by CORS.
- **Management & MCP API (`knr_pat_...` / `knr_at_...`)**: Server / AI tool only. **NEVER** put `knr_pat_` in browser bundles or `NEXT_PUBLIC_*` variables.
- **Draft Preview (`knr_pv_...`)**: Read-only HMAC preview token passed via `X-Kanorio-Preview: knr_pv_...` from your server-side draft route only.

### 3. Initialize Delivery Client & Read Collections / Blog / Media

```ts
import { createDeliveryClient } from "@kanorio/sdk";

export const siteUrl = process.env.NEXT_PUBLIC_KANORIO_SITE_URL ?? "https://s-xxxxxxxxxxxx.kanorio.com";
export const kanorio = createDeliveryClient({ siteUrl });
```

- **Top-level `assets` map resolution**: `image` and `file` fields in `fieldData` hold an `assetId` string (`gallery` holds `assetId[]`). The response top level includes `assets: Record<assetId, { url, width, height, alt, mimeType, fileSize, kind, placeholder }>`, where `placeholder` is a 16px WebP LQIP data URL and responsive widths support `400`, `800`, `1200`, `1600`.
- **Querying collection items**:
  `GET https://s-xxxxxxxxxxxx.kanorio.com/api/v1/collections/{key}/items?filter[featured][eq]=true&expand=author,category&sort=-publishedAt&limit=20`
  (15 filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `ncontains`, `match`, `has`, `has_slug`, `eq_slug`, `exists`, plus 2-level `any` OR groups and 1-layer `expand`).
- **Querying blog posts**:
  `GET https://s-xxxxxxxxxxxx.kanorio.com/api/v1/collections/blog/items?expand=authors,categories,tags&formats=markdown,html`
  Returns portable Markdown, semantic `contentHtml`, structured `segments[]`, extracted H2/H3 `toc[]`, `primary_author`, `primary_category`, and `cover_image`.

---

## Phase 3 — Forms, Automated SEO / LLMs.txt, Edge Crawler Firewall & Cache Sync

### 1. Drop-in Anti-Abuse Online Forms (`@kanorio/elements`)

```tsx
import { KanorioForm } from "@kanorio/elements";

export function ContactSection({ formId }: { formId: string }) {
  return <KanorioForm siteUrl={siteUrl} formId={formId} />;
}
```
Includes built-in ALTCHA Proof-of-Work bot protection, honeypot, disposable-email filtering, and private R2 file upload tickets. Submissions automatically merge into Kanorio CRM `contacts` and trigger webhooks.

### 2. Proxy `/sitemap.xml`, `/robots.txt`, `/llms.txt`, `/llms-full.txt`, `/feed.xml` & JSON-LD

```ts
import { seoRewrites, fetchDeliveryJsonLd } from "@kanorio/sdk";

// In next.config.ts rewrites():
const rules = seoRewrites({ siteUrl, framework: "next" });

// In page layout / generateMetadata:
const jsonLd = await fetchDeliveryJsonLd({ siteUrl, path: pathname });
```

### 3. Edge Middleware (301 Redirects + 30+ AI Crawler Firewall & Bot Telemetry)

```ts
import { createKanorioMiddleware } from "@kanorio/sdk/edge";
export const kanorioEdge = createKanorioMiddleware({ siteUrl });
```
Enforces 301/302 rules from `/api/v1/redirects`, blocks disallowed AI training crawlers with HTTP 403 while keeping `Googlebot` whitelisted, and reports bot visits to the Kanorio dashboard.

### 4. Tag-Based Cache Invalidation (`X-Kanorio-Cache-Tags`) & First-Party Analytics

- Every Delivery API 2xx response includes `X-Kanorio-Cache-Tags` (`site:<id>`, `collection:<key>`, `item:<id>`).
- Expose a webhook route using `createRevalidateHandler({ signingSecret, revalidateTag })` from `@kanorio/sdk` and register it via MCP `webhooks.create` (up to 10 endpoints per site on all plans, including Free).
- Mount `<KanorioAnalytics siteUrl={siteUrl} />` from `@kanorio/elements` in your root layout to track real-time visitors, UTM campaigns, and AI assistant referrals (ChatGPT, Perplexity, Claude, Gemini).
- After deploying your external storefront, call MCP `site.update_allowed_origins` and `site.update_developer_settings({ externalStorefrontUrl })`, then run `site.check_external_frontend` (or `npx @kanorio/cli doctor --site <websiteId>`) to verify all health checks pass.

---

## Phase 4 — 7 Business Systems + 5 Infrastructure Pillars (Support Matrix SSOT)

Do not hallucinate endpoints for domains marked `Coming soon (Planned)`. Check live contract details at https://kanorio.com/developers/capabilities.

### 7 Core Business Systems
- **1. Content** [Available (100% Ready)]: Custom collections, blog system collections, pages, header/footer globals, redirects, draft & preview.
- **2. Customers & Membership** [Available (100% Ready)]: Unified Contact SSOT, dynamic segments, passwordless customer login, commercial entitlements.
- **3. Credits & Stored Value** [Coming soon (Planned)]: Points, store credit, prepaid passes, FIFO expiration and append-only ledger.
- **4. Products & Promotions** [Available (100% Ready)]: Digital and physical products, variants (pricing tiers), categories, discount codes and automatic promotions.
- **5. Bookings & Resources** [Coming soon (Planned)]: Time slots, staff/equipment resources, holds, rescheduling and cancellation.
- **6. Orders & Forms** [Available (100% Ready)]: Commerce transactions (Order, checkout, refunds, receipts) and form data submissions (FormSubmission, anti-abuse).
- **7. Deliverables** [Available (100% Ready)]: Entitlement-protected digital content (courses, downloads), chapter/unit trees, signed playback and progress.

### 5 Cloud Infrastructure Pillars
- **8. Identity, Tenant & Authorization** [Available (100% Ready)]: Site team RBAC, tenant isolation (WebsiteScope), PAT/OAuth 2.1 for agents, Customer Session Bearer for buyers.
- **9. Media & Assets** [Available (100% Ready)]: WebsiteAsset ledger, Cloudflare Images variants, LQIP placeholders, R2 private bucket signed URLs.
- **10. Events & Reliable Execution** [Available (100% Ready)]: Signed webhooks with retry, per-event filters, publicVersion & cacheTags for ISR cache invalidation.
- **11. Messaging & Reach** [Available (100% Ready)]: Transactional notifications, email campaigns, custom sender domains, per-channel consent & suppression.
- **12. Site Delivery & Operations** [Partial]: Edge-cached Delivery API, full-text search, custom domains, plus hosted-site SEO, speed and analytics.

### Available Capabilities (Production Ready Today)
- **Collections (structured content)** (content): API Agent `collections.*` (18 field types + `json`, field-level `accessPolicy`), `items.*`; Delivery `GET /collections/*` (`filter[f][op]`, `filter[any]`, relative dates `now-30d`, `sort`, `total=false`, `assets` map, `expand` full `fieldData`, `has_slug` / `eq_slug`, `access` summary & `Bearer knr_cat_` gating); CLI `kanorio types` | Elements — | Webhooks `collections.item.*`, `collections.items.bulkChanged`, `collections.schema.changed`
- **Blog (system collections)** (content): API Agent `posts.*`, `blog_categories.list`, `blog_tags.list`; Delivery `GET /collections/blog/items` (`?formats=markdown,html,plaintext`, `segments[]`, `toc[]`, `primary_author`, `primary_category`), `GET /feed` (RSS 2.0) & `GET /feed.atom` | Elements — | Webhooks `collections.item.*`
- **Pages, globals (header/footer) & redirects** (content): API Agent `pages.*`, `globals.*`, `site.publish`; Delivery `GET /pages`, `GET /pages/:slug`, `GET /globals/headers/:key`, `GET /globals/footer`, `GET /redirects` | Elements — | Webhooks `content.page.*`, `content.site.published` (with `previousSlug` & `cacheTags`)
- **Draft preview tokens (`knr_pv_`)** (content): API Agent `site.create_preview_token`; Delivery `X-Kanorio-Preview: knr_pv_...` (edge HMAC verified, bypasses cache); SDK `@kanorio/sdk/preview` (`createPreviewRouteHandler`, `previewHeaders`, `tokenFromCookieHeader`) | Elements — | Webhooks —
- **Contacts & dynamic segments** (customers): API Agent `contacts.*`, `segments.*` | Elements — | Webhooks `customers.form.submitted`
- **Customer login (magic link / 6-digit code)** (customers): API Customer `POST /auth/challenge`, `POST /auth/verify` → Bearer; `GET /me`; `DELETE /session` | Elements `<kanorio-login>` (stores Bearer in localStorage, `kanorio:login` event) | Webhooks —
- **Entitlements (who may access what)** (customers): API Agent `entitlements.grant` / `revoke` / `list` / `check`; Customer `GET /access/:id` | Elements `<kanorio-unit>` shows locked / preview / not-released states | Webhooks `deliverables.entitlement.granted`, `deliverables.entitlement.revoked`
- **Products, variants & categories** (catalog): API Agent `products.*`, `product_categories.*`; Delivery `GET /products`, `GET /products/:slug` | Elements — | Webhooks —
- **Promotions & discount codes** (catalog): API Agent `promotions.*` (applied automatically at hosted checkout) | Elements — | Webhooks —
- **Orders & hosted checkout** (orders): API Agent `orders.*`; Customer `GET /orders`, `GET /orders/:id` | Elements — | Webhooks `ec.order.paid`
- **Forms & lead capture** (orders): API Agent `forms.list/get`, `submissions.list/get`; Delivery `GET /forms/:id`, `GET /forms/:id/challenge`, `POST /forms/:id/upload-request`, `POST /forms/:id/submit`; SDK `forms.client({ siteUrl })` | Elements `<KanorioForm />` (`<kanorio-form>`), `<KanorioBotProtection />`, `useKanorioBotProtection()` | Webhooks `customers.form.submitted`
- **Deliverables (courses, downloads)** (deliverables): API Agent `deliverables.*`, `deliverable_units.*`; Delivery `GET /products/:slug` outline; Customer `GET /deliverables`, `GET /deliverables/:key` | Elements `<kanorio-curriculum>` (public outline, free previews) | Webhooks —
- **Protected playback & downloads** (deliverables): API Customer `POST /units/:id/open` (600 s signed URL); Delivery `POST /units/:id/open` for previews | Elements `<kanorio-unit>` (video, audio, PDF, text, files, embeds) | Webhooks —
- **Progress & completion** (deliverables): API Customer `POST /progress`, `GET /deliverables/:key/progress`; Agent `progress.list` | Elements `<kanorio-unit>` reports progress automatically; `kanorio:progress` event | Webhooks `deliverables.progress.completed`
- **Site team RBAC (custom roles, access requests), Agent PAT / OAuth 2.1 & Customer Session Bearer** (identity): API PAT (`knr_pat_`), OAuth 2.1 (`knr_at_`) with site scope; `auth.whoami?websiteId=` reports role vs. token scope; Customer Bearer (`knr_cat_`) bound to `(websiteId, contactId)` | Elements `<kanorio-login>` | Webhooks `team.accessRequest.created`
- **Public media, responsive images, LQIP placeholders & lightbox** (media): API Agent `media.*` (images, files, protected deliverable files, `media.update` focus & alt text); Delivery `assets` map (`url`, `width`, `height`, `alt`, `focus`, `watermarked`, `placeholder` 16px WebP data URL); `GET /api/v1/site` `mediaProtection` | Elements `<kanorio-media src mime-type>`, `<kanorio-lightbox images='[…]'>` (reads the site's media protection when `protection` is omitted) | Webhooks —
- **Signed webhooks, per-event filters & ISR cache tags** (events): API Agent `webhooks.*` (`filter.collectionKeys`, `filter.formIds`); SDK `parseDeliveryCacheTags` | Elements — | Webhooks All `TEAM_SUBSCRIBABLE_EVENT_KEYS` (HMAC-SHA256 signed, automatic retries)
- **Transactional emails, newsletters & custom sender domain** (messaging): API Agent `campaigns.*` | Elements — | Webhooks —
- **Full-text site search** (delivery): API Delivery `GET /search`; Agent `site.search` | Elements — | Webhooks —
- **Automatic OG image generation, `sitemap.xml`, `robots.txt` & JSON-LD output** (delivery): API Delivery `GET /seo/sitemap.xml`, `GET /seo/robots.txt`, `GET /seo/jsonld?path=`, plus `seo` object on `/pages/:slug` and `/collections/blog/items/:slug` (`ogImage` includes `autoOgImage`); SDK `seo.rewrites({ framework })`, `seo.jsonLd(path)` | Elements — | Webhooks —
- **`llms.txt`, `llms-full.txt` & AI crawler management** (delivery): API Delivery `GET /seo/llms.txt`, `GET /seo/llms-full.txt`, `GET /seo/robots.txt`, `GET /site` (`crawlerRules`), `POST /analytics/bot-hit`; SDK `@kanorio/sdk/edge` (`createKanorioMiddleware`) | Elements — | Webhooks —
- **First-party visitor & AI crawler traffic analytics (`/analytics`)** (delivery): API Delivery `POST /analytics/pageview` (anonymous, per-IP rate-limited, records `path` / `referrer` / UA category); Agent `analytics.*` | Elements `<KanorioAnalytics />` | Webhooks —

### Planned Capabilities (Coming Soon — Do Not Scaffold Custom Endpoints Yet)
- **Membership tiers (ranked segments & automatic perks)** (customers): Planned (`tiers.*`)
- **Points, store credit & prepaid pass ledger** (credits): Planned (`credits.*`)
- **Resource scheduling, time slots & bookings** (bookings): Planned (`resources.*`, `bookings.*`)

## Machine-Readable References

- Developer Portal (Markdown): https://kanorio.com/developers.md (HTML: https://kanorio.com/developers)
- Capabilities & Headless Support Matrix (Markdown): https://kanorio.com/developers/capabilities.md
- Content Delivery API Reference (Markdown): https://kanorio.com/developers/delivery-api.md
- Management & MCP API Reference (Markdown): https://kanorio.com/developers/api.md
- Customer API Reference (Markdown): https://kanorio.com/developers/customer-api.md
- Webhooks Reference (Markdown): https://kanorio.com/developers/webhooks.md
- Elements & SDK Reference (Markdown): https://kanorio.com/developers/elements.md (CDN: https://cdn.kanorio.com/elements/v1/kanorio-elements.js)
- API Changelog (Markdown): https://kanorio.com/developers/api/changelog.md
- OpenAPI 3.1 JSON: https://app.kanorio.com/api/v1/openapi.json
- Full Platform Knowledge Base: https://kanorio.com/llms-full.txt
