Skip to main content
Glama

agent-cms

Agent-first headless CMS. Runs as a Cloudflare Worker backed by D1 and R2 in your own account. No hosted service, no admin UI. Agents define schemas, manage content, and publish — via MCP.

What you get

  • Structured text with typed blocks — a document tree where rich components (code blocks, media, custom types) are embedded inline. One GraphQL query returns the full tree with discriminated block unions. Map directly to React/Svelte/Vue components in a single server hop. Render with react-datocms, vue-datocms, or datocms-svelte — the structured text format is DAST, an open standard.

  • Hybrid search — FTS5 for keyword matching, Cloudflare Vectorize for semantic similarity, combined with reciprocal rank fusion. All on D1.

  • Draft/publish with preview — records start as drafts. Publishing captures a version snapshot. Models can declare a canonicalPathTemplate so agents and editors get preview URLs for drafts. Short-lived preview tokens grant draft access to GraphQL without editor credentials. Schedule publish/unpublish at future datetimes. Full version history — restore to any snapshot, and the restore itself is reversible.

  • Geospatial filteringlat_lon field type with near(latitude, longitude, radius) queries in GraphQL.

  • Automatic reverse references — link model A to model B, and B gets a query field for all records in A that reference it, with full filtering, ordering, and pagination.

  • Two MCP servers — admin MCP (/mcp) for schema and content, editor MCP (/mcp/editor) scoped to content operations only. Create editor tokens with optional expiry.

  • Multi-locale with fallback chains — per-field opt-in. Locale A falls back to B falls back to C. The GraphQL resolver walks the chain.

  • 19 field types — string, text, boolean, integer, float, date, date_time, slug (auto-generated), media (with focal point + blurhash), media_gallery, link, links, structured_text, rich_text, seo (title + description + image + twitter card), json, color (RGBA), lat_lon, video. All validated with Effect schemas.

  • Tree hierarchies and sortable collections — parent-child nesting and explicit position ordering as first-class model properties.

  • Dynamic SQL builder — the query engine builds SQL at runtime from the content schema. No ORM, no generated client. The content schema is decoupled from your application schema — run this on the same D1 database as your site.

  • Responsive images — Cloudflare Image Resizing with focal points, blurhash for progressive loading, color palette extraction. R2 storage, no external service.

  • Bulk operations — create up to 1000 records in a single call.

  • Schema portability — export the full schema as JSON (no IDs, just api_keys), import it on a fresh instance.

  • Three interfaces — REST API, GraphQL, and MCP, all auto-generated from the content schema.

  • Effect-TS throughout — typed errors, dependency injection via services and layers, no try/catch. The whole CMS is a single Worker.

Related MCP server: SkillStream MCP

Quick start

Copy the prompt from PROMPT.md into Claude Code. It assesses your project, asks how you want to integrate (standalone Worker, service binding, or mounted in an existing Worker), and wires everything up — including D1 database, wrangler config, and MCP server connection.

Interfaces

/mcp — Admin agent interface

MCP server with tools for schema management, content operations (CRUD, bulk insert, publish/unpublish, reorder), asset management, search, and schema import/export. Requires writeKey.

When the LOADER binding is configured, /mcp serves Code Mode instead — a single code tool where the LLM writes JavaScript that chains multiple tool calls in a V8 sandbox. This reduces round-trips: instead of one MCP call per tool, the LLM generates a script that calls all the tools it needs in one shot.

The sandbox exposes a codemode object with all admin tools as async methods:

// The LLM writes this as the `code` argument:
async () => {
  const schema = await codemode.schema_info({ includeFieldDetails: true });
  const record = await codemode.create_record({
    modelApiKey: "blog_post",
    data: { title: "Hello World", slug: "hello-world" }
  });
  return { schema, record };
}

Tool names and argument shapes match the standard MCP tools exactly — codemode.create_model(...), codemode.create_field(...), etc. The code tool's description includes full type signatures for all available methods.

Code Mode requires Dynamic Workers (Workers Paid plan). Add the binding to wrangler.jsonc:

"worker_loaders": [{ "binding": "LOADER" }]

Without the LOADER binding, /mcp serves the standard multi-tool MCP server.

/mcp/editor — Editorial agent interface

Reduced MCP server for content-authoring agents. Accepts either an editor token or writeKey. Exposes schema introspection, record CRUD, drafts, publish/unpublish, version restore, assets, site settings, and search. Does not expose schema mutation, token management, or admin operations.

When LOADER is configured, /mcp/editor also serves Code Mode with the editor tool subset.

/graphql — Content delivery

Read-only GraphQL API. Supports filtering, ordering, pagination, locale fallback, and draft previews via X-Include-Drafts.

{
  allPosts(
    filter: { _status: { eq: "published" } }
    orderBy: [_createdAt_DESC]
    first: 10
  ) {
    id
    title
    slug
    coverImage {
      url
      width
      height
      alt
    }
    body {
      value
      blocks {
        ... on CodeBlockRecord {
          id
          code
          language
        }
      }
    }
  }
}

Naming conventions

Model api_key values (snake_case) map to camelCase/PascalCase GraphQL names:

api_key

GraphQL type

Single query

List query

Meta query

blog_post

BlogPostRecord

blogPost

allBlogPosts

_allBlogPostsMeta

category

CategoryRecord

category

allCategories

_allCategoriesMeta

Block types also get a Record suffix: code_blockCodeBlockRecord.

Field api_key values become camelCase in queries: cover_imagecoverImage, published_atpublishedAt.

Performance model

GraphQL nesting is not compiled into one giant SQL join. The server fetches root records, batches linked records and StructuredText work into set-oriented SQL, then assembles the nested shape in memory. See PERFORMANCE.md.

MCP resources and prompts

Agents connecting via MCP get two resources:

  • agent-cms://guide — workflow order, naming conventions, field value formats

  • agent-cms://schema — current schema as JSON

Two prompts for common workflows:

  • setup-content-model — design and create content models from a description

  • generate-graphql-queries — generate typed GraphQL queries for a model

/api — REST

JSON REST API for programmatic access. Models, fields, records, assets, locales, publish/unpublish, scheduling, bulk operations, schema import/export.

/api/search — Search

FTS5 keyword search with BM25 ranking and snippets, scoped to all models or a single model. When AI + VECTORIZE bindings are configured:

  • keyword — FTS5. Phrases ("exact match"), prefix (word*), boolean (AND/OR).

  • semantic — Vectorize cosine similarity.

  • hybrid (default) — Reciprocal rank fusion of keyword + semantic results.

Draft preview

Records on draft-enabled models start as drafts. The CMS stores both the draft state (real columns) and the published snapshot. GraphQL serves published content by default. Draft preview lets agents and editors see unpublished content on the real site before publishing.

How it works

  1. Set a URL template on your modelcanonicalPathTemplate: "/posts/{slug}". The CMS resolves {slug} from the record and includes _previewPath in tool/REST responses.

  2. Configure the site URL — pass siteUrl to createCMSHandler. The CMS uses this to generate fully assembled preview links.

  3. Agent or editor requests a preview — the get_preview_url MCP tool returns a ready-to-share link with a short-lived preview token baked in. One tool call, no assembly required.

  4. User clicks the preview link — the site's enable route validates the token against the CMS, sets a cookie, and redirects to the content page. The site then fetches draft content from GraphQL.

  5. Disable draft mode — clear the cookie via /api/draft-mode/disable?redirect=/.

MCP workflow

The agent never assembles preview URLs manually. One tool call does everything:

Agent: create_record({ modelApiKey: "post", data: { title: "Draft Post", ... } })
CMS:   { id: "abc", _status: "draft", _previewPath: "/posts/draft-post" }

Agent: get_preview_url({ recordId: "abc", modelApiKey: "post" })
CMS:   { url: "https://mysite.com/api/draft-mode/enable?token=pvt_...&redirect=/posts/draft-post",
         previewPath: "/posts/draft-post", expiresAt: "2026-03-24T17:00:00Z" }

Agent: "Here's your draft preview: https://mysite.com/api/draft-mode/enable?token=pvt_...&redirect=/posts/draft-post"

If the agent has browser access, it can follow the link to visually verify content and iterate before publishing.

Site integration

Your site needs an enable route that validates the preview token against the CMS, sets an HttpOnly cookie (__agentcms_preview) with the token, and redirects to the content page. The cookie's Max-Age should match the token's remaining TTL. See examples/nextjs/ and examples/blog/ for complete implementations.

In your GraphQL client, forward the cookie as a header when present:

const previewToken = getCookie("__agentcms_preview");
const headers: Record<string, string> = {};
if (previewToken) {
  headers["X-Preview-Token"] = previewToken;
  headers["Cache-Control"] = "no-store"; // bypass CDN for draft content
}

GraphQL responses in preview mode include Cache-Control: private, no-store. Render a preview banner in your site to indicate draft mode — see the examples for Astro and Next.js implementations.

Service bindings

When your site and CMS are in the same Cloudflare account, skip cookies entirely. Pass X-Preview-Token directly on the service binding call:

const res = await env.CMS.fetch("https://internal/graphql", {
  headers: {
    "X-Preview-Token": previewToken, // from your site's own session/cookie
  },
  body: JSON.stringify({ query }),
});

No CORS, no cross-origin cookies, zero latency. This is the recommended path for Cloudflare deployments.

Framework notes

Astro / SvelteKit / generic Workers — build an enable route that validates the token and sets the cookie. Read the cookie in middleware and forward as X-Preview-Token.

Next.js — your enable route must also call draftMode().enable() to integrate with Next.js ISR/caching. Set SameSite=None; Secure on the cookie for iframe compatibility. See the DatoCMS Next.js pattern — the same approach applies.

URL templates

Templates use {field_name} placeholders resolved from the record:

Template

Record

Result

/posts/{slug}

{ slug: "hello-world" }

/posts/hello-world

/docs/{category}/{slug}

{ category: "guides", slug: "setup" }

/docs/guides/setup

/{slug}

{ slug: "about" }

/about

Templates are paths only — no origin, no locale prefix. Locale URL strategies (prefix, subdomain, root folding) are handled by your site's routing, not the CMS. The enable route accepts an optional locale param for your middleware to use.

Preview tokens

  • Created internally by get_preview_url or via POST /api/preview-tokens

  • Default expiry: 24 hours (editorial workflows are async)

  • Stored as SHA-256 hashes in D1 (a database breach doesn't leak usable tokens)

  • Grant read-only access to all draft content via GraphQL

  • X-Preview-Token header takes precedence over __agentcms_preview cookie if both are present

Editor tokens

Editor tokens are the credential for non-admin editing flows. Create them via POST /api/tokens or the editor_tokens MCP tool (with action: "create"). The raw token is shown once; the server stores a hash.

Editor tokens can access /mcp/editor, REST content/asset operations, and draft GraphQL previews. They cannot mutate schema, manage tokens, or run admin operations.

For editor onboarding with OAuth, the package exports createCmsAdminClient and createEditorMcpProxy to stand up an app-land MCP gateway. See examples/editor-mcp/.

Scheduling

Schedule publish/unpublish at future datetimes via REST or MCP. To execute schedules automatically, add a cron trigger:

import { createCMSHandler } from "agent-cms";

let cachedHandler: ReturnType<typeof createCMSHandler> | null = null;

function getHandler(env: Env) {
  if (!cachedHandler) {
    cachedHandler = createCMSHandler({
      bindings: { db: env.DB, assets: env.ASSETS, writeKey: env.CMS_WRITE_KEY },
    });
  }
  return cachedHandler;
}

export default {
  fetch(request: Request, env: Env) {
    return getHandler(env).fetch(request);
  },
  scheduled(_controller: ScheduledController, env: Env) {
    return getHandler(env).runScheduledTransitions();
  },
};
{ "triggers": { "crons": ["* * * * *"] } }

Without a cron trigger, schedules are stored and queryable but do not execute.

Lifecycle hooks

React to content events with hooks passed to createCMSHandler:

createCMSHandler({
  bindings: { db: env.DB, assets: env.ASSETS, writeKey: env.CMS_WRITE_KEY },
  hooks: {
    onPublish: ({ modelApiKey, recordId }) => fetch(env.DEPLOY_HOOK_URL, { method: "POST" }),
    onRecordCreate: ({ modelApiKey, recordId }) => { /* notify, sync, etc. */ },
  },
});

Available: onRecordCreate, onRecordUpdate, onRecordDelete, onPublish, onUnpublish. All receive { modelApiKey, recordId }. Fire-and-forget.

Bindings

Only DB is required. Everything else is optional and degrades gracefully.

Binding

Type

What it enables

DB

D1

Required. Content storage, schema, FTS5 search.

ASSETS

R2

Asset file storage and serving via /assets/.

AI

Workers AI

Embedding generation for semantic search.

VECTORIZE

Vectorize

Semantic vector search. Requires AI.

CMS_WRITE_KEY

Secret

Auth for writes, MCP, and publish. Without it, writes are open.

ASSET_BASE_URL

Variable

Public URL prefix for assets and Image Resizing. Must be a custom domain for transforms.

SITE_URL

Variable

Your site's public URL (e.g. https://mysite.com). Required for get_preview_url to generate fully assembled preview links.

LOADER

Worker Loader

Code Mode — collapses MCP tools into a single code tool. Requires Dynamic Workers (Workers Paid plan).

{
  "d1_databases": [{ "binding": "DB", "database_name": "my-cms-db", "database_id": "..." }],
  "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-cms-assets" }],
  "vectorize": [{ "binding": "VECTORIZE", "index_name": "my-cms-content" }],
  "ai": { "binding": "AI" },
  "worker_loaders": [{ "binding": "LOADER" }],
  "vars": { "ASSET_BASE_URL": "https://cms.example.com" }
}

To create the Vectorize index: npx wrangler vectorize create my-cms-content --dimensions=384 --metric=cosine

Assets

Asset binaries live in R2. Metadata in D1. Served from /assets/:id/:filename.

  • MCP/editor: import_asset_from_url — download, store, register in one step

  • Browser: PUT /api/assets/:id/file then register metadata

  • Server: upload to R2, then POST /api/assets

Focal points, blurhash, and color palette are stored per-asset. Cloudflare Image Resizing generates responsive variants at the edge.

Stack

  • Runtime: Cloudflare Workers

  • Database: D1 (managed SQLite)

  • Assets: R2 + Cloudflare Image Resizing

  • Search: SQLite FTS5 + Cloudflare Vectorize

  • Application: Effect

  • GraphQL: graphql-yoga with generated SDL

  • Testing: Vitest (pnpm test)

Examples

  • examples/blog/ — CMS Worker + Astro SSR site with typed GraphQL (gql.tada), structured text rendering, responsive images, service bindings, draft preview mode

  • examples/nextjs/ — Next.js App Router with draftMode() integration, multi-root GraphQL queries, preview bar component

  • examples/editor-mcp/ — editor onboarding: app-land OAuth gateway, scoped editor tokens, separate MCP URLs for developers and editors

License

MIT

A
license - permissive license
-
quality - not tested
B
maintenance

Maintenance

Maintainers
2hResponse time
3dRelease cycle
2Releases (12mo)
Commit activity
Issues opened vs closed

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jokull/agent-cms'

If you have feedback or need assistance with the MCP directory API, please join our Discord server