Working on the SitecoreAI platform itself: OAuth auth, Agent, Pages, Publishing and Sites APIs, GraphQL schemas, Edge (admin webhooks, GraphQL capture), Sitecore CLI and serialization, search sources, languages, personalization, site templates, Marketer MCP page composition, brand voice and a read-only health check.

version
0.22.0
GitHub stars
12

Install

/plugin install sitecore-platform@sitecore-skills-pocs

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Chris1415/sitecore-skills-pocs.

Contents

Discovered from source

Skills 17

Agent API

Business-level actions on Sitecore content, experiments, personalization, and briefs. One call replaces 3–5 low-level Pages/Sites calls. Prefer this over the raw Pages/Sites APIs whenever the task maps to a marketer-level outcome.


Base URL

https://edge-platform.sitecorecloud.io/stream/ai-agent-api

(Unchanged from v1 — the spec servers block still lists this single production server.)

Auth & scopes

The Agent API uses a single security scheme: HTTPBearer — HTTP bearer with bearerFormat: JWT. Every operation in the spec is secured with HTTPBearer: [].

Client-credentials flow (default — service principal). OAuth 2.0 client-credentials → JWT Bearer. See the sitecoreai-auth skill for token acquisition (it is the source of truth for the host/token/scope mechanics):

  • Token endpoint: POST https://auth.sitecorecloud.io/oauth/token
  • grant_type=client_credentials, fixed audience=https://api.sitecorecloud.io
  • Forward the returned access_token as Authorization: Bearer {JWT} + Accept: application/json.
  • JWT lifetime is 24 h (expires_in: 86400) — cache per sitecoreai-auth § 5.

The client-credentials response carries scope: xmcloud.cm:admin.

Authorization-code flow (optional — user-delegated). The Agent API also supports the OAuth 2.0 authorization-code flow for acting as a user. This requires an OAuth app registration submitted to Sitecore Support, requesting these exact scope strings (from the spec's Authorization section):

ScopeCovers
xmcloud.cm:adminContent management (pages, content, components, assets, jobs)
personalize.exp:mngManage personalization experiences / experiments
personalize.tmpl:rRead personalization condition templates
personalize.pos:mngManage personalization point-of-sale / placement
ai.org.bri:rRead briefs (org scope)
ai.org.bri:wWrite briefs (org scope)
co.briefs:rRead briefs (collaboration)
co.briefs:wWrite briefs (collaboration)
ai.org.brd:rRead brand kits (org scope)
cmp.sites:readRead sites (added to the list by 2026-10)
platform.tenants:listList tenants (added to the list by 2026-10)

For most Marketplace apps and backend automations the client-credentials flow is correct and simpler; reach for authorization-code only when a per-user audit trail / per-user permissions are required.

Versioning

info.version is v2.0. Most paths are prefixed /api/v1/...; personalization now exposes a parallel /api/v2/... lane for the two endpoints that changed shape (create variant, list variants by page). The /api/v1 personalization create + list-by-page are deprecated (announced removal 2026-08-04) — use the /api/v2 equivalents. The /api/v1/briefs/generate endpoint is also deprecated (announced removal 2026-09-20) in favour of /api/v1/brief/generate. All three are past their date and still in the 2026-10-01 spec (deprecated: true); do not build on them.


Endpoints

Resource groups: Sites · Pages · Content · Components · Assets · Environments · Experiments · Personalization · Flow definitions · Brand Kits · Brand contexts · Briefs · Jobs.

The full path × method table is in references/endpoints.md; request bodies and key response fields per operation are in references/schemas.md. Both are regenerated from the spec — read them when you need an exact path, method or field name; the sections below carry what the spec does not say.

Errors

The spec declares one explicit error response per operation plus the bearer-auth default:

StatusMeaning
422Unprocessable entity — HTTPValidationError ({ detail: ValidationError[] }, each { loc, msg, type }). The catch-all for malformed bodies / bad params (e.g. a non-integer version).
401Unauthorized — implied by HTTPBearer; expired/invalid JWT. Re-auth per sitecoreai-auth § 6.
201Returned on successful creates (pages, content, components, datasources, experiments, personalization variants, briefs, flow-variant setup, job revert).

The spec does not enumerate 429 or 5xx shapes — rate limits are undocumented (see Pitfalls).


Patterns

Create a page with content in one sequence

  1. POST /pages/create → get pageId.
  2. GET /pages/{pageId}/placeholders/{ph}/allowed-components → find usable component IDs.
  3. POST /pages/{pageId}/components for each placement.
  4. POST /components/{componentId}/datasources → attach content.
  5. POST /pages/{pageId}/components/{componentId}/datasource → bind.

For bulk scenarios the higher-level "create_page_with_components" pattern combines these — check the OpenAPI spec for composite endpoints.

Language traps (measured 2026-10-02). DELETE /content/{id} removes every language version, and so does MCP delete_content {language}: the whole item went. Never use it to drop one language. add-language returns no version number. v2 has no translate operation (use Authoring translatePage or the Pages API; sitecoreai-localization).

Reverting an agentic action

The job id is client-supplied, not returned in the body: send a stable x-sc-job-id request header on every call of a sequence (the spec declares it on nearly every operation). To undo the whole sequence:

POST /api/v1/jobs/{jobId}/revert

This is the safety net for autonomous agents — always surface the jobId to the user and keep it for the audit trail.

Agent-driven personalization

Full recipe (audiences, COPY / SWAP / HIDE, publish, verify, undo): sitecoreai-personalization. The Agent-API-level facts:

  1. GET /personalization/condition-templates → pick a template (param keys = the placeholder labels in the template).
  2. POST /api/v2/personalization/{pageId}/versions with condition_groups → new flow + variant. Use v2 only: the deprecated v1 create (single condition_template_id + flat condition_params) returned 400 "Failed to update flow definition" for the multi-param utm_value template on 2026-09-22, where the identical params succeeded on v2. The flow is PRODUCTION at create and its supplied name is replaced by <page> <lang> - <PAGEID>.
  3. POST /flows/{flowId}/variants/{variantId} (COPY / SWAP / HIDE) and POST /flows/{flowId}/variants/reset (undo one component).
  4. POST /personalization/{pageId}/components/{componentId}/hide hides a component on the default variant; it needs an existing personalization on the page.

Two variant ids — the variant endpoints want the 32-hex one. A flow carries transpiledVariants[].ref (dashed uuid, the "variant ref") and the template variant id (32-hex, no dashes, in templateRenderTask.input.template / traffic.splits[].template). The spec text says to pass the ref; live, GET /flows/{flowId}/variants/{variantId} with the dashed ref returns 400 "Requires template Variant Id, not variant ref", and the setup write succeeded with the 32-hex id (2026-10-01).

"None" is a 404. GET /api/v2/personalization/by-page/{pageId} on a page with no personalization returns 404 Not Found, not []. Treat it as "none"; GET /flows/by-page/{pageId} returns [] and is the better existence check.

No delete, pause or archive for experiences. There is no endpoint to remove an EXPERIENCE flow; PUT /experiments/{flowId} with archived: true on one returned 500 and changed nothing. reset leaves a Default-only ruleset in __Final Renderings, and the flow keeps answering decisions. Removal is a Pages UI task — tell the user.


Screenshot endpoint quirks

Confirmed empirically + via the OpenAPI bundle (a Marketplace app build, 2026-04-22). The public reference is silent on all three; document them here until upstream fixes land.

Query parameters:

ParamTypeRequired?DefaultNotes
versionintegeryes—Must be an integer. "latest" returns 400 "Input should be a valid integer"; omission returns 400 "Field required". Pass 1 when you don't want to surface a version selector.
widthintegerno1200Rendered viewport width (also controls output image width).
heightintegerno—EXACT output-image height — not a viewport hint, not a minimum. Taller page content is cropped; shorter content gets solid-color padding at the bottom. Consumers who want "whole page" must pick a generous value (4000–8000 px) and trim whitespace client-side.
languagestringnoenLanguage code for the rendered page.

No fullPage query parameter exists. The fullPage: true field in the response body (below) is informational only — it describes rendering mode, not a togglable input. Do not document it or pass it as a query param.

Response body shape:

{
  "type": "png",
  "fullPage": true,
  "encoding": "base64",
  "timestamp": "2026-04-22T13:47:00.233131",
  "screenshot_base64": "<base64 string>"
}

The image payload is under screenshot_base64 — not image, not data. The string is bare base64 (no data:image/png;base64, prefix); add the prefix client-side if you need a data URL.


Pitfalls

  • JWT expires in 24 h. Cache per the sitecoreai-auth skill, § 5.
  • All requests are production. No sandbox audience.
  • x-sc-job-id is mandatory for audit. A call made without it cannot be reverted as part of a job.
  • Composite endpoints return partial success. A POST /pages/create that succeeds in page creation but fails on a follow-up component add will still return a 201 on the page. Always check the operations array in the response or via GET /jobs/{jobId}/operations.
  • Site context is required for most page-level reads (GET /pages/search, GET /components). Passing siteId vs. siteName differs per endpoint — always check the path.
  • Rate limits undocumented. Implement exponential backoff on 429 + 5xx.

OpenAPI bundle

Full schema: api-docs.sitecore.com/_bundle/sai/agent-api/@v2.0/index.yaml. The Agent API bundle is version-pinned: the unversioned _bundle/sai/agent-api/index.yaml returns 404.

Sources

SitecoreAI API Authentication

All four SitecoreAI APIs use the same OAuth 2.0 client-credentials flow. Authenticate once, reuse the pattern everywhere.


0. Credential-acquisition protocol (MANDATORY before implementing any API call)

Whenever a task involves calling any SitecoreAI API, the agent must resolve client_id and client_secret before writing implementation code, in this order:

  1. Ask the user directly, upfront. One question, offered as a choice:

    "This app will call the SitecoreAI . To authenticate I need a client_id and client_secret from an Automation Client in Cloud Portal. Options: (a) paste them now, (b) I don't have them — use whatever is in .env / .env.local, (c) leave blank, I'll provide them later."

  2. If (a): write the values to .env.local (never commit) under the three-segment naming pattern below. Do not echo the secret back to chat.
  3. If (b): read .env.local → .env in that order. If either variable is present, use it. If both are empty or missing, escalate to step 4.
  4. If (c), or if (b) finds nothing: leave the variables blank in the env file and report this as a missing piece in the final summary / task report. Do not invent placeholder values, do not scaffold fake credentials, do not skip auth silently. The app can still be scaffolded and compiled; the first real API call will 401 until the user supplies credentials — that is the correct failure mode.

This protocol applies to every task that touches Agent, Pages, Publishing, or Sites API. Skipping it means the dev loop stalls later on a 401 the user has to diagnose themselves — the exact friction this skill exists to prevent.

0a. Env-var naming — three-segment convention

Use three segments so a single project can hold multiple, purpose-distinct automation clients without name collisions:

SITECORE_<PURPOSE>_CLIENT_ID
SITECORE_<PURPOSE>_CLIENT_SECRET

Where <PURPOSE> names the scope of calls that credential covers. Common values:

<PURPOSE>ScopeExample var
DEPLOYDeployment, screenshot / proxy-to-Agent-APISITECORE_DEPLOY_CLIENT_ID
CMAuthoring GraphQL and the XM Apps Pages API (the deploy client returns 500 on GET /pages/{id}/state, measured 2026-08-12)SITECORE_CM_CLIENT_ID
AIAI-driven API calls — Brand Management, Brand Review, Pipeline (future)SITECORE_AI_CLIENT_ID
CDPStandalone Sitecore CDP / Personalize REST (api-engage-{region}), only with a separate CDP/Personalize licence. Not needed for SitecoreAI embedded analytics or personalization (see § 0b)SITECORE_CDP_CLIENT_ID
EDGEEdge Admin API (webhooks, Edge settings, cache clear). Needs an Edge administration client (one per environment; created in Deploy or by POST https://xmclouddeploy-api.sitecorecloud.io/api/clients/v1/edge with an org automation client, live 2026-10-02), not an automation client: org and environment automation clients get 401 edge.cdn.11 … Failed to find tenant. See sitecoreai-edge-admin-webhooksSITECORE_EDGE_CLIENT_ID (per environment SITECORE_EDGE_<ENV>_CLIENT_ID)
bespokeAny other integration with its own automation clientSITECORE_<SLUG>_CLIENT_ID

The credential-acquisition protocol above stays the same — just rename the placeholders in your examples to match the purpose of the client. A project that calls both Agent API (for deploy / screenshot) AND, later, the AI-driven APIs will want two separate automation clients with distinct scopes, each under its own SITECORE_<PURPOSE>_CLIENT_* pair.

0b. Personalization and analytics: which credential (none, usually)

Do not ask for a CDP client for a SitecoreAI site. Embedded personalization and analytics split three ways:

NeedCredential
Runtime: page views, events, personalize decisions from the head app (Content SDK proxy, Bootstrap, CdpPageView)None. Only the public Edge context id, sent as x-sitecore-contextid (SITECORE_EDGE_CONTEXT_ID / NEXT_PUBLIC_SITECORE_EDGE_CONTEXT_ID). No OAuth, no client key: client_key / point of sale are derived server-side
Management: create / update variants, audiences, A/B testsAgent API (v2 personalization endpoints) with an environment-scoped automation client, token as § 3. An org-level client gets 401 on edge-platform.sitecorecloud.io and xmapps-api endpoints. The Marketer MCP uses the signed-in user's OAuth, no client at all
Standalone CDP / Personalize REST (/v3/flowDefinitions etc.)A SITECORE_CDP_* client, only for customers licensed for standalone CDP / Personalize

Delegated (authorization-code, § 7) apps that manage personalization through the Agent API need these scopes beyond the default: personalize.exp:mng, personalize.tmpl:r, personalize.pos:mng, cmp.sites:read, platform.tenants:list. Client-credentials tokens from an environment client already carry what the Agent API needs (xmcloud.cm:admin in the token scope).

Backend workflow: sitecoreai-personalization. Head-app wiring: content-sdk-personalization.

Earlier skill revisions (and some older examples further down this page) used the two-segment SITECORE_CLIENT_ID / SITECORE_CLIENT_SECRET. Treat those as legacy — new projects should adopt the three-segment pattern from day one.


1. Prerequisites

  • Role: Organization Admin or Owner in Sitecore Cloud Portal. Without this role, the automation-client form is hidden.
  • Tenant: You authenticate against a SitecoreAI tenant. The client is scoped to that tenant.
  • Secure storage: Prepare a secret store (AWS Secrets Manager, Doppler, Vercel env vars, .env.local for dev) before creating the client — the secret is shown once.

2. Create an automation client

  1. Cloud Portal → your tenant → Settings → Automation clients (sometimes labelled "Application access" / "Client credentials" depending on the portal rev).
  2. Click Create client, give it a descriptive name (e.g. myapp-prod-agent-api).
  3. Select Scopes required for the APIs you will call. Grant only what you need:
    • Agent API / Pages API / Sites API: generally covered by the default XM Apps scopes granted to automation clients.
    • Publishing API: requires additional xmcloud.cm:admin for application tokens. Read vs. write vs. limited-write is differentiated by :r, :w, :wl scope suffixes.
  4. Copy both the client_id and client_secret immediately — the secret disappears on refresh.

3. Token request

POST https://auth.sitecorecloud.io/oauth/token
Content-Type: application/x-www-form-urlencoded

client_id={CLIENT_ID}
&client_secret={CLIENT_SECRET}
&grant_type=client_credentials
&audience=https://api.sitecorecloud.io

Response (abbrev.):

{
  "access_token": "eyJhbGciOi...",
  "token_type": "Bearer",
  "expires_in": 86400
}
  • Lifetime: 24 hours (expires_in: 86400).
  • Audience is fixed: https://api.sitecorecloud.io for all four APIs. Do not substitute the API's base URL — it will return 401.

4. Calling an API

GET https://xmapps-api.sitecorecloud.io/api/v1/sites
Authorization: Bearer {access_token}
Accept: application/json

Accept: application/json is required by the Pages API and is good practice everywhere.

5. Token caching (mandatory in production)

A fresh token per request will hit the auth endpoint's own rate limits and add ~200 ms latency. Cache aggressively.

Minimal reference implementation (TypeScript):

// token-cache.ts — reusable across all four SitecoreAI APIs
type Cached = { token: string; expiresAt: number };
let cached: Cached | null = null;

async function fetchFreshToken(): Promise<string> {
  const res = await fetch("https://auth.sitecorecloud.io/oauth/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      client_id: process.env.SITECORE_DEPLOY_CLIENT_ID!,
      client_secret: process.env.SITECORE_DEPLOY_CLIENT_SECRET!,
      grant_type: "client_credentials",
      audience: "https://api.sitecorecloud.io",
    }),
  });
  if (!res.ok) throw new Error(`Sitecore auth failed: ${res.status}`);

  const { access_token, expires_in } = await res.json() as { access_token: string; expires_in: number };
  cached = { token: access_token, expiresAt: Date.now() + expires_in * 1000 };

  // Log the tenant identifier on every cold-cache fetch. This must live
  // INSIDE fetchFreshToken — NOT at the route-handler call site, which has
  // no observable signal to distinguish cold-cache from warm-cache hits
  // and would therefore log on every request.
  const sub = decodeJwtSub(access_token); // Auth0 client-credentials puts
                                          // the client_id in `sub` with the
                                          // `@clients` suffix, e.g.
                                          // `<client_id>@clients`
  if (sub) console.log(`[app-name] tenant=${sub}`);

  return access_token;
}

export async function getSitecoreToken(): Promise<string> {
  const now = Date.now();
  if (cached && cached.expiresAt - now > 60_000) return cached.token;  // 1-min safety margin
  return fetchFreshToken();
}

Tenant-id logging placement (a Marketplace app build, 2026-04-22). If you emit structured logs tagging each request with the tenant identifier on first successful auth, the log call belongs inside fetchFreshToken() — not at the route-handler call site. The route handler cannot distinguish a cold-cache fetch from a warm-cache hit, so logging there fires on every request (noisy + gives a false impression of per-request auth).

Which claim carries the tenant id? Sitecore's Auth0 tenant follows the Auth0 client-credentials convention: the sub claim of the access-token JWT contains the automation client's client_id with a @clients suffix (e.g. <client_id>@clients). Decode sub (no signature verification needed — the cache trusts the JWT because it just came back from the token endpoint). If sub is empty or missing, fall back to tid if present; otherwise skip the log. Never log the bearer token or the full JWT — only the sub claim.

For multi-instance deployments, promote the cache to Redis / a KV store keyed by client_id to avoid one token-refresh per instance.

6. Handling 401

A 401 Unauthorized on a previously-working request almost always means the token expired between the cache-check and the upstream call (clock skew, long-running request). Strategy:

  1. Invalidate the cache.
  2. Retry the original request once with a fresh token.
  3. If the second call also 401s, fail loudly — credentials or scopes are wrong.

Do not retry more than once. A persistent 401 is a configuration bug, not a transient fault.

7. Alternative: OAuth 2.0 authorization code flow (Agent API only)

The Agent API also supports user-delegated access via the authorization-code flow, registered through Sitecore Support. Use this when the caller needs to act as a user (audit trail, per-user permissions) rather than as a service principal. For most Marketplace apps and backend automations, the client-credentials flow above is correct and simpler.

8. Pitfalls

  • Environment client, not org client. Agent, Pages and Sites APIs reject an org-level automation client with 401; create the client on the environment.

  • Secrets viewable once. Creating a second secret without storing the first means creating a third client.

  • Audience must be literal. https://api.sitecorecloud.io — not .com, not trailing slash, not the API base URL.

  • Token is tenant-scoped. A token from tenant A cannot read tenant B.

  • Production only. No sandbox audience. Destructive endpoints (e.g. DELETE /collections/{id}) affect live content immediately.

  • Accept: application/json is required by Pages API; omitting it returns 406.

  • Clock skew on the caller can make the cache think the token is valid when Sitecore rejects it. Always keep a 60 s safety margin as in the snippet above.

Sources

Brand voice — write as the brand, from what the spec says

sitecoreai-content-composition decides which components go on the page. This skill decides how the words in them sound: the voice belongs to the brand, and it comes from a written source. The agent's own taste is not a source.

When to use

  • Filling a Sitecore page or component with copy for a brand or client site.
  • Reviewing authored content against the brand it was written for.
  • Writing the "Brand voice and identity" section of a PRD or spec.

Not for: which components to use (sitecoreai-content-composition), reference documentation, or a person's own blog voice.

Step 1 — Find the source, in this order

  1. The PRD or spec. Look for its "Brand voice and identity" section (template below). This wins, because it is what was agreed for this build.
  2. A Sitecore brand kit or brand context, through the Marketer MCP: list_brand_contexts, get_brand_context, get_brand_context_items, list_brandkits, get_brandkit_by_id. An empty list is a normal result: many environments have none.
  3. Guidelines the user points you at, such as a linked document or an existing site.

If none of them exists, stop and ask. Do not invent a personality. Offer to write the spec section with the user, then continue. If the user wants placeholder copy for a build test, use the technical-neutral register and say that the copy is a placeholder.

If two sources disagree, follow the spec and name the conflict in your output.

Step 2 — Pick the register

The register is how it sounds. The brand is whose voice it is. Take the register from the spec for that surface; otherwise use the default for the surface and say so.

RegisterUse forDialsAvoid
brand (default for site copy)Page copy on the brand's surfaceThe spec's voice attributes, vocabulary and toneAny voice the spec does not describe
marketingLaunch, landing or campaign contentBenefit first; second person; superlatives earned by specifics; rhythmic and tight; imperative closersEmpty buzzwords, walls of text, hedging
technical-neutralDocumentation, specs, legal or factual contentThird person or imperative; no emoji; flat, precise statements of behaviour, inputs and limitsPersonality, persuasion, hype

State the register and the source at the top of your output, so a reviewer can check the choice:

Register: brand | Source: spec, "Brand voice and identity"

Step 3 — Write to the slot

  • Fit the field. Read the component's fields first and write to them: an eyebrow is a few words, a heading is one line, and a body field can hold a paragraph.
  • Claims need a source. Use only the facts, numbers, prices and customer names the spec or the brand's material gives you. Mark anything else as needing confirmation; never present it as fact.
  • Identity reaches past the words. Image alt text and any imagery brief follow the spec's visual identity.
  • Language. Write each locale as native copy for that market. Do not translate word for word if the spec gives a tone for that locale.

Generic AI tells to avoid, in every register

  • "In today's fast-paced world…", "Let's dive in", "It's worth noting that", "In conclusion", "Unlock the power of…".
  • Hedging everything, or a balanced "on one hand… on the other" that never takes a position.
  • Superlatives with nothing concrete behind them.
  • Uniform paragraph lengths and repeated sentence shapes.

Spec template: "Brand voice and identity"

Put this in the PRD or spec. It is short on purpose, and every field is something a writer or a reviewer can check against.

## Brand voice and identity

- **Brand and surface:** whose site this is, and which sites or pages this covers
- **Source:** brand kit or brand context id, guidelines link, or "defined here"
- **Audience:** who reads it, and what they already know
- **Voice attributes:** three to five, each with a line on what it means in practice
- **Tone by surface:** for example hero: confident; forms: plain; errors: calm
- **Vocabulary:** words to use, and words to avoid
- **Claims allowed:** facts, numbers and names that may be stated, and what needs sign-off
- **Register default:** brand, marketing or technical-neutral
- **Example:** two or three sentences that sound right
- **Visual identity:** palette, typography and imagery direction, or where they are defined

Check before you hand it over

  • The source is named, and it exists.
  • The copy could not belong to a different brand with the name swapped out.
  • Every number, price and customer name traces back to the source.
  • Each text fits its field on the rendered page, read in preview.

Relationship to other skills

  • sitecoreai-content-composition — the page structure and the Marketer MCP write recipe. Load it together with this skill when authoring a page.
  • sitecoreai-localization — language versions and per-locale publishing.
  • sitecoreai-agent — the API behind the Marketer MCP, including brand kits, brand contexts and briefs. Brand review is in marketplace-sdk-ai.

Sitecore CLI — Cloud Workflow

A first-time login + connect + pull against a SitecoreAI Cloud environment touches at least four undocumented traps. This skill captures the canonical order, the exact commands, and the fixes for each trap so the user never has to discover them again.

When to use

  • User asks to "pull items from the tenant," "ser pull," "connect the playground to SitecoreAI," "login to Sitecore CLI," or anything that requires serialization commands against a live Cloud env.
  • Setting up a new local project that needs to mirror authoring state from a CM instance.
  • Diagnosing "Environment default was not defined" or "Environment is not configured to allow writing data" errors.

How to perform

Run these in order from the directory containing sitecore.json:

  1. Device-flow login. dotnet sitecore cloud login. Prints a URL + device code; user authenticates in a browser. Token persists in .sitecore/user.json under endpoint xmCloud.
  2. Find the project ID. dotnet sitecore cloud project list — prints every project the user's org can see. There is no --name filter; grep by name yourself. Capture Project Id (e.g. <22-character id>).
  3. List environments for that project. dotnet sitecore cloud environment list --project-id <PROJECT_ID>. --project-id is REQUIRED — the command errors without it. Capture Environment Id and Environment Name.
  4. Connect to one environment. dotnet sitecore cloud environment connect --environment-id <ENV_ID>. This appends a new endpoint to .sitecore/user.json named after the environment (e.g. "prod"). It does NOT set this as the default; defaultEndpoint remains "default", which doesn't exist.
  5. Patch user.json. Open .sitecore/user.json and set "allowWrite": true on the new endpoint (otherwise even read commands like ser pull are blocked). Optionally set "defaultEndpoint": "<env-name>" so subsequent commands work without -n.
  6. Pull. dotnet sitecore ser pull -n <env-name> (or omit -n if you patched defaultEndpoint). Output lists items added/updated/deleted ([A], [U], [D]).

Hard Rules

  • cloud project list outputs prose, not JSON. Use --json if you need structured output for piping. There is no name filter — grep yourself.

  • cloud environment list requires --project-id. Get it from step 2.

  • cloud environment connect does not update defaultEndpoint. Either pass -n <env-name> on every subsequent command, or hand-edit user.json to set defaultEndpoint to the new endpoint key.

  • allowWrite: false blocks ser pull, not just push. The CLI treats local filesystem writes as "writes." Set allowWrite: true on the endpoint before pulling.

  • The connect command supports --allow-write flag at connect time — pass -aw (--allow-write) to skip the user.json edit step.

  • Never commit .sitecore/user.json. It contains an access token + refresh token. Verify it is .gitignore'd.

  • Endpoint name in user.json matches Environment Name from the list output, not the ID. So if the env is named "PROD" the endpoint key is "prod" (lowercased by the CLI in some versions — read the file after connect to confirm).

  • Run the repo-local tool, never a global one: dotnet tool run sitecore …. A global sitecore.cli (5.2.109) shadowed the repo's pinned local CLI, then refused to load the Serialization / Publishing plugins at the sitecore.json pin (6.0.23) and at the only version plugin add offered (7.0.24): "Plugin is not supported by the current version of the CLI". dotnet tool run sitecore (6.0.23, from .config/dotnet-tools.json) worked (measured 2026-09-28).

  • Never bump one plugin pin in sitecore.json on its own. Plugin versions track the CLI major. Move the CLI in .config/dotnet-tools.json and every Sitecore.DevEx.Extensibility.* pin together, or not at all.

A pull that finds 0 changes is not proof the tree is in sync

ser pull diffs by revision, not by value. A live write that does not bump __Shared revision / __Revision is invisible to the pull, which reports "Discovered 0 changes" while the tenant and cm/ disagree. Measured twice in one build (2026-09-27 → 28): a rendering registered live but missing from the serialized Renderings field, and three renderings newline-joined into it, both with disk and live revisions identical.

  • After a raw live write, grep the pulled YAML for the new value. A "0 changes" result proves nothing about a field you just wrote.
  • To force it through, re-write the field with a normal updateItem (a real value change, such as normalising a GUID's format). That bumps the revision, and the next pull applies it.
  • Re-pull after the LAST live write of a unit of work, not just after the write that prompted the pull. A fix applied after the pull stays live-only until the next one.

Pushing into a CM that builds from the repo (items as resources)

A repo-deployed CM serves serialized items as read-only resources; a CM edit makes a DB copy that silently wins over git forever after. Before any push to such a CM, read references/serialization-overlays.md. The short form:

  • ser push skips items that exist only as resources (90 of 1,026 written in one module), so it is not a way to materialize a module into the DB.
  • A DB-only item at a git item's path (a CM-generated site thumbnail, a duplicate template folder) aborts push AND pull with NonUniquePathException; clear it first, in the order the reference gives.
  • Measure overlays by __Revision as well as values; --trace truncates long values, so a "byte-identical" blob may be a prefix compare.
  • -n <endpoint> and -i <module> on every op, the endpoint host asserted, --what-if --trace first, every [D] explained.

Moving a site's delivery to another tenant (probe → clean → push → publish → parity → repoint → revert): references/estate-move.md.

Adjacent: reading an environment's git link from the Deploy API

GET /api/environments/v1/{id} carries no repositoryDetails. Read the link (repositoryDetails, repositoryBranch, deployOnCommit) from GET /api/environments/v2/{id}. A v1 read reports every environment as unlinked.

Stop Conditions

  • Stop and ask if cloud project list returns multiple projects whose names look plausible — never guess. The org may have 10+ projects.
  • Stop and ask if the environment list shows multiple envs (e.g., PROD + solo-website + ...). The right env is the one whose Environment Host matches the host in the existing layout response (or the host in .env.local's SITECORE_API_HOST if set).
  • Do not enable push (--allow-write on connect, or hand-toggling endpoint to allowWrite=true with intent to push) without explicit user approval. Pulls are recoverable; pushes overwrite tenant state.
  • Do not delete .sitecore/user.json to "reset" — it carries the live token. Re-login from scratch if reset is needed.

Verification

  • After step 6, the pull output should end with [<env>] Changes have been applied to serialized items (N subtrees). and a [roles] + [users] summary. If you see [<env>] Discovered 0 changes after evaluating N total items. and no errors, nothing with a newer revision exists on the tenant. That is not the same as "in sync" (§ A pull that finds 0 changes).
  • The CLI updates .sitecore/user.json with "lastUpdated" and a fresh accessToken on each command — that's expected.

Related

  • sitecoreai-serialization — module DESIGN: what to serialize, include scope and push policy, one module per collection in its own folder, items-as-resources vs scsModules, the push that stops at a missing template. Read it before creating or changing a *.module.json.
  • setup-content-sdk — canonical scaffold; CLI must be installed before this skill applies.
  • content-sdk-debug-layout-probe — useful after pull to compare local YAML vs live layout response.

References

Sitecore Content Composition — inventory-first, via the Marketer MCP

Filling one field is half of content authoring. To manage content on a page properly, understand the site's existing components — what they are, what content they take, and how they look — then compose: select and order components for a coherent page structure, fill each from a content POV and a visual/structural POV.

When to use

  • Authoring or extending a Sitecore page (not a single field edit) via the Marketer MCP.
  • Pairs with sitecoreai-brand-voice (the words / register) — this skill is the structure (which components, in what order, with what content shape).

The principle: inventory BEFORE you compose

Never compose from assumptions about what components exist. Read the live palette first; the field names are case-sensitive and the child shapes are non-obvious.

Step 1 — Inventory the palette (Marketer MCP)

Prefer a Components Map if one exists (a project-local inventory with variants + screenshots + when-to-use). Use the inline inventory below only when no map exists.

  1. list_sites → the site id + name.
  2. get_all_pages_by_site(siteName) → the existing page tree (also your structural reference for how real pages are built).
  3. For 1–3 representative existing pages: get_components_on_page(pageId) → which components exist, their rendering IDs, the placeholder (/headless-main), and each rendering's ComponentQuery (which reveals the datasource + child field names).
  4. For every child-bearing component, read a sample datasource: get_content_item_by_path("…/Home/Data/<Component>") → the parent template ID, the child template ID, and the exact (case-sensitive) field names. Flat components only need their parent template/fields.
  5. Look-and-feel: get_page_screenshot(pageId, version) — note: the PNG comes back as a large base64 blob that often exceeds tool limits; when it does, fall back to the live preview URL (get_page_preview_url) for the user to eyeball, and describe look-and-feel from component role + real sample content.
  6. Cache the result as a component catalog (component → role/when-to-use → parent fields → child template+fields → look&feel). Reuse it for the whole authoring session.

Step 1.5 — Check what each placeholder ALLOWS (the guardrail)

Sitecore placeholders are governed by placeholder settings — each placeholder has an allowed-renderings set. The Marketer MCP exposes it directly: get_allowed_comps_by_ph(pageId, placeholderPath) returns the rendering IDs permitted in that placeholder. Placing a rendering a placeholder does not allow either fails or produces an invalid / uneditable layout in Pages — so this is a real guardrail, not a nicety.

Policy — enforce vs ignore (the user's call; default = enforce). Persist the choice with the authoring session:

  • Enforce (default — "follow the rules"): for every rendering you plan to place, resolve its target placeholder and call get_allowed_comps_by_ph; place the rendering only if it is in the allowed set. If a component you wanted is not allowed there, do not force it — pick an allowed alternative that serves the same intent, or surface it to the user (never silently drop the section). For structural components, re-check the inner placeholder's allowed set before filling it.
  • Ignore ("add renderings as you think"): the user has waived the rule — compose by best-fit judgement regardless of the allowed set, but still record each placement that falls outside get_allowed_comps_by_ph as a deviation in your report.

Resolve the allowed set per placeholder (the body placeholder is usually /headless-main; structural components expose their own inner placeholders with their own allowed sets) and cache it alongside the component catalog for the session.

Step 2 — Compose for structure + look-and-feel

  • Pick components by intent, and order them into a page arc: opener (Hero) → substance (prose / grids) → proof (stats / testimonials) → close (CTA).
  • Mirror the site's heading pattern. Many marketing sites use an Eyebrow (small kicker) + a Heading whose tail is split into HeadingAccent (the emphasized/colored continuation) — e.g. "Obsession you can " + "taste." Read a real page first; do not invent the field split.
  • Match the words to the brand: sitecoreai-brand-voice takes the voice from the PRD or spec, and sets the register.

Step 3 — Author each component (the write recipe)

  • Before each add_component_on_page, apply the Step 1.5 policy. In enforce mode, confirm componentRenderingId is in get_allowed_comps_by_ph(pageId, placeholderPath) for the target placeholder; if it is not, substitute an allowed component or surface it to the user — never force-place it. In ignore mode, place it but log the deviation (rendering + placeholder + "outside allowed set") in your report.
  • add_component_on_page(pageId, componentRenderingId, placeholderPath: "/headless-main", componentItemName, fields) → adds the rendering and creates a local parent datasource with the flat fields. Returns the datasourceId. The MCP auto-sets GridParameters + DynamicPlaceholderId to match siblings. Read back WHERE the datasource landed (datasourceLocation on the response / get_content_item_by_path) — do not assume it matched your local-vs-global intent (next section).
  • For child-bearing components: per child, create_content_item(name, templateId: <child template>, parentId: <datasourceId>, fields).
  • Verify (integration boundary): get_components_on_page (component set + order) and get_content_item_by_path (parent fields + children landed). Re-read; don't trust the write call.
  • Publishing is a separate explicit step (Publishing REST / sitecoreai-publishing); Preview renders unpublished.

Local vs global datasources — the reuse check (WHERE the datasource item lives)

Every datasource-backed rendering can store its content in either home, and Sitecore offers both:

  • the page's own ./Data folder — always available, for every such rendering;
  • the global per-component container under the site Data node — available because the rendering's Datasource Location field lists it as an additional root. That field adds roots; it does not remove the local one or pick a winner.

So placement is your decision, per datasource — make it deliberately, not by accepting whatever the write produced.

ContentHomeWhere
Page-specific (default)LOCAL<Page>/Data/<Component> — folder template Page Data {1C82E550-EBCD-4E5D-8ABD-D50D0809541E}, created on demand under the page
Genuinely reused on ≥2 pagesGLOBAL/<COLLECTION>/<SITE>/Data/<Component Folder>/<Item> — the folder item built from that component's folder template (insert options allow only its datasource). Author once, bind each placement with set_component_datasource
Partial-design chrome (Header, Footer, promo/utility bars)ALWAYS LOCALunder the Partial Design item — it is chrome inherited via the Page Design, not reused content

Decide in the PLAN, not mid-write. The Marketer MCP has no move/rename primitive, so promoting later means re-creating the item. After composing the page set, run a cross-page reuse pass over the planned datasources: anything the plan places on ≥2 pages becomes one global item; everything else stays local. When unsure, stay local — a single-page datasource is cheap to promote, a wrongly-global one clutters the shared Data folder and invites accidental edits across pages.

The two recipes (verified live, 2026-07-27)

LOCAL — one call, no cleanup:

add_component_on_page(pageId, renderingId, "/headless-main", componentItemName, fields)

It always writes <Page>/Data/<componentItemName> (local:/Data/X in the layout) and auto-creates the page's Data folder if absent. It ignores the rendering's global Datasource Location. Spaces in componentItemName become underscores.

GLOBAL — create in the container, rebind, delete the stray:

1. create_content_item(name, templateId: <DS template>, parentId: <component's global container>)
2. add_component_on_page(...)                      // still makes a local datasource
3. set_component_datasource(pageId, componentId, datasourceId)
4. delete_content(<the local datasource step 2 created>)

Step 4 is mandatory, not tidy-up: there is no way to place a component without producing a local datasource — omitting fields still creates an empty one.

Reuse on page 2..n: search_component_ds(component_id, term) to find the shared item, then the same add → rebind → delete-stray sequence. Filter the hits by path — the search matches on the datasource template, so it returns page-local items from other pages too, not just shared ones.

LOCAL when add_component_on_page is NOT the creator — you must build Data yourself:

1. ensure <Page>/Data exists   // createItem(name:"Data", templateId:{1C82E550-EBCD-4E5D-8ABD-D50D0809541E}, parent:<pageId>)
2. create_content_item(name, templateId: <DS template>, parentId: <that Data item>)   // NOT the page

create_content_item does NOT auto-create the Data folder — only add_component_on_page does. It parents exactly where you point it, so parentId: <the PAGE> drops the datasource bare under the page and nothing complains. You land on this path whenever set_component_datasource is unavailable — it 422s on renderings created via raw AGQL (measured 2026-07-06: setting the rendering's Datasource Template does NOT fix it; the Agent API does not read that field), so the flow degrades to create_content_item + a raw layout-level attach.

This is not hypothetical — one brand shipped 35 datasources bare under their pages (2026-08-05). Every page rendered, build and tests were green, and a rendering-level schema audit scored 15/15 clean, because each rendering's Datasource Location read the literal ./Data — pointing at a folder that never existed. Only a person reading the content tree caught it.

MOVING a datasource to local page level (global → local, or re-homing between pages): the target parent is <Page>/Data, created on demand — never the page item. moveItem preserves the item GUID and layout references are by GUID, so relocation is safe; but it is a live content mutation, so canary one page and re-assert the route before rolling.

Two traps:

  • set_component_datasource's componentId is the rendering instance id (components[].id from get_components_on_page) — not the rendering id (components[].componentId). Both sit in the same payload.
  • create_component_ds(siteName, componentId, dataFields) does place globally (resolving Datasource Location) and helpfully returns datasourceLocation — but it takes no name and auto-names the item <Component>_<32-hex>. Unusable for something whose whole purpose is being picked by name from a shared list. Use create_content_item with an explicit parentId instead; keep create_component_ds for the case where its one-call children[] support outweighs the name.

Then verify — assert the PARENT, not just existence. Re-read the created/moved item's path and confirm the home you chose: a local datasource's parent segment must be Data (…/<Page>/Data/<Item>), a global one must sit in its component container. "The item exists" and "the field is non-empty" both pass on the broken placement, which is exactly how 35 misplaced items survived a full build. Global items need self-descriptive names (GT Hero, Brand Heritage Timeline) — the name is all an author sees in a shared picker.

Derive or author? Decide per field, before you type a number

Every number or list on a page is either derived at render time or authored as content. Getting it wrong is invisible until it is embarrassing, so decide deliberately:

Derive it if the CM can know the answer. Author it if the CM cannot. NEVER author a value whose wording asserts liveness.

ValueDecisionWhy
"7 developments · 29 residences available today"deriveCM knows it, and today asserts liveness
"Six residences remain at X."deriveSame — and it is the largest claim on the page at the point of conversion
a <select> of the developmentsderiveAn authored list drifts the moment a building is added or renamed
"17 completed · 143 sold since 2011"authorNothing in the CM knows these — facts about the business, not the content
budget bandsauthorNot derivable without inventing a bucketing rule

The liveness test is the sharp edge. "143 sold since 2011" ages gracefully; "six remain" is false the day after the next reservation and nothing about the page changes to reveal it. If the copy contains remain, available, today, now, left — it cannot be authored text.

Three obligations that come with deriving:

  1. Degrade honestly, never to a number. Unreadable data, a zero result and a missing link must each fall back to authored copy or render nothing — never "Zero residences remain", never a partial sum. A truncated count is a false claim; a truncated list (a picker) is merely degraded — so those two degrade differently.
  2. One fetch, or two surfaces will disagree. Wrap the resolver in React.cache() so every component on the page shares it. Two independent counts is exactly how "6 of 14 remaining" and "Sold out" end up in the same viewport.
  3. Do not offer an inline editor for a computed string. Render derived text as plain text, not <Text field=…> — otherwise Pages offers an editor writing to a value nothing reads.

Corollary — never derive a URL. A route slugified from an item name is syntactically valid and silently wrong. Add an explicit link field so Sitecore resolves the real route and "no page yet" becomes a representable state that renders non-interactively.

Gotchas — live-proven

  • Emoji: BMP-safe only. The Marketer MCP write corrupts 4-byte supplementary-plane emoji (😉 U+1F609, 🌱 U+1F331, 🔥 U+1F525) to ����. 3-byte BMP symbols survive (☕ U+2615, ⏳ U+23F3, ♨ U+2668, em-dash U+2014). For HTML fields (RichText Body) use HTML hex entities (&#x1F609;) — they round-trip and render. For plain-text fields (e.g. ValueCard Icon) entities render literally, so use a BMP symbol or leave it empty.
  • Creation order is not sort order — set __Sortorder on every list row. Children with an empty or equal __Sortorder resolve in item-NAME order, however (and in whatever sequence) they were created; correct-looking order is often an alphabetical coincidence. Give every row an explicit, distinct value (100, 200, 300 …) in create_content_item fields or via update_fields_on_item, which writes it but omits system fields from its updatedFields reply. Verify the rendered order, not the write response.
  • add_component_on_page creates the PARENT datasource only — never the children. Children are separate create_content_item calls under the returned datasourceId.
  • Field names are case-sensitive and must match the datasource template exactly — read a real sample, never paraphrase.
  • Sanitize item names. Sitecore's default ItemNameValidation is ^[\w\*\$][\w\s\-\$]*(\(\d{1,}\)){0,1}$: parentheses are only allowed at the end and only around digits, so Foo (2) passes and Foo (draft) is rejected.
  • Per-language composition (measured 2026-10-02). __Final Renderings is versioned, so a new language starts with an empty layout. Version each datasource with update_content(language, createNewVersion: true). Always pass language: omitted means en, and with createNewVersion that silently adds en v2. update_fields_on_item takes no language. create_page fields is [{"Title":"…"}] (key = field name), unlike update_content's {name, value}. Never delete_content to drop one language: it deletes the whole item. Runbook: sitecoreai-localization.

Variants — set them per page via the Pages API (the MCP can't)

A Headless rendering variant is code-driven (<Component>.<Variant>.tsx export + a Variant Definition item + a deploy — see content-sdk-variants-vs-siblings). The Marketer MCP cannot select a variant on a page (set_component_variant is A/B-test / personalization, not Headless). Use the Pages API:

  • Host https://xmapps-api.sitecorecloud.io, header Accept: application/json. Token = the CM automation client (SITECORE_CM_CLIENT_ID/SECRET → client_credentials, audience=https://api.sitecorecloud.io). The deploy client 500s on state (measured 2026-08-12).
  • READ: GET /api/v1/pages/{pageId}/state?site=<site>&language=en&withLayout=true → finalLayout is the layout body JSON string ({ devices:[{ renderings:[{ id, instanceId, placeholderKey, dataSource, parameters:{ FieldNames, GridParameters, … } }] }] }) plus a revision.
  • WRITE (total replace — fetch → modify → write back): set renderings[n].parameters.FieldNames to the variant item GUID ("" = Default; it stores the GUID, not the export name — the layout service resolves it), then POST /api/v1/pages/{pageId}/layout with { layout:{kind:"Final",body:<modified string>}, originalLayout:{kind:"Final",body:<original string>}, language, site, pageVersion, revision }. No pageVersion in state (single version): send 1.
  • GOTCHA — the editing/render endpoint CACHES. A FieldNames change is confirmed in the data immediately (re-read), but the rendered page lags; bust the cache / wait / republish before screenshotting a changed variant.

Worked example — anonymized catalog (shape only; resolve real IDs from the live tenant)

Placeholder for all: /headless-main. Flat = single datasource; List = heading + child items. IDs below are illustrative placeholders — always read the live palette (Step 1); never copy these GUIDs into a real tenant.

ComponentKindParent fieldsChild template → child fields
PageHeroflatTitle, Subtitle, HeroImage—
RichTextSectionflatSectionHeading, Body (HTML)—
ValuePropslistHeading, Eyebrow, HeadingAccentValueCard → Icon, CardTitle, Body
StatsBandlistBandHeadingStat → StatValue, StatLabel
DestinationsGridlistHeading, Eyebrow, HeadingAccent, Introcard → Name, Tagline, Distance, Detail, CardImage, CardLink
ExperienceShowcaselistHeading, Eyebrow, HeadingAccentitem → ItemTitle, Summary, ItemImage, Duration, Cta
TestimonialslistHeading, Eyebrow, HeadingAccentquote → Quote, Author, Role, Avatar
JourneyStepslistTitle, Introstep → StepTitle, Description, StepImage
Promoflat(fixed FieldNames)—
NewsletterCTAflatHeading, HeadingAccent, TitleAccent, Body, Placeholder, ButtonLabel—

Resolve rendering IDs + template IDs on demand by reading a sample datasource / get_components_on_page.

Worked composition (sample journal-style page): PageHero → RichTextSection → StatsBand (4× Stat) → ValueProps (3× ValueCard) → NewsletterCTA — opener → prose → proof → benefits → close.

Relationship to other skills

  • sitecoreai-brand-voice — the words/register (load for the copy inside each field).
  • content-sdk-resolver-patterns — the build-side view (how these renderings resolve data in the head app). This skill is the authoring-side view (filling them via the Marketer MCP).
  • sitecoreai-agent and sitecoreai-publishing — the lower-level API behind the Marketer MCP, and the Publishing REST contract.

Experience Edge Admin API and webhooks

SitecoreAI does have a publish webhook. It is not in the Publishing API (which has no callback) and not in the CLI (the edge plugin has only login, tenant, apikey). It lives in the Experience Edge Admin REST API, which has no UI: REST is the only management path.

An Edge webhook fires at the very end of an Edge publish, after the Edge cache clear, so the receiver can read the newly published content. That is why it, and not the CM publish:end event, is the right trigger for head-app revalidation.

1. Credential: the Edge administration client

CredentialEdge Admin API
Edge administration client (one per environment)200
Org automation client401 edge.cdn.11: Unauthorized. Failed to find tenant. (live, 2026-10-02)
Environment automation clientCovers the Edge Platform admin API, a different API. Not this one

This 401 is your known-bad control: the org token carries no tenant, so the global host cannot resolve one.

Create it by API (live-proven 2026-10-02, no UI step): the org automation client (sitecoreai-auth) calls the Deploy API.

StepCallResult
CreatePOST https://xmclouddeploy-api.sitecorecloud.io/api/clients/v1/edge body { "name", "description", "projectId", "environmentId" }201 { name, description, clientId, clientSecret }. The secret is returned once: store it in the secret store immediately, never in chat or a manifest
ListGET https://xmclouddeploy-api.sitecorecloud.io/api/clients/v1/environmentItems { id, name, description, clientId, createdAt, clientType, projectName, environmentName }. Edge administration client = clientType: 2
DeleteDELETE https://xmclouddeploy-api.sitecorecloud.io/api/clients/v1/{id}202. id is the list's internal id, not clientId (the clientId returns 404)
  • Deleting a client does not revoke tokens already issued (live, 2026-10-02). After the 202 the list drops it at once and new token requests fail within a minute (401 access_denied; one minted at +2 s still worked). A token minted before the delete still passed GET /webhooks at +1, +5 and +15 min: it lives until its exp, up to 24 h, with every scope including edge.content:clearall. No revoke endpoint is known. A leaked secret therefore means "delete the client, then treat the environment as exposed for 24 h".
  • Creating a credential on a real tenant is a live write: get the user's go-ahead first.

Token:

POST https://auth.sitecorecloud.io/oauth/token
grant_type=client_credentials&client_id=…&client_secret=…&audience=https://api.sitecorecloud.io
  • expires_in ≈ 86400 s (24 h). Cache it.
  • Older tenants may need the legacy audience https://delivery.sitecore.cloud/<tenant-name>.
  • Tenant and org come from token claims (…/claims/tenant_id, tenant_name, org_id, sc_org_region). One global host: the token decides which environment you hit, so read the claims before any write.
  • Scopes granted: edge.webhooks:create|read|update|delete, edge.settings:read|update, edge.caches:clear, edge.tokens:*, edge.content:publish, edge.content:clearall. There is no narrower client type, so every holder of this credential can wipe the environment (§ Hard rules).
  • Scope is per environment: webhooks, tokens and cache clears cannot be limited by site.
  • Env vars: SITECORE_EDGE_CLIENT_ID / SITECORE_EDGE_CLIENT_SECRET, or per environment SITECORE_EDGE_<ENV>_CLIENT_ID (three-segment naming, sitecoreai-auth) passed to the script with --id-env / --secret-env.

2. Endpoints

Base: https://edge.sitecorecloud.io/api/admin/v1, header Authorization: Bearer <JWT>.

OpRouteSuccess
List / get webhookGET /webhooks, GET /webhooks/{id}200
CreatePOST /webhooks201; take the GUID id from the body (Location names an internal http host)
UpdatePUT /webhooks/{id} (replaces what you send; an omitted or null body is kept)204
DeleteDELETE /webhooks/{id}204
SettingsGET / PUT / PATCH /settings200 / 202 / 200
Clear Edge cacheDELETE /cache202, whole environment
Delete contentDELETE /contentNever. Wipes all environment data

Webhook fields (WebhookEdit): label, uri (HTTPS only, so localhost needs a tunnel; a Cloudflare quick tunnel works), method (GET/POST), headers (object of strings), body (OnEnd only), bodyInclude (OnUpdate only, a JSON object merged into the top level), createdBy, executionMode (OnEnd default | OnUpdate), disabled. Read-only: id (GUID), tenantId (the tenant name), created (reset by every PUT), lastRuns[{ timestamp, success, message }] (the 10 newest).

GET echoes headers including secret values: redact every read you print or store. Full tables: references/admin-api.md.

3. OnEnd vs OnUpdate

OnEnd (default)OnUpdate
BodyYour static body string, verbatimapplication/json { invocation_id, updates[], continues } (+ bodyInclude)
BatchingOne call per publish (debounce documented only for Content Hub)Batches share invocation_id; continues: true until the last
UseDeploy hooks, "something was published", sitewide purgePer-item OSR, incremental search sync, per-item mirroring

OnUpdate row (live): { "identifier": "22222222222242228222222222222222-layout", "entity_definition": "LayoutData", "operation": "Update", "entity_culture": "en" }. Dashless uppercase GUIDs, -layout / -media suffixes, PascalCase entity_definition and operation, entity_culture: "" on MediaItem. Under snapshot publishing a datasource-only publish emits the dependent page's Item + LayoutData rows. Publishes on an SXA site can trigger a second invocation for the regenerated sitemap file. Your custom headers arrive on every delivery (live), so a per-webhook secret header works. Unpublish and delete send operation: "Delete" rows with NO entity_definition key (live): { "identifier": "3556…1637", "operation": "Delete", "entity_culture": "en" } plus the -layout row. Only the removed item's own rows are sent, never the pages that link to it. Full shapes and timing: references/payload.md.

Use OnUpdate for anything that must follow the content. OnEnd cannot be attributed: one publish produced three OnEnd deliveries (+1.6 s, +9 s, +120 s), two of them before Edge had the content. Use it as "something was published", never as "my publish is live", and never to trigger a purge or rebuild that re-reads Edge.

4. Reliability

  • A non-2xx is a failure, and Edge retries it without backoff (live): each retry has a new invocation_id and the same rows. The lastRuns message is the response's status text: Status: Unauthorized, reason: Unauthorized, Status: BadRequest, reason: Bad Request.
  • 10 consecutive failures → auto-disable, and the retries alone get there: ONE publish disables the webhook, for a 401 and for a 400 alike (live). The 401 run sent 10 deliveries in 7 s; the 400 run sent 10 over 137 s at irregular gaps (1–39 s, not growing). Then disabled: true and the last lastRuns message The webhook has failed the past 10 consecutive invocations and will be disabled. (it takes one of the 10 slots, so the first failure falls off). So "10 failures" means one bad publish, not ten, and the retry window is seconds to about 2 minutes, too short to fix a receiver in.
  • Re-enable with webhooks enable <id> --yes (a PUT carrying disabled: false); lastRuns is not cleared. Fix the receiver first or the next publish disables it again.
  • 30 s without a response counts as a failure (doc; not probed).
  • lastRuns is the only delivery log and keeps 10 entries. A success has an empty message; its timestamp is about 1 s before the receiver sees the request.
  • Delivery is at-least-once while you answer non-2xx and at-most-once when your receiver is down past the retries: keep a TTL backstop on the receiver.
  • No test or ping endpoint exists. A synthetic POST to the receiver proves the receiver; only a real publish proves Edge.
  • Latency (live): publish start → webhook 86–175 s (median ≈ 135 s), about 1–2.5 min after the content is already readable on Edge (23–60 s). Wait for lastRuns, not for Edge, and budget about 3 minutes before calling a delivery missed.
  • Webhook cap per environment and Admin API rate limits are undocumented.

5. Recipe: the OSR webhook for a Content SDK head app

export SITECORE_EDGE_CLIENT_ID=… SITECORE_EDGE_CLIENT_SECRET=…
node scripts/edge-admin.mjs webhooks list                     # duplicate check, prints tenant
node scripts/edge-admin.mjs webhooks create \
  --label "<site> OSR" --uri https://<production-domain>/api/revalidate \
  --mode OnUpdate --method POST \
  --header x-revalidate-secret=env:SITECORE_REVALIDATE_SECRET \
  --header x-vercel-protection-bypass=env:VERCEL_AUTOMATION_BYPASS_SECRET \
  --created-by "<who>"                                          # dry run: prints the plan
# re-run with --yes to create
  • uri = the production domain, never a per-deployment URL (it dies on the next deploy) and never preview (preview gets no Edge webhook).
  • Vercel Deployment Protection (live): under the default Standard protection (ssoProtection.deploymentType: all_except_custom_domains) the production *.vercel.app alias answered 200 without a bypass, while the per-deployment URL answered 302 → vercel.com/sso-api (and 401 {"error":{"message":"Protected deployment"}} to a POST). An x-vercel-protection-bypass header in the webhook's headers does pass Edge's delivery through a protected URL (lastRuns OK, page refreshed). Create the secret with PATCH /v1/projects/{id}/protection-bypass ({"generate":{}}) or Settings → Deployment Protection → Protection Bypass for Automation.
  • Header values via env:NAME keep secrets off the command line and out of shell history.
  • The receiver contract (secret, responses, tags) is content-sdk-app-router-cache-components-and-osr.
  • Order: controls pass → then the webhook exists. Run revalidate-controls.mjs against the deployed route (secret set on the target, bypass if protected) before create --yes: one publish against a receiver answering 401 or 400 sends 10 retries within seconds to about 2 minutes and disables the webhook (both live). Creating it with disabled: true and enabling after the controls would be the safer shape, but whether POST honours disabled is unverified [probe-gated] (a fresh create read back disabled: null); until a probe shows it, create only after the controls pass.
  • Verify after a real publish: webhooks get <id> → newest lastRuns success true, disabled false, then the content marker on the page (not 200, not x-vercel-cache).

Shared CM / multi-site: one Edge environment serves every site on it, and every webhook receives every site's publishes. One webhook per head app per environment; receivers must tolerate foreign ids (the SDK route does). Put the owning app in label and check for an existing webhook with the same uri before creating.

6. Safe updates and the debugging ladder

  • Update = GET → merge → PUT → GET and diff. Send every field: the doc's re-enable example omits executionMode, which (doc) resets to OnEnd, so the receiver gets no rows, answers 400, and the webhook disables itself on the next publish. edge-admin.mjs update|enable|disable does the merge.
  • A stored body survives a PUT that omits it or sends null, and body: "" is rejected under OnUpdate (live). Switching OnEnd → OnUpdate therefore needs two PUTs: OnEnd + body: "", then OnUpdate. The script plans both and fails the post-PUT check if a stale body remains.
  • Delete prints a redacted snapshot first so the webhook can be recreated.
  • Rotate the receiver secret without downtime: accept old and new on the receiver, update --header x-revalidate-secret=env:NEW, then drop the old.

"The webhook doesn't fire": (1) the token's tenant_name is the environment you think → (2) the webhook exists, executionMode is right, disabled is false → (3) the publish reached Edge (query Edge, not the CM) → (4) lastRuns has an entry for that time → (5) its message (timeout, status) → (6) the receiver: a 302 to an SSO page is a false success, check the bypass header → (7) the receiver's tags match the cache (the OSR skill).

7. Settings and cache

  • edge-admin.mjs settings get: contentCacheTtl, mediaCacheTtl (format d.hh:mm:ss; documented default 04:00:00, observed 1.00:00:00 on one tenant: always read it), *AutoClear, tenantCacheAutoClear.
  • cache clear (DELETE /cache, --yes): environment-wide Edge cache clear, every site on it. Not needed after a normal publish (Edge clears on its own).

Which webhook for which job

JobUse
Revalidate a head app after publishEdge, OnUpdate → /api/revalidate
Keep a SitecoreAI search index freshEdge, OnUpdate → push upsert; replay after every reindex, which wipes pushed documents (sitecoreai-search-sources)
Sitewide purge / trigger a rebuildThe pipeline, after a read-back shows the content on Edge. An OnEnd webhook fires early and repeatedly (§ 3); use it only where a premature trigger is harmless
Sync external searchEdge, OnUpdate, filter LayoutData rows
Notify on workflow approval / block on an external checkWorkflow Submit Action / Validation Action (CM)
Alert on a failed publishCM event handler publish:fail
Know when your Publishing API job finishedPoll the job (sitecoreai-publishing); the Edge webhook says when it is live

Full table with the CM webhook families and their traps: references/decision-table.md. Never point a CM webhook at /api/revalidate: its payload has no updates, and publish:end fires before Edge is live.

Hard rules

  • Never call DELETE /content (scope edge.content:clearall). It instantly wipes all published data of the environment. The bundled script has no command for it and refuses the route even if asked. Not with a flag, not for a test.
  • Every write needs explicit intent: read the token's tenant claims first; the script is read-only unless --yes is passed.
  • Never print or store a secret: client secret, JWT, webhook header values. Record only ids (clientId, webhook id).
  • Never use an automation client against the Edge Admin API. Mint an Edge administration client.
  • Never update with a partial PUT.
  • Webhook creation on a real tenant is a live write: get the user's go-ahead first.

References

  • scripts/edge-admin.mjs: token, webhooks list|get|create|update|enable|disable|delete, settings get, cache clear, --self-test. Live-tested 2026-10-02 (create, get, list, two-step mode switch, enable, delete).
  • references/admin-api.md · references/payload.md · references/decision-table.md
  • sitecoreai-auth (org automation client, token caching) · sitecoreai-publishing (jobs, polling) · content-sdk-app-router-cache-components-and-osr (the receiver)
  • Sitecore docs (doc.sitecore.com, SitecoreAI developer docs → Experience Edge): Admin REST API, Webhook objects, The webhook execution modes, The publishing process, Create a JSON Web Token for Experience Edge APIs.

Sitecore Edge GraphQL — Capture Recipe

How to talk directly to Sitecore Experience Edge with curl and produce an edge-snapshot/ folder (introspection + per-pattern layout JSON) for a playground or a product. No SDK, no CLI, no auth header — just POST + GraphQL.

When to use

  • Initializing the edge-snapshot/ of a new playground (per content-sdk-playground-pattern).
  • Capturing per-type introspection to pin Sitecore types as a reference fixture.
  • Probing live layout / sites / routes without booting the head app.
  • Debugging Edge errors (depth-limit, complexity-limit, unknown-arg) seen from the SDK.
  • Reproducing a layout response from the command line for sharing in a bug report.

Endpoint and auth

POST https://edge-platform.sitecorecloud.io/v1/content/api/graphql/v1?sitecoreContextId=<CONTEXT_ID>
Content-Type: application/json
  • No Authorization header. The sitecoreContextId in the query string IS the access control. Treat it like a public-ish API key — anyone with it can read your Edge data, but they can't write.
  • Two distinct Edge URLs. Don't confuse:
    • https://edge-platform.sitecorecloud.io — service endpoints incl. GraphQL (this skill).
    • https://edge.sitecorecloud.io — media URL replacement only (legacy / asset CDN).
  • POST is required. GET is not accepted. There is NO /schema URL that returns SDL — you must POST a query.

The Edge limits to plan around

1. Query depth limit: 15 levels

The standard GraphQL "full IntrospectionQuery" (the one every GraphiQL ships with) is 26 levels deep. It will fail with:

{"errors":[{"message":"Query is too nested to execute. Depth is 26 levels, maximum allowed on this endpoint is 15.","extensions":{"code":"INVALID_OPERATION"}}]}

Workaround: use per-type introspection (see § Workaround below). Do NOT try to fetch the whole schema in one shot.

2. Query complexity limit (no published number — scales with page size + nesting)

A wide pagination (first: 100) with a moderately nested selection will be rejected as too complex:

{"errors":[{"message":"Query is too complex to execute. The field with the highest complexity is: ...","extensions":{"code":"INVALID_OPERATION"}}]}

Empirical rule of thumb (verified on the training tenant 2026-05-27):

  • routes(first: 4, …) with selection { routePath route { id name } } → too complex
  • routes(first: 100, …) with selection { routePath } → too complex
  • routes(first: 10, …) with selection { routePath } → works

So: shrink page size first, then shrink selection set. Paginate with after cursor across multiple requests rather than fetching everything in one call.

A literal first: costs more than a variable (preview, measured 2026-10-02): siteInfo.dictionary(first: 61){ results{ key value } } is too complex, while first: $f with f = 1000 resolves. Pass page sizes as variables, as the SDK does. first: 1001 is a warning plus clamp on live and a hard error on preview. The language argument is case-insensitive.

Measured on a real preview endpoint, 2026-08-11 (a 7-item children connection — so this is the SELECTION cost, not a data-volume effect):

QueryResult
children(first:20) each with a nested units(first:30) connection + one fieldrefused
children(first:50) selecting name displayName + two field(...)refused
children(first:50) selecting two field(...) onlyok
children(first:30) selecting name + two field(...)ok
children(first:50) selecting id name (no field(...))ok

Two things that table shows and prose does not:

  1. field(name:"X"){ value } selections are expensive — far more than plain name/id. Dropping one redundant scalar (displayName) was enough to bring a refused query back under budget at the same page size.
  2. A connection INSIDE a connection is the reliable way to exceed it. No reduction of the outer first: rescued a "developments each with their units" aggregate. Fetch the parents in one flat query and the children per-parent (deliberate N+1), deduplicated with React.cache() so components on one page share the fan-out.

⚠️ THE FAILURE IS LOUD AT THE ENDPOINT AND SILENT IN THE UI. Every sensible consumer catches the rejection and degrades — so an over-budget query shows up as an empty select, a missing count, or a section that vanished, none of which look like a query error. One instance shipped this way and was found by reading the rendered page, not by a test. Probe the budget with a single POST whenever a query grows a field or raises first:.

2b. A rendering's ComponentQuery budget (measured 2026-09-26 → 28, preview Edge)

A ComponentQuery runs through the same limits, and one build hit them on six of about twenty renderings. The numbers below are one tenant's ceilings. They tell you what to probe first; they never replace the probe:

ShapeMeasured
Depth 1: children(first:50), 2 row fields + template{name}too complex. first:10 resolves.
Depth 3, three nested children(first:N)The limit is the product of the three first values: about 15 passes (5·1·3), 16 fails (4·2·2), whichever level carries the weight.
Rows at real countsComplexity tracks row fields × first. A 9-field row union failed at first:14; 8 selections held at first:16. Field types weigh differently: a 7-field row topped out at 14, a 4-field row at 21.
field(name:){jsonValue} selectionsAbout 11 per query (11 passes, 12 fails) before "Query is too nested … Depth is 17", whatever first is.
Three sibling children connections"Depth is 18 … maximum 15", whatever the field count. The depth ceiling is 15.
children nested two levels inside a ComponentQueryFails silently. The rendering arrives with isContentResolved: false, no fields and no error, because the SDK swallows it. The same query succeeds as a standalone client.getData.
A standalone 2-level getData (groups × links)Groups × links up to about 22 passed (1×22, 2×11, 3×7, 4×5); 2×12, 3×8 and 4×6 failed.

What follows from the table:

  • Keep a ComponentQuery to one level of children. Fetch deeper rows server-side with client.getData, one call per parent, in parallel.
  • first must be strictly greater than the authored row count. Edge returns the first N rows with no error, so a row an author adds past first is silently dropped from the page. When the budget cannot hold that headroom, move secondary fields (images, logos, labels) to a server-side fetch. If the field set cannot shrink further, record the ceiling as the list's maximum authorable row count.
  • Probe from a file with a direct POST, never through the app. The app turns a rejection into an empty component, and the error text naming the limit is visible only at the endpoint.

3. No GET schema retrieval

Endpoints like /v1/content/api/graphql/v1/schema and ?query=schema both return {"errors":[{"message":"No query was provided!"}]}. The only way to get type info is per-type introspection via POST.

Workaround: per-type introspection (one POST per type)

# Single type (e.g., Item)
curl -s -X POST "$EDGE_URL?sitecoreContextId=$CTX" \
  -H "Content-Type: application/json" \
  --data '{"query":"{ __type(name: \"Item\") { name kind fields { name description args { name type { name kind } } type { name kind ofType { name kind } } } } }"}'

The canonical type list to capture for an edge-snapshot/:

FileType
type-LayoutData.jsonLayoutData
type-Item.jsonItem
type-ItemField.jsonItemField
type-RoutesResult.jsonRoutesResult
type-SearchPredicate.jsonSearchPredicate
type-SiteData.jsonSiteData
type-SiteInfo.jsonSiteInfo

These cover the head-app-relevant surface. Add others (ItemTemplate, ItemLanguage, ItemUrl, etc.) if your work needs them.

Sites + routes discovery (two queries — don't combine)

All sites

curl -s -X POST "$EDGE_URL?sitecoreContextId=$CTX" \
  -H "Content-Type: application/json" \
  --data '{"query":"{ site { allSiteInfo { total results { name hostname language rootPath } } } }"}'

Routes for one site (paginate with first: 10)

curl -s -X POST "$EDGE_URL?sitecoreContextId=$CTX" \
  -H "Content-Type: application/json" \
  --data '{"query":"{ site { siteInfo(site: \"<siteName>\") { name rootPath routes(first: 10, language: \"en\") { total results { routePath } } } } }"}'

Argument gotchas (will silently confuse you if you guess):

  • siteInfo takes site: String! (NOT name: String!).
  • routes takes language: String! REQUIRED (omitting it returns an error).
  • For sites with >10 routes, paginate with after: "<cursor>" from the previous page's pageInfo.endCursor.

Layout capture (the actual rendered tree)

curl -s -X POST "$EDGE_URL?sitecoreContextId=$CTX" \
  -H "Content-Type: application/json" \
  --data '{
    "query": "query ($routePath: String!, $language: String!, $siteName: String!) { layout(routePath: $routePath, language: $language, site: $siteName) { item { rendered } } }",
    "variables": { "routePath": "/", "language": "en", "siteName": "training" }
  }'

item.rendered is opaque JSON (no GraphQL type — see content-sdk-resolver-patterns for what's inside). Save the raw response to layouts/<page-or-pattern>.json.

For probing multiple patterns, capture one layout per page that demonstrates a distinct delivery model:

  • layouts/components-standard-datasource.json (a page using a standard datasource rendering)
  • layouts/components-all-fields-datasource.json (a page using the field-type-catalog rendering)
  • layouts/components-integratedgraphql.json (a page using an Integrated GraphQL rendering)
  • layouts/components-content-resolvers.json (a page using one or more content resolvers)

Capture script (bundled, one-shot)

scripts/capture-edge.mjs writes the canonical edge-snapshot/ layout — per-type introspection, sites.json, routes.json (every page, paginated with after), one layouts/<route>.json per route — with no dependencies beyond Node 18:

SITECORE_EDGE_CONTEXT_ID=… node scripts/capture-edge.mjs --site <siteName> [--language en] [--out edge-snapshot] [--max-routes 50]

It pages routes 10 at a time: on its first live run first: 50 + pageInfo was rejected as "Query is too complex to execute" (2026-09-16) — the § 2 limit, reproduced. Exit 1 on any Edge error; the erroring response is still written so the limit that fired is inspectable.

Hard Rules

  • Always POST. GET isn't supported; there's no /schema URL.
  • No auth header — the sitecoreContextId in the query string IS the auth. Putting Authorization: Bearer … is silently ignored.
  • Never run the standard "full IntrospectionQuery" — it's >15 levels deep and Edge will reject it. Use per-type introspection.
  • Shrink page size before shrinking selection when hitting complexity limits — first: 10 is the safe default for routes.
  • siteInfo(site: …), not siteInfo(name: …). Easy to misremember from the response shape.
  • routes(…, language: "<lang>") is REQUIRED. Omitting it returns a missing-arg error, not an empty result.
  • item.rendered is opaque JSON — there's no GraphQL type for what's inside. Use content-sdk-resolver-patterns to interpret.
  • Don't commit .env.local — the contextId there is project-specific. Document only in .env.example.

Stop Conditions

  • Don't try to scrape the full schema in one query. The depth limit ensures this will always fail; per-type is the only path.
  • Don't combine allSiteInfo and siteInfo.routes in one query — both work alone, together they trip complexity limits. Split into two POSTs.
  • Don't paginate routes with first: 100 even if the site has 4 routes — the complexity calculation is based on the cap, not the actual count.
  • Don't capture and commit a Layout JSON containing real PII — these snapshots end up in edge-snapshot/ which IS committed; treat them as public-visible content.

Verification

  • The endpoint should return {"data":{"__schema":{"queryType":{"name":"Query"}}}} for the smoke query { __schema { queryType { name } } }.
  • Per-type introspection responses should have shape {"data":{"__type":{"name":"<Type>","kind":"OBJECT|INTERFACE","fields":[...]}}}. An empty __type (null) means the type doesn't exist on this tenant.
  • Layout query should return {"data":{"layout":{"item":{"rendered":{"sitecore":{"context":...,"route":...}}}}}}. An empty route means the path doesn't exist or isn't published.

Related

  • content-sdk-playground-pattern — the workspace layout that consumes edge-snapshot/.
  • content-sdk-debug-layout-probe — for capturing layout responses through the head app's /api/layout-debug route (alternative to direct curl when the SDK's pre-processing matters).
  • content-sdk-resolver-patterns — for interpreting item.rendered once you have it.
  • sitecoreai-graphql-schemas — the broader catalog of types across Authoring + Edge endpoints.

References

  • Endpoint default: @sitecore-content-sdk/core/dist/cjs/constants.js → SITECORE_EDGE_PLATFORM_URL_DEFAULT = 'https://edge-platform.sitecorecloud.io'.
  • The 15-depth limit was captured as the actual error response of a full introspection (2026-05-27); the per-type workaround above is the measured way around it.
  • Live-tested 2026-05-27 against a live SitecoreAI tenant.

SitecoreAI GraphQL schemas — Authoring + Edge

This skill is the schema reference; it is NOT the SDK call reference. Use this with marketplace-sdk-xmc (which documents the SDK envelope: xmc.authoring.graphql is a client.mutate, xmc.preview.graphql is a client.query, response unwrap rules, etc.). This skill answers "what GraphQL fields actually exist on the server?"

When to load

  • Before writing or reviewing any xmc.authoring.graphql body (any item read or write, item template introspection, search, publishing, language management, role/user management).
  • Before writing or reviewing any xmc.preview.graphql / xmc.live.graphql body (read-only published-content access — Edge endpoint).
  • When the .d.ts for xmc.*.graphql shows data: [key: string]: unknown and you need to know what shape to expect underneath.
  • When porting a query that worked in MVC/JSS days — the parameter names and where-clause shapes have changed.

Endpoints at a glance

EndpointURL patternAuthSchema flavorUse for
Authoringhttps://<tenant>.sitecorecloud.io/sitecore/api/authoring/graphql/v1Authorization: Bearer <OAuth-JWT>Generic — Item/ItemField/ItemTemplate work for any templateRead unpublished content, mutate items, manage versions, publishing, sites, roles, users
Edge / Preview / Livehttps://<tenant>.sitecorecloud.io/sitecore/api/graph/edgesc_apikey: <api-key>Concrete-types-per-template — every Sitecore template gets its own GraphQL type (Edge schema introspected with 872 types in the test tenant)Read published content via typed queries; layout / route resolution; Pages-app preview rendering

The SDK calls map onto these endpoints:

  • xmc.authoring.graphql → Authoring endpoint (via the portal's bearer-token bridge).
  • xmc.preview.graphql → Edge endpoint, preview variant. (Confirm via node_modules/@sitecore-marketplace-sdk/xmc/dist/...client-authoring/types.gen.d.ts and client-pages-or-equivalent / preview module's .d.ts.)
  • xmc.live.graphql → Edge endpoint, live variant.

When inside a Marketplace app, use the SDK call (the portal handles auth). The direct-curl form documented below is for introspection / spike work.


1. Authoring schema — verified shapes

The verified Authoring shapes — root Query, ItemQueryInput, Item, ItemField, ItemTemplateField, the connection types and the mutation surface — are in references/authoring-shapes.md (distilled JSON in references/authoring-types.json). Open it before writing any xmc.authoring.graphql query — citing a verified shape is the whole point of this skill.

2. Edge / Preview / Live schema — verified shapes

872 types total. Edge schema is dramatically different from Authoring — it's a "concrete-types-per-template" model. Every Sitecore template (Accordion, ArticlePage, BrandList, ...) becomes its own GraphQL type with strongly-typed fields. The 14-type distilled subset for the generic Item lives at references/edge-types.json.

2.1 Root Query

type Query {
  item(path: String, language: String!, version: String): Item
  layout(site: String!, routePath: String!, language: String!): LayoutData
  search(where: ItemSearchPredicateInput!, after: String, first: Int, orderBy: ItemSearchOrderByInput): ItemSearchResults
  site: SiteData
}

That's it — only 4 root queries on Edge. No mutations (Edge is read-only).

2.2 ⚠️ Trap — version is String on Edge, Int on Authoring

# Edge:
item(path: $path, language: $lang, version: "5") { ... }       # String!

# Authoring:
item(where: { path: $path, language: $lang, version: 5 }) { ... }   # Int!

When porting between endpoints, this trips up implementations. The $version variable type must match the endpoint.

2.3 Edge Item (generic; concrete templates inherit)

type Item {
  id(format: String): ID!
  name: String!
  displayName: String
  path: String!
  url: ItemUrl!
  language: ItemLanguage!
  languages: [Item]!
  version: Int!                       # the resolved version (always Int on output)
  template: ItemTemplate!
  parent: Item
  ancestors(hasLayout: Boolean, includeTemplateIDs: [String]): [Item]!
  children(hasLayout: Boolean, includeTemplateIDs: [String], first: Int, after: String): ItemSearchResults
  hasChildren(...): Boolean!
  fields(ownFields: Boolean): [ItemField]!
  field(name: String!): ItemField
  rendered: JSON!                     # JSON-rendered form for headless heads
  personalization: ItemPersonalization
}

Key differences vs Authoring:

  • No versions(allLanguages: ...) — Edge serves one version at a time.
  • fields returns [ItemField]! directly, not a Connection. ownFields: Boolean is the only arg.
  • rendered: JSON! — gives back the headless rendering shape (used by Content SDK heads).
  • id(format: String) (lowercase, takes a String) vs Authoring's itemId(format: IdFormat) (typed enum).

2.4 Concrete template types

For any template the tenant uses — say, ArticlePage — Edge exposes a typed object:

type ArticlePage {
  ... # specific fields per template
  ... # plus all the generic Item fields
}

This means a Pages-aware client can write strongly-typed queries. For a generic content diff (no template-specific knowledge), use the generic Item interface paths.

2.5 LayoutData (the layout query)

type Query {
  layout(site: String!, routePath: String!, language: String!): LayoutData
}

Returns a typed layout/rendering tree for a route. Used by Content SDK for headless rendering. Useful for Marketplace apps that want to inspect the rendered layout per route — though for per-version layout, the Authoring endpoint's Item.field(name: "__Final Renderings") is more direct.

2.6 ItemSearchResults and search

Edge search(where: ItemSearchPredicateInput!, ...) returns:

type ItemSearchResults {
  total: Int!
  pageInfo: PageInfo!
  results: [Item]
  facets: [ItemSearchFacet]!
}

ItemSearchPredicateInput supports faceted queries; useful for content-discovery apps.

Edge search(where:) and Authoring search(query:) are item search over CM / Edge, not SitecoreAI integrated search sources (sitecoreai-search-sources, content-sdk-search).


3. Auth — verified

EndpointHeaderSource
AuthoringAuthorization: Bearer <OAuth2-JWT>OAuth2 client-credentials grant (per sitecoreai-auth); Marketplace SDK manages this internally for xmc.authoring.graphql.
Edge / Preview / Livesc_apikey: <API-KEY>Per-environment Edge API key from Cloud Portal.

⚠️ The API key header for Edge is named sc_apikey (lowercase, with underscore) — not Authorization, not X-API-Key, not apiKey. Confirmed via 200-vs-403 test on the introspected tenant.

⚠️ The Authoring header is Authorization: Bearer <token> — not sc_apikey: bearer <token>. The latter returns HTTP 200 with a GraphQL errors array ("The current user is not authorized to access this resource"), which is misleading because it looks like a successful HTTP exchange.


4–6b. Worked examples

Four copy-ready examples live in references/worked-examples.md, section numbers kept:

  • § 4 — fetch two versions of an item with all field values + types in one query (batched versions() form, alias-per-version fallback, SDK call wrapper).
  • § 5 — fetch item template field metadata (fallback for field-type detection).
  • § 6 — fetch published content via Edge.
  • § 6b — upload a media item and link it onto a field (Authoring, 2-STEP uploadMedia → POST binary).

7. Pitfalls and gotchas

  1. version arg type differs. Authoring Int!, Edge String. Mismatched variable type → cryptic GraphQL validation error.
  2. where: is mandatory on Authoring. No item(path: ..., language: ...) shortcut — wrap in where: { ... }.
  3. Authoring fields(...) connection requires three args with no defaults. excludeStandardFields: Boolean!, ownFields: Boolean!, withLanguageFallback: Boolean! — all marked NON_NULL, so omitting them errors out.
  4. ItemField.value is always String!. Image fields return XML strings (e.g. <image mediaid="{...}" alt="..."/>); Link fields return XML; multilist returns pipe-separated GUIDs. Parse client-side per field type.
  5. ItemPublish and ItemAccess are nested objects, not booleans. Item.publish.published (or similar) — verify the exact subfield via introspection.
  6. xmc.authoring.graphql is a MUTATION on the SDK. Single .data unwrap, not double. The schema underneath has a Query root, but the SDK call signature is client.mutate(...) because the SDK wraps both reads and writes through the same POST endpoint. See marketplace-sdk-xmc § 8b for the unwrap matrix.
  7. Edge schema is huge (872 types in this tenant) because every Sitecore template gets a generated GraphQL type. Trying to search the type list by name is faster than reading the introspection JSON top-to-bottom.
  8. Edge Item.fields: [ItemField]! is plain list, not a Connection. No pagination, no nodes wrapper — just access the array.
  9. The "/ide/" suffix is a 404 on the Edge endpoint — drop it. The base URL is /sitecore/api/graph/edge (no trailing path).
  10. JWT bearer tokens expire. The OAuth client-credentials token typical lifetime is 24h; re-acquire per sitecoreai-auth. The Marketplace SDK handles this internally for in-app calls.
  11. A write is validated as a string, never as the field type (measured 2026-09-26 → 29). updateItem / createItem accept a newline-joined multi-value field, an undashed GUID or an unescaped & in Link XML. They read it back unchanged and report success. Then inheritance resolves zero fields, the page loses its layout, or the link renders empty. Multi-value fields are |-joined on write as well as read, and GUIDs are braced, dashed and uppercase. The full table is in the content-sdk-create-component skill, section "Write-side wire formats" of its GraphQL sequence reference (install sitecore-content-sdk to get it).
  12. Language reads lie in two ways (measured 2026-10-02). Authoring language(name:) returns a value for any valid culture, so it is no existence check (use languageItem). Edge preview counts a literal first: toward complexity: siteInfo.dictionary(first: 61){ results{ key value } } is "Query is too complex", while the same value passed as a variable works up to 1000. first: 1001 is a warning plus clamp on live and a hard error on preview. The Edge language argument is case-insensitive. Shapes: references/authoring-shapes.md § 1.8.

8. Re-introspecting the schemas

The schemas WILL evolve. When in doubt, re-introspect:

# Edge / Preview
curl -sS -X POST 'https://<tenant>/sitecore/api/graph/edge' \
  -H 'Content-Type: application/json' \
  -H 'sc_apikey: <YOUR-EDGE-KEY>' \
  --data-binary @references/introspection-query.graphql.json \
  -o edge-schema.json

# Authoring
curl -sS -X POST 'https://<tenant>/sitecore/api/authoring/graphql/v1' \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <YOUR-OAUTH-JWT>' \
  --data-binary @references/introspection-query.graphql.json \
  -o authoring-schema.json

(The .json form is the introspection query wrapped as {"query": "..."} per GraphQL POST convention. References ship the query in .graphql form for human reading; wrap before posting.)

After re-introspecting, python -m json.tool < schema.json | grep '"name"' | sort -u to spot newly-added types or removed ones, and update references/{authoring,edge}-types.json here if the changes affect any of the documented types.


9. Cross-references

  • marketplace-sdk-xmc — SDK envelope, xmc.authoring.graphql / xmc.preview.graphql call signatures, module-vs-experimental modes, response unwrap matrix.
  • marketplace-sdk-client — client.query vs client.mutate, params-wrapper behavior (Mode A wraps body under params, Mode B doesn't), error codes.
  • sitecoreai-auth — OAuth2 client-credentials grant for Authoring header.
  • sitecoreai-pages / sitecoreai-publishing / sitecoreai-sites — REST equivalents (when the SDK has no GraphQL surface).

10. Files in this skill

  • SKILL.md — this file.
  • references/worked-examples.md — the four worked examples (§ 4 two-version fetch, § 5 template field metadata, § 6 Edge fetch, § 6b media upload + link).
  • references/introspection-query.graphql — the introspection query used.
  • references/authoring-types.json — distilled subset of the Authoring schema (37 types most relevant to content reads/writes/templates/publishing).
  • references/edge-types.json — distilled subset of the Edge schema (14 types covering generic Item, search, layout).

The full introspection results (5.4 MB Edge + 3.5 MB Authoring) are intentionally NOT shipped with the skill — re-introspect against your own tenant to capture template-specific Edge types.

SitecoreAI health check (doctor)

Nothing doctor-shaped exists in SitecoreAI behind an API: the Broken Links report, EdgeOrphans and Validate are UI-only, there is no referrers query, and logs live on a separate Monitoring API. This skill composes its own read-only checks across four instruments and writes one prioritized report. Every instrument sees one truth:

InstrumentSeesNever use it as
Authoring GraphQLmaster (and the search index)proof of publication
Edge, live contextwhat is publishedproof that master is fine
Edge, preview contextmaster in Edge shapethe "published" side of any join
Browser / unfollowed HTTPwhat a visitor getsa followed status (curl -L behind SSO = false 200)

Read-only contract (hard rules)

All traffic goes through scripts/lib/http.mjs, which refuses before the network:

  • any verb other than GET, HEAD, POST;
  • any POST except a GraphQL query (the document is parsed: a mutation or subscription anywhere is refused), the client_credentials token mint, and the non-JSON /api/revalidate probe with no credential header (it cannot revalidate);
  • any Edge Admin path outside GET /webhooks, /webhooks/{id}, /settings, and every /content route (the Edge administration client also holds edge.content:clearall);
  • redirects are never followed; Edge is throttled (default 8 rps live, 4 rps preview, hard caps 80 and 5).

Each guard is mutation-tested (scripts/__tests__/http.mutation.test.mjs). Beyond the layer: never --yes, never ser pull into a product repo, never ser validate --fix, never change a log level, never republish, never create a credential. Declared side effect: the crawl fires the head app's page-view tracking once per URL.

Step 1: choose the scope

ScopeFlagsRuns
env--env <cmEnvId>X0, X1, ops (O3-O5), editing hosts (E2, E3), webhooks (D10), logs (O1, O2, T2 from logs)
site (default with --site)+ --site <name> [--url <live>]everything: census, content graph, drift, delivery, crawl
page+ --page /routeD1, R1 and the graph for that page's subtree, crawl of one page, media; logs SKIPPED
language--lang <code>[,<code>…] (default en)census (R1, D11) per language; graph, drift and D1 on the first; W3 on exactly these, or on every environment + version language when absent

--checks narrows by id or family (binding ops eh delivery census graph crawl logs); X0 and X1 always run. A URL-only run (no --env) does the delivery checks alone. --root overrides the site root when Authoring sites cannot resolve it.

Git Bash rewrites /sitecore/... and /route arguments into Windows paths. Under Git Bash (MSYSTEM + EXEPATH set) the scripts undo the rewrite for paths under the Git install root; any other drive-letter path is refused, never guessed. MSYS_NO_PATHCONV=1 still works and is the safe choice in other shells.

Step 2: credentials (X1). Missing = SKIPPED, never pass

Credential (env names, three-segment convention)EnablesWithout it
Org automation client SITECORE_DEPLOY_<LABEL>_ADMIN_CLIENT_ID/_SECRET (--org <label>)X0, Deploy, Authoring, Monitoring logs, context idsdelivery-only run
Edge administration client SITECORE_EDGE_<LABEL>_CLIENT_ID/_SECRETD10 webhooks + settingsD10 SKIPPED
Tenant-scoped automation clientO6 Publishing jobs, E4 Sites APISKIPPED (the org client gets 403 / 401 there)
Access-gate cookie DOCTOR_GATE_COOKIE / --auth-cookieauthenticated robots + crawl on a private surfacethose checks UNKNOWN
Playwright (cwd or PLAYWRIGHT_MODULE)hydrated crawl, console errorscrawl degraded to server HTML, D9 SKIPPED

Unsuffixed fallback: when --org <label> finds no SITECORE_DEPLOY_<LABEL>_ADMIN_CLIENT_* but the unsuffixed SITECORE_DEPLOY_ADMIN_CLIENT_* exists, that pair is used and a note says so. It names no estate, so it is only safe because every check reads the named environment with it: a client of the wrong estate cannot read it and the check answers UNKNOWN, never pass.

The org token carries no tenant claim: X0 binds by the Deploy env read (host + context ids) and proves Authoring answers on that host. An editing-host env id is refused (its env read reports the CM host). Credentials come from env or --env-file; values are registered for redaction and never printed.

Step 3: run

MSYS_NO_PATHCONV=1 node scripts/doctor.mjs --org <label> --env-file <creds.env> \
  --env <cmEnvId> --site <SiteName> --url https://<live-host> [--visibility private --auth-cookie "<c>"] \
  --out <dir> [--redact]

Run order (any P0 in the cheap steps is already in the report if you stop early):

  1. X0 binding, X1 matrix.
  2. Aggregates: O4 org health + /healthz, O3 deployments (advisory), O5 log levels, E2 registrations + stale Rendering Host items, E3 EH variables, D10 webhooks, D1 context, D2 robots, D3 protection, D4 revalidate, E1 editing config.
  3. Census: R1 every live route's layout, D11 preview vs live.
  4. D8 sitemap, D14-D16.
  5. Content graph: inventory → forward edges → resolve on Authoring and live Edge → L1-L6, T2, M1, L5, D12, then R2/R3 joins, W5 drift, W3 language versions (orphan languages, missing versions, live keys absent or equal to the key; sitecoreai-localization).
  6. Crawl D5/D7/D9, media D6.
  7. Logs: O1 newest CM file per type → T2 confirmation on Authoring; O2 editing-host files.

Cost: about 3 minutes and 260 calls for a 43-route, 553-item site with a 60-page crawl; the graph costs ~7.4 calls per 100 items. Cap with --max-routes, --max-pages, --log-max-bytes.

Severity and verdict rules

SevMeansExamples
P0broken or invisible for everyone nowDisallow: / on a public site, live route route:null, app on the preview context, open revalidate endpoint, media from the CM
P1broken for some readers, or breaks the next publishinternal 404, missing datasource/reference, item whose template is gone, sitemap on the CM host, disabled webhook
P2degraded or riskysoft 404, no webhook, editing secret unset on a delivery-only app, unpublished pages
P3hygiene, candidates, infounreferenced data items, preview-only routes, noisy log lines
  • Instrument error = UNKNOWN, never clean; UNKNOWN makes the exit code 1. Compare total with what was received everywhere.
  • Assert the first status; a 3xx to /sso-api means locked.
  • --visibility private inverts robots, protection and noindex verdicts: ask whether the site is meant to be public or private, never infer it.
  • Deployment records are advisory (they can flip after completion).
  • Reverse drift (master broken, Edge good) prints a "Do not republish" banner: a publish would push the broken state live. Repair master, verify on preview, publish only the repaired items.
  • may_be_intentional marks policy findings (no webhook, unset editing secret on a delivery-only app, drafts): the user decides.

Read the report, then remediate (never from the doctor)

Exit 0 clean · 1 findings ≥ P1 or UNKNOWN · 2 harness error. Work P0 first. Each finding carries evidence, a remediation line, an owner (cms / code / ops) and, with an item id, Pages and Content Editor links. Typical routes:

  • content (cms): fix on master, verify on preview, publish only the item; stale Edge orphans → smart-publish the parent or an EdgeOrphans scan (UI);
  • code: a bug report with the evidence;
  • ops: variables, context ids, webhook re-enable after the receiver is fixed (sitecoreai-edge-admin-webhooks).

Layout of the report, statuses and the finding schema: references/report-format.md.

The five gates, standalone

Go-live pipelines can call these directly; same scripts, same verdicts (exit 0 pass, 1 fail, 2 unknown):

ScriptGate
scripts/check-edge-context.mjs --env <cm> --site <s> [--app-env-file <pulled .env>]...LIVE id serves the home route; each app env carries the LIVE id (preview = P0)
scripts/check-live-robots.mjs --url <live> --visibility public|private [--auth-cookie]robots per visibility; CM-host Sitemap: line is advisory
scripts/check-media-delivery.mjs --url <live> [--pages /,/x]unfollowed 200, non-HTML, from Edge; no media found = unknown
scripts/check-live-templates.mjs --root <site root> [--context-id <live id>]no item of the site reads UnknownTemplate on LIVE Edge (unpublished template); a template not on Edge at all is a P2 advisory; absent root = unknown
scripts/crawl-live-links.mjs --url <live> [--require-browser]every internal link resolves; MissingComponent; media sources on a dev host; noindex; console errors

Run standalone, the crawl finds Playwright only from the cwd: point PLAYWRIGHT_MODULE at a head app's node_modules/playwright (with --require-browser, no browser = exit 2, never a pass). The context gate reads credentials from DOCTOR_ENV_FILES / --env-file. Exit codes are set via process.exitCode (a hard process.exit() while sockets close tripped a libuv assertion on Windows: exit 127 after a printed verdict).

Estate parity: before moving a site to another tenant

scripts/check-estate-parity.mjs --site <s> --a-ctx-file <f> --b-ctx-file <f> [--lang en,de-DE] [--normalize-cm-host] compares one site's LIVE Edge delivery on two contexts (source and target tenant): route set, component structure, fields, route metadata, dictionary, media set, and an unfollowed GET of the target's media. Exit 0 parity, 1 differences, 2 undecided. A context file holds a bare id or a pulled .env. Prove the instrument first: A vs A must give 0; --pair /x=/y of two different routes and --site-b <other> must give 1. The full move procedure (drift probe, same-path cleanup, push, publish, parity, repoint, revert): the sitecoreai-cli-cloud-workflow skill, its estate-move reference.

When NOT to use

  • To fix anything, publish, re-enable a webhook or clear a cache: those are writes; route the finding to its owner.
  • As proof that a page is published: only the live Edge leg proves that, and the doctor reports it, it does not change it.
  • For a disk-only audit of a checkout (schema, map keys, authorability): use those audits directly.
  • For load testing: the throttle and caps exist because Edge limits are shared with production.

References and related skills

  • references/check-catalogue.md: every check with surface, cost, severity, v0.1 status and the measured traps.
  • references/query-recipes.md: Authoring, Edge, Deploy, Monitoring and Edge Admin reads with their measured limits.
  • references/log-signatures.md: formats, the level-aware signature table, reading rules.
  • references/report-format.md: exit codes, statuses, finding schema, redaction.
  • Shapes: sitecoreai-graphql-schemas · census: sitecoreai-edge-graphql-capture · webhooks: sitecoreai-edge-admin-webhooks · CLI logs and ser pull to scratch: sitecoreai-cli-cloud-workflow · robots: content-sdk-app-router-sitemap-robots · revalidate: content-sdk-app-router-cache-components-and-osr.

SitecoreAI localization (CM + Edge)

A language exists at three layers, versions live per item, Edge serves what was published per language, and the head app 404s whatever Edge does not return. This skill orders the CM work and says how to prove each step. The head app (routing.ts, next-intl, <html lang>, links) is content-sdk-app-router-dictionary-and-i18n.

Tags: [measured 2026-10-02] observed on a real tenant; [probe-gated: X] unproven, X names the open check.

1. Three layers

LayerHoldsWrite surface
Environment/sitecore/system/Languages/<name> items: Iso, Regional Iso Code, Fallback Language, charset/codepageAGQL addLanguage (org client OK); Sites POST/PATCH/DELETE /api/v1/languages (env client)
SitesupportedLanguages[] (subset of env)Sites PATCH /sites/{id}; Channels > Localization
Host (Site Grouping)languageSettings{defaultLanguage, languageEmbedding, itemLanguageFallback, fieldLanguageFallback}, analyticsIdentifiers[]Sites PATCH /sites/{id}/hosts/{hostId}; the Site Grouping item

Read the effective site values with AGQL site(siteName){ language properties{ key value } } (enableItemLanguageFallback, enableFieldLanguageFallback, languageEmbedding, dictionaryDomain).

Existence check: languageItem(name:"de-DE") (null when absent). Not language(name:): it returns a culture object for any valid name, existing or not [measured].

2. New-language runbook

Each step ends with a read-back on an instrument other than the one that wrote.

  1. Add the environment language. AGQL:
    mutation { addLanguage(input:{ languageCode:"de", regionCode:"DE", fallbackCode:"en" }){ successful } }
    
    Read back languages{ nodes{ name } } and languageItem(name:"de-DE"){ fields(ownFields:true){ nodes{ name value } } }: expect Regional Iso Code=de-DE, Fallback Language=en [measured]. Env-wide: every site's language list shows it. Removing a language deletes its versions everywhere; treat the add as permanent. Custom cultures: [probe-gated: G15].
  2. Enable it on the site (supportedLanguages) and set the host language settings. Env client or UI [probe-gated: G8].
  3. Assign an analytics identifier for the language on the host; a new language has none, so personalization and analytics are off for it (sitecoreai-personalization R2).
  4. Create versions (§ 3) or AI-translate (§ 6). Compose layout per language: __Final Renderings is versioned, so a new version starts with an empty final layout; shared __Renderings stays shared.
  5. Version datasources in place (update_content(language, createNewVersion:true) or addItemVersion + updateItem(language)); never build a parallel Data/ tree per language.
  6. Dictionary phrases (§ 5).
  7. Workflow per language version (shared fields bypass it).
  8. Publish every language once (§ 7), including /Dictionary with subitems or the site root.
  9. Read back per locale on live with a known-bad locale as control (§ 8), then run the census.
  10. Keep the head app in step: check-locale-drift.mjs in the i18n skill (routing.locales must list the language with identical casing).

3. Creating language versions: what each surface does

[measured 2026-10-02]

CallResult
AGQL addItemVersion(input:{itemId, language:"de-DE"})version 1, every versioned field empty (standard-value tokens such as $name are not re-expanded), __Final Renderings empty. The route exists on preview and renders blank
MCP add_language_to_page {pageId, languageRequest:{language}}{success:true}, same empty version, no version number returned
MCP update_content {itemId, siteName, language:"de-DE", createNewVersion:true, fields} on an item without de-DEcreates de-DE v1 with only the written fields
MCP update_content without languagewrites en (schema default) — and with createNewVersion:true adds en v2, not a language version
AGQL updateItem(input:{itemId, language:"de-DE"}) without a de-DE versionerror "does not contain version # in 'de-DE' language"; nothing created
AGQL createItem(language:"de-DE")item with no en version (Edge en → null)
Unknown language (xx-XX) on addItemVersion / add_language_to_page"Value cannot be null. Parameter name: language"
Pages POST /pages/{id}/version {language, site, baseVersion}[probe-gated: G7-REST] (copies or empty?)

Whole-site copy: the SXA Add Site Language script copies all items and values from a source language (UI).

4. Fallback

NeedUseRequires
Regional variant (en-AU → en)item-level fallbackFallback Language on the language item, Enable Item Fallback on the item or its __Standard Values, the environment patch, a first publish of each fallback version
Template partly translatedfield-level fallbackfield-definition flag; not on shared, __Standard Values or __ system fields; never combined with item-level on one item
Genuinely different contentno fallbackmissing version = 404 in the head app (honest)
"Show the default language if missing" in the appnot an SDK featurefallback above, or custom getPage retry code
  • Edge delivery fallback is governed by the environment patch ExperienceEdge.EnableItemLanguageFallback / EnableFieldLanguageFallback (both default false, a /platform config patch + CM deploy, infra under the repo's change rules). Measured on an environment without it: the de-DE → en rule plus __Enable item fallback=1 on the item → Edge preview layout(language:"de-DE") null, and AGQL fields(withLanguageFallback:true) empty. Whether the host itemLanguageFallback flag alone changes Edge: [probe-gated: G1].
  • Rules are applied at publish time: publish each fallback version once; after any fallback toggle, republish everything affected [probe-gated: G3 on this platform; documented].
  • __Enable item fallback is a shared field. Dictionary entries have it on by default in their __Standard Values [measured], which still delivers nothing without the env patch [measured].
  • Detection in the head app: layout.sitecore.context.language / route.itemLanguage [probe-gated: G3].

Details: references/fallback-config.md.

5. Dictionary

  • One domain per site: <site>/Dictionary, template Dictionary Domain 0a2847e6-9885-450b-b61e-f9e6528480ef; the site property dictionaryDomain points at it. Entries: template 6d1cd897-1936-4a3a-a511-289a94c2a7b1, Key = Shared, Phrase = Unversioned (one value per language) [measured].
  • Write (AGQL): createItem(input:{name, templateId:"{6D1CD897-…}", parent:<domain id>, language:"en", fields:[{name:"Key",value:"HeaderOpenMenu"},{name:"Phrase",value:"Open menu"}]}), then addItemVersion(language:"de-DE") + updateItem(language:"de-DE", fields:[{name:"Phrase", value:…}]). The Key carries over (shared).
  • Edge returns the KEY as the phrase when the language version is missing, the phrase is empty, or the language is not even an environment language; total counts entries regardless of language [measured]. "value === key" is the only untranslated signal.
  • Dots in keys are accepted by Edge but next-intl treats them as nesting: keep keys dot-free.
  • Publishing a single entry does not refresh Edge; publish the /Dictionary item with subitems or the site root [documented; probe-gated: H5]. Measured symptom of skipping it: every site on a test environment had a populated dictionary in master and on preview and total: 0 on live.
  • Shared dictionaries: Fallback Domain on the consuming domain → the shared domain; publish the shared site first [probe-gated: G4].
  • Serialization: /Dictionary as ItemAndDescendants, push Create-only, so content edits are not overwritten.

6. AI translation

SurfaceShapeWorks with
AGQL translatePage / translateItem / translateSite{pageId|itemId|siteId, sourceLanguage, targetLanguage, translateIfTargetVersionExists: Boolean!, resetWorkflow: Boolean! = false, brandKitId} (+ translateDescendants: Boolean! on item) → { job { handle done status{ jobState processed messages exceptions } } }org client [measured]
Sites POST /sites/{id}/translate, Pages POST /pages/{id}/translate{sourceLanguage, targetLanguage, translationStrategy: AddVersion|SkipIfExists} → bare stringenv client; return value [probe-gated: G6-REST]
Pages / Channels UIadds "Keep workflow state" (UI-only)author
  • One target language per call. Poll AGQL with job(input:{handle}) until done (a one-page job finished within 5 s, processed:1) [measured].
  • Translated [measured]: Single-line, Rich text (markup kept), NavigationTitle, metadata description. Documented list: Single-line, Multi-line, Rich text, General Link text/title, Image alt; versioned or unversioned only; shared fields never. Audit field sharing first (itemTemplate → field items Shared/Unversioned).
  • translateIfTargetVersionExists:false on a page that already has the version → job finishes with no units processed, no new version (idempotent skip) [measured].
  • Unknown target → SiteManagement:400: Invalid target language name. Never invent enum values: REST has exactly AddVersion and SkipIfExists.
  • Workflow state of an API translation: [probe-gated: V3]. Cost: AI credits per call; tell the user before bulk runs.

Input types verbatim: references/agql-language-mutations.md. Surface/credential map: references/api-surface.md.

7. Publishing per language

  • AGQL: publishItem(input:{rootItemId, languages:["en","de-DE"], targetDatabases:["experienceedge"], publishItemMode:SMART, publishSubItems:false, publishRelatedItems:false}){ operationId }; poll publishingStatus(publishingOperationId){ isDone isFailed state } [measured].
  • Publishing REST: locales go per item or in options.xmc.locales, never both (400). options.xmc.site publishes the whole environment; use item-rooted jobs (sitecoreai-publishing).
  • Unpublish one item without touching parents: set __Hide version=1 on each language version and publish the item again in those languages → live layout null [measured]. Then delete from master.
  • Orphan versions: versions can exist in a language the environment does not define (serialization pushes them). Preview serves them; live had none [measured]. Adding the language later makes them publishable by the next all-language publish: decide before that publish.

8. Read back on Edge

Live is the strict surface; preview is permissive (it serves master, orphan languages included).

query($s:String!,$p:String!,$l:String!){ layout(site:$s, routePath:$p, language:$l){ item{ language{ name } url{ path } rendered } } }
  • Run with the target language (known-good) and an unlisted one such as fr-FR (known-bad: null). Edge's language argument is case-insensitive [measured]; the head app's is not.
  • url.path has no language segment on live or preview [measured].
  • siteInfo(site).routes(language:$l) lists the published routes per language; item(path, language){ languages{ language{ name } } } lists the languages with a version on that surface (no supported-language list exists on SiteInfo).
  • Dictionary: siteInfo(site).dictionary(language:$l, first:$f, after:$a) with first as a variable. Live clamps first > 1000 with a warning; preview errors on it, and preview rejects a literal first ≥ 61 as "Query is too complex" [measured].

Census:

node scripts/language-census.mjs --site <Site> --cm https://<cm-host> --env-file .env --cred-prefix <CLIENT_PREFIX> --edge-context-env <CTX_VAR> [--strict] [--json]
node scripts/language-census.mjs --self-test

Read-only (every document passes assertQuery; a mutation is refused before any request). Reports env languages, site fallback flags, pages / datasources / dictionary entries per language, Edge routes and dictionary per language; findings orphan-language, missing-page-version, dict-missing-version, dict-empty-phrase, edge-route-missing, edge-dict-absent, edge-dict-untranslated, unused-env-language.

9. Traps

TrapEffect
MCP delete_content {language:"de-DE"}deletes the whole item, every language [measured]; Agent DELETE /content documents the same. Delete one language with AGQL deleteItemVersion
MCP update_content without languagewrites en silently [measured]; always pass it
MCP update_fields_on_itemhas no language parameter
MCP create_page fields[{"Title":"…"}]; {name,value} objects fail "Cannot find a field with the name name" [measured]
language(name:) used as an existence checkalways non-null for a valid culture
New language, no analytics identifierpersonalization/analytics off for it
__Final Renderings versionednew language starts with an empty layout
Shared fieldsleak across languages, bypass workflow, are not translated
Edge dictionary untranslatedreturns the key, never empty
Org automation client on Sites/Pages REST401 (host-addressed AGQL works) [measured]
Sites GET /api/v1/languages/supported without a tokennot anonymous: 404 "Authorization header is missing" [measured]

Stop conditions

  • Stop before deleteLanguage: it removes every version in that language across the environment.
  • Stop before any publish that covers a whole site or /sitecore/content in all languages on a shared CM: check for orphan-language versions first (census).
  • Stop before the fallback env patch or a host fallback toggle without an explicit ask: both need a full republish of affected content.
  • Before the first MCP write of a session, probe the binding (one throwaway item, read back through AGQL and Edge with known-good/known-bad controls, delete).

References

  • references/agql-language-mutations.md: introspected input/payload types.
  • references/fallback-config.md: env patch, host flags, field flags, doc conflicts.
  • references/api-surface.md: which operation on which API with which credential.
  • REST shapes: sitecoreai-sites, sitecoreai-pages, sitecoreai-agent, sitecoreai-publishing; GraphQL shapes: sitecoreai-graphql-schemas; MCP composition: sitecoreai-content-composition.

Pages API

Direct CRUD on pages. Lower-level than the Agent API — prefer Agent API when the task maps to a marketer-level outcome, use Pages API when you need per-field control, version/variant lifecycle, or layout manipulation.


Base URL

https://xmapps-api.sitecorecloud.io

(Spec servers[0] — "Production server". All requests run against the production environment.)

Auth & scopes

OAuth 2.0 client-credentials → JWT Bearer. See the sitecoreai-auth skill.

  • Security scheme: Bearer (HTTP bearer), applied globally (security: [{ Bearer: [] }]). Every operation requires the JWT; the spec defines no per-operation OAuth scope strings.
  • Token request: POST https://auth.sitecorecloud.io/oauth/token with grant_type=client_credentials and audience=https://api.sitecorecloud.io.
  • Granted scope: the token response carries xmcloud.cm:admin — a single admin-level scope, not granular per-endpoint :r / :w scopes.
  • Accept: application/json header is required on every request (per the spec's auth section). Header format: Authorization: Bearer {JWT}.

Versioning

Current: v1 (info.version: v1). Paths are /api/v1/....


Endpoints

Resource groups: Pages · Versions · Live / Variants · Aggregation (batch).

The full path × method table is in references/endpoints.md; request bodies and key response fields per operation are in references/schemas.md. Both are regenerated from the spec — read them when you need an exact path, method or field name; the sections below carry what the spec does not say.

Errors

All operations share RFC-7231 ProblemDetails error bodies (type, title, status, detail, instance, plus traceId + per-field errors map in examples):

  • 400 Bad Request — validation failure (e.g. a required property missing).
  • 404 Not Found — page / resource not found (not returned by the create, blueprint, and the two aggregation endpoints).
  • 503 Service Unavailable — GET /pages/search only, when the search service is down.

(There is no 406 response declared in the spec — see the curated Pitfalls note for the empirical Accept-header behavior.)


Version / variant model

  • Versions are composite-keyed by (versionNumber, language). Deleting a version requires both.
  • Variants are personalization variations of a page. They are created/managed via the Agent API personalization endpoints; the Pages API only reads which variants are currently live.
  • To audit Edge state: GET /pages/{pageId}/live for the page, GET /pages/{pageId}/live/variants for its variants.
  • Numbered vs language version. A language version is the first version in a language; a numbered version is version N+1 in a language that already has one. Whether POST /pages/{id}/version copies the base version is still open (probe-gated), while Authoring addItemVersion and MCP add_language_to_page were measured to create an EMPTY language version (2026-10-02). translate covers local datasources (documented). "Keep workflow state" exists in the UI only. Language work: sitecoreai-localization.

Patterns

Safe update

const token = await getSitecoreToken();
const res = await fetch(`https://xmapps-api.sitecorecloud.io/api/v1/pages/${pageId}`, {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${token}`,
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ fields: { Title: "New title" } }),
});

Duplicate → modify → rename (common "make a variation" flow)

  1. POST /pages/{pageId}/duplicate → get new pageId.
  2. PATCH /pages/{newId} → set the fields that differ.
  3. POST /pages/{newId}/rename → give it a proper system name.

Check live state before publishing

Before telling a marketer "this is live", call GET /pages/{pageId}/live. Edge publication can lag authoring.


Pitfalls

  • Accept: application/json required. Missing header → 406 Not Acceptable.
  • /pages/search matches names, not body content. For content-aware search use Agent API.
  • Version deletion is irreversible. No soft-delete; no revert equivalent at the Pages API level. (Use Agent API jobs to mutate if revertibility matters.)
  • Layout replacement is total. POST /pages/{pageId}/layout replaces the whole layout, not a merge. Fetch → modify → write back.
  • JWT expires in 24 h. Cache. See the sitecoreai-auth skill.
  • Rate limits undocumented. Implement backoff.

OpenAPI bundle

Full schema: api-docs.sitecore.com/_bundle/sai/pages-api/index.yaml

Sources

SitecoreAI personalization — backend setup

The ask looks like "on the home page hero, visitors from audience X see different content". This skill turns that into: pick the mechanism, check prerequisites, create the audience and variant, give the hero its own content in that variant, publish, and prove it works at every layer. The head app must already be able to serve variants; that side is content-sdk-personalization.

When to use

  • Creating, changing, auditing or removing a page personalization on a SitecoreAI tenant.
  • Translating a marketer's audience description into condition templates and params.
  • Not for the proxy, rewrite, rendering, caching or consent wiring in the head app (content-sdk-personalization), and not for Headless rendering variants (the FieldNames display variant; see sitecoreai-content-composition § Variants). set_component_variant is personalization / A/B only.

Mental model: four layers, written by different APIs

LayerHoldsWritten byRead by
Flow (embedded Personalize)audience (condition groups), splits, status, friendlyId embedded_[scope_]<pageIdNoDashes>_<lang>create_perso_version_multi / POST /api/v2/personalization/{pageId}/versionslist_page_flows, get_flow_definition
CM page layoutper-variant COPY / SWAP / HIDE on a rendering, per page version and languageset_component_variant / POST /api/v1/flows/{flowId}/variants/{variantId}get_flow_variant_by_id, get_components_on_page(variantId)
Edge projectionpersonalization.variantIds, each rendering's experiences{}publishEdge GraphQL, Pages GET /pages/{id}/live/variants
Enablementanalytics identifier per site language; PAGES_PERSONALIZE_SCOPESites API / Channels UI; Deploy env varSites API, Deploy API

All variants travel in the Edge layout JSON; the head app's proxy asks the decision service which one to render, server-side, and fails open to the default on any error. So "the page renders" proves nothing.

1. Choose the mechanism

Page variant (default)Component personalization (decision tables)A/B/n test
Decideswhich page variant a visitor gets; each variant changes one or more componentswhich variant of one component; rows top-down, first match winsrandom split
Hero optionsCOPY, SWAP, HIDE, per-variant layout/styling (UI only)Duplicate / Hide / SwapCopy / Swap / Hide
Limits≤ 10 variants per page, ≤ 5 conditions per audience, one embedded experience per pageundocumented≤ 6 variants, ≤ 6 concurrent tests per page
Versioningper page version and languageshared across versions, including live (a draft edit changes production)—
API / MCPyes, end to end except publishnoneyes; no start/stop verb
StatusGAphased rolloutGA

Decision rule

  • One to ten audiences, each with its own hero → page variant with COPY. The default.
  • Many fine-grained rules on one component, maintained by a marketer → decision tables. UI-only: hand off, do not attempt by API.
  • "Which hero converts better?" → A/B/n, on a page without personalization. The docs say A/B/n is refused on a personalized page, so the two are mutually exclusive per page (API enforcement direction [probe-gated: P8]).
  • Hero must vanish for audience X → page variant with HIDE.
  • Hero only for audience X → add the hero, create the variant, then hide_component_perso_default_page hides it on the default page.

2. Prerequisites — check read-only before any write

#CheckHowFails as
R1Personalization enabled on the tenantget_perso_cond_tmpls returns 18 templateserror or empty
R2Analytics identifier on the site language. Never assume one: a serialization-pushed site has none (measured 2026-10-15) and added languages get none. Create it in the portal; the Sites API only assigns existing onesSites API host analyticsIdentifiers (sitecoreai-sites), then the portal's Site hosts page shows no "missing analytics identifier" warningthat language never personalizes or tracks
R3Scope match: CM env var PAGES_PERSONALIZE_SCOPE equals the head app's personalize.scope (both empty is a match). Alphanumeric, case-sensitive; changing it later orphans existing rulesDeploy API env vars (read); head-app envwrong friendlyId → 404 No experiences found for friendlyId … at the wire (measured P7); the SDK turns it into the default, silently
R4Head app serves variants: PersonalizeProxy in the chain, production build against LIVE Edgeask, or check via content-sdk-personalizationdefault hero, silently
R5Consent narrows reach: visitors without consent get the default hero by designhead-app consent gateexpected; put it in the acceptance criteria
R6Publish path: neither the MCP nor the Agent API publishessitecoreai-publishing credentialsvariant never reaches Edge
R7Binding probe before the first MCP write of the session: throwaway item, read back through Authoring GraphQL and Edge with known-good and known-bad controls, delete it. get_page_preview_url names the bound tenant—writes land on the wrong tenant
R8Read before write: list_page_flows(pageId, language). A create on a page that already has an EXPERIENCE flow appends another variant; an EXPERIMENT flow means A/B conflictlist_page_flowsduplicate variants
R9Every write below is a real-tenant mutation: get the user's go-aheaduser—

Existence check: use list_page_flows ([] = none). get_perso_ver_by_page returns an error Not Found (404) on a page with no personalization; treat it as "none", never as a failure to retry.

3. Recipe: "personalize the home hero for audience X" (Marketer MCP)

MCP first. Exact params: references/mcp-tools.md. REST bodies for the same steps: references/rest-bodies.md. Every write tool has a confirmation flag (userConfirmation / userConfirmed): show the inputs to the user, then send true.

  1. Locate. list_sites → get_all_pages_by_site(siteName, language) → the home pageId.
  2. Find the hero. get_components_on_page(pageId, language) → note the hero's id (instance uid), componentId (rendering definition), and dataSourceItem.path.
  3. Pre-check (R8). list_page_flows. Existing EXPERIENCE → reuse it (step 4 appends a variant; that is the only way to add one). Existing EXPERIMENT → stop and escalate.
  4. Translate the audience. Map the requested audience to templates in references/condition-templates.md. Prefer request-context templates (UTM, referrer, device, OS, country, point of sale): they decide on the first request and are testable with a negative control. History templates (page views, new/returning, affinity) need tracked VIEW events, therefore consent and prior visits. page_view ("viewed page X this visit") joined within seconds for a fresh consented visitor (3/3, 2026-10-07): the choice for behaviour in the session (test method: references/condition-templates.md § page_view). Params are keyed by the placeholder label in the template JS, verbatim: utm_value needs type, compares to, UTM value and UTM value(s) (both required).
  5. Create. create_perso_version_multi(pageId, name, variantName, audienceName, conditionGroups, language). conditionTemplateId is the uuid ref. The first group has no unionType; later groups need AND or OR. Do not use create_perso_version (flat v1 shape; the v1 create 400s on utm_value). An audienceName with parentheses → 400; plain text works.
  6. Get the ids. The create response (or list_page_flows / get_flow_definition) carries the flow ref and two variant ids. Use the template variant id: the 32-hex value inside transpiledVariants[].tasks[0].input.template / traffic.splits[].template ({"variantId": "7de9…"}). The dashed transpiledVariants[].ref is the "variant ref". Variant tools reject it: Requires template Variant Id, not variant ref (400). The 32-hex id is also what Edge variantIds, _variantId_<v> and pageVariantId use. The create ignores your name and names the flow <page name> <lang> - <PAGEID>; variant and audience names are kept.
  7. Give the hero its own content. set_component_variant(flowId, pageId, componentId=<instance uid>, variantId, variantStrategy="COPY", language, pageVersion=0). The response's datasource is the path of the new copy: a sibling of the original datasource named <original>_var1. If the original lives in a site-shared Data folder, so does the copy.
  8. Edit the copy. get_content_item_by_path(<copy path>) → update_content(itemId, siteName, fields, language) (siteName is required). Edit the copy, never the original.
  9. Read back. get_flow_variant_by_id → hero variantStrategy: COPY and the new datasourcePath; get_components_on_page(pageId, language, variantId) → the copy's fields; the default page's hero still points at the original.
  10. Publish (§ 5), then verify (§ 8).

Audience builder (Performance → Audiences) is a different surface: batch segments over profile, session and event attributes, not the 18 condition templates. Its filterable attributes (observed 2026-10-06): references/audience-builder-attributes.md. It is UI-only and batch-scheduled: for behaviour in the current session prefer the embedded page_view condition. Two consequences: event extension data (ext) is not selectable, so put the segmenting value in a custom event's type (or name); UTM is a session attribute, so a campaign audience needs no custom event.

4. Variant content: COPY, SWAP, HIDE

StrategyEffectUse when
COPYcopies the component and its rendering parameters into the variant, creates and assigns a copy of the datasource; you then edit the copynew hero copy for the audience (default)
SWAPreplaces the rendering with swappedComponent{componentRenderingId, datasourcePath} (both required)a prebuilt hero datasource, or a different hero rendering. Same rendering id + another datasource = the UI's "assign content item": via the MCP it worked first try on a rendering created through the normal component path, no Agent API fallback (measured 2026-10-07)
HIDEremoves the component in that variantthe hero must vanish for the audience

The naming trap. get_components_on_page returns two ids per component. components[].id is the instance uid: set_component_variant.componentId, reset_component_variant, hide_component_perso_default_page take it. components[].componentId is the rendering definition: only swappedComponent.componentRenderingId takes it. Swapping them fails or targets the wrong thing.

Editing traps

  • Inline editing in Pages inside a variant edits the default page unless the variant already has its own datasource. Same rule by API: COPY (or SWAP) first, then edit the copy.
  • The COPY datasource is a normal content item: it needs its own language version, its own workflow state and its own publish. Measured: it lands next to the original as <original>_var1, inherits the source's __Created, and has no workflow of its own. reset_component_variant does not delete it: it becomes an orphan to remove (and unpublish) yourself.
  • CM serialization: COPY writes a personalization rule on the rendering into __Final Renderings: rule s:name = template variant id, condition {8E7426A4-…} s:VariantName=<v>, action {0F3C6BEC-…} s:DataSource=<copy path> (a path, not a GUID), plus a Default rule. Details: references/rest-bodies.md.
  • Per-variant layout or styling has no API (UI only).
  • Under workflow, the page version carrying the variant and the copy both need the approved state before publish [probe-gated: P23].

5. Publish

Visitors see nothing until the page and the copied datasource are published to the single Edge target. Use sitecoreai-publishing (scoped item publish, locales in one place) or Authoring GraphQL publishItem (rootItemIds:[page, copy], SMART, publishSubItems:false, publishRelatedItems:false). The REST API needs xmcpub.jobs.*: an org client with only xmcloud.cm:admin gets 403 there, while AGQL publishItem works with the same token. Measured: job FINISHED in about 37 s, Edge LIVE carried the variant on the next read.

  • The flow is PRODUCTION from the moment of create, and publish does not touch it. What gates visitors is only Edge LIVE variantIds, which appear when the page is published.
  • Edge PREVIEW shows the variant right after set_component_variant, with no publish: use it for sign-off, never as proof for LIVE.
  • A page under an unpublished parent has no LIVE route (layout: null). Publish the parent (item only) too, and expect null, not [], as the pre-publish control.

6. Change and undo

NeedToolNote
Change the audienceupdate_perso_versionfull replace: send variantName, audienceName, conditionGroups
Undo the hero setup in a variantreset_component_variant(flowId, pageId, componentId, variantId)omit variantId to reset the default page's component
Undo a whole REST sequencePOST /api/v1/jobs/{jobId}/revert with the sequence's x-sc-job-idcoverage [probe-gated: P23]
Delete / pause / schedule / archive the experienceno verb in the MCP or the Agent API. update_ab_test(archived:true) on an EXPERIENCE flow returns 500 and changes nothingreset + republish + delete the orphaned copy, then hand the flow removal to the user (Pages UI). Until then /v1/personalize keeps returning the variant; harmless only because Edge variantIds is empty. reset leaves a Default-only ruleset in __Final Renderings (Edge then emits experiences: {})

After any undo, republish the page.

7. Per-language behaviour

  • The flow is per language: friendlyId ends _<lang> (lowercased, first hyphen → _). A German hero needs its own create with language: "de", its own datasource language version, and an analytics identifier on the de site language (R2).
  • One create per language = one flow per language; region locales; the locale-prefix path trap [probe-gated: P11].
  • Duplicated environments that share page ids share their variants; PAGES_PERSONALIZE_SCOPE exists to separate them.

8. Verification ladder — each layer independent

#LayerCheckPassControl
1Flowlist_page_flowsone EXPERIENCE; audience as writtenno duplicate variants (append trap)
2Variant setupget_flow_variant_by_idhero variantStrategy: COPY, new datasourcePathdefault hero still on the original datasource
3EdgePages GET /pages/{pageId}/live/variants; Edge layout{ item{ personalization{ variantIds } } }<v> present; hero has experiences["<v>"]before publish: [], or layout: null if the route was never published. After reset + republish: [] and experiences: {}
4DecisionPOST /v1/personalize with the audience's input{variantId: "<v>"}same call without it → 200 {"message":"No matching variant"} (measured). Unknown or wrongly scoped friendlyId → 404 No experiences found for friendlyId …
5Renderproduction build on LIVE Edge, real browser UA, consent set, e.g. ?utm_campaign=…HTML shows the copywithout the input → original hero; a headless UA counts as a bot
6Beaconbrowser network POST …/v1/events/v1.2/events2xx, ext.pageVariantId ends _<v>default visit ends _default
7AnalyticsPage builder Personalize analytics / dashboardLinksvariant views appearhuman read only (no API). dashboardLinks was null at create and after publish (P7): send the user to Pages → page → Personalize

Layers 4–6 are head-side; the scripted probes live in content-sdk-personalization. Calls and bodies: references/rest-bodies.md § Verification.

9. Fallback: Pages UI click path

Page builder → Editor → select the page and language → Personalize tab → Create variant → name → Create your audience → add up to 5 conditions (AND/OR, groups) → Save → select the variant → click the hero → assign content item (or create one; never inline-edit first), or replace / hide the component → edit; a teal border marks a personalized component → Preview → publish page and datasource. Decision tables are only reachable this way.

10. Gaps — escalate, do not work around

  • No analytics read API. An agent can set up a personalization but cannot report its performance or pick a winner (only dashboardLinks and the Data lake export).
  • Decision tables have no API or MCP tool, and the head-app contract is undocumented [probe-gated: P9].
  • Missing lifecycle verbs: no delete, pause, start, schedule or archive for experiences; no publish in the MCP or Agent API; no per-variant rendering-parameter API; no custom-condition create.
  • Decision as data (an arbitrary JSON payload per audience, web or interactive experiences) is a standalone Sitecore Personalize capability, not embedded personalization.
  • v1 deprecation is inconsistent: the v1 create/list are marked removed (August 2026) yet still answered in September 2026 and 400 on multi-param templates. Write only through v2 create; PUT …/versions/{variantId} and /api/v1/flows/* stay current.
  • Geo audiences fall back to cf-ipCountry / cf-region-code headers, which describe the proxy's server unless the head app forwards visitor geo [probe-gated: P12].

Related skills

  • content-sdk-personalization — head side: proxy decision, variant grammar, rendering, caching, decision and beacon probes.
  • sitecoreai-agent — full Agent API endpoint tables (the API behind the Marketer MCP).
  • sitecoreai-pages — /live/variants, page components and layout.
  • sitecoreai-publishing — the publish step.
  • sitecoreai-sites — analytics identifiers on site hosts.
  • sitecoreai-auth — environment automation client and scopes.
  • sitecoreai-content-composition — page composition; Headless variants are not personalization.

References

  • references/condition-templates.md — the 18 OOTB templates: uuid ref, param keys with types and enums, output sentence, request vs history.
  • references/mcp-tools.md — Marketer MCP read and write tools with real parameter names.
  • references/rest-bodies.md — Agent API v2 bodies for every recipe step, undo and verification calls.
  • references/audience-builder-attributes.md — audience builder filter attributes (profile, session, five event kinds) and what cannot be filtered on.

Publishing API

Create and monitor publishing jobs for a SitecoreAI tenant.


Base URL

https://edge-platform.sitecorecloud.io

All endpoints live under /authoring/publishing/v1/jobs.

Auth & scopes

OAuth 2.0 client-credentials → JWT Bearer (the spec's Bearer HTTP security scheme, bearerFormat: JWT; sent as Authorization: Bearer <token> without the Bearer prefix in the token value). See the sitecoreai-auth skill.

The spec defines per-operation scope requirements. Each operation accepts one of an a (all-jobs) scope or a t (tenant/own-jobs) scope:

Endpoint groupRequired scope (one of)
Read — GET /jobs, GET /jobs/{id}, GET /jobs/filters, GET /jobs/summaryxmcpub.jobs.a:r, xmcpub.jobs.t:r, or xmcpub.jobs.t:rl
Permissions — GET /jobs/permissionsNo scope — only a valid token is required
Write — POST /jobs (create)xmcpub.jobs.a:w, xmcpub.jobs.t:w, or xmcpub.jobs.t:wl
Cancel — POST /jobs/{jobId}/cancelxmcpub.jobs.a:w, xmcpub.jobs.t:w, or xmcpub.jobs.t:wl
  • The :rl / :wl suffix is limited (read-limited / write-limited): the principal operates only on the jobs they initiated, not all tenant jobs.
  • Limited-write (xmcpub.jobs.t:wl) for create/cancel additionally requires the Sitecore Client Advanced Publishing or Sitecore Client Publishing role, or the admin flag set in SitecoreAI.
  • Application/client-credentials tokens additionally require the xmcloud.cm:admin scope (spec note on POST /jobs and POST /jobs/{jobId}/cancel). Without it, calls return 403.

Versioning

Spec info.version: v1.0. Path prefix is /authoring/publishing/v1/.


Endpoints

Resource groups: .

The full path × method table is in references/endpoints.md; request bodies and key response fields per operation are in references/schemas.md. Both are regenerated from the spec — read them when you need an exact path, method or field name; the sections below carry what the spec does not say.

Errors

All error bodies use ProblemDetails ({ type, title, status, detail, instance }, RFC 7807-style):

StatusWhen
400Invalid parameters / job ID / name / items / mode / locales / source / tenant.
401Unauthorized request or invalid access token.
403Authorization failed (missing scopes/roles, or xmcloud.cm:admin missing on an app token), or context tenant cannot be resolved.
404Job not found (GET /jobs/{id}, POST /jobs/{jobId}/cancel).
409Cancel rejected — job is not Queued/Running (POST /jobs/{jobId}/cancel).
501Cancel not supported for SitecoreAI Content (POST /jobs/{jobId}/cancel).

POST /jobs returns 201 with the job; POST /jobs/{jobId}/cancel returns 202 (cancellation accepted, async).


Job lifecycle

queued → in progress → completed
                    ↘ failed
                    ↘ canceled
  • queued: created, waiting for a worker.
  • in progress: executing. Cancellable via POST /jobs/{jobId}/cancel.
  • completed: finished successfully. Final state.
  • failed: terminated with error. Final state. Inspect job details for error payload.
  • canceled: user-cancelled. Final state.

GET /jobs/summary returns a count in each state — drive dashboards off this endpoint, not by listing all jobs.


Create-job request body (the shape POST /jobs needs)

⚠️ POST /jobs takes a NESTED body; the FLAT shape that GET /jobs/{id} returns will 500. Verified live + against the official OpenAPI (api-docs.sitecore.com/_bundle/sai/publishing-api/index.yaml):

{
  "name": "content publish",   // required, ≤256 chars
  "source": "my-app",          // required, free string (later filterable via ?source=)
  "options": {
    "xmc": {
      "locales": ["en"],                 // required for a site publish
      "site": { "mode": "Smart" }        // Republish (full) | Incremental | Smart (changes only)
    }
  }
}
  • options.xmc.site = whole-ENVIRONMENT publish (named site for legacy XM reasons but it publishes every site on the env — there is NO site-identifier field). Mutually exclusive with the Tier-1 item form: { "options": { "items": [{ "id", "type", "locale?" }], "xmc": { "items": { "mode": "Smart", "publishRelatedItems?": false, "publishChildren?": false } } } }.
  • mode: Smart = items modified since the last publish (fast, the usual choice) · Republish = full re-emit · Incremental.
  • publishChildren is job-wide, not per item. There is no exclude: an item with children on takes every descendant, so a site Home with children also publishes a build-only subtree under it. To publish a site minus a subtree, list every item explicitly (publishChildren: false, publishRelatedItems: false); ~1,000 items in one job completed with 0 failed (measured 2026-10-06). Adding a locale to such a job reports language-variant deletes in the statistics; they are expected.
  • GET /jobs/{id} normalizes this to a FLAT options.xmc.{ type:"Site", mode, locales } — that read-back shape is informational; never POST it.

Patterns

Kick off a publish and wait

const token = await getSitecoreToken();
const base = "https://edge-platform.sitecorecloud.io/authoring/publishing/v1/jobs";

// Create — body per "Create-job request body" above
const create = await fetch(base, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    name: "content publish", source: "my-app",
    options: { xmc: { locales: ["en"], site: { mode: "Smart" } } },
  }),
});
const { id } = await create.json();

// Poll (exponential backoff — do NOT poll every second).
// ⚠️ status lives at job.system.status (US spelling), NOT a top-level job.status.
const TERMINAL = ["Completed", "Failed", "Canceled"];
let delay = 2_000;
while (true) {
  await new Promise(r => setTimeout(r, delay));
  const res = await fetch(`${base}/${id}`, { headers: { Authorization: `Bearer ${token}` } });
  const job = await res.json();
  if (TERMINAL.includes(job.system?.status)) return job;   // job.statistics has itemsProcessed / itemsFailed
  delay = Math.min(delay * 1.5, 30_000);
}

Publishing dashboard widget

  1. GET /jobs/summary on a timer (60 s is plenty) → counters.
  2. GET /jobs?status=in_progress → live list, capped at page size.
  3. Use GET /jobs/filters once on load to populate filter dropdowns.

Limited-write cancel

Users with only :wl can cancel only the jobs they initiated. If cancelling someone else's job is required (e.g. platform-admin tooling), the principal needs :w.


Pitfalls

  • Offset pagination caps at 1000 records. For larger audits use checkpoint pagination (see OpenAPI schema). Do not naively loop beyond offset 1000 — the API will reject it.
  • :wl users can cancel only their own jobs. Surface clear error messaging when the principal lacks scope.
  • xmcloud.cm:admin gotcha. Application tokens (client_credentials) need this extra scope or every call returns 403. This is the #1 setup mistake.
  • Job creation is async. POST /jobs returns quickly with a job ID; the actual publish runs afterwards. Always poll — do not assume immediate completion.
  • No callback: push instead of poll. The Publishing API cannot notify you. For "content is live on Edge" register an Edge webhook (sitecoreai-edge-admin-webhooks, OnUpdate; it arrives 86–175 s after publish start, live 2026-10-02). Poll only jobs you started yourself.
  • An org automation (deploy-admin) token gets 403 here (no publishing scope). Use the environment's CM client token, or publish through Authoring GraphQL publishItem, which worked with the CM client in the S5 probes (2026-10-02).
  • Statistics are eventually consistent. /jobs/summary may lag individual job-detail reads by a few seconds.
  • Rate limits undocumented. Back off on 429 / 5xx.
  • Nested create body is mandatory. POST /jobs needs options.xmc.site.{mode} + options.xmc.locales (see "Create-job request body"). The flat GET shape → 500. The #2 setup mistake after the xmcloud.cm:admin scope.
  • itemsFailed is env-wide and often chronic — do NOT attribute it to your items. A Smart publish re-attempts EVERY modified-since item across EVERY site on the env, so a backlog of broken items (bad links, missing required fields) shows up as failures on an unrelated publish. Confirm scope first with GET /jobs/permissions (canCreate: true); compare itemsProcessed vs itemsFailed in job.statistics; check job history (GET /jobs — note: OLDEST-first, pageSize max ~100) to see the chronic baseline before blaming your change.
  • A "Completed" job can still have failures. Terminal status Completed only means the job ran; inspect statistics.itemsFailed. Individual failure reasons are not in the job payload — surface them from Pages UI.

Sources

SitecoreAI search sources (integrated search backend)

A search source is the index a SitecoreAI search component queries. It is managed under Content > Search sources in the SitecoreAI app, per environment. The head-app half (hooks, SearchService, the starter component) is content-sdk-search.

Status markers: [confirmed] = measured 2026-10-02 (read-only); [docs] = documented, not yet measured; [probe-gated: Pn] = open, the named hands-on probe closes it.

The three programmatic surfaces (and what is missing)

SurfaceEndpointCredentialStatus
QueryPOST https://edge-platform.sitecorecloud.io/v1/search, /v1/search/suggestEdge context id in x-sitecore-contextid (public)[confirmed] reachable; every CM context of a test org was recognised (preview and live)
Config readGET https://edge-platform.sitecorecloud.io/search/v1/config?sitecoreContextId=<id>Bearer with a search-config scope[confirmed] no auth → 401 Config endpoint requires Authorization; org automation client (Deploy + xmcloud.cm:admin) → 403 insufficient scopes; Edge admin client → 403. Works through the Marketplace SDK (xmc.search.getConfigs); which non-Marketplace credential carries the scope [probe-gated: P3]
Push (Ingestion Service API)POST {base_url}/v1/index/{source id}/pushAuthorization: ApiKey <key> (instance-wide)[docs]; {base_url} host [probe-gated: P3/P6]
Create / edit / reindex a source——No documented API. UI only, until a network capture proves otherwise [probe-gated: P3]

Not this: Authoring GraphQL search(query:), Edge search(where:), sitecore index rebuild and the Indexing Manager all target CM Solr / item search. Standalone Sitecore Search (discover.sitecorecloud.io, 52-char API key, rfk.domainId) is a different product. The Marketer MCP has no search-source tools (search_site etc. search pages and assets).

Rollout preflight (per environment)

  1. Search sources appear under Content > Search sources in the SitecoreAI app for that environment. The docs flag every page "phased rollout"; push sources appear only in the developer docs, so check push separately [probe-gated: P2-UI].
  2. The Search Configuration Manager Marketplace app is installed for that environment (it adds the Search Configuration tab in Page builder). Scriptable install [probe-gated: P2-UI].
  3. The search plane recognises the environment's context id: the probe-search script of content-sdk-search (fake-context control → 404 No sitecore context; your context + fake index → 404 no search index found). A recognised context proves the plane, not that the Search sources UI is enabled or that any source exists.
  4. A source id exists: from the source's Settings tab (field "ID"), or scripts/search-config.mjs with a credential that carries the scope.

Choose the source type

Content lives in…SourceCaveat
Sitecore items of ONE template, simple field typesContentpublished items only; manual reindex; one template per source (the config API's templateIds[] hints at more [probe-gated: P4])
Rendered pages, metadata, a non-Sitecore siteSite (crawler)crawler must reach the site; sitemap required; scheduled re-index
External system of record, or must be fresh in real timePushyou own the full document set; no history kept
Sitecore items that must be fresh on publishContent source + Edge webhook → push upsert, replayed after every reindex; or a push source fed only by the webhookpushes into a content/site source are temporary

Field types. Content: Checkbox, Text, Rich Text, Single-Line, Multi-Line, Number, Date, Datetime, Image. Site: Boolean, String, Number, Tag. Push: the schema you declare. Reference fields (Multilist, Droplink, Treelist, General Link) cannot be indexed; the UI rejects them at configuration time [docs]. Denormalise into a text field on the item, or use a push source. A third-party report adds __Created / __Updated and page components as non-indexable [probe-gated: P4].

Field flags and the language multiplier

Each field has Include, Searchable, Filterable and Sortable. Filterable fields become facets, and the head app filters them by the facet's display name (content-sdk-search). The Searchable allowance grows with the number of languages on the source; the cap is unpublished. Plan languages before fields: adding a language later multiplies the cost of every searchable field. Whether languages can be added after creation, how fallback versions index, and the locale format [probe-gated: P4].

Rules: Boost / Bury per keyword or all keywords (higher in the list wins), Pin to a slot; boost/bury override semantic relevancy and pins survive reranking. Advanced: semantic reranking and fuzzy search (fuzzy needs at least one Searchable field; with both on, fuzzy runs only after a zero-result query). Toggling either after creation [probe-gated: P4].

Setup is UI-only (click paths in references/source-setup-checklists.md)

Creating a source, editing fields and rules, reindexing, creating push credentials and mapping a page component to a source all happen in the UI. These are manual steps for the user, never something an agent claims to have done. Record the source id the user reports and verify it with a live query.

Wire a page to a source. The datasource item's search field (type Plugin, Source = Search Configuration Manager) holds {"searchIndex":"<source id>","fieldsMapping":{…}}. The supported writer is the Search Configuration tab in Page builder. Writing the JSON with the Marketer MCP update_fields_on_item is possible in principle; probe the MCP binding first (sitecoreai-content-composition). The exact JSON the app writes [probe-gated: P7].

Environment promotion. The source id lives in content (the datasource JSON). If source ids differ per environment, a serialized or content-transferred datasource points at the wrong index after promotion; re-map per environment or keep the datasource out of shared serialization [probe-gated: P2-UI] (whether ids or an export exist per env).

Multisite. A content source binds a template environment-wide, and the context id is environment-scoped, not site-scoped: two sites sharing the template share the index unless you filter [probe-gated: P4].

Freshness: reindex discipline

  • Content sources do not update on publish. Saving a new source runs the first ingestion; after that, new or changed published items appear only after a manual Reindex content [docs]. Latency, and whether unpublished items linger until the reindex [probe-gated: P5].
  • A reindex rebuilds and swaps the index, and a crawl or reindex replaces it: documents pushed into a content or site source are wiped [docs; probe-gated: P6]. There is no push history; replay the full set.
  • Publish-driven freshness = Edge OnUpdate webhook (sitecoreai-edge-admin-webhooks) → handler reads the item from Edge → push upsert with id = item id → replay everything after each reindex. Or make a push source the single system of record.
  • Search does not run on Preview or in Page Builder; verify with a live query after publish + reindex.

Ingestion Service API (push) in one screen

Full contract and the replay algorithm: references/ingestion-api.md.

  • POST {base_url}/v1/index/{source id}/push, Authorization: ApiKey <key>. A bearer token fails with tenant ID not found in JWT claims [docs; probe-gated: P6].
  • Keys: Search sources > Settings > Create credential (the docs also name a "Profile import" page: which is real [probe-gated: P6]), shown once, instance-wide (one key writes every source), Org Owner/Admin only in production. Server-only: never a NEXT_PUBLIC_ variable; store as SITECORE_SEARCH_PUSH_APIKEY.
  • Body { "operations": [ { "action": "upsert"|"delete", "id" | "sc_url", "canonical_url"?, "locale"?, "fields"? } ] }: 1-50 operations and ≤ 512 KiB per request, else the whole request is rejected (413 on size).
  • Every value is a string; datetimes YYYYMMDDTHHMMSSZ (ISO 8601 rejected); field names case-sensitive and must exist in the schema; sc_* and @search.action reserved.
  • 200 all succeeded · 207 partial: walk results[].succeeded · 400 / 401 / 403 (search.pushapi:m) / 404 (source missing, unpublished, other instance) / 413 / 500 / 503 (ingestion disabled). Rate limits undocumented.
  • Writes go straight to the live index. There is no dry run on the server: scripts/search-push.mjs validates locally and sends only with --yes.

Site sources

Crawler NAT IPs (allowlist these, not the standalone-Search IPs): East US 20.172.208.83 · West Europe 108.143.62.79 · Southeast Asia 137.116.136.218 · Central US 172.202.98.116 · Japan East 20.89.57.44 · Australia East 68.218.91.35 · West US 2 20.69.120.121 · UAE North 20.74.155.9 [docs]. The crawler reads the sitemap (content-sdk-app-router-sitemap-robots). WAF / bot protection blocks it. Whether it honours robots.txt, gets through a private-delivery access gate, and its user-agent [probe-gated: P9]: a site with Disallow: / or an auth gate should be assumed uncrawlable.

Analytics

Performance > Search (CTR, null searches, ignored searches; 30-min sessions; 2 months back) needs both an index and a search component sending type:'search' events. The starter's nullResults: false defect and the consent gate are in content-sdk-search. Dashboard ingestion [probe-gated: P7].

Scripts

  • scripts/search-config.mjs --context-env <VAR> [--env-file <f>] (--bearer-env <VAR> | --client-prefix <PREFIX>) [--json] [--datasource <source id>] — read-only. Fake-context control first; lists sources with id, name, type, template ids and per-field flags (search/filter/facet/sort with display names); explains 401/403. --datasource prints a datasource JSON stub for that source.
  • scripts/search-push.mjs --endpoint <base_url> --source <source id> --file <ops.json> [--yes] [--key-env SITECORE_SEARCH_PUSH_APIKEY] — validates locally (count, size, strings, datetime format, reserved names, identity); sends only with --yes; refuses without an explicit --source, refuses a key on argv, refuses non-HTTPS endpoints; exit 1 on any 207 failure.
  • Both: --self-test runs a fake-fetch suite plus a mutation sweep that disables each guard in turn and fails if nothing notices.

Hard rules

  1. Never claim a source, reindex or credential was created by an agent: they are UI steps; record what the user reports and verify by query.
  2. Never put the push ApiKey in client code, argv, logs or captures.
  3. After every reindex of a source that also receives pushes, replay the pushes.
  4. Treat 404 No sitecore context as "wrong or dead context id", and 404 no search index found as "context fine, source id wrong or not yet created".

Related

content-sdk-search · sitecoreai-edge-admin-webhooks (OnUpdate feed) · marketplace-sdk-xmc (xmc.search.getConfigs) · content-sdk-app-router-sitemap-robots · sitecoreai-content-composition (MCP writes) · sitecoreai-health-check.

Sitecore Content Serialization: module design

Serialization (SCS) is how developer-owned items (templates, renderings, placeholder settings, branches, the site shell) travel with the code. The CLI mechanics of reaching a tenant (login, connect, user.json, allowWrite, endpoint names) live in sitecoreai-cli-cloud-workflow. This skill is the layer above: what a module contains, how it is cut, and how it is deployed. Almost every failure here is silent or destructive: a default that deletes, a pull that writes the wrong tenant, a push that stops halfway and exits 0.

Schema tables, an annotated module and the xmcloud.build.json options: references/module-json-reference.md.

The model in five lines

  1. sitecore.json → modules: [globs] finds every *.module.json. serialization.defaultModuleRelativeSerializationPath sets where YAML lands when a module gives no items.path.
  2. A module = namespace (unique) + items.includes[] (+ optional references, roles, users, excludedFields).
  3. An include = name (it is the on-disk folder name) + path + scope + allowedPushOperations + rules[].
  4. Rules are first-match-wins, relative to the include path; finish a selective include with { "path": "*", "scope": "Ignored" }.
  5. A content item may be included only once across all modules.

Defaults that hurt

PropertyDefaultWhy it hurts
scopeItemAndDescendantsAn include with no scope takes the whole subtree, including author content under it
allowedPushOperationsCreateUpdateAndDeleteA push deletes every item in scope that is not on disk, author-created items included
items.paththe shared default rootSibling modules share one folder tree (§ Grain)
-n (environment)defaultResolves to whatever endpoint the last login wrote, which can be another tenant

Set scope and allowedPushOperations on every include explicitly, and treat a missing one as a review finding.

Choose the site strategy first: shell or full record

Decide this once per collection; it changes every site include.

StrategySite includeWhen
Full record (default here)ItemAndDescendants, CreateAndUpdate, no "*" → Ignoredgit must be able to rebuild a tenant or move an estate; content is pulled after authoring
Shell only (Sitecore's Accelerate sample)selected children, /Home SingleItem CreateOnly, "*" → Ignoredauthors own all pages and git never holds them

The shell shape fails quietly when someone expects a record: a site seeded from it serialized the home item and none of its pages, and every subtree an author added later was dropped without a word. Under the full record, add rules only to change a push policy for a subtree, never to opt a subtree in.

Push policy by item class

Item classPushWhy
Templates, branches, renderings, placeholder settings, /sitecore/system/Settings/Project/<C>CreateUpdateAndDeleteDeveloper-owned: removals must propagate
Site /Presentation (page and partial designs, headless variants)CreateUpdateAndDeleteStructure the code depends on
Tenant root /sitecore/content/<C>CreateAndUpdate, SingleItemThe container only, never its sites
Pages, datasources, dictionary, mediaCreateAndUpdateA push must never delete an authored item
/Settings/Site Grouping (hostnames, robots)CreateOnlyEnvironment-coupled: lands once on a fresh target, never overwritten

Never serialize:

  • A Rendering Host item. Its fields are absolute editing-host URLs for one tenant. CreateOnly does not save you: a fresh tenant still gets the item with dead URLs and the push then refuses to fix it (2026-08-13). Bind the host per environment through the Site Grouping RenderingHost field (a host name).
  • Auto-captured thumbnails. The platform writes a media item per page and site thumbnail under <site media>/System/…; with media at ItemAndDescendants every pull committed them as base64 blobs (632 files, ~14 MB across six sites, 2026-09-28). Cap that folder with a rule at ItemAndChildren.
  • Individual media items as IAR (Sitecore: performance; ship media through scsModules), personalization variants and A/B tests (tenant state), Edge or cache state, and anything under /sitecore/system you did not create. Sitecore's guidance: serialize only under */Project/*.

Include order matters: a template include must come before content that uses it in the same module; use references for templates in another module. An annotated module: references/module-json-reference.md.

Grain: one module per site collection

On a CM that hosts several collections:

  • One module per COLLECTION. A new site in an existing collection gets a new site include in that collection's module, never a second module. A second module would claim the collection's template and rendering paths with CreateUpdateAndDelete, which is exactly the collision.
  • Give every module its own folder. Put <x>.module.json in its own directory and set items.path: ".". A distinct items.path alone is not enough: the items-as-resources build groups modules by where the manifest sits, and fails on two manifests in one folder sharing an include name ("There are several modules … with the same include name … split those modules into folders"), after MSBuild reported 0 Error(s). In one measured CM, 9 of 15 conventional include names collided across 6 modules.
  • Without isolation, validate turns destructive. Two modules sharing the default root made ser validate list the other collection's files as "EXTRA ITEM … > Fix will delete file", and ser pull aborted. One --fix would have deleted another site's source.
  • Include names must be unique within a module (site, site-b, …). Unique across modules is better still: an unscoped op on a CM with shared include names fails at config load.

Operating discipline

  • Every op is scoped and targeted: -i "<Module.Namespace>" -n <endpoint>. Never run unscoped ser pull, ser validate --fix or --force on a shared repo. An unscoped pull from the wrong default endpoint applied 26 changes from another tenant and reported success (2026-09-26).
  • Predict, then verify by count. Before a pull or push, write down what you expect to change. --what-if first, then explain every [D] line before the real run.
  • Live tenant first, then pull. Write through the authoring API or MCP, then ser pull the module, then commit. Do not hand-edit YAML and push it.
  • Pull after the last live write of a unit of work, then run your schema audit before committing. The audit should parse the serialized templates and renderings for broken bases, missing fields and dangling references, and must fail when it finds zero modules: a flat directory scan that finds none after a folder move passes on an empty set.
  • "0 changes" is not "in sync". Pull compares by revision; the signature ignores __Revision, __Updated, __Owner and __Lock, so a value write that does not bump the revision is invisible. Grep the YAML for the value you just wrote.
  • ser validate (read-only) before every commit; --fix only after you have read the delete list. --fix deletes local files: it keeps the newest of a duplicate id and drops whole trees it considers not included.
  • After an item's path changes on the tenant (a site or media-folder rename), the include's .scindex still maps the old paths. ser pull then reports an item "on disk in more than one place", and validate --fix and pull undo each other on every run. Move that include's folders and its .scindex aside (a move, not a delete) and pull it fresh; a second pull must report 0 changes (measured 2026-10-28).

Deploy: IAR or database

Mechanismxmcloud.build.jsonEffect
Items as resourcesdeployItems.modules (omitted = every module)YAML → .dat at deploy; read-only, merged at runtime
Database pushpostActions.actions.scsModules.modulesA push into the DB after every deploy, with each include's push policy
  • An edited IAR item becomes a DB copy that wins forever. Thumbnail generation does it too. Later git changes to that item never apply, and a rebuild does not clear it. Measure overlays by __Revision and by value; a value-only compare missed 9 of 11.
  • ser push skips IAR-only items (90 of 1,026 written in one module). Turning IAR off before materializing them makes them disappear.
  • Removing files only drops the resource copy. An item that an earlier ser push also wrote to the database survives the deployment that drops its YAML: three removed schema folders still listed on the CM afterwards. A scoped ser push of the module removes them where the include is CreateUpdateAndDelete; its --what-if must list exactly the removed subtree roots (measured 2026-10-28). Content includes are CreateAndUpdate, so a site goes through the Sites API delete instead.
  • scsModules with CreateUpdateAndDelete deletes CM-authored dev items that were never pulled, on every deploy. On a developer CM, prefer manual scoped pushes.
  • Roles do not deploy as IAR; use scsModules. A role or user pattern pushed before a pull deletes the matching items on the tenant, because orphans are removed.
  • First deploy of a fresh CM: a module whose paths do not exist yet fails the build (source item path … did not exist). Disable it for the first deploy, create the site, then enable it and pull.

The full push-into-an-IAR-CM procedure (NonUniquePathException recovery, the --trace blob truncation, the reconciliation of what-if results) is the serialization-overlays reference of sitecoreai-cli-cloud-workflow; moving a site to another tenant is its estate-move reference.

Push failures that look like success

  • A missing template aborts the rest of the push and exits 0. Template ID <guid> did not exist stops at that item; everything after it in tree order is stranded. continueOnItemFailure: true does not help. Usual culprit: an empty, unreferenced SXA <site>/Data/Datasource Content Resolver item whose base template ships with a foundation the target lacks. Delete it from disk (keep the Headless Variant of the same name), or serialize and push the missing template first. Verify with a second what-if that reports 0.
  • NonUniquePathException aborts push and pull before any evaluation when a DB-only item sits at a git item's path (a generated site thumbnail, a duplicate folder). Recovery order: the overlays reference.
  • Duplicate sibling names are unsupported by the CLI even under ignored nodes.

Review checklist for a module change

  • Every include has explicit scope and allowedPushOperations; nothing authored is CreateUpdateAndDelete
  • The site strategy (full record or shell) is deliberate; rules ordered most specific first, none wider than its include
  • No Rendering Host item; the auto-thumbnail folder is capped
  • Module sits in its own folder with items.path: "." and a correct $schema path; include names unique
  • No path is included by two modules (ser explain -p <path> answers which module owns it)
  • ser info -i <module> lists the expected subtrees; ser validate -i <module> reports no errors
  • The scoped pull applied the predicted count; the YAML contains the values just written
  • The build config's deployItems / scsModules choice is deliberate for this environment

Related

Site templates and page blueprints

A site template is one item of data template Solution template {1B2DFD3B-F2F2-4F40-A75C-F6C2490919C4}. The Create Site dialog lists every such item through Authoring GraphQL solutionTemplates, wherever it sits. It lists immediately: no deploy, publish or index rebuild.

A new site runs the setup root (HeadlessSiteSetupRoot) of every module in the template's Site Modules. Those setup roots hold AddItem, ExecuteScript and PostSetupStep actions. "Skatepark" is the built-in Basic template.

A page blueprint is a branch template in a collection's Branches/Project/<collection> folder. It is offered through insert options, so "Create a page" produces a prefilled page with $name expanded and page-local datasources. Ids and the scaffold order: references/anatomy.md.

Decide first: site, blueprint or capture

The requirement saysBuildWhy
own hostname, own navigation or brand, separate micrositesite template (build-template)Only a site has its own host, start item, header/footer and Edge site entry. Going live still needs a head-app rebuild (sites are discovered at build) and a host.
campaign / landing / event pages inside an existing sitepage blueprint (build-blueprint)Seconds for a marketer, no new site, host or deploy.
every new site of a template should offer such pagesblueprints inside the site template spec (blueprints[])Each new collection gets its own branch copies.
"save this site / this page as a template"capture (extract-spec), then buildRound trip measured exact on Edge (components, placeholders, grid, styles, text).

Procedures

All scripts take --cm-host <xmc-….sitecorecloud.io> --client-prefix <PREFIX> [--env-file <.env>]. Secrets come only from <PREFIX>_ID/_SECRET.

Site template

  1. Write the spec (references/spec-format.md, example assets/example.spec.json): page types, pages, components, partials, renderingHost, thumbnail (or make-thumbnail.mjs --primary #hex --accent #hex), optional blueprints.

  2. build-template.mjs --spec x.json --component-map <head-app>/.sitecore/component-map.ts --dry-run.

    • The live lint checks that renderings exist and are registered in the head app, datasource and page field names, and the host. Fix the spec until it is clean.
    • Never hand-edit the generated PowerShell.
  3. Run the same command without --dry-run to build.

  4. verify-template.mjs --spec x.json --smoke --environment-id <deploy env id> creates a fresh collection and a site, then checks:

    • the scaffold job exceptions;
    • page types and component counts;
    • partials and the page-design mapping;
    • Home's insert options;
    • every blueprint, by creating a page from it;
    • the host;
    • Edge preview componentNames.

    It then cleans up: the site and collection this run created, nothing else. --keep keeps the site. --site-name <name> names the site and requires --keep, and a name that already exists is refused (exit 2), so an existing site is never removed. --collection <name> reuses an existing collection and requires --keep; it is refused otherwise, so a shared collection is never removed. Done = VERIFIED, plus one site created through the dialog by a human, checked in Page Builder.

Page blueprint in an existing site

  1. Write the blueprint spec: { site, name, pageTemplate?, offerOn?, fields?, components }.
  2. build-blueprint.mjs --spec bp.json --component-map … --smoke --environment-id …. It lints, writes the branch, and offers it on the offerOn templates' standard values and on Home (Home overrides at item level). It then creates a test page, checks it including Edge, and deletes it.

Capture an existing site or page

  1. extract-spec.mjs --site <name> --out x.json --name "…" gives a site-template spec. Add --page "<path under Home>" [--target-site <s>] to get a blueprint spec instead.
  2. Read every WARN. Set renderingHost when the source binds to Default, add a thumbnail, then build and verify as above.
    • Ids that point into the source site (Styles, NavigationRoot, …) become site:<relative path> tokens. They resolve in the new site, and a missing one is logged and skipped.
    • The capture does not carry personalization, child rows under a datasource (add them by hand as datasource.children), or internal links into the source site; each is warned.

Optional, durable: emit-module.mjs writes a serialization module for ser pull -i; without it a template lives only in this CM. Remove: remove-template.mjs. It refuses while foreign items sit under the module roots, Templates or the script library's Functions (hand-made templates; --force overrides) and while sites carry the template's id in SiteTemplate, and reports a locked path instead of stopping.

How generated scaffolds behave

  • Page types. Module page types /sitecore/templates/<Layer>/<module>/<Type> inherit the five base templates of a collection Page. At site creation the script creates collection types of the same name that inherit the module type and the collection Page, which owns Title and Content. It throws if another template family already owns that type name in the collection, and never edits shared collection templates.
  • Pages are created by the script at deterministic paths (Test-Path guards), not by AddItem.
  • Home insert options are set at item level, because the skeleton's item-level Base Page would otherwise hide every page type.
  • Components: -FinalLayout on pages and shared layout on partials. Datasources sit under <owner>/Data as local:/Data/<name>, and each rendering gets a DynamicPlaceholderId. A Container places its children in /<ph>/container-<id>, nested to any depth.
  • Variants: a missing variant is created beside the rendering's Default. A custom rendering has no Headless Variants folder on a new site, so the folder is created too (template from a sibling folder; definition template from an existing definition), and FieldNames is the variant item id.
  • Datasource rows: datasource.children creates child items (gallery frames, list rows, nested to any depth) in array order with explicit __Sortorder. datasource.insertOptions writes the datasource's __Masters, so authors can add rows in Pages. Pages, partials and blueprints take both. A failing child is collected like a failing component, and verify checks the child count and the __Masters read-back. Syntax: references/spec-format.md.
  • Dictionary and settings: dictionary[] makes Dictionary entries and settings{} sets fields on <site>/Settings (e.g. RobotsContent). An unknown top-level spec key warns in the lint. Failures: each component is added inside try/catch, so one failure no longer drops the rest. Failures are collected and thrown once, so the job reports them.
  • Partials become Partial Designs. A Default Page Design maps the collection Page and every type to them. The host is bound in a PostSetupStep, which logs when the host is missing.

Traps (full list with evidence: references/traps.md)

  1. The dialog is a different runtime than the API. A site created in the dialog from a script that passed template paths came out with pages but no components (Spe.log: NullReferenceException in New-Item). Generated scripts use template IDs and master: paths. Have a human create one site through the dialog before calling a template done.
  2. Scaffold failures are silent. The job ends FINISHED and the dialog shows success; only job.status.exceptions has the error. Always smoke-verify.
  3. The collection decides page templates. The starter's scripts rewrite the collection Page base. The dialog keeps one template family per collection, but createSite over the API does not.
  4. Home's item-level __Masters (Base Page) overrides page-type insert options.
  5. The rendering host is a literal name with no existence check. Sites from Basic bind to Default.
  6. Sites depend on template modules after creation: renderings are referenced, page types are inherited. Deleting or un-deploying breaks the layout while the content survives.
  7. Site names are unique CM-wide. Enabled=0 shows greyed out. No thumbnail gives a skeleton card.
  8. Captured layouts carry ?-prefixed s:par (Basic), site-local Styles and NavigationRoot ids, and site-created variants (Banner on Image). The extractor and scaffold handle all of them.
  9. Edge preview lags creation by seconds. In Git Bash, / arguments become Windows paths (MSYS_NO_PATHCONV=1).

Scope

  • Proven live: three templates (one written by hand, one captured from a stock Basic site plus a blueprint page) and blueprints both in templates and in an existing Basic site. Coverage includes two-deep containers, partials, custom text and date fields, thumbnails, host binding, Edge on every route, and an exact capture round trip.
  • Not generated: column splitters, personalization, multi-language content, workflow, media copying across CMs. Custom renderings need an availableRenderings group and must exist in the head app.
  • Starter templates as a worked example: references/starter-ccl.md.

Sites API

Manage the structure of a SitecoreAI tenant: sites, collections, languages, hosts, editor profiles, and the page hierarchy underneath each site. This is the XM Apps Sites API — the core entity model is the Site Collection (group of related sites that share resources), the Site (a website in the portfolio), the Language (tenant/site language management), and the Job (background work handle). All requests run against your production environment.


Base URL

https://xmapps-api.sitecorecloud.io

Single production server (info.servers[0]). No sandbox/staging host.

Auth & scopes

OAuth 2.0 client-credentials → JWT Bearer. See the sitecoreai-auth skill for the full flow. The spec declares a single global security scheme — Bearer (type: http, scheme: Bearer) applied to every operation; there are no per-operation scope requirements declared in the spec.

Concrete values (from the spec's info authorization section, matching sitecoreai-auth):

  • Token endpoint: POST https://auth.sitecorecloud.io/oauth/token with grant_type=client_credentials.
  • Audience (literal, fixed): audience=https://api.sitecorecloud.io — not the API base URL, not .com, no trailing slash.
  • Scope returned on the token: xmcloud.cm:admin (the admin scope covering XM Apps automation; the spec's sample token response shows "scope": "xmcloud.cm:admin"). The spec does not enumerate finer-grained per-endpoint scope strings — automation clients are granted the default XM Apps scopes.
  • Header: Authorization: Bearer {JWT} plus Accept: application/json on every request.
  • Token lifetime: 24 h (expires_in: 86400); cache and refresh on 401.

Creating the automation client requires Organization Admin or Owner role in Cloud Portal — the credential form is hidden otherwise.

Path prefixes:

  • /api/v1/... — standard endpoints (sites, collections, languages, hosts, hierarchy, favorites, jobs, statistics, sitemap, translate).
  • /api/ui/v1/... — editor-profile (page-builder toolbar) endpoints only.

Versioning

  • info.version: v1.
  • Two path prefixes carry the version: /api/v1/... (standard) and /api/ui/v1/... (editor-profile UI surface).

Endpoints

Resource groups: Sites · Hierarchy (page tree) · Hosts · Site Collections · Languages · Favorites · Editor Profiles · Background Jobs.

The full path × method table is in references/endpoints.md; request bodies and key response fields per operation are in references/schemas.md. Both are regenerated from the spec — read them when you need an exact path, method or field name; the sections below carry what the spec does not say.

Errors

Standard RFC-7807 ProblemDetails body { type, title, status, detail, instance } plus optional errors map (e.g. { "sampleProperty": ["...required"] }).

StatusWhere it appears
400 Bad RequestValidation failures — present on nearly every operation.
401 UnauthorizedEditor-profile endpoints (and any expired/invalid token).
403 ForbiddenEditor-profile endpoints (insufficient role).
404 Not FoundAny {id}/{handle} lookup miss.
409 ConflictHost create / update (hostname collision).
503 Service Unavailablename/validate, localization & workflow statistics (search service down).

Async write operations return 200 with a JobResponse { handle } (or 202 Accepted) rather than the finished resource — poll GET /jobs/{jobHandle}/status.


Patterns

Build a site tree view

  1. GET /sites/{siteId}/hierarchy → root level.
  2. Lazy-expand: GET /sites/{siteId}/hierarchy/{pageId}/children on node click.
  3. Breadcrumbs: GET /sites/{siteId}/hierarchy/{pageId}/ancestors.

Create a new site

  1. GET /sites/templates → pick a template id.
  2. POST /sites/name/validate with { name } → validate.
  3. POST /sites with { siteName, templateId, collectionId, language } (measured 2026-10-28; templateId as a braced GUID) → returns a job handle.
  4. Poll GET /jobs/{jobHandle}/status until done: true with errors: [].

A new collection (POST /collections with { name, displayName, description }) is a job too: poll it before the POST /sites that names its id, or the collection is not listed yet. A site may not carry its collection's name. POST /sites answers 400 "A site with that name already exists" even though validate said valid. Create the site under a temporary name and rename it (below); a collection and a site of the same name then work.

Rename, swap or delete a site

Measured 2026-10-27/28 on one environment (two renames, a swap, a delete):

  1. POST /sites/{id}/rename with { name } (not newName: that is 400 "The name field is required") → job. It renames the site root and its media folder.
  2. It does not rename the Site Grouping item or its SiteName field, which is what the runtime resolves the site by. Set both through Authoring GraphQL (updateItem on SiteName, renameItem on the grouping item) and read them back.
  3. Republish each renamed site's Settings subtree and read siteInfoCollection on the live Edge context. After two renames plus one subtree republish, live Edge listed neither name while layout(site: …) still resolved and preview was correct. A Content SDK build reading the site list then fails IV-007 Site "<name>" does not exist.
  4. DELETE /sites/{id}?force=true → job; it removes the site's content and media. It does not unpublish: live Edge keeps the site in siteInfoCollection until its parent is republished. Items that serialization deployed as resources come back from the deployment, so take them out of git first.

Set a custom site thumbnail (the dashboard card image)

Measured 2026-09-28:

  1. POST /sites/{siteId}/upload-thumbnail with multipart/form-data field File (PNG verified). The call returns 200 with the media item { id, name, itemPath, url }. The item lands at <site media root>/System/thumbnail_<siteId>, and a re-upload overwrites that same item.
  2. Max 1 MB. A larger file returns 400 "Thumbnail size is more than 1MB" and nothing is written.
  3. The image is stored as uploaded, with no resize. The card crops it to 400×221, so upload at about 1.81:1. 800×442 is 2× and comes to roughly 430 KB as a PNG screenshot.
  4. Read back with GET /sites/{siteId}. Expect thumbnail.autogenerated: false and a url naming thumbnail_<siteId>. The media url is on the CM with db=master: it answers 302 anonymously and 200 with the bearer token.
  5. The custom thumbnail is sticky. A no-op PATCH /sites/{siteId} leaves it in place. resetThumbnail: true on the PATCH presumably goes back to the auto-generated one, but that path has not been probed.

Why bother. The auto-generated thumbnail is a 600×600 capture of the home page that can land without CSS on a Content SDK head app: real content rendered as raw monospace text. It stays wrong until something replaces it. A full-viewport screenshot fails the 1 MB limit at 1440 wide with a 1× scale, so render at a 1440 viewport and set deviceScaleFactor to about 0.55.

Add a language tenant-wide

  1. GET /languages/supported → find the ISO code.
  2. POST /languages with the code → becomes available for page versions.

Multi-language (measured 2026-10-02 unless marked). SiteLanguageSettings live on the hosts (PATCH /sites/{id}/hosts/{hostId}), not the site. PATCH /languages/{isoCode} takes the regional code (de-DE) and sets the fallback rule. GET /languages/supported is not anonymous: without a token it answers 404 "Authorization header is missing"; an org automation client gets 401 (use an environment client). Localization statistics answer 503 while search is down. Site.languages vs supportedLanguages is still open. Full runbook (add, enable, translate, fallback, publish, census): sitecoreai-localization.

Batch live-variant check

For a dashboard listing many pages, do one POST /aggregation/pages/live/variants with the page IDs instead of N calls to the Pages API /pages/{id}/live/variants.

⚠️ Sync note (2026-06-24): the aggregation endpoints this pattern relies on are not present in the v1 Sites API spec (sha a26e933…) — neither /aggregation/pages nor /aggregation/pages/live/variants. They may have been removed, never shipped under Sites, or live on a different API surface. Verify against a live tenant before depending on this pattern; if you need active variants today, fall back to N calls against the Pages API. Pattern retained pending re-confirmation.


Pitfalls

  • Cascading deletes. DELETE /collections/{id} removes every site in the collection. DELETE /sites/{id} also breaks shared-item links that other sites depend on. Always confirm via UI flow before calling from an automation.
  • Site-name rules. Max 50 chars, Latin alphanumeric + spaces/dashes, no leading/trailing space, no leading dash. Use /sites/name/validate rather than inventing your own regex.
  • Deprecated renderinghosts. Already marked deprecated — migrate any integration to editinghosts now, not later.
  • Site creation is async. POST /sites returns a job handle, not a ready-to-use site. Poll /jobs/{jobHandle}/status.
  • Automation client requires Org Admin/Owner role — plan for a role-bearing account to register the client, even if the app itself runs as a service.
  • Rate limits undocumented. Back off on 429 / 5xx.
  • Analytics identifiers: assign, never create. The host PATCH takes analyticsIdentifiers: [{ name, language }] (a list; the GET returns a { "<lang>": "<name>" } map, and sending the map back is a 400). It only assigns an identifier that already exists. An unknown name still returns 204, lands in the Site Grouping POS field and in GET /sites/analytics-identifiers/{name}, and the portal then flags the host "missing their analytics identifier": no API read catches it (probed 2026-10-15). Create the identifier in the portal (Site hosts → Analytics and personalization → Create new), then assign it. A site created by serialization push has none.

OpenAPI bundle

Full schema: api-docs.sitecore.com/_bundle/sai/sites-api/index.yaml

Sources

Sponsors

Details

Marketplace
Chris1415/sitecore-skills-pocs
Source
plugins/sitecore-platform
Category
Sitecore
License
Apache-2.0

More from Chris1415/sitecore-skills-pocs

All 8