Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/access-context-threading.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
'@tanstack/search-cms': minor
---

Read through an explicit access context. An access context says who reads (the actor and permissions) and in which mode (`live`, `preview` or `edit`).

- `@tanstack/cms-core/server` exports:
- the `AccessContext` type and its builders: `publicContext()`, `accessContext({ session, mode, agent })`, `systemContext(reason)` (the reason is required), `previewContext`, `previewTokenContext` and `withMode`;
- the checks `canReadCollection`, `canReadDocument`, `assertReadable` and `redactFor`;
- the bound handle `cmsAs(cms, ctx)`, which accepts a `createCms` instance or the `defineCms` result;
- the `…As(ctx, …)` form of every read verb.
- `postRead` hooks receive `access`.
- Event handlers receive `access`, a system context naming the handler, and the outbox `cms` client reads as it (`cms.access`).
- `runOp(name, input, actor, access)` and `cmsTools(actor, { access })` run as an explicit context. A tool call's runtime context under `CMS_ACCESS_KEY` takes precedence.
- `@tanstack/cms-api`:
- builds one context per request with `requestAccessContext(request)`, and the `x-cms-read-mode` header narrows it;
- hands it to operations as `CmsOpContext.access`;
- runs WebMCP and `/api/mcp` as an agent context per request.
- `@tanstack/cms-api/start` builds the context from `getRequest()` and exports `getCmsAccessContext()` for app server functions.
- `@tanstack/cms-client`: `createCmsClient({ mode })` sends the read mode on every call and keys its cache by it.
- `@tanstack/search-cms`: `createCmsSearch({ access })` searches as the context (default `publicContext()`).

The old forms keep working: the `session`, `publishedOnly` and `publicRead` read options, `runWithSession`, and `createCmsSearch({ session, publishedOnly, publicRead })`. They are deprecated for reads.

Breaking: `CmsOpContext` has a required `access` field. Code that builds a `CmsOpContext` by hand, for example to call an op's `run` in a test, must add `access: accessContext({ session, mode: 'edit' })`. The interface functions (`executeInterface`, `submitInterface`, …) still take `{ session, actor }`.

Behaviour change: `getPublicDocument` now skips a draft the caller can't read and returns the next match. Previously that draft shadowed the match and the call returned `null`.
6 changes: 4 additions & 2 deletions .claude/skills/search-integration/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ objects; do not invent `text()`/`number()` builders. Declare
and arbitrary JSON need a custom adapter/derived scalar field. Non-facet
registry fields can support text filters, such as `notes`.

Register the collection with `defineCms`. On the server, resolve the current
session and create `createCmsSearch({ collection, session })` per request.
Register the collection with `defineCms`. On the server, build the caller's
access context and create `createCmsSearch({ collection, access })` per request
(`publicContext()` for anonymous search, which is the default, or
`accessContext({ session, mode: 'edit' })` for editors).
Keep publication, tenant, and authorization restrictions inside the adapter;
client filters are user selections and will be pruned for refinement counts.
Do not bypass the CMS read path to compute restricted facet counts.
Expand Down
4 changes: 3 additions & 1 deletion app/base/src/schema-registry.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,9 @@ export async function discardSchemaDraft(
return { ok: true }
})
}
export function publishedSchemas(ctx: CmsOpContext): PublishedSchemas {
export function publishedSchemas(
ctx: Pick<CmsOpContext, 'actor' | 'session'>,
): PublishedSchemas {
const config = getCmsConfig()
const registry = registryContext.getStore()!
return {
Expand Down
13 changes: 9 additions & 4 deletions app/base/tests/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { defineCms, normalizeSession } from '@tanstack/cms-core'
import {
accessContext,
approve,
closeStore,
createApiKey,
Expand Down Expand Up @@ -47,10 +48,14 @@ import {
} from '../src/operations.server'

let dir: string
const context = (role = 'admin'): CmsOpContext => ({
actor: 'human',
session: normalizeSession({ id: role, role, name: role }),
})
const context = (role = 'admin'): CmsOpContext => {
const session = normalizeSession({ id: role, role, name: role })
return {
actor: 'human',
session,
access: accessContext({ session, mode: 'edit' }),
}
}
const owner = {
email: 'owner@example.com',
name: 'Owner',
Expand Down
13 changes: 9 additions & 4 deletions app/base/tests/schema-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { beforeEach, afterEach, describe, it, expect } from 'vitest'
import { defineCms, getCmsConfig, normalizeSession } from '@tanstack/cms-core'
import type { CmsOpContext, Doc } from '@tanstack/cms-core'
import {
accessContext,
closeStore,
getStorage,
commitDocument,
Expand Down Expand Up @@ -32,10 +33,14 @@ import {
} from '../src/schema-registry.server'

let dir: string
const ctx = (role = 'admin'): CmsOpContext => ({
actor: role,
session: normalizeSession({ id: `test-${role}`, role }),
})
const ctx = (role = 'admin'): CmsOpContext => {
const session = normalizeSession({ id: `test-${role}`, role })
return {
actor: role,
session,
access: accessContext({ session, mode: 'edit' }),
}
}
const definition = (): CollectionDefinition => ({
name: 'customers',
label: 'Customers',
Expand Down
8 changes: 7 additions & 1 deletion app/base/tests/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
interfaceScheduleHandlers,
} from '@tanstack/cms-core'
import {
accessContext,
closeStore,
commitDocument,
submitInterface,
Expand Down Expand Up @@ -64,7 +65,12 @@ describe('Base background interface worker', () => {
password: 'worker-owner-password',
})
).user
const ctx = { actor: owner.id, session: normalizeSession(owner) }
const session = normalizeSession(owner)
const ctx = {
actor: owner.id,
session,
access: accessContext({ session, mode: 'edit' }),
}
const draft = await saveSchemaDraft(
{
definition: {
Expand Down
2 changes: 1 addition & 1 deletion app/prm/bakeoff/latest.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"ranAt": "2026-11-03T23:46:43.841Z",
"ranAt": "2026-11-06T03:03:19.126Z",
"mode": "fixture",
"winner": "exa",
"summary": {
Expand Down
37 changes: 28 additions & 9 deletions docs/api/cms-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ pnpm add @tanstack/cms-api @tanstack/cms-core

| Import | Contents |
| --- | --- |
| `@tanstack/cms-api` | `ops`, `allOps`, `findOp`, `invokeOp`, `invokeAnyOp`, operation types, media server functions, `cmsMcp`, AI helpers, the HTTP handlers, and the OpenAPI builder. |
| [`@tanstack/cms-api/start`](#tanstackcms-apistart) | One TanStack Start server function per operation, `callOp`, plus the media server functions. |
| `@tanstack/cms-api` | `ops`, `allOps`, `findOp`, `invokeOp`, `invokeAnyOp`, `requestAccessContext`, operation types, media server functions, `cmsMcp`, AI helpers, the HTTP handlers, and the OpenAPI builder. |
| [`@tanstack/cms-api/start`](#tanstackcms-apistart) | One TanStack Start server function per operation, `callOp`, `getCmsAccessContext`, plus the media server functions. |
| [`@tanstack/cms-api/http`](#tanstackcms-apihttp) | `createCmsApiHandler()`, the individual `handle*` functions, and `requestIdFor`, with no TanStack Start dependency. |
| [`@tanstack/cms-api/markdown`](#tanstackcms-apimarkdown) | `loadMarkdownDir()` and the frontmatter parser, for markdown files as a data source. No TanStack Start dependency. |

Expand Down Expand Up @@ -73,7 +73,7 @@ interface ResolvedOp<TInput = unknown, TOutput = unknown> extends CmsOperation<T
function invokeOp<N extends CmsOpName>(
name: N,
input: z.output<(typeof ops)[N]['input']>,
ctx?: CmsContext, // { request?: Request; actor?: string }
ctx?: CmsContext, // { request?: Request; actor?: string; access?: AccessContext }
): Promise<OpOutput<N>>

function invokeAnyOp(
Expand All @@ -86,9 +86,9 @@ function invokeAnyOp(
Runs an operation the way every transport does:

1. rejects cross-site requests that rely on cookies (`assertTrustedOrigin`),
2. resolves the session from `ctx.request`,
2. takes the caller's access context from `ctx.access`, or builds it from `ctx.request` with `requestAccessContext`,
3. enforces the operation's `access` (and the `ai` rate limit for `agent.use` operations),
4. runs it with the session bound, so nested agent tools see the same caller.
4. runs it with that context (`CmsOpContext.access`), so the operation and nested agent tools read as the same caller.

`invokeOp` is typed to the built-in `ops` table (`input` must already match the operation's schema; parse it with `ops[name].input` first when it comes from outside). `invokeAnyOp` looks up `name` in `allOps()` (built-in ops, agent tools, and app-defined `defineOp()` operations), validates `input` against the op's Zod schema, and runs it.

Expand All @@ -102,6 +102,17 @@ export async function publishedPosts(request: Request) {
}
```

### `requestAccessContext(request?, options?)`

```ts
function requestAccessContext(request?: Request, options?: { mode?: ReadMode; defaultMode?: ReadMode }): Promise<AccessContext>
const READ_MODE_HEADER = 'x-cms-read-mode'
```

Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public operations (`getPublicDocument`, `listPublishedDocuments`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents.

`agentActorName(surface, session?)` names the agent actor for a surface (`mcp`, `webmcp`, `content-agent`). It appends the session's `x-cms-agent` name, as in `mcp:claude`.

### `resolveAuthSession(request?)`

```ts
Expand All @@ -120,15 +131,15 @@ The caller's session plus the available AI features. This is the `getAuthSession
| `CmsOperation<TInput, TOutput>` | A built-in operation definition. |
| `ResolvedOp<TInput, TOutput>` | Any resolved operation from `allOps()` (`source: 'builtin' \| 'agent' \| 'app'`). |
| `OpAccess` | `'public' \| Permission`. |
| `CmsContext` | `{ request?: Request; actor?: string }`, the transport context. |
| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string }`, what `run` receives. |
| `CmsContext` | `{ request?: Request; actor?: string; access?: AccessContext }`, the transport context. |
| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string; access: AccessContext }`, what `run` receives. Read through `access` (`cmsAs`, `queryDocumentsAs`, `assertReadable`). |
| `MediaItem` | Re-exported from `@tanstack/cms-core/server`. |

---

## `@tanstack/cms-api/start`

One `createServerFn` per operation, with the same name, validating input with the operation's schema and running it through `invokeOp` with the current request. Plus `callOp({ data: { name, input } })` to run any operation in `allOps()` (including agent tools and app-defined `defineOp()` operations). They run in-process: no HTTP hop. `@tanstack/cms-ui-react` uses them for everything.
One `createServerFn` per operation, with the same name, validating input with the operation's schema and running it through `invokeOp` with the current request's access context (`requestAccessContext(getRequest())`). Plus `callOp({ data: { name, input } })` to run any operation in `allOps()` (including agent tools and app-defined `defineOp()` operations). They run in-process: no HTTP hop. `@tanstack/cms-ui-react` uses them for everything.

Call them with `{ data }`:

Expand Down Expand Up @@ -186,6 +197,14 @@ function Blog() {

Inputs and results match the [operations table](./routes-and-endpoints#operations). `/start` also re-exports the media server functions below and the operation types.

### `getCmsAccessContext(options?)`

```ts
function getCmsAccessContext(options?: { mode?: ReadMode }): Promise<AccessContext> // server-only
```

The current Start request's access context, for your own server functions: `cmsAs(cms, await getCmsAccessContext())`. It reads as the request's session, in `options.mode`, else the `x-cms-read-mode` header, else `live` (published only). Pass `{ mode: 'edit' }` to show signed-in editors the drafts they may read. See [Building Pages](../schema/building-pages#2-your-own-server-function-over-the-store).

### Media server functions

Exported from both `@tanstack/cms-api` and `@tanstack/cms-api/start`.
Expand Down Expand Up @@ -381,7 +400,7 @@ The frontmatter parser handles a YAML subset, one `key: value` per line: strings
const cmsMcp: ReturnType<typeof createMCPServer> // from @tanstack/ai-mcp/server
```

The CMS as an MCP server named `tanstack-cms`, exposing the agent tools (`cmsTools('mcp')`). `handleMcpApi` authorizes the request with `verifyMcpAccess` and then runs `cmsMcp.fetch(request)` with the caller's session bound. Mount `handleMcpApi`, not `cmsMcp` directly, so access checks and rate limits apply. See [HTTP MCP Server](../mcp/http-mcp-server).
The CMS as an MCP server named `tanstack-cms`, exposing the agent tools (`cmsTools('mcp')`). `handleMcpApi` authorizes the request with `verifyMcpAccess` and then runs `cmsMcp.fetch(request, access)` with the caller's agent context (`accessContext({ session, agent: agentActorName('mcp', session), mode: 'edit' })`). The tools are listed for that context, and every tool call reads and writes as it. Mount `handleMcpApi`, not `cmsMcp` directly, so access checks and rate limits apply. See [HTTP MCP Server](../mcp/http-mcp-server).

---

Expand Down
6 changes: 6 additions & 0 deletions docs/api/cms-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,13 @@ interface CmsClientOptions {
baseUrl: string // origin of the API handler, plus any mount prefix; a trailing slash is ignored
fetch?: typeof fetch // default: global fetch
getAuthHeader?: () => string | undefined | Promise<string | undefined> // called per request
cacheScope?: string // see "Cache scope" under @tanstack/cms-client/db
mode?: 'live' | 'preview' | 'edit' // read mode sent as `x-cms-read-mode`
}

interface CmsClient {
readonly cacheScope?: string
readonly mode?: 'live' | 'preview' | 'edit'
op<N extends CmsOpName>(name: N, input: OpInput<N>): Promise<OpOutput<N>>
call<T = unknown>(name: string, input?: unknown): Promise<T>
collection<C extends RegisteredCollectionName>(name: C): CmsCollectionClient<RegisteredDoc<C>>
Expand All @@ -59,6 +63,8 @@ const { items, total } = await cms.collection('post').published({ 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.

### `op(name, input)` and `call<T>(name, input?)`

`op(name, input)` calls any built-in operation by name: a `POST` with a JSON body to `<baseUrl>/api/cms/v1/ops/<name>`, resolving to the `result`. Input and output are typed per operation. `call<T>(name, input?)` hits the same endpoint for untyped or dynamic operations — including agent tools (`list_documents`, `search_documents`, …) and app-defined operations registered with `defineCms({ ops })`. The list of operations and their access levels is in [Routes & HTTP Endpoints](./routes-and-endpoints#operations).
Expand Down
Loading
Loading