Skip to content

Latest commit

 

History

History
251 lines (204 loc) · 15.9 KB

operations-registry.md

File metadata and controls

251 lines (204 loc) · 15.9 KB
title Operations Registry
id operations-registry
order 1
description How TanStack CMS defines every operation once, with a declared access level, and serves it through TanStack Start server functions, the versioned HTTP API, the typed client, and every agent surface.
keywords
tanstack cms
ops
invokeOp
opSchemas
runOp
cmsTools
openapi
http api

TanStack CMS follows one rule for its API: define each operation once, then let every transport serve it with the same access checks. Every operation is a CmsOpDefinition, and allOps() from @tanstack/cms-api is the one registry every transport reads. It combines:

  1. The built-in operations (ops) in @tanstack/cms-api: what the admin UI, the HTTP API, and @tanstack/cms-client call, each with a declared access level.
  2. The agent tools (opSchemas) in @tanstack/cms-core: the tools AI agents get (the content agent, the MCP server, and WebMCP). Whether a write stages for review or commits at once is decided by each collection's document state strategy (the default stages; directStrategy commits), not a universal rule.
  3. Your operations, from defineCms({ ops }) (see Adding Your Own Operations).

The Operations Registry (ops)

Each entry in ops (packages/api/src/ops.ts) is a plain object:

interface CmsOperation<TInput, TOutput> {
  method: 'GET' | 'POST' // GET ops also accept query params over HTTP
  access: 'public' | Permission // who may call it
  description: string
  input: z.ZodType<TInput> // validated before `run`
  output?: z.ZodType // describes the result in OpenAPI; not checked at runtime
  run: (
    input: TInput,
    ctx: { request?: Request; session: CmsSession; actor: string },
  ) => Promise<TOutput>
}

access is either public or one of the permissions. Operations narrow further inside run: collection access rules, API key collection scope, field redaction, and write protection all apply there.

Operation Method Access Purpose
getAuthSession GET public Current session and AI capabilities
get GET public One document by id or locator, with its relations (drafts only for readers)
list GET public Paginated documents, filtered and sorted, with their relations (drafts only for readers)
getPublicDocument GET public Deprecated, removed in the next alpha: use get. Resolve a document by slug or id across collections
resolveRedirect GET public Look up a path in the redirects collection
listDocumentSummaries GET content.read Admin list with search, status filter, sort, and pagination
getDocument GET content.read One document for editing, with any pending version overlaid
getDocEditorMeta GET content.read Revisions, translations, inbound references, and the document's state and actions
reviewSnapshot GET content.read Pending changes (with their strategy label and the caller's actions) and audit trail
save POST content.write Save a document (commit, draft, or stage for review, as the collection's workflow decides); create: true refuses an existing id
discardDraft POST content.write Drop the draft of a published document (publishers only)
bulkDocuments POST content.write Publish, unpublish, or delete up to 100 documents
savePageBlocks POST content.write Save a page's blocks from the on-page editor
restoreDocRevision POST content.publish Restore a revision
deleteDoc POST content.delete Delete a document (force to ignore references)
approveChange POST review.decide Approve a staged change (optionally as a draft); a reviewer who can't publish moves it to Approved
rejectChange POST review.decide Reject a staged change
act POST content.read Run an action the document's workflow offers the caller (approve, reject, a custom approval, a discard, a schedule)
agentChat POST agent.use Conversational content agent
proposeEdit POST agent.use AI proposal for a document's fields (does not save)
editPageBlocks POST agent.use AI proposal for a page's blocks (does not save)
editBlockWithAi POST agent.use AI proposal for one block (does not save)
editFieldWithAi POST agent.use AI proposal for one text field (does not save)
listApiKeys GET settings.manage List API keys (never the keys themselves)
createApiKey POST settings.manage Create an API key (returned once)
revokeApiKey POST settings.manage Revoke an API key

| listUploadedMedia | GET | content.read | The media library | | getUploadedMedia | GET | content.read | One media item (alt text, size, filename) | | getMediaUsage | GET | content.read | Documents that reference a media item | | updateUploadedMedia | POST | media.upload | Edit alt text or filename | | uploadImage | POST | media.upload | Upload an image as a base64 data URL | | deleteUploadedMedia | POST | media.delete | Delete a media item (force to ignore references) | | aiImage | POST | agent.use | Generate or edit an image with the image adapter |

Large uploads should use multipart POST /api/media instead of uploadImage. The agent tools are in the same registry: /api/cms/v1/ops/list_documents works like any other operation, with staged writes attributed to the api actor.

invokeOp

Every transport runs an operation through invokeOp(name, input, { request }) from @tanstack/cms-api. It:

  1. checks the request origin for cookie-authenticated writes (CSRF),
  2. resolves the session from the request (API key, your auth adapter, or the dev fallback),
  3. enforces the operation's access and, for agent.use operations, the ai rate limit,
  4. binds the session for the duration of the call (so agent tools invoked underneath enforce the same rules), and runs the operation.

input must already match the operation's schema; transports validate it with ops[name].input first. You can call invokeOp from your own server code:

import { invokeOp } from '@tanstack/cms-api'

export async function latestPosts(request: Request) {
  const { items } = await invokeOp(
    'list',
    { collection: 'post', limit: 5, populate: false },
    { request },
  )
  return items.map((item) => ({ id: item.id, title: item.doc.title }))
}

Transports

The same registry is served three ways:

  • @tanstack/cms-api/start exports one TanStack Start server function per operation, with the same name (save, reviewSnapshot, ...). @tanstack/cms-ui-react uses these in-process, with no HTTP hop.
  • @tanstack/cms-api/http exports createCmsApiHandler(), a (request: Request) => Promise<Response> handler for any WinterTC-compatible server (Nitro, Hono, and others). Node is the tested runtime; Bun and Deno provide the Node built-ins it imports, and Workers need nodejs_compat. In a Start app the CMS route /api/cms/v1/$ mounts it for you.
  • @tanstack/cms-client calls the HTTP API with types inferred from the ops table.

The Versioned HTTP API

Endpoint Description
GET /api/cms/v1 Catalog: { version, ops: [{ name, description, method, access }] }
GET /api/cms/v1/openapi.json OpenAPI 3.1 document generated from the operation schemas
POST /api/cms/v1/ops/:name Run any operation with a JSON body
GET /api/cms/v1/ops/:name?input=<json> Run a GET operation with its input as URL-encoded JSON (or flat query params)

Responses are { result } on success and { error: { code, message, details? } } on failure, with the HTTP status that matches code (BAD_REQUEST 400, UNAUTHORIZED 401, FORBIDDEN 403, NOT_FOUND 404, CONFLICT 409, VALIDATION_FAILED 422, RATE_LIMITED 429, NOT_CONFIGURED 501, and so on). Every response carries an x-cms-api-version: v1 header. The v1 segment changes only for breaking changes.

# Public: no credentials needed
curl 'https://cms.example.com/api/cms/v1/ops/list?input=%7B%22collection%22%3A%22post%22%7D'

# Authenticated with an API key
curl -X POST https://cms.example.com/api/cms/v1/ops/save \
  -H "Authorization: Bearer $CMS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"collection":"post","id":"hello-world","doc":{"title":"Hello"},"expectedRevision":3}'

Or with the typed client:

import { CmsApiError, createCmsClient } from '@tanstack/cms-client'

const cms = createCmsClient({
  baseUrl: 'https://cms.example.com',
  getAuthHeader: () => `Bearer ${process.env.CMS_API_KEY}`,
})

export async function publishPost(id: string) {
  try {
    return await cms.op('bulkDocuments', {
      collection: 'post',
      ids: [id],
      action: 'publish',
    })
  } catch (e) {
    if (e instanceof CmsApiError && e.code === 'FORBIDDEN') return null
    throw e
  }
}

The Agent Tool Registry (opSchemas)

Agents get a smaller, task-shaped set of tools. opSchemas (packages/core/src/ops.ts) is client-safe: it holds only { name, description, inputSchema, kind }, so the browser (WebMCP) and the server read the same definitions.

Tool Kind Behavior
list_collections read Collections and their fields
list_documents read The canonical list: documents of one collection (or every readable one) with locale, where, sort, paging (limit, offset, cursor) and populate (default false: relation fields stay ids). Returns { items: [{ id, collection, doc, relations? }], total, nextCursor? }
get_document read The canonical get: one document by id or locator, including staged creates and updates in the agent's edit mode, with its relations populated (populate: false for ids only). Returns { id, locator, collection, doc, relations } or null
read_document read Deprecated, use get_document. One document by id, including staged creates and updates; NOT_FOUND when missing
search_documents read Full-text search and structured where / sort queries with collection, locale, a read mode (live for published only; never wider than the caller's), pagination (limit, offset, cursor), and populate (default false)
list_revisions read Revision history, newest first
list_translations read A document's locale variants
save_document write Stage a new document or a change: doc holds only the fields to change, create: true refuses an existing id. Returns { id, collection, doc, state, availableActions }
delete_document write Stage a deletion
unpublish_document write Stage unpublishing
restore_revision write Stage restoring a revision
schedule_document write Stage setting or clearing publishAt

The read tools come from the canonical read vocabulary, readVerbs: each verb's agent tool name is derived as <verb>_<noun> (get → get_document, list → list_documents, see agentToolName), and its input schema is the verb's bag (getInput, listInput), the same one the get and list operations, client.get/list and cmsAs(cms, ctx).get/list take. The one difference is the populate default: get_document populates like get, while list_documents and search_documents return ids unless the agent asks (populate: true, or the paths it needs), to keep tool results small. Full-text search stays its own tool, search_documents.

The write tool comes from the canonical write vocabulary, writeVerbs, the same way: save → save_document, with the saveInput bag the save operation, client.save and cmsAs(cms, ctx).save take. An agent's save is always the strategy's submit, so it is staged for review. act (approve, reject, discard, …) is not an agent tool: review decisions stay with people.

Two server-side pieces in @tanstack/cms-core/server attach behavior:

  • runOp(name, input, actor, access) executes a tool as an access context (every transport builds one per request; a call without one throws UNAUTHORIZED). With a session-bearing context, it requires content.read for read tools and content.write for write tools (content.delete for delete_document and content.publish for unpublish_document, matching the human operations), checks the collection's access rules and API key scope, hides collections the session cannot read, redacts unreadable fields, and preserves fields the session cannot write. Write tools never commit: they stage the change (save_document through saveAs, the others through stageWrite()), so it waits in the review queue with actor recorded.
  • cmsTools(actor, { access }) wraps every agent tool (agentOpSchemas(): opSchemas plus your ops marked agent) as a @tanstack/ai server tool bound to an actor and a context. A host serving many callers from one tool set passes each call's context under CMS_ACCESS_KEY instead.
Surface How it uses the tools Actor
Content agent (/agent) chat({ tools: await cmsTools('content-agent') }) content-agent
HTTP MCP server (/api/mcp) createMCPServer({ tools: await cmsTools('mcp') }) mcp
WebMCP (unstable_WebMcpBadge) Registers each agentOpSchemas() entry in the browser; calls POST /api/cms, which runs runOp(name, input, 'webmcp', access) webmcp

You can hand the same tools to your own agent:

import { chat } from '@tanstack/ai'
import { accessContext, cmsTools, resolveSession } from '@tanstack/cms-core/server'

const access = accessContext({
  session: await resolveSession(request),
  agent: 'my-agent',
  mode: 'edit',
})
const reply = await chat({
  adapter,
  tools: await cmsTools('my-agent', { access }),
  messages,
  stream: false,
})

The tools enforce that user's permissions, collection access and field rules. A systemContext(reason) skips those checks (writes are still staged); use it only for trusted server code.

Adding Your Own Operations

Define an operation with defineOp() and register it with defineCms({ ops }). It joins the same registry as the built-ins: allOps() from @tanstack/cms-api lists all of them, so your op is served at /api/cms/v1/ops/<name>, listed in the OpenAPI document and the /api/cms/v1 catalog, and callable from Start with callOp and from @tanstack/cms-client with cms.call(name, input). Mark it agent to make it a tool for the content agent, the MCP server, and WebMCP as well:

import { z } from 'zod'
import { defineCms, defineOp } from '@tanstack/cms-core'
import { stageWrite } from '@tanstack/cms-core/server'

const suggestTitle = defineOp({
  name: 'suggest_title',
  access: 'content.write',
  description: 'Propose a new title for a post. Staged for review.',
  input: z.object({ id: z.string(), title: z.string() }),
  agent: { kind: 'write' },
  run: async (input, { actor }) => {
    const pending = await stageWrite({
      collection: 'post',
      docId: input.id,
      type: 'update',
      doc: { title: input.title },
      actor,
    })
    return { pendingId: pending.id }
  },
})

export const cms = defineCms({ ops: [suggestTitle], collections, blockTypes })

Every transport enforces access before run, validates the input with input, and passes { request, session, actor }. For agent ops, collection access rules apply to any collection field in the input, the same as the built-in tools. Names must be unique across the registry; a clash with a built-in throws when the registry is first read. Because cms.config.ts is also bundled for the browser, import server-only modules inside run with import().

Next Steps