# Discovery & System Prompts

> How AI agents bootstrap against OvertCMS using /.well-known/agent-cms.json, /llms.txt, /agent/v1/prompt, /agent/v1/schema, and If-Schema-Fingerprint drift protection.

OvertCMS is designed so an AI agent can connect to a running instance with zero hardcoded knowledge of your content model, discover its exact permissions and editorial rules in one or two requests, and safely detect schema changes before writing data.

## Recommended Agent Bootstrap Flow

1. **Discover endpoints & capabilities:** `GET /.well-known/agent-cms.json` (public, no key required).
2. **Load tailored operating instructions (optional for LLM prompts):** `GET /agent/v1/prompt` with your Bearer API key.
3. **Inspect exact field schemas & cache `schemaFingerprint`:** `GET /agent/v1/schema` (or `GET /agent/v1/schema/{postTypeSlug}` for a single post type).
4. **Pin every write to the cached fingerprint:** Send `If-Schema-Fingerprint: <fingerprint>` on all mutating requests so breaking schema changes fail fast with `409 schema_drift_detected`.

---

## 1. Public Discovery (`GET /.well-known/agent-cms.json`)

The well-known discovery document is served on the Agent Plane and **remains public even when `OVERTCMS_AUTH_REQUIRED=true`**. It advertises protocol capabilities, active schema metadata, kill-switch status, and canonical endpoint paths.

```bash
curl -s https://cms.example.dev/.well-known/agent-cms.json
```

```json
{
  "protocolVersion": "1.0",
  "cms": "overt-cms-core",
  "version": "0.1.0-dev",
  "schemaVersion": 14,
  "schemaFingerprint": "sha256:8f4e2a1c9b7d6e5f4a3b2c1d0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f",
  "agentWritesPaused": false,
  "capabilities": {
    "discovery": true,
    "mcp": true,
    "batch": true,
    "dryRun": true
  },
  "endpoints": {
    "discovery": "/.well-known/agent-cms.json",
    "llmsTxt": "/llms.txt",
    "prompt": "/agent/v1/prompt",
    "mcp": "/mcp",
    "health": "/agent/v1/health",
    "schema": "/agent/v1/schema",
    "collections": "/agent/v1/collections",
    "singletons": "/agent/v1/singletons",
    "operations": "/agent/v1/operations",
    "media": "/agent/v1/media"
  }
}
```

<Note>
  Check `agentWritesPaused` before starting a write workflow. When an administrator activates the site kill switch, all agent write endpoints (REST and MCP) return `503 agent_writes_paused`.
</Note>

---

## 2. Compact Public Summary (`GET /llms.txt`)

`GET /llms.txt` returns a token-efficient `text/plain; charset=utf-8` Markdown overview of the site's locales, editorial instruction, post types (with kinds, capabilities, and one-line summaries), reusable components, and Agent Plane endpoints.

- Strictly omits secrets, API keys, internal database IDs, and private users.
- Public by default; gated behind a `delivery:read` Bearer API key when `OVERTCMS_DELIVERY_REQUIRE_API_KEY=true`.

```text
# Acme Engineering Blog

> OvertCMS Core Agentic Headless CMS

- **Site:** `default`
- **Base URL:** https://acme.dev
- **Default Locale:** `en` (locales: en, de)
- **Schema Version:** 14
- **Schema Fingerprint:** `sha256:8f4e2a1c...`

## Post Types

- `authors` (collection; capabilities: draft,publish,schedule,delete): Author profiles and bios.
- `posts` (collection; capabilities: draft,publish,schedule,delete,localize): Technical blog posts.

## Reusable Components

- `callout` (Callout Box): Highlight warnings, tips, or breaking notes inside rich_html.

## Agent Plane & MCP Endpoints

- Discovery JSON: `GET /.well-known/agent-cms.json`
- Tailored Skill Prompt (requires API key): `GET /agent/v1/prompt`
- Streamable HTTP MCP Server (requires API key): `POST /mcp`
- Site Schema: `GET /agent/v1/schema`
- Post Type Schema: `GET /agent/v1/schema/{postType}`
- Entries: `GET/POST /agent/v1/collections/{postType}/entries`
- Media: `GET/POST /agent/v1/media`
```

---

## 3. Tailored Agent Skill Prompt (`GET /agent/v1/prompt`)

`GET /agent/v1/prompt` generates a live, copy-pasteable `SKILL.md` system prompt dynamically tailored to the **authenticated API key** (`Authorization: Bearer ocms_...`, requires `schema:read`).

What makes `/agent/v1/prompt` unique:

- **Explicit API key permission boundaries:** Lists the key's name, prefix, preset, scopes, and an explicit `ALLOWED` / `FORBIDDEN` matrix for drafting, publishing, deleting, media upload, and schema management so the LLM never wastes turns attempting unauthorized actions.
- **Filtered post-type catalog:** Includes only post types permitted by the key's `allowedPostTypes` map, annotating each as `read/write` or `read-only`, along with every field's type, `requiredOn`, constraints, reference `searchEndpoint`, and authoring `instruction`.
- **Reusable components & `<cms-block>` syntax:** Documents every component's props and the exact `<cms-block type="..." data-props='...'>` markup.
- **Mandatory safety contracts:** Embeds the active `schemaFingerprint` and reminds the agent of canonical HTML5 rules, `bodyPatches`, `clearFields` null semantics, `expectedVersion`, `Idempotency-Key`, and `confirmUnpublish: true`.

### Content Negotiation

- **Default (`text/markdown; charset=utf-8`):** Returns the raw Markdown prompt.
- **JSON (`?format=json` or `Accept: application/json` without `text/markdown`):** Returns `{ "prompt": "...", "schemaVersion": 14, "schemaFingerprint": "sha256:..." }`.
- Always includes the `X-Schema-Fingerprint` response header.

```bash
curl -s https://cms.example.dev/agent/v1/prompt \
  -H "Authorization: Bearer ocms_live_0123456789abcdef_..."
```

---

## 4. Machine-Readable Schemas

### Full Site Schema (`GET /agent/v1/schema`)

Requires `schema:read`. Returns the complete `SiteSchemaContract` with `postTypes` filtered by the caller's `allowedPostTypes`, `searchEndpoint` populated on every `reference` field, `instructionCoverage` metrics, and `X-Schema-Fingerprint` header.

```json
{
  "site": {
    "slug": "default",
    "name": "Acme Engineering Blog",
    "baseUrl": "https://acme.dev",
    "timezone": "UTC",
    "defaultLocale": "en",
    "locales": ["en", "de"],
    "instruction": "Use clear, concise technical prose in American English."
  },
  "components": [
    {
      "id": "0195c8a0-...",
      "slug": "callout",
      "label": "Callout Box",
      "instruction": "Use tone=warning for breaking changes.",
      "aiWritable": true,
      "fields": [
        { "key": "tone", "label": "Tone", "type": "select", "required": true, "requiredOn": "publish", "constraints": { "options": [{ "value": "info", "label": "Info" }, { "value": "warning", "label": "Warning" }] } },
        { "key": "body", "label": "Body", "type": "text", "required": true, "requiredOn": "publish" }
      ],
      "schemaVersion": 1,
      "schemaFingerprint": "sha256:..."
    }
  ],
  "postTypes": [
    {
      "id": "0195c8a1-...",
      "slug": "posts",
      "singularName": "Post",
      "pluralName": "Posts",
      "kind": "collection",
      "urlTemplate": "/blog/{slug}",
      "displayField": "title",
      "slugSourceField": "title",
      "fields": [
        {
          "fieldId": "0195c8a2-...",
          "key": "author",
          "label": "Author",
          "type": "reference",
          "required": true,
          "requiredOn": "publish",
          "constraints": { "targets": ["authors"], "integrity": "strong" },
          "searchEndpoint": "/agent/v1/collections/posts/fields/author/options"
        }
      ],
      "schemaVersion": 4,
      "schemaFingerprint": "sha256:..."
    }
  ],
  "instructionCoverage": {
    "siteInstructionPresent": true,
    "postTypesTotal": 2,
    "postTypesWithInstruction": 2,
    "fieldsTotal": 12,
    "fieldsWithInstruction": 10
  },
  "schemaVersion": 14,
  "schemaFingerprint": "sha256:8f4e2a1c9b7d6e5f4a3b2c1d0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f"
}
```

### Single Post-Type Schema (`GET /agent/v1/schema/{postTypeSlug}`)

Requires `schema:read` and read permission for `{postTypeSlug}`. Ideal for keeping LLM context windows small—returns only the requested `postType` plus the **transitive closure of `components`** referenced by its `object`, `list`, `variants`, and `rich_html.allowedComponents` fields.

---

## 5. Schema Drift Detection (`If-Schema-Fingerprint`)

Schemas evolve over time. To prevent agents operating on stale cached schemas from corrupting content or silently hitting confusing validation errors, pass the cached fingerprint on Agent Plane requests using the `If-Schema-Fingerprint` HTTP header (or the `ifSchemaFingerprint` parameter on MCP `cms_create_entry` and `cms_update_entry`).

You may pass **either** a site-level `schemaFingerprint` **or** a post-type-level `schemaFingerprint`. OvertCMS evaluates it against current and historical schema snapshots:

| Evaluation Result | HTTP Status | Response Behavior |
| --- | --- | --- |
| **Exact match** (current site or current post-type fingerprint) | Normal (`2xx`) | Request proceeds transparently with no warnings. |
| **Non-breaking drift only** (historical snapshot differs only by capability gains: e.g., new optional field, relaxed limit, updated instruction, new component) | Normal (`2xx`) | Request **succeeds**. Response includes `X-Schema-Warning: schema_capability_gain` and updated `X-Schema-Fingerprint` headers (MCP responses include `schemaWarnings[]`). |
| **Breaking drift** (e.g., field removed, type changed, tightened constraint, new required field, post type deleted, `aiWritable` revoked) | **`409 Conflict`** | Request is **rejected before execution** (`applied: false`) with code `schema_drift_detected` and structured diff details. |
| **Unknown fingerprint** (not current and not found in site or post-type snapshot history) | **`409 Conflict`** | Rejected with `schema_drift_detected` and `details.reason: "unknown_schema_fingerprint"`. |

<Tip>
  Cosmetic `ui` hints (`group`, `order`, `placeholder`, `width`) are excluded from `schemaFingerprint`, so Admin UI layout tweaks never trigger agent drift alerts.
</Tip>

### Example `409 schema_drift_detected` Response

```json
{
  "error": {
    "code": "schema_drift_detected",
    "message": "site schema has breaking changes since expected fingerprint; re-fetch /agent/v1/schema before retrying",
    "retryable": false,
    "applied": false,
    "details": {
      "expectedFingerprint": "sha256:1111...",
      "currentFingerprint": "sha256:8f4e2a1c...",
      "breakingChanges": [
        {
          "field": "postTypes.posts.fields.canonicalUrl",
          "kind": "field_made_required",
          "breaking": true,
          "message": "field \"canonicalUrl\" changed from optional to required",
          "oldValue": false,
          "newValue": true
        }
      ],
      "nonBreakingChanges": []
    }
  }
}
```

### Agent Recovery Loop

1. Receive `409 schema_drift_detected` (or observe `X-Schema-Warning: schema_capability_gain`).
2. Re-fetch `GET /agent/v1/schema` or `GET /agent/v1/schema/{postTypeSlug}` (or call MCP `cms_get_context` / `cms_get_post_type_schema`).
3. Update cached `schemaFingerprint` and adjust payload to satisfy any breaking changes.
4. Retry the mutation with a **new** `Idempotency-Key` and the updated `If-Schema-Fingerprint`.
