From c3c203f3196c6f168b45eb18bf6ed22aaaf537e0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 14:22:50 +0000 Subject: [PATCH] =?UTF-8?q?feat!:=20one=20read=20vocabulary=20=E2=80=94=20?= =?UTF-8?q?get/list=20rooted=20in=20the=20operations=20registry=20(3a)=20(?= =?UTF-8?q?#34)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chain step 16 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: jherr --- .changeset/read-verbs-get-list.md | 19 + docs/agents/content-agent.md | 2 +- docs/agents/review-queue.md | 2 +- docs/api/cms-client.md | 27 +- docs/api/cms-core-server.md | 71 +++- docs/api/cms-core.md | 2 +- docs/api/routes-and-endpoints.md | 8 +- docs/deployment/upgrading.md | 29 ++ docs/mcp/http-mcp-server.md | 2 +- docs/mcp/operations-registry.md | 7 +- docs/tutorials/mcp-and-webmcp.md | 4 +- packages/api/src/ops.ts | 77 ++++- packages/api/src/outputs.ts | 15 + packages/api/src/start.ts | 8 + packages/api/tests/read-verbs.test.ts | 174 ++++++++++ packages/client/src/client.ts | 37 +- packages/client/tests/client.test.ts | 33 ++ packages/core/src/index.ts | 10 + packages/core/src/ops.ts | 165 +++++++-- packages/core/src/server.ts | 2 + packages/core/src/server/cms-as.ts | 20 +- packages/core/src/server/cms-ops.ts | 30 +- packages/core/src/server/store.ts | 1 + packages/core/src/server/store/read.ts | 16 +- packages/core/src/server/store/verbs.ts | 86 +++++ packages/core/tests/access-context.test.ts | 14 +- packages/core/tests/read-verbs.test.ts | 383 +++++++++++++++++++++ 27 files changed, 1161 insertions(+), 83 deletions(-) create mode 100644 .changeset/read-verbs-get-list.md create mode 100644 packages/api/tests/read-verbs.test.ts create mode 100644 packages/core/src/server/store/verbs.ts create mode 100644 packages/core/tests/read-verbs.test.ts diff --git a/.changeset/read-verbs-get-list.md b/.changeset/read-verbs-get-list.md new file mode 100644 index 00000000..4c2a5e2f --- /dev/null +++ b/.changeset/read-verbs-get-list.md @@ -0,0 +1,19 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-client': minor +--- + +`get` and `list` are the canonical reads, with one bag each at every layer, rooted in the operations registry (`readVerbs`, `getInput`, `listInput` in `@tanstack/cms-core`). + +- Server: `cmsAs(cms, ctx).get({ collection, id | locator, locale?, populate? })` and `.list({ collection?, locale?, where?, sort?, limit?, offset?, cursor?, populate? })`, and the argument forms `getAs(ctx, options)` and `listAs(ctx, options)`. A `live` context reads published documents; `preview` and `edit` read the working copy, with staged changes overlaid. `get` resolves to `{ id, collection, doc }` or `null`, and `list` to `{ items, total, nextCursor? }`. `list` pages 100 at a time by default (at most 500). `populate` defaults to `false`. +- HTTP and Start: the public `get` and `list` operations (and Start server functions), reading as the public site does: published documents for anyone, and the working copy for callers who may read drafts unless they ask for `live`. +- Client: `client.get(options)` and `client.list(options)`, typed from `Register`. +- Agents: `get_document` (new), and `list_documents`, both named `_` from the registry (`agentToolName`). `search_documents` stays its own verb. + +**Breaking:** + +- `list_documents` takes the `list` bag and returns `{ items: [{ id, collection, doc }], total, nextCursor? }` instead of an array of summaries. `limit` defaults to 100, and staged creates are no longer listed (`get_document` reads them). +- `get` and `list` are reserved operation names, so an app op named either one fails as a duplicate. + +`read_document` is deprecated in favour of `get_document`. The older read verbs and operations keep their behaviour. diff --git a/docs/agents/content-agent.md b/docs/agents/content-agent.md index bf2b933b..751c843c 100644 --- a/docs/agents/content-agent.md +++ b/docs/agents/content-agent.md @@ -88,7 +88,7 @@ const reply = await chat({ ### Tools and Permissions -The agent uses the twelve [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `read_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. +The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. The tools run with the signed-in user's session, so the agent sees only the collections and fields that user may read, and preserves fields they may not write. Every write is **staged** in the [review queue](./review-queue) with `actor: 'content-agent'`, even when an admin is chatting. When the agent stages something, the page shows a **Review changes** link to `/review`. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 119c6b3b..15857220 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -80,7 +80,7 @@ An agent often makes several edits to the same document before anyone reviews th The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first. -Agents can read their own staged work. `read_document` and `update_document` fall back to the pending version when a document hasn't been committed yet, and `list_documents` includes pending creates. An agent can create a document, read it back, and refine it before anyone approves. +Agents can read their own staged work. `get_document` (in the agent's `edit` mode) and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue. ## Reviewing Changes diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 31866c97..8b4d46c7 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -59,11 +59,30 @@ const cms = createCmsClient({ getAuthHeader: () => (process.env.CMS_API_KEY ? `Bearer ${process.env.CMS_API_KEY}` : undefined), }) -const { items, total } = await cms.collection('post').published({ limit: 10 }) +const { items, total } = await cms.list({ collection: 'post', limit: 10 }) console.log(`${items.length} of ${total} posts`) ``` -`mode` asks every call for a read mode. The client sends it as the `x-cms-read-mode` header (`CMS_READ_MODE_HEADER`), and the server builds the caller's access context in that mode. `live` reads published documents only, even for an editor's key. `edit` reads the working copy, meaning the drafts the caller may read. Without `mode` the server reads in `edit`, so a CMS reader's `published()` includes drafts. A client with a `mode` appends it to its cache scope, so live and edit reads never share a query key. +`mode` asks every call for a read mode. The client sends it as the `x-cms-read-mode` header (`CMS_READ_MODE_HEADER`), and the server builds the caller's access context in that mode. `live` reads published documents only, even for an editor's key. `edit` reads the working copy, meaning the drafts the caller may read. Without `mode` the server reads in `edit`, so a CMS reader's `list()` includes drafts. A client with a `mode` appends it to its cache scope, so live and edit reads never share a query key. + +### `get(options)` and `list(options?)` + +The canonical reads, the `get` and `list` operations. They take the same bags as [`getAs` and `listAs`](./cms-core-server#getasctx-options-and-listasctx-options) on the server, and their document types come from `Register`. + +```ts validate=type +import { createCmsClient } from '@tanstack/cms-client' + +const cms = createCmsClient({ baseUrl: 'https://cms.example.com', mode: 'live' }) + +const about = await cms.get({ collection: 'page', locator: 'about' }) +const first = await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20 }) +const next = first.nextCursor + ? await cms.list({ collection: 'post', sort: { field: 'title' }, limit: 20, cursor: first.nextCursor }) + : undefined +console.log(about?.doc, first.items.length, next?.total) +``` + +`get` resolves to `{ id, collection, doc }`, or `null` when the document is missing or the caller can't see it. `list` resolves to `{ items: [{ id, collection, doc }], total, nextCursor? }`. Both are public: anonymous callers read published documents, and callers who may read drafts see the working copy unless the client's `mode` is `live`. ### `op(name, input)` and `call(name, input?)` @@ -82,7 +101,7 @@ console.log(found?.collection, redirect?.to, custom.count) ### `collection(name)` -Typed helpers for one collection, wrapping the document operations: +Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads; for content, use the client's `get` and `list`: | Method | Operation | Access | Returns | | --- | --- | --- | --- | @@ -94,7 +113,7 @@ Typed helpers for one collection, wrapping the document operations: | `delete(id, options?)` | `deleteDoc` | `content.delete` | `{ ok }`. Option: `force`. | | `discardDraft(id)` | `discardDraft` | `content.write` + publish rights | `{ ok }` | -`get()` is an editing read and needs `content.read`. Anonymous readers use `published()`, or `op('getPublicDocument', { slugOrId })` for one document. +`collection(name).get()` is an editing read and needs `content.read`. Anonymous readers use the client's `get` and `list`. Saving follows the [workflow rules](./cms-core-server#workflow-drafts-review-queue-revisions-scheduling): changes to a published document are a draft until saved with `publish: true`, and callers without publish rights have their changes staged for review (`staged: true`). diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 33e155b3..4dc62b10 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -76,7 +76,7 @@ Contexts are frozen and come from the builders. A copied object is not a context function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsReads ``` -The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned): `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. +The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned). `get` and `list` are the canonical reads (see [`getAs` and `listAs`](#getasctx-options-and-listasctx-options)). The older vocabulary is bound too: `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. ```ts validate=type import { defineCms } from '@tanstack/cms-core' @@ -91,7 +91,11 @@ import { const cms = defineCms({ collections: [], blockTypes: [] }) export async function homePage() { - return cmsAs(cms, publicContext()).queryDocuments({ collection: 'post', limit: 10 }) + return cmsAs(cms, publicContext()).list({ collection: 'post', limit: 10 }) +} + +export async function postPage(slug: string) { + return cmsAs(cms, publicContext()).get({ collection: 'post', locator: slug }) } export async function editorDrafts(request: Request) { @@ -106,7 +110,7 @@ export async function sitemapIds() { } ``` -Each verb also has an argument form taking the context first: `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These read against the registered CMS. +Each verb also has an argument form taking the context first: `getAs(ctx, options)`, `listAs(ctx, options)`, `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These read against the registered CMS. ### Checks @@ -127,6 +131,67 @@ The plain read functions below (`queryDocuments`, `readDocument`, …) are depre ## Documents and queries +### `getAs(ctx, options)` and `listAs(ctx, options?)` + +```ts +function getAs(ctx: AccessContext, options: GetOptions): Promise +function listAs(ctx: AccessContext, options?: ListOptions): Promise + +type GetOptions = { + collection: string + locale?: string // with `locator`: match the document in this locale + populate?: boolean // default false +} & ({ id: string } | { locator: string }) // exactly one + +interface ListOptions { + collection?: string // omit to list every collection ctx may read + locale?: string // only documents in this locale + where?: WhereInput // object form, see Filters below + sort?: { field: string; dir?: 'asc' | 'desc' } + limit?: number // 1–500, default 100 + offset?: number + cursor?: string // `nextCursor` from the previous page + populate?: boolean // default false +} + +interface ReadResult { + id: string + collection: string + doc: TDoc + relations?: Record | null> // with `populate` +} + +interface ListResult { + items: Array> + total: number + nextCursor?: string +} +``` + +The canonical reads. One bag each, the same at every layer: the store (`cmsAs(cms, ctx).get/list`), HTTP and Start (the `get` and `list` operations), `@tanstack/cms-client` (`client.get/list`), and the agent tools (`get_document`, `list_documents`). The bag carries no visibility. The context decides it: + +- A `live` context reads published documents only. +- A `preview` or `edit` context reads the working copy, with staged changes overlaid. + +A `locator` is the document's slug or its id, with leading slashes ignored. A document that is missing, or that `ctx` can't see, is `null` from `get` and absent from `list`. Documents are redacted for `ctx`, and filtering or sorting on a field it can't read is `FORBIDDEN`. Both functions validate the bag (`getInput`, `listInput` from `@tanstack/cms-core`) and throw `BAD_REQUEST` for an invalid one. + +Full-text search stays its own verb, `queryDocumentsAs` with `query`, and `search_documents` for agents. The older read verbs below keep their behaviour. + +```ts validate=type +import { listAs, publicContext } from '@tanstack/cms-core/server' + +export async function allPosts() { + const ids: Array = [] + let cursor: string | undefined + do { + const page = await listAs(publicContext(), { collection: 'post', limit: 500, cursor }) + ids.push(...page.items.map((i) => i.id)) + cursor = page.nextCursor + } while (cursor) + return ids +} +``` + ### `queryDocumentsAs(ctx, options?)` ```ts diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 0195a6f0..b98e9b2d 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -809,7 +809,7 @@ interface OpSchema { const opSchemas: Array ``` -The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `read_document`, `search_documents`, `list_revisions`, `list_translations` (read), and `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry). +The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations` (read), and `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry). These agent tools are separate from the HTTP API operations (`saveDoc`, `getPublicDocument`, …) in [`@tanstack/cms-api`](./cms-api). diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index b042f6da..5dea234e 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -226,8 +226,8 @@ curl -X POST https://example.com/api/cms/v1/ops/saveDoc \ Runs a `GET` operation (and only those). Pass the input as JSON in `?input=`, or as flat query parameters for string-only inputs. ```bash -curl 'https://example.com/api/cms/v1/ops/listPublishedDocuments?input={"collection":"post","limit":10}' -curl 'https://example.com/api/cms/v1/ops/getPublicDocument?slugOrId=about' +curl 'https://example.com/api/cms/v1/ops/list?input={"collection":"post","limit":10}' +curl 'https://example.com/api/cms/v1/ops/get?collection=page&locator=about' ``` ### Operations @@ -237,6 +237,8 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/ | Operation | Method | Access | Input | Result | | --- | --- | --- | --- | --- | | `getAuthSession` | GET | public | `{}` | The caller's `CmsSession` plus `ai: { text, image }` capabilities. | +| `get` | GET | public | `{ collection, id \| locator, locale?, populate? }` | `{ id, collection, doc, relations? }` or `null`. The canonical read ([`getAs`](./cms-core-server#getasctx-options-and-listasctx-options)): published only, except for callers who may read drafts of the collection and don't ask for `live`; drafts are read with staged changes overlaid. | +| `list` | GET | public | `{ collection?, locale?, where?, sort?: { field, dir? }, limit? (1–500, default 100), offset?, cursor?, populate? }` | `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }`. The canonical list, with the same visibility as `get`. | | `listDocumentSummaries` | GET | `content.read` | `{ collection, search?, status?: 'all' \| 'published' \| 'draft' \| 'scheduled', locale?, ids? (≤ 500), sort?: { field, dir? }, limit? (1–500, default 50), offset?, columns? (≤ 20) }` | `{ items: DocSummary[], total }` | | `getDocument` | GET | `content.read` | `{ collection, id }` | `{ doc, isPending, pendingId?, pendingSource?, livePublished }`, including any staged change. | | `resolveRedirect` | GET | public | `{ path }` | `{ to, status }` or `null` | @@ -278,7 +280,7 @@ Operations that need `agent.use` also count against the `ai` rate limit and retu ### `/api/mcp` -A [Model Context Protocol](../mcp/http-mcp-server) server over Streamable HTTP (`GET`, `POST`, `DELETE`), exposing the agent tools (`list_documents`, `read_document`, `create_document`, …). Write tools stage their changes for review. +A [Model Context Protocol](../mcp/http-mcp-server) server over Streamable HTTP (`GET`, `POST`, `DELETE`), exposing the agent tools (`list_documents`, `get_document`, `create_document`, …). Write tools stage their changes for review. Access is granted to: diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index 7782a20a..faf36680 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -422,6 +422,35 @@ becomes `accessContext({ session, mode })`, `publishedOnly: true` becomes warning. Replace that reason with a real one, or with the visitor's context where the read serves the public. +### 26. One read vocabulary: `get` and `list` + +`get` and `list` are the canonical reads, with one bag each at every layer: +`cmsAs(cms, ctx).get/list` (or `getAs`/`listAs`) on the server, the `get` +and `list` operations over HTTP and Start, `client.get/list`, and the agent +tools `get_document` and `list_documents`. See +[`getAs` and `listAs`](../api/cms-core-server#getasctx-options-and-listasctx-options). + +```ts +const post = await cmsAs(cms, ctx).get({ collection: 'post', locator: 'hello' }) +const { items, nextCursor } = await cmsAs(cms, ctx).list({ collection: 'post', limit: 20 }) +``` + +The older verbs (`queryDocumentsAs`, `readDocumentBySlugAs`, +`listPublishedDocuments`, `getPublicDocument`, …) keep working as they did, +and a later alpha moves the starters and docs over. + +- **`list_documents` is the canonical `list`.** It takes the `list` bag + (`where`, `sort`, `cursor` and `populate` are new; `limit` defaults to 100) + and returns `{ items: [{ id, collection, doc }], total, nextCursor? }` + instead of an array of summaries. Staged creates are no longer listed; + `get_document` still reads them. +- **`read_document` is deprecated** in favour of `get_document`, which takes + `id` or `locator` and returns `{ id, collection, doc }` or `null`. + `read_document` still returns the bare document and is removed in a later + alpha. +- **`get` and `list` are reserved operation names**: an app op with either + name now fails as a duplicate. + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/docs/mcp/http-mcp-server.md b/docs/mcp/http-mcp-server.md index fba246bb..3ba86ed4 100644 --- a/docs/mcp/http-mcp-server.md +++ b/docs/mcp/http-mcp-server.md @@ -37,7 +37,7 @@ export const cmsMcp = createMCPServer({ - `GET /api/mcp` opens the server-to-client stream. - `DELETE /api/mcp` ends a session. -The tools are the twelve agent tools listed in the [Operations Registry](./operations-registry#the-agent-tool-registry-opschemas): six read tools (`list_collections`, `list_documents`, `read_document`, `search_documents`, `list_revisions`, `list_translations`) and six write tools that stage changes (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`). +The tools are the agent tools listed in the [Operations Registry](./operations-registry#the-agent-tool-registry-opschemas): the read tools (`list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations`) and six write tools that stage changes (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`). ## Who Can Connect diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index eeabefbb..de3461cb 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -164,8 +164,9 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ | Tool | Kind | Behavior | | --- | --- | --- | | `list_collections` | read | Collections and their fields | -| `list_documents` | read | Document summaries, filtered by collection and locale, paginated (`limit`, `offset`, `cursor`) | -| `read_document` | read | One document, including staged creates and updates | +| `list_documents` | read | The canonical `list`: documents of one collection (or every readable one) with `locale`, `where`, `sort`, paging (`limit`, `offset`, `cursor`) and `populate`. Returns `{ items: [{ id, collection, doc }], 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. Returns `{ id, collection, doc }` 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), and pagination (`limit`, `offset`, `cursor`) | | `list_revisions` | read | Revision history, newest first | | `list_translations` | read | A document's locale variants | @@ -176,6 +177,8 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ | `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 `_` (`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. Full-text search stays its own tool, `search_documents`. + 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 call `stageWrite()`, so the change waits in the [review queue](../agents/review-queue) with `actor` recorded. diff --git a/docs/tutorials/mcp-and-webmcp.md b/docs/tutorials/mcp-and-webmcp.md index aa92a9f6..65978da6 100644 --- a/docs/tutorials/mcp-and-webmcp.md +++ b/docs/tutorials/mcp-and-webmcp.md @@ -14,7 +14,7 @@ keywords: - unstable_WebMcpBadge --- -Every TanStack CMS app exposes the same 12 content tools (`list_collections`, `list_documents`, `read_document`, `create_document`, `update_document`, `delete_document`, `unpublish_document`, `search_documents`, `list_revisions`, `restore_revision`, `schedule_document`, `list_translations`) across three agent surfaces: +Every TanStack CMS app exposes the same content tools (`list_collections`, `list_documents`, `get_document`, `create_document`, `update_document`, `delete_document`, `unpublish_document`, `search_documents`, `list_revisions`, `restore_revision`, `schedule_document`, `list_translations`) across three agent surfaces: 1. **In-app content agent** at `/agent` (actor `content-agent`; needs a text adapter in `defineCms({ ai })`) 2. **HTTP MCP server** at `/api/mcp` (actor `mcp`) @@ -137,7 +137,7 @@ curl http://localhost:3003/api/cms # Read a document curl -X POST http://localhost:3003/api/cms \ -H "Content-Type: application/json" \ - -d '{"op":"read_document","input":{"collection":"page","id":"home"}}' + -d '{"op":"get_document","input":{"collection":"page","id":"home"}}' ``` For integrations that are not agents, use the versioned HTTP API instead: `GET /api/cms/v1` lists its operations, `GET /api/cms/v1/openapi.json` describes them, and `POST /api/cms/v1/ops/:name` runs one (for example `/api/cms/v1/ops/getDocument` with `{"collection":"page","id":"home"}`). `@tanstack/cms-client` wraps it with types. diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 50528055..75778825 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -26,8 +26,11 @@ import { configuredOps, emptyDoc, opSchemas, + readVerbs, getCmsConfig, + getInput, hasPermission, + listInput, normalizeBlocks, resolveDocumentLocale, scalarSchemaFor, @@ -61,8 +64,9 @@ import { findDocumentBySlugAs, findReferencesAs, listRevisionsAs, - queryDocumentsAs, queryDocumentSummariesAs, + getAs, + listAs, accessContext, systemContext, assertReadable, @@ -105,6 +109,8 @@ import { interfaceOps } from './interface-ops' import { documentOutput, documentSummariesOutput, + getOutput, + listOutput, okOutput, publicDocumentOutput, publishedDocumentsOutput, @@ -119,7 +125,9 @@ import type { CmsOpDefinition, CmsSession, Doc, + GetOptions, OpAccess, + ReadVerbName, } from '@tanstack/cms-core' import type { AccessContext, @@ -619,6 +627,26 @@ const _ops = { run: async (input: { path: string }) => resolveRedirect(input.path), }, + get: { + method: 'GET', + access: 'public', + description: `${readVerb('get').description} Anyone may call it; drafts are visible only to callers who may read them.`, + input: getInput, + output: getOutput, + run: async (input: z.infer, ctx: CmsOpContext) => + getAs(readerContext(ctx, input.collection), input as GetOptions), + }, + + list: { + method: 'GET', + access: 'public', + description: `${readVerb('list').description} Anyone may call it; drafts are visible only to callers who may read them.`, + input: listInput, + output: listOutput, + run: async (input: z.infer, ctx: CmsOpContext) => + listAs(readerContext(ctx, input.collection), input), + }, + getPublicDocument: { method: 'GET', access: 'public', @@ -659,21 +687,14 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - const result = await queryDocumentsAs( - siteRead( - ctx, - ctx.access.mode === 'live' || - !canReadCollection(editing(ctx), input.collection), - ), - { - collection: input.collection, - where: input.where, - sort: input.sort, - limit: input.limit, - offset: input.offset, - cursor: input.cursor, - }, - ) + const result = await listAs(readerContext(ctx, input.collection), { + collection: input.collection, + where: input.where, + sort: input.sort, + limit: input.limit, + offset: input.offset, + cursor: input.cursor, + }) return { items: result.items.map((i) => ({ id: i.id, @@ -1977,7 +1998,7 @@ const contentAgentSystem = (ctx: CmsOpContext) => `Rules:\n` + `- Answer data questions by calling search_documents with filters, sort, limit and offset. Use its total for counts. Read actual records; do not invent query results. Arrays use the configured nested fields, not strings.\n` + `- To create content, call create_document with a url-safe id and every field.\n` + - `- To edit, call read_document first, then update_document with the COMPLETE updated document.\n` + + `- To edit, call get_document first, then update_document with its COMPLETE doc, updated.\n` + `- For a page, compose "blocks" as an array, e.g. a hero then a few richText blocks. ` + `Use markdown in richText. Start most pages with a hero.\n` + `- Every record write you make is STAGED for human approval in the review queue; it is ` + @@ -2180,6 +2201,28 @@ function siteRead(ctx: CmsOpContext, liveOnly: boolean): AccessContext { }) } +/** + * The context `get` and `list` read with over a transport: the site's read, + * live unless the caller asked for more and may read `collection` (any + * content, without one) beyond what's published. + */ +function readerContext(ctx: CmsOpContext, collection?: string): AccessContext { + return siteRead( + ctx, + ctx.access.mode === 'live' || + !(collection + ? canReadCollection(editing(ctx), collection) + : hasPermission(ctx.session, 'content.read')), + ) +} + +/** A canonical read verb from the registry. */ +function readVerb(name: ReadVerbName) { + const verb = readVerbs.find((v) => v.name === name) + if (!verb) throw new Error(`Unknown read verb: ${name}`) + return verb +} + const onPageSystem = () => `You edit the blocks of a CMS page in place. Given the current blocks and an ` + `instruction, return the COMPLETE updated blocks array. Keep blocks the ` + diff --git a/packages/api/src/outputs.ts b/packages/api/src/outputs.ts index 1118b2b8..0d9e72d4 100644 --- a/packages/api/src/outputs.ts +++ b/packages/api/src/outputs.ts @@ -55,6 +55,21 @@ export const redirectOutput = z export const publicDocumentOutput = docEntry.nullable() +const readResult = docEntry.extend({ + relations: z + .record(z.string(), z.union([doc, z.array(doc), z.null()])) + .optional() + .describe('With `populate`: related documents by relation field path.'), +}) + +export const getOutput = readResult.nullable() + +export const listOutput = z.object({ + items: z.array(readResult), + total: z.number(), + nextCursor: z.string().optional(), +}) + export const publishedDocumentsOutput = z.object({ items: z.array(z.object({ id: z.string(), doc })), total: z.number(), diff --git a/packages/api/src/start.ts b/packages/api/src/start.ts index f392a93e..2f4eba17 100644 --- a/packages/api/src/start.ts +++ b/packages/api/src/start.ts @@ -116,6 +116,14 @@ export const getAuthSession = createServerFn({ method: 'GET' }) .validator(ops.getAuthSession.input) .handler(async ({ data }) => invokeOp('getAuthSession', data, await req())) +export const get = createServerFn({ method: 'GET' }) + .validator(ops.get.input) + .handler(async ({ data }) => invokeOp('get', data, await req())) + +export const list = createServerFn({ method: 'GET' }) + .validator(ops.list.input) + .handler(async ({ data }) => invokeOp('list', data, await req())) + export const listDocumentSummaries = createServerFn({ method: 'GET' }) .validator(ops.listDocumentSummaries.input) .handler(async ({ data }) => diff --git a/packages/api/tests/read-verbs.test.ts b/packages/api/tests/read-verbs.test.ts new file mode 100644 index 00000000..ac08eb04 --- /dev/null +++ b/packages/api/tests/read-verbs.test.ts @@ -0,0 +1,174 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { getInput, listInput, readVerbs } from '@tanstack/cms-core' +import { commitDocument, stageWrite } from '@tanstack/cms-core/server' +import { createCmsApiHandler } from '../src/http' +import { allOps, ops } from '../src/ops' +import { cleanup, req, setupCms } from './helpers' +import type { CmsConfig } from '@tanstack/cms-core' + +afterEach(cleanup) + +const handler = createCmsApiHandler() + +async function call( + name: string, + input: unknown, + init: { role?: string; headers?: Record; get?: boolean } = {}, +) { + const res = await handler( + init.get + ? req( + `/api/cms/v1/ops/${name}?input=${encodeURIComponent(JSON.stringify(input))}`, + { role: init.role, headers: init.headers }, + ) + : req(`/api/cms/v1/ops/${name}`, { + method: 'POST', + role: init.role, + headers: { 'content-type': 'application/json', ...init.headers }, + body: JSON.stringify(input), + }), + ) + const body = (await res.json()) as { + result?: unknown + error?: { code: string } + } + return { status: res.status, result: body.result, code: body.error?.code } +} + +const collections: Partial = { + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { + name: 'internalNotes', + label: 'Internal notes', + type: 'text', + access: { read: ['editor', 'admin'] }, + }, + ], + }, + { + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], + access: { read: ['admin'], write: ['admin'] }, + }, + ], +} + +async function seed() { + await commitDocument('post', 'hello', { + title: 'Hello', + slug: 'hello-world', + internalNotes: 'secret', + published: true, + }) + await commitDocument('post', 'draft', { title: 'Draft' }) + await commitDocument('page', 'about', { title: 'About', published: true }) + await stageWrite({ + collection: 'post', + docId: 'hello', + type: 'update', + doc: { title: 'Hello (staged)', slug: 'hello-world', published: true }, + actor: 'ada', + }) +} + +describe('get and list over HTTP', () => { + it('are registry ops with the canonical bags', () => { + expect(ops.get.input).toBe(getInput) + expect(ops.list.input).toBe(listInput) + const all = allOps() + for (const verb of readVerbs) { + expect(all[verb.name]?.description).toContain(verb.description) + expect(all[`${verb.name}_${verb.noun}`]?.input).toBe(verb.input) + } + }) + + it('read published documents for anyone, redacted', async () => { + setupCms(collections) + await seed() + const got = await call( + 'get', + { collection: 'post', locator: 'hello-world' }, + { get: true }, + ) + expect(got.status).toBe(200) + expect(got.result).toEqual({ + id: 'hello', + collection: 'post', + doc: expect.objectContaining({ title: 'Hello' }), + }) + expect(JSON.stringify(got.result)).not.toContain('secret') + expect( + (await call('get', { collection: 'post', id: 'draft' })).result, + ).toBeNull() + const listed = await call('list', { collection: 'post' }) + expect(listed.result).toMatchObject({ total: 1, items: [{ id: 'hello' }] }) + // Published pages read as the public site reads them, as before. + expect((await call('list', { collection: 'page' })).result).toMatchObject({ + total: 1, + }) + }) + + it('show content readers the working copy unless they ask for live', async () => { + setupCms(collections) + await seed() + const got = (await call( + 'get', + { collection: 'post', id: 'hello' }, + { role: 'editor' }, + )) as { result: { doc: Record } } + expect(got.result.doc).toMatchObject({ + title: 'Hello (staged)', + }) + expect( + (await call('list', { collection: 'post' }, { role: 'editor' })).result, + ).toMatchObject({ total: 2 }) + const live = { 'x-cms-read-mode': 'live' } + expect( + ( + await call( + 'get', + { collection: 'post', id: 'draft' }, + { role: 'editor', headers: live }, + ) + ).result, + ).toBeNull() + expect( + ( + await call( + 'list', + { collection: 'post' }, + { role: 'editor', headers: live }, + ) + ).result, + ).toMatchObject({ total: 1 }) + }) + + it('validate the bag', async () => { + setupCms(collections) + await seed() + expect( + (await call('get', { collection: 'post', id: 'a', locator: 'b' })).code, + ).toBe('BAD_REQUEST') + expect((await call('list', { limit: 501 })).code).toBe('BAD_REQUEST') + }) + + it('leave listPublishedDocuments as it was', async () => { + setupCms(collections) + await seed() + const old = await call('listPublishedDocuments', { collection: 'post' }) + expect(old.result).toEqual({ + items: [ + { id: 'hello', doc: expect.objectContaining({ title: 'Hello' }) }, + ], + total: 1, + }) + }) +}) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index b2d054ab..9f3ea65c 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -9,17 +9,25 @@ * ```ts * import { createCmsClient } from '@tanstack/cms-client' * - * const cms = createCmsClient({ baseUrl: 'https://cms.example.com' }) - * const { items } = await cms.collection('post').published({ limit: 10 }) - * const raw = await cms.op('listPublishedDocuments', { collection: 'post' }) + * const cms = createCmsClient({ baseUrl: 'https://cms.example.com', mode: 'live' }) + * const { items } = await cms.list({ collection: 'post', limit: 10 }) + * const post = await cms.get({ collection: 'post', locator: 'hello' }) * ``` * + * `get` and `list` are the canonical reads (the `get` and `list` operations). + * `collection(name)` keeps the older helpers: `published` (the + * `listPublishedDocuments` operation) and the admin editor's `list`/`get`. + * * Document types come from the `Register` augmentation of * `@tanstack/cms-core` (`interface Register { cms: typeof cms }`). */ import type { CmsOpName, OpInput, OpOutput } from '@tanstack/cms-api' import type { CmsErrorCode, + GetOptions, + ListOptions, + ListResult, + ReadResult, RegisteredCollectionName, RegisteredDoc, RegisteredOpInput, @@ -90,11 +98,17 @@ export interface CmsCollectionClient { total: number nextCursor?: string }> - /** Admin listing with search, status, and locale filters. */ + /** + * Admin listing with search, status, and locale filters. For reading + * content, use the client's `list`. + */ list: ( options?: Without, 'collection'>, ) => Promise> - /** One document for editing, with any pending draft overlaid. */ + /** + * One document for editing, with any pending draft overlaid. For reading + * content, use the client's `get`. + */ get: (id: string) => Promise /** * Save a document. For a published one, changes are a draft until @@ -121,6 +135,17 @@ export interface CmsClient { readonly cacheScope?: string /** The read mode the client asks for, when set. */ readonly mode?: ReadMode + /** + * One document by `id` or `locator` (its slug), or `null` when it is + * missing or the caller can't see it. Typed from `Register`. + */ + get: ( + options: GetOptions, + ) => Promise> | null> + /** One page of documents, with filters, sort, and cursor paging. */ + list: ( + options?: ListOptions, + ) => Promise>> /** * Call a CMS operation by name. POSTs a JSON body to * `/api/cms/v1/ops/:name`. Fully typed per operation. @@ -237,6 +262,8 @@ export function createCmsClient(options: CmsClientOptions): CmsClient { fetch: authedFetch, op, call, + get: (opts) => call('get', opts), + list: (opts) => call('list', opts ?? {}), collection, cacheScope: options.cacheScope, ...(options.mode && { mode: options.mode }), diff --git a/packages/client/tests/client.test.ts b/packages/client/tests/client.test.ts index 0933884c..20c6ca75 100644 --- a/packages/client/tests/client.test.ts +++ b/packages/client/tests/client.test.ts @@ -74,6 +74,39 @@ describe('createCmsClient', () => { ).toEqual(['cms', 'site', 'post']) }) + it('reads with the canonical get and list', async () => { + await commitDocument('post', 'a', { + title: 'A', + slug: 'first', + published: true, + }) + await commitDocument('post', 'b', { title: 'B', published: false }) + const anon = client() + expect(await anon.get({ collection: 'post', locator: 'first' })).toEqual({ + id: 'a', + collection: 'post', + doc: expect.objectContaining({ title: 'A' }), + }) + expect(await anon.get({ collection: 'post', id: 'b' })).toBeNull() + const page = await anon.list({ collection: 'post' }) + expect(page.items.map((i) => i.id)).toEqual(['a']) + expect(page.total).toBe(1) + + const editor = client('Bearer editor') + expect((await editor.get({ collection: 'post', id: 'b' }))?.doc).toEqual( + expect.objectContaining({ title: 'B' }), + ) + expect((await editor.list({ collection: 'post' })).total).toBe(2) + const live = client('Bearer editor', { mode: 'live' }) + expect(await live.get({ collection: 'post', id: 'b' })).toBeNull() + expect((await live.list({ collection: 'post' })).total).toBe(1) + + const err = (await anon + .get({ collection: 'post', id: 'a', locator: 'first' } as never) + .catch((e: unknown) => e)) as CmsApiError + expect(err.code).toBe('BAD_REQUEST') + }) + it('surfaces structured errors', async () => { const err = await client() .collection('post') diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d5a59c77..986a3740 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -216,9 +216,13 @@ export type { LocalizedValue } from './i18n' // The CMS operation registry (client-safe: names, descriptions, input schemas). export { agentOpSchemas, + agentToolName, configuredOps, defineOp, + getInput, + listInput, opSchemas, + readVerbs, sortInput, validateWithStandardSchema, whereInput, @@ -227,11 +231,17 @@ export type { CmsOpContext, CmsOpDefinition, CmsToolResult, + GetOptions, + ListOptions, + ListResult, OpAccess, OpInputSchema, OpInputOf, OpOutputOf, OpSchema, + ReadResult, + ReadVerbName, + Relations, } from './ops' // Async events: the post-commit, durable half of the eventing design. The diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index 522ea8fd..a3c008cf 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -20,6 +20,7 @@ import type { Permission } from './lib/access' import type { AccessContext } from './lib/access-context' import type { CmsSession } from './lib/auth' import type { + Doc, InferStandardInput, InferStandardOutput, JsonValue, @@ -215,6 +216,143 @@ export const sortInput = z.object({ dir: z.enum(['asc', 'desc']).optional(), }) +const populateInput = z + .boolean() + .optional() + .describe( + 'Also return the documents its relation fields point to, under `relations` (keyed by field path). Default false.', + ) + +/** + * The `get` bag: one document by `id` or by `locator`, never both. What the + * reader sees (published only, or the working copy) comes from the access + * context, not the bag. + */ +export const getInput = z + .object({ + collection: z.string().min(1).describe('Collection name, e.g. "post".'), + id: z + .string() + .min(1) + .optional() + .describe('The document id. Give `id` or `locator`, not both.'), + locator: z + .string() + .min(1) + .optional() + .describe( + 'The document’s locator: its slug, or its id (leading slashes ignored). Give `id` or `locator`, not both.', + ), + locale: z + .string() + .optional() + .describe('With `locator`: match the document in this locale.'), + populate: populateInput, + }) + .refine((v) => (v.id === undefined) !== (v.locator === undefined), { + message: 'Give exactly one of `id` or `locator`.', + }) + +/** The `list` bag. Visibility comes from the access context, not the bag. */ +export const listInput = z.object({ + collection: z + .string() + .min(1) + .optional() + .describe( + 'Collection name, e.g. "post". Omit to list every collection the reader may read.', + ), + locale: z + .string() + .optional() + .describe('Only documents in this locale (a BCP-47 code, e.g. "en").'), + where: whereInput.optional(), + sort: sortInput.optional(), + limit: z.coerce + .number() + .int() + .min(1) + .max(500) + .default(100) + .describe('Page size, 1–500. Default 100.'), + offset: z.coerce.number().int().min(0).optional(), + cursor: z + .string() + .optional() + .describe('`nextCursor` from the previous page of the same query.'), + populate: populateInput, +}) + +/** Related documents by relation field path (`author`, `blocks.2.author`). */ +export type Relations = Record | null> + +/** `get`'s options: `collection` plus exactly one of `id` or `locator`. */ +export type GetOptions = { + collection: C + locale?: string + populate?: boolean +} & ({ id: string; locator?: never } | { locator: string; id?: never }) + +/** `list`'s options (see `listInput`). */ +export interface ListOptions { + collection?: C + locale?: string + where?: z.input + sort?: z.input + limit?: number + offset?: number + cursor?: string + populate?: boolean +} + +/** One document as `get` and `list` return it. */ +export interface ReadResult { + id: string + collection: string + doc: TDoc + /** With `populate`: the related documents the reader may see. */ + relations?: Relations +} + +/** One page of `list`. */ +export interface ListResult { + items: Array> + total: number + /** Pass as `cursor` to read the next page; absent on the last page. */ + nextCursor?: string +} + +/** + * The canonical read vocabulary. Each transport derives its name from this + * registry: the store (`cmsAs(cms, ctx).get`), HTTP and Start (`get`), the + * client (`client.get`) and the agent tools (`get_document`, via + * `agentToolName`). Full-text search stays its own verb + * (`search_documents`). + */ +export const readVerbs = [ + { + name: 'get', + noun: 'document', + description: + 'Read one document by collection and id, or by collection and locator (its slug). Returns { id, collection, doc }, or null when it is missing or not visible to the reader. A live reader sees the published version; preview and edit readers see the working copy, staged changes included.', + input: getInput, + }, + { + name: 'list', + noun: 'documents', + description: + 'List documents of one collection (or of every collection the reader may read), with field filters, sort, and paging. Returns { items: [{ id, collection, doc }], total, nextCursor? }. A live reader sees published documents only.', + input: listInput, + }, +] as const + +export type ReadVerbName = (typeof readVerbs)[number]['name'] + +/** The agent tool name of a read verb: `get` → `get_document`, `list` → `list_documents`. */ +export function agentToolName(verb: { name: string; noun: string }): string { + return `${verb.name}_${verb.noun}` +} + export const opSchemas: Array = [ { name: 'list_collections', @@ -223,30 +361,17 @@ export const opSchemas: Array = [ 'List the content collections (e.g. page, post) and the fields each one has.', inputSchema: z.object({}), }, - { - name: 'list_documents', + ...readVerbs.map((verb): OpSchema => ({ + name: agentToolName(verb), kind: 'read', - description: - 'List documents. Optionally filter by collection and/or locale. Each result has id, collection, title, published, pending, revision, locale, and publishAt schedule metadata.', - inputSchema: z.object({ - collection: z - .string() - .optional() - .describe('Collection name to filter by, e.g. "page" or "post".'), - locale: z - .string() - .optional() - .describe( - 'Optional BCP-47 locale code to filter by, e.g. "en" or "es".', - ), - limit: z.number().int().min(1).max(500).optional(), - offset: z.number().int().min(0).optional(), - }), - }, + description: verb.description, + inputSchema: verb.input, + })), { name: 'read_document', kind: 'read', - description: 'Read the full contents of one document by collection and id.', + description: + 'Deprecated: use get_document. Read the full contents of one document by collection and id.', inputSchema: z.object({ collection: z.string(), id: z.string(), diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 2054fee9..ef9a6216 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -282,6 +282,8 @@ export { cmsAs } from './server/cms-as' export type { CmsReads } from './server/cms-as' // The read verbs' context forms, underneath `cmsAs`. export { + getAs, + listAs, queryDocumentsAs, groupDocumentsAs, queryDocumentSummariesAs, diff --git a/packages/core/src/server/cms-as.ts b/packages/core/src/server/cms-as.ts index d77c19b2..95d8604f 100644 --- a/packages/core/src/server/cms-as.ts +++ b/packages/core/src/server/cms-as.ts @@ -5,9 +5,13 @@ * * ```ts * const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) - * await db.queryDocuments({ collection: 'post' }) + * const post = await db.get({ collection: 'post', locator: 'hello' }) + * const { items } = await db.list({ collection: 'post', limit: 10 }) * ``` * + * `get` and `list` are the canonical verbs; the others are the older + * vocabulary, kept until the codemod moves callers over. + * * It is a function rather than a `cms.as(ctx)` method because `Cms` lives in * the client-safe config module, which must not reach the server read verbs. * @@ -28,7 +32,9 @@ import { readSingletonAs, } from './store/read' import { listRevisionsAs } from './store/revisions' -import type { Cms, ResolvedCmsConfig } from '../config' +import { getAs, listAs } from './store/verbs' +import type { Cms, RegisteredDoc, ResolvedCmsConfig } from '../config' +import type { GetOptions, ListOptions, ListResult, ReadResult } from '../ops' import type { AccessContext } from './access-context' type Bound = F extends (ctx: AccessContext, ...args: infer A) => infer R @@ -38,6 +44,14 @@ type Bound = F extends (ctx: AccessContext, ...args: infer A) => infer R /** The read verbs bound to one context (see `cmsAs`). */ export interface CmsReads { readonly context: AccessContext + /** One document by `id` or `locator`, or `null` (see `getAs`). */ + get: ( + options: GetOptions, + ) => Promise> | null> + /** One page of documents (see `listAs`). */ + list: ( + options?: ListOptions, + ) => Promise>> queryDocuments: Bound groupDocuments: Bound queryDocumentSummaries: Bound @@ -81,6 +95,8 @@ export function cmsAs( runInConfigScope(config, () => verb(ctx, ...args)) return Object.freeze({ context: ctx, + get: bind(getAs) as CmsReads['get'], + list: bind(listAs) as CmsReads['list'], queryDocuments: bind(queryDocumentsAs), groupDocuments: bind(groupDocumentsAs), queryDocumentSummaries: bind(queryDocumentSummariesAs), diff --git a/packages/core/src/server/cms-ops.ts b/packages/core/src/server/cms-ops.ts index 9d2bd4c0..efc91dfb 100644 --- a/packages/core/src/server/cms-ops.ts +++ b/packages/core/src/server/cms-ops.ts @@ -21,6 +21,7 @@ import { narrowMode, redactFor, systemContext, + withMode, } from './access-context' import { assertCollectionAccess, @@ -479,19 +480,24 @@ async function dispatch( } case 'list_documents': - return store.listDocumentsAs(ctx, input?.collection, { - locale: input?.locale, - limit: input?.limit, - offset: input?.offset, - collections: readableCollections(ctx), - }) + return store.listAs(ctx, input) - case 'read_document': - return redactFor( - ctx, - input.collection, - await readOrPending(input.collection, input.id), - ) + case 'get_document': + return store.getAs(ctx, input) + + case 'read_document': { + const found = await store.getAs(withMode(ctx, 'edit'), { + collection: input.collection, + id: input.id, + }) + if (!found) { + throw new CmsError( + `No ${input.collection} document with id "${input.id}".`, + 'NOT_FOUND', + ) + } + return found.doc + } case 'create_document': { const doc = session diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 14a5c82c..0112b39f 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -76,6 +76,7 @@ export type { WhereInput, QueryDocumentsResult, } from './store/query' +export { getAs, listAs } from './store/verbs' export { stageWrite, submitWrite, diff --git a/packages/core/src/server/store/read.ts b/packages/core/src/server/store/read.ts index a59abefc..65c08236 100644 --- a/packages/core/src/server/store/read.ts +++ b/packages/core/src/server/store/read.ts @@ -691,11 +691,18 @@ export function readDocumentBySlugAs( return readBySlug(ctx, collectionName, slugOrId, options?.populate) } -async function readBySlug( +/** + * `readDocumentBySlugAs`'s lookup. With `locale`, only documents in that + * locale match, by id or by slug. + * + * @internal + */ +export async function readBySlug( ctx: AccessContext, collectionName: string, slugOrId: string, populate: boolean | undefined, + locale?: string, ): Promise<{ id: string; doc: Doc; relations?: Relations } | null> { if (!canReadCollection(ctx, collectionName)) return null const storage = await getStorage() @@ -713,7 +720,11 @@ async function readBySlug( // rather than falling through to slug matches). Trashed documents are // hidden, same as `findDocumentsBySlug`. const direct = await storage.getDocument(collectionName, slugOrId) - if (direct && !direct.deletedAt) { + if ( + direct && + !direct.deletedAt && + (locale === undefined || direct.locale === locale) + ) { if (live && !direct.published) return null if (!canReadDocument(ctx, collectionName, direct)) return null return withRelations( @@ -725,6 +736,7 @@ async function readBySlug( collectionName, slugOrId, )) { + if (locale !== undefined && row.locale !== locale) continue if (live && !row.published) continue if (!canReadDocument(ctx, collectionName, row)) continue const doc = await applyPostRead(collectionName, row.id, row.doc, ctx) diff --git a/packages/core/src/server/store/verbs.ts b/packages/core/src/server/store/verbs.ts new file mode 100644 index 00000000..3099b962 --- /dev/null +++ b/packages/core/src/server/store/verbs.ts @@ -0,0 +1,86 @@ +/** + * The canonical read verbs, `getAs` and `listAs`. Their bags are the + * registry's (`getInput`, `listInput` in `../../ops`), parsed here so every + * transport gets the same defaults and limits. What the reader sees comes + * from the access context alone. + * + * Server-only. + */ +import { getInput, listInput, validateWithStandardSchema } from '../../ops' +import { canReadCollection, isLiveRead } from '../access-context' +import { collections } from './internal' +import { queryDocumentsAs } from './query' +import { + populateRelationsAs, + readBySlug, + readDocumentAs, + readDocumentWithPendingAs, +} from './read' +import type { AccessContext } from '../access-context' +import type { GetOptions, ListOptions, ListResult, ReadResult } from '../../ops' + +/** + * One document as `ctx` reads it, by `id` or by `locator` (the slug, or the + * id; leading slashes ignored). A `live` context reads the published + * version; `preview` and `edit` read the working copy, with staged changes + * overlaid. `null` when the document is missing or `ctx` can't see it; the + * returned document is redacted for `ctx`. + */ +export async function getAs( + ctx: AccessContext, + options: GetOptions, +): Promise { + const bag = await validateWithStandardSchema(getInput, options) + const { collection } = bag + if (!collections()[collection] || !canReadCollection(ctx, collection)) + return null + const id = + bag.id ?? + (await readBySlug(ctx, collection, bag.locator ?? '', false, bag.locale)) + ?.id + if (id === undefined) return null + const doc = isLiveRead(ctx) + ? await readDocumentAs(ctx, collection, id) + : (await readDocumentWithPendingAs(ctx, collection, id)).doc + if (!doc) return null + return { + id, + collection, + doc, + ...(bag.populate + ? { relations: await populateRelationsAs(ctx, collection, doc) } + : {}), + } +} + +/** + * One page of the documents `ctx` may read, in one collection or across + * every collection `ctx` may read. Filtering or sorting on a field `ctx` may + * not read is `FORBIDDEN`; documents are redacted for `ctx`. + */ +export async function listAs( + ctx: AccessContext, + options: ListOptions = {}, +): Promise { + const bag = await validateWithStandardSchema(listInput, options) + const result = await queryDocumentsAs(ctx, { + collection: bag.collection, + locale: bag.locale, + where: bag.where, + sort: bag.sort, + limit: bag.limit, + offset: bag.offset, + cursor: bag.cursor, + populate: bag.populate, + }) + return { + items: result.items.map((item) => ({ + id: item.id, + collection: item.collection, + doc: item.doc, + ...(item.relations ? { relations: item.relations } : {}), + })), + total: result.total, + ...(result.nextCursor ? { nextCursor: result.nextCursor } : {}), + } +} diff --git a/packages/core/tests/access-context.test.ts b/packages/core/tests/access-context.test.ts index 2ee94504..789c741d 100644 --- a/packages/core/tests/access-context.test.ts +++ b/packages/core/tests/access-context.test.ts @@ -42,7 +42,7 @@ import { withMode, } from '../src/server/access-context' import { cmsAs } from '../src/server/cms-as' -import type { Cms, CmsConfig } from '../src/index' +import type { Cms, CmsConfig, ListResult } from '../src/index' import type { CmsReads } from '../src/server/cms-as' const dirs: Array = [] @@ -494,8 +494,8 @@ describe('derivation', () => { list, 'agent', systemContext('test: list memos'), - )) as Array - expect(asSystem).toHaveLength(2) + )) as ListResult + expect(asSystem.items).toHaveLength(2) await expect( runOp( 'list_documents', @@ -520,8 +520,8 @@ describe('derivation', () => { const editor = accessContext({ session: as('editor'), mode: 'edit' }) const viaCall = (await listTool.execute!(list, { context: { [CMS_ACCESS_KEY]: editor }, - } as never)) as Array - expect(viaCall).toHaveLength(2) + } as never)) as ListResult + expect(viaCall.items).toHaveLength(2) // A look-alike object is not a context: the bound one applies. await expect( listTool.execute!(list, { @@ -554,8 +554,8 @@ describe('derivation', () => { mode: 'live', }), }, - } as never)) as Array<{ id: string }> - expect(viaCall.map((d) => d.id)).toEqual(['live']) + } as never)) as ListResult + expect(viaCall.items.map((d) => d.id)).toEqual(['live']) }) }) diff --git a/packages/core/tests/read-verbs.test.ts b/packages/core/tests/read-verbs.test.ts new file mode 100644 index 00000000..6400eb83 --- /dev/null +++ b/packages/core/tests/read-verbs.test.ts @@ -0,0 +1,383 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + agentToolName, + createCms, + defineCollection, + getInput, + listInput, + normalizeSession, + opSchemas, + readVerbs, +} from '../src/index' +import { + closeStore, + commitDocument, + getAs, + listAs, + queryDocuments, + readDocumentBySlug, + runOp, + stageWrite, +} from '../src/server' +import { + accessContext, + publicContext, + systemContext, +} from '../src/server/access-context' +import { cmsAs } from '../src/server/cms-as' +import type { Cms, CmsConfig, Doc, ListResult, ReadResult } from '../src/index' + +const dirs: Array = [] + +afterEach(async () => { + await closeStore() + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +const as = (role: string) => + normalizeSession({ + isAuthenticated: true, + isAdmin: role === 'admin', + user: { id: `u-${role}`, name: role, role }, + }) + +const author = defineCollection({ + name: 'author', + label: 'Authors', + titleField: 'name', + fields: [{ name: 'name', label: 'Name', type: 'text' }], +}) + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'slug' }, + { name: 'rank', label: 'Rank', type: 'number' }, + { + name: 'secret', + label: 'Secret', + type: 'text', + access: { read: ['admin'] }, + }, + { name: 'author', label: 'Author', type: 'relation', collection: 'author' }, + ], +}) + +const memo = defineCollection({ + name: 'memo', + label: 'Memos', + titleField: 'title', + access: { read: ['editor', 'admin'] }, + fields: [{ name: 'title', label: 'Title', type: 'text' }], +}) + +function config(): CmsConfig { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-verbs-')) + dirs.push(dataDir) + return { dataDir, collections: [author, post, memo], blockTypes: [] } +} + +async function seeded(): Promise { + const cms = createCms(config()) + await cms.run(async () => { + await commitDocument('author', 'ada', { name: 'Ada', published: true }) + await commitDocument('author', 'bob', { name: 'Bob' }) + await commitDocument('post', 'hello', { + title: 'Hello', + slug: 'hello', + rank: 2, + secret: 's1', + author: 'ada', + published: true, + }) + await commitDocument('post', 'hola', { + title: 'Hola', + slug: 'hello', + rank: 3, + locale: 'es', + published: true, + }) + await commitDocument('post', 'draft', { + title: 'Draft', + slug: 'draft', + rank: 1, + author: 'bob', + }) + await commitDocument('memo', 'm1', { title: 'Memo', published: true }) + await stageWrite({ + collection: 'post', + docId: 'hello', + type: 'update', + doc: { title: 'Hello (staged)', slug: 'hello', published: true }, + actor: 'ada', + }) + }) + return cms +} + +const editor = () => accessContext({ session: as('editor'), mode: 'edit' }) + +describe('get', () => { + it('reads by id or locator, as the context sees it', async () => { + const cms = await seeded() + const pub = cmsAs(cms, publicContext()) + const byId = await pub.get({ collection: 'post', id: 'hello' }) + expect(byId).toEqual({ + id: 'hello', + collection: 'post', + doc: expect.objectContaining({ title: 'Hello' }), + }) + expect(byId?.doc).not.toHaveProperty('secret') + expect((await pub.get({ collection: 'post', locator: '/hello' }))?.id).toBe( + 'hello', + ) + expect(await pub.get({ collection: 'post', id: 'draft' })).toBeNull() + expect(await pub.get({ collection: 'post', locator: 'draft' })).toBeNull() + expect(await pub.get({ collection: 'post', id: 'missing' })).toBeNull() + expect(await pub.get({ collection: 'nope', id: 'hello' })).toBeNull() + }) + + it('reads the working copy in edit and preview modes', async () => { + const cms = await seeded() + const db = cmsAs(cms, editor()) + expect((await db.get({ collection: 'post', id: 'hello' }))?.doc.title).toBe( + 'Hello (staged)', + ) + expect((await db.get({ collection: 'post', id: 'draft' }))?.doc.title).toBe( + 'Draft', + ) + const live = cmsAs( + cms, + accessContext({ session: as('editor'), mode: 'live' }), + ) + expect( + (await live.get({ collection: 'post', id: 'hello' }))?.doc.title, + ).toBe('Hello') + expect(await live.get({ collection: 'post', id: 'draft' })).toBeNull() + }) + + it('matches a locator in the requested locale', async () => { + const cms = await seeded() + const db = cmsAs(cms, publicContext()) + expect( + (await db.get({ collection: 'post', locator: 'hello', locale: 'es' })) + ?.id, + ).toBe('hola') + expect( + (await db.get({ collection: 'post', locator: 'hello', locale: 'en' })) + ?.id, + ).toBe('hello') + }) + + it('hides collections the context may not read', async () => { + const cms = await seeded() + const viewer = accessContext({ session: as('viewer'), mode: 'edit' }) + expect( + await cmsAs(cms, viewer).get({ collection: 'memo', id: 'm1' }), + ).toBeNull() + expect( + (await cmsAs(cms, editor()).get({ collection: 'memo', id: 'm1' }))?.id, + ).toBe('m1') + }) + + it('populates only when asked (no default flip in this phase)', async () => { + const cms = await seeded() + const db = cmsAs(cms, publicContext()) + expect( + await db.get({ collection: 'post', id: 'hello' }), + ).not.toHaveProperty('relations') + const populated = await db.get({ + collection: 'post', + id: 'hello', + populate: true, + }) + expect(populated?.relations?.author).toEqual( + expect.objectContaining({ name: 'Ada' }), + ) + }) + + it('takes exactly one of id or locator', async () => { + const cms = await seeded() + const ctx = publicContext() + await cms.run(async () => { + await expect( + getAs(ctx, { collection: 'post' } as never), + ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + await expect( + getAs(ctx, { collection: 'post', id: 'a', locator: 'b' } as never), + ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + }) + }) +}) + +describe('list', () => { + it('lists what the context sees, with filters, sort, and paging', async () => { + const cms = await seeded() + const pub = cmsAs(cms, publicContext()) + const page = await pub.list({ collection: 'post', sort: { field: 'rank' } }) + expect(page.items.map((i) => i.id)).toEqual(['hello', 'hola']) + expect(page.total).toBe(2) + expect(page.items[0]).toEqual({ + id: 'hello', + collection: 'post', + doc: expect.not.objectContaining({ secret: 's1' }), + }) + expect( + (await pub.list({ collection: 'post', locale: 'es' })).items.map( + (i) => i.id, + ), + ).toEqual(['hola']) + expect( + ( + await pub.list({ collection: 'post', where: { rank: { gte: 3 } } }) + ).items.map((i) => i.id), + ).toEqual(['hola']) + + const first = await cmsAs(cms, editor()).list({ + collection: 'post', + sort: { field: 'rank' }, + limit: 2, + }) + expect(first.items.map((i) => i.id)).toEqual(['draft', 'hello']) + expect(first.nextCursor).toBeTruthy() + const second = await cmsAs(cms, editor()).list({ + collection: 'post', + sort: { field: 'rank' }, + limit: 2, + cursor: first.nextCursor, + }) + expect(second.items.map((i) => i.id)).toEqual(['hola']) + expect(second.nextCursor).toBeUndefined() + }) + + it('lists every readable collection without one', async () => { + const cms = await seeded() + const viewer = accessContext({ session: as('viewer'), mode: 'live' }) + const all = await cmsAs(cms, viewer).list() + expect(new Set(all.items.map((i) => i.collection))).toEqual( + new Set(['author', 'post']), + ) + }) + + it('pages 100 at a time by default and at most 500', async () => { + const cms = await seeded() + await cms.run(async () => { + const bag = await listInput.parseAsync({}) + expect(bag.limit).toBe(100) + await expect( + listAs(publicContext(), { limit: 501 }), + ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + }) + }) + + it('populates per item only when asked', async () => { + const cms = await seeded() + const db = cmsAs(cms, systemContext('test: populate')) + const plain = await db.list({ collection: 'post' }) + expect(plain.items.every((i) => !('relations' in i))).toBe(true) + const populated = await db.list({ + collection: 'post', + sort: { field: 'rank' }, + populate: true, + }) + expect(populated.items.map((i) => i.relations?.author ?? null)).toEqual([ + expect.objectContaining({ name: 'Bob' }), + expect.objectContaining({ name: 'Ada' }), + null, + ]) + }) +}) + +describe('the old verbs keep their defaults', () => { + it('legacy reads are unchanged', async () => { + const cms = await seeded() + await cms.run(async () => { + expect( + (await queryDocuments({ collection: 'post' })).items.every( + (i) => !('relations' in i), + ), + ).toBe(true) + expect(await readDocumentBySlug('post', 'hello')).not.toHaveProperty( + 'relations', + ) + }) + }) +}) + +describe('the registry', () => { + it('derives the agent tools from the canonical verbs', () => { + expect(readVerbs.map(agentToolName)).toEqual([ + 'get_document', + 'list_documents', + ]) + const tool = (name: string) => opSchemas.find((s) => s.name === name) + expect(tool('get_document')?.inputSchema).toBe(getInput) + expect(tool('list_documents')?.inputSchema).toBe(listInput) + expect(tool('read_document')?.description).toMatch(/^Deprecated/) + expect(tool('search_documents')).toBeDefined() + }) + + it('serves get and list as agent tools; read_document keeps its shape', async () => { + const cms = await seeded() + await cms.run(async () => { + const ctx = editor() + const got = (await runOp( + 'get_document', + { collection: 'post', locator: 'hello' }, + 'agent', + ctx, + )) as ReadResult + expect(got.doc.title).toBe('Hello (staged)') + const listed = (await runOp( + 'list_documents', + { collection: 'post', limit: 1 }, + 'agent', + ctx, + )) as ListResult + expect(listed.items).toHaveLength(1) + expect(listed.total).toBe(3) + const legacy = (await runOp( + 'read_document', + { collection: 'post', id: 'hello' }, + 'agent', + ctx, + )) as Doc + expect(legacy.title).toBe('Hello (staged)') + await expect( + runOp( + 'read_document', + { collection: 'post', id: 'missing' }, + 'agent', + ctx, + ), + ).rejects.toMatchObject({ code: 'NOT_FOUND' }) + expect( + await runOp( + 'get_document', + { collection: 'post', id: 'missing' }, + 'agent', + ctx, + ), + ).toBeNull() + }) + }) + + it('types the bound verbs', () => { + type Db = ReturnType + const bags = (db: Db) => [ + db.get({ collection: 'post', id: 'a' }), + db.get({ collection: 'post', locator: 'a' }), + // @ts-expect-error -- `id` and `locator` are exclusive + db.get({ collection: 'post', id: 'a', locator: 'b' }), + // @ts-expect-error -- one of them is required + db.get({ collection: 'post' }), + ] + expect(typeof bags).toBe('function') + }) +})