
sitecore-platform
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-pocsRun it inside Claude Code after adding the marketplace with /plugin marketplace add Chris1415/sitecore-skills-pocs.
Contents
Discovered from sourceSkills 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, fixedaudience=https://api.sitecorecloud.io- Forward the returned
access_tokenasAuthorization: Bearer {JWT}+Accept: application/json. - JWT lifetime is 24 h (
expires_in: 86400) — cache persitecoreai-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):
| Scope | Covers |
|---|---|
xmcloud.cm:admin | Content management (pages, content, components, assets, jobs) |
personalize.exp:mng | Manage personalization experiences / experiments |
personalize.tmpl:r | Read personalization condition templates |
personalize.pos:mng | Manage personalization point-of-sale / placement |
ai.org.bri:r | Read briefs (org scope) |
ai.org.bri:w | Write briefs (org scope) |
co.briefs:r | Read briefs (collaboration) |
co.briefs:w | Write briefs (collaboration) |
ai.org.brd:r | Read brand kits (org scope) |
cmp.sites:read | Read sites (added to the list by 2026-10) |
platform.tenants:list | List 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:
| Status | Meaning |
|---|---|
422 | Unprocessable entity — HTTPValidationError ({ detail: ValidationError[] }, each { loc, msg, type }). The catch-all for malformed bodies / bad params (e.g. a non-integer version). |
401 | Unauthorized — implied by HTTPBearer; expired/invalid JWT. Re-auth per sitecoreai-auth § 6. |
201 | Returned on successful creates (pages, content, components, datasources, experiments, personalization variants, briefs, flow-variant setup, job revert). |
The spec does not enumerate
429or5xxshapes — rate limits are undocumented (see Pitfalls).
Patterns
Create a page with content in one sequence
POST /pages/create→ getpageId.GET /pages/{pageId}/placeholders/{ph}/allowed-components→ find usable component IDs.POST /pages/{pageId}/componentsfor each placement.POST /components/{componentId}/datasources→ attach content.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:
GET /personalization/condition-templates→ pick a template (param keys = the placeholder labels in the template).POST /api/v2/personalization/{pageId}/versionswithcondition_groups→ new flow + variant. Use v2 only: the deprecated v1 create (singlecondition_template_id+ flatcondition_params) returned400 "Failed to update flow definition"for the multi-paramutm_valuetemplate on 2026-09-22, where the identical params succeeded on v2. The flow isPRODUCTIONat create and its suppliednameis replaced by<page> <lang> - <PAGEID>.POST /flows/{flowId}/variants/{variantId}(COPY / SWAP / HIDE) andPOST /flows/{flowId}/variants/reset(undo one component).POST /personalization/{pageId}/components/{componentId}/hidehides 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:
| Param | Type | Required? | Default | Notes |
|---|---|---|---|---|
version | integer | yes | — | 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. |
width | integer | no | 1200 | Rendered viewport width (also controls output image width). |
height | integer | no | — | 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. |
language | string | no | en | Language 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-authskill, § 5. - All requests are production. No sandbox audience.
x-sc-job-idis mandatory for audit. A call made without it cannot be reverted as part of a job.- Composite endpoints return partial success. A
POST /pages/createthat succeeds in page creation but fails on a follow-up component add will still return a201on the page. Always check theoperationsarray in the response or viaGET /jobs/{jobId}/operations. - Site context is required for most page-level reads (
GET /pages/search,GET /components). PassingsiteIdvs.siteNamediffers 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:
- Ask the user directly, upfront. One question, offered as a choice:
"This app will call the SitecoreAI . To authenticate I need a
client_idandclient_secretfrom 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." - 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. - If (b): read
.env.local→.envin that order. If either variable is present, use it. If both are empty or missing, escalate to step 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> | Scope | Example var |
|---|---|---|
DEPLOY | Deployment, screenshot / proxy-to-Agent-API | SITECORE_DEPLOY_CLIENT_ID |
CM | Authoring 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 |
AI | AI-driven API calls — Brand Management, Brand Review, Pipeline (future) | SITECORE_AI_CLIENT_ID |
CDP | Standalone 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 |
EDGE | Edge 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-webhooks | SITECORE_EDGE_CLIENT_ID (per environment SITECORE_EDGE_<ENV>_CLIENT_ID) |
| bespoke | Any other integration with its own automation client | SITECORE_<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:
| Need | Credential |
|---|---|
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 tests | Agent 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.localfor dev) before creating the client — the secret is shown once.
2. Create an automation client
- Cloud Portal → your tenant → Settings → Automation clients (sometimes labelled "Application access" / "Client credentials" depending on the portal rev).
- Click Create client, give it a descriptive name (e.g.
myapp-prod-agent-api). - 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:adminfor application tokens. Read vs. write vs. limited-write is differentiated by:r,:w,:wlscope suffixes.
- Copy both the
client_idandclient_secretimmediately — 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.iofor all four APIs. Do not substitute the API's base URL — it will return401.
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:
- Invalidate the cache.
- Retry the original request once with a fresh token.
- 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/jsonis 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
- 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.
- 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. - 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.
| Register | Use for | Dials | Avoid |
|---|---|---|---|
| brand (default for site copy) | Page copy on the brand's surface | The spec's voice attributes, vocabulary and tone | Any voice the spec does not describe |
| marketing | Launch, landing or campaign content | Benefit first; second person; superlatives earned by specifics; rhythmic and tight; imperative closers | Empty buzzwords, walls of text, hedging |
| technical-neutral | Documentation, specs, legal or factual content | Third person or imperative; no emoji; flat, precise statements of behaviour, inputs and limits | Personality, 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 inmarketplace-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:
- Device-flow login.
dotnet sitecore cloud login. Prints a URL + device code; user authenticates in a browser. Token persists in.sitecore/user.jsonunder endpointxmCloud. - Find the project ID.
dotnet sitecore cloud project list— prints every project the user's org can see. There is no--namefilter; grep by name yourself. CaptureProject Id(e.g.<22-character id>). - List environments for that project.
dotnet sitecore cloud environment list --project-id <PROJECT_ID>.--project-idis REQUIRED — the command errors without it. CaptureEnvironment IdandEnvironment Name. - Connect to one environment.
dotnet sitecore cloud environment connect --environment-id <ENV_ID>. This appends a new endpoint to.sitecore/user.jsonnamed after the environment (e.g."prod"). It does NOT set this as the default;defaultEndpointremains"default", which doesn't exist. - Patch
user.json. Open.sitecore/user.jsonand set"allowWrite": trueon the new endpoint (otherwise even read commands likeser pullare blocked). Optionally set"defaultEndpoint": "<env-name>"so subsequent commands work without-n. - Pull.
dotnet sitecore ser pull -n <env-name>(or omit-nif you patcheddefaultEndpoint). Output lists items added/updated/deleted ([A],[U],[D]).
Hard Rules
-
cloud project listoutputs prose, not JSON. Use--jsonif you need structured output for piping. There is no name filter — grep yourself. -
cloud environment listrequires--project-id. Get it from step 2. -
cloud environment connectdoes not updatedefaultEndpoint. Either pass-n <env-name>on every subsequent command, or hand-edituser.jsonto setdefaultEndpointto the new endpoint key. -
allowWrite: falseblocksser pull, not just push. The CLI treats local filesystem writes as "writes." SetallowWrite: trueon the endpoint before pulling. -
The connect command supports
--allow-writeflag 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 Namefrom 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 afterconnectto confirm). -
Run the repo-local tool, never a global one:
dotnet tool run sitecore …. A globalsitecore.cli(5.2.109) shadowed the repo's pinned local CLI, then refused to load theSerialization/Publishingplugins at thesitecore.jsonpin (6.0.23) and at the only versionplugin addoffered (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.jsonon its own. Plugin versions track the CLI major. Move the CLI in.config/dotnet-tools.jsonand everySitecore.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 pushskips 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
__Revisionas well as values;--tracetruncates 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 --tracefirst, 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 listreturns 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 whoseEnvironment Hostmatches the host in the existing layout response (or the host in.env.local'sSITECORE_API_HOSTif set). - Do not enable push (
--allow-writeon 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.jsonto "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.jsonwith"lastUpdated"and a freshaccessTokenon 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 vsscsModules, 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.
list_sites→ the site id + name.get_all_pages_by_site(siteName)→ the existing page tree (also your structural reference for how real pages are built).- 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). - 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. - 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. - 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_phas 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-voicetakes 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, confirmcomponentRenderingIdis inget_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 flatfields. Returns thedatasourceId. The MCP auto-setsGridParameters+DynamicPlaceholderIdto match siblings. Read back WHERE the datasource landed (datasourceLocationon 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) andget_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
./Datafolder — always available, for every such rendering; - the global per-component container under the site
Datanode — available because the rendering'sDatasource Locationfield 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.
| Content | Home | Where |
|---|---|---|
| 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 pages | GLOBAL | /<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 LOCAL | under 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'scomponentIdis the rendering instance id (components[].idfromget_components_on_page) — not the rendering id (components[].componentId). Both sit in the same payload.create_component_ds(siteName, componentId, dataFields)does place globally (resolvingDatasource Location) and helpfully returnsdatasourceLocation— 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. Usecreate_content_itemwith an explicitparentIdinstead; keepcreate_component_dsfor the case where its one-callchildren[]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.
| Value | Decision | Why |
|---|---|---|
| "7 developments · 29 residences available today" | derive | CM knows it, and today asserts liveness |
| "Six residences remain at X." | derive | Same — and it is the largest claim on the page at the point of conversion |
a <select> of the developments | derive | An authored list drifts the moment a building is added or renamed |
| "17 completed · 143 sold since 2011" | author | Nothing in the CM knows these — facts about the business, not the content |
| budget bands | author | Not 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:
- 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.
- 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. - 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 (RichTextBody) use HTML hex entities (😉) — they round-trip and render. For plain-text fields (e.g. ValueCardIcon) entities render literally, so use a BMP symbol or leave it empty. - Creation order is not sort order — set
__Sortorderon every list row. Children with an empty or equal__Sortorderresolve 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 …) increate_content_itemfieldsor viaupdate_fields_on_item, which writes it but omits system fields from itsupdatedFieldsreply. Verify the rendered order, not the write response. add_component_on_pagecreates the PARENT datasource only — never the children. Children are separatecreate_content_itemcalls under the returneddatasourceId.- Field names are case-sensitive and must match the datasource template exactly — read a real sample, never paraphrase.
- Sanitize item names. Sitecore's default
ItemNameValidationis^[\w\*\$][\w\s\-\$]*(\(\d{1,}\)){0,1}$: parentheses are only allowed at the end and only around digits, soFoo (2)passes andFoo (draft)is rejected. - Per-language composition (measured 2026-10-02).
__Final Renderingsis versioned, so a new language starts with an empty layout. Version each datasource withupdate_content(language, createNewVersion: true). Always passlanguage: omitted meansen, and withcreateNewVersionthat silently adds en v2.update_fields_on_itemtakes no language.create_pagefieldsis[{"Title":"…"}](key = field name), unlikeupdate_content's{name, value}. Neverdelete_contentto 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, headerAccept: application/json. Token = the CM automation client (SITECORE_CM_CLIENT_ID/SECRET→ client_credentials,audience=https://api.sitecorecloud.io). The deploy client 500s onstate(measured 2026-08-12). - READ:
GET /api/v1/pages/{pageId}/state?site=<site>&language=en&withLayout=true→finalLayoutis the layout body JSON string ({ devices:[{ renderings:[{ id, instanceId, placeholderKey, dataSource, parameters:{ FieldNames, GridParameters, … } }] }] }) plus arevision. - WRITE (total replace — fetch → modify → write back): set
renderings[n].parameters.FieldNamesto the variant item GUID (""= Default; it stores the GUID, not the export name — the layout service resolves it), thenPOST /api/v1/pages/{pageId}/layoutwith{ layout:{kind:"Final",body:<modified string>}, originalLayout:{kind:"Final",body:<original string>}, language, site, pageVersion, revision }. NopageVersionin state (single version): send 1. - GOTCHA — the editing/render endpoint CACHES. A
FieldNameschange 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.
| Component | Kind | Parent fields | Child template → child fields |
|---|---|---|---|
| PageHero | flat | Title, Subtitle, HeroImage | — |
| RichTextSection | flat | SectionHeading, Body (HTML) | — |
| ValueProps | list | Heading, Eyebrow, HeadingAccent | ValueCard → Icon, CardTitle, Body |
| StatsBand | list | BandHeading | Stat → StatValue, StatLabel |
| DestinationsGrid | list | Heading, Eyebrow, HeadingAccent, Intro | card → Name, Tagline, Distance, Detail, CardImage, CardLink |
| ExperienceShowcase | list | Heading, Eyebrow, HeadingAccent | item → ItemTitle, Summary, ItemImage, Duration, Cta |
| Testimonials | list | Heading, Eyebrow, HeadingAccent | quote → Quote, Author, Role, Avatar |
| JourneySteps | list | Title, Intro | step → StepTitle, Description, StepImage |
| Promo | flat | (fixed FieldNames) | — |
| NewsletterCTA | flat | Heading, 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-agentandsitecoreai-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
| Credential | Edge Admin API |
|---|---|
| Edge administration client (one per environment) | 200 |
| Org automation client | 401 edge.cdn.11: Unauthorized. Failed to find tenant. (live, 2026-10-02) |
| Environment automation client | Covers 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.
| Step | Call | Result |
|---|---|---|
| Create | POST 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 |
| List | GET https://xmclouddeploy-api.sitecorecloud.io/api/clients/v1/environment | Items { id, name, description, clientId, createdAt, clientType, projectName, environmentName }. Edge administration client = clientType: 2 |
| Delete | DELETE 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 passedGET /webhooksat +1, +5 and +15 min: it lives until itsexp, up to 24 h, with every scope includingedge.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 environmentSITECORE_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>.
| Op | Route | Success |
|---|---|---|
| List / get webhook | GET /webhooks, GET /webhooks/{id} | 200 |
| Create | POST /webhooks | 201; take the GUID id from the body (Location names an internal http host) |
| Update | PUT /webhooks/{id} (replaces what you send; an omitted or null body is kept) | 204 |
| Delete | DELETE /webhooks/{id} | 204 |
| Settings | GET / PUT / PATCH /settings | 200 / 202 / 200 |
| Clear Edge cache | DELETE /cache | 202, whole environment |
DELETE /content | Never. 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 | |
|---|---|---|
| Body | Your static body string, verbatim | application/json { invocation_id, updates[], continues } (+ bodyInclude) |
| Batching | One call per publish (debounce documented only for Content Hub) | Batches share invocation_id; continues: true until the last |
| Use | Deploy hooks, "something was published", sitewide purge | Per-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_idand the same rows. ThelastRunsmessage 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: trueand the lastlastRunsmessageThe 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 carryingdisabled: false);lastRunsis 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).
lastRunsis the only delivery log and keeps 10 entries. A success has an emptymessage; itstimestampis 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.appalias answered 200 without a bypass, while the per-deployment URL answered302→vercel.com/sso-api(and401 {"error":{"message":"Protected deployment"}}to a POST). Anx-vercel-protection-bypassheader in the webhook'sheadersdoes pass Edge's delivery through a protected URL (lastRunsOK, page refreshed). Create the secret withPATCH /v1/projects/{id}/protection-bypass({"generate":{}}) or Settings → Deployment Protection → Protection Bypass for Automation. - Header values via
env:NAMEkeep 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.mjsagainst the deployed route (secret set on the target, bypass if protected) beforecreate --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 withdisabled: trueand enabling after the controls would be the safer shape, but whetherPOSThonoursdisabledis unverified[probe-gated](a fresh create read backdisabled: null); until a probe shows it, create only after the controls pass. - Verify after a real publish:
webhooks get <id>→ newestlastRunssuccess true,disabledfalse, then the content marker on the page (not200, notx-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 toOnEnd, so the receiver gets no rows, answers 400, and the webhook disables itself on the next publish.edge-admin.mjs update|enable|disabledoes the merge. - A stored
bodysurvives a PUT that omits it or sendsnull, andbody: ""is rejected under OnUpdate (live). Switching OnEnd → OnUpdate therefore needs two PUTs:OnEnd+body: "", thenOnUpdate. 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(formatd.hh:mm:ss; documented default04:00:00, observed1.00:00:00on 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
| Job | Use |
|---|---|
| Revalidate a head app after publish | Edge, OnUpdate → /api/revalidate |
| Keep a SitecoreAI search index fresh | Edge, OnUpdate → push upsert; replay after every reindex, which wipes pushed documents (sitecoreai-search-sources) |
| Sitewide purge / trigger a rebuild | The 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 search | Edge, OnUpdate, filter LayoutData rows |
| Notify on workflow approval / block on an external check | Workflow Submit Action / Validation Action (CM) |
| Alert on a failed publish | CM event handler publish:fail |
| Know when your Publishing API job finished | Poll 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(scopeedge.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
--yesis passed. - Never print or store a secret: client secret, JWT, webhook header values. Record only ids (
clientId, webhookid). - 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.mdsitecoreai-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 (percontent-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
Authorizationheader. ThesitecoreContextIdin 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
/schemaURL 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 complexroutes(first: 100, …)with selection{ routePath }→ too complexroutes(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):
| Query | Result |
|---|---|
children(first:20) each with a nested units(first:30) connection + one field | refused |
children(first:50) selecting name displayName + two field(...) | refused |
children(first:50) selecting two field(...) only | ok |
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:
field(name:"X"){ value }selections are expensive — far more than plainname/id. Dropping one redundant scalar (displayName) was enough to bring a refused query back under budget at the same page size.- 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 withReact.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:
| Shape | Measured |
|---|---|
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 counts | Complexity 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} selections | About 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 ComponentQuery | Fails 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
ComponentQueryto one level ofchildren. Fetch deeper rows server-side withclient.getData, one call per parent, in parallel. firstmust be strictly greater than the authored row count. Edge returns the first N rows with no error, so a row an author adds pastfirstis 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/:
| File | Type |
|---|---|
type-LayoutData.json | LayoutData |
type-Item.json | Item |
type-ItemField.json | ItemField |
type-RoutesResult.json | RoutesResult |
type-SearchPredicate.json | SearchPredicate |
type-SiteData.json | SiteData |
type-SiteInfo.json | SiteInfo |
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):
siteInfotakessite: String!(NOTname: String!).routestakeslanguage: String!REQUIRED (omitting it returns an error).- For sites with >10 routes, paginate with
after: "<cursor>"from the previous page'spageInfo.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
/schemaURL. - No auth header — the
sitecoreContextIdin the query string IS the auth. PuttingAuthorization: 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: 10is the safe default forroutes. siteInfo(site: …), notsiteInfo(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.renderedis opaque JSON — there's no GraphQL type for what's inside. Usecontent-sdk-resolver-patternsto 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
allSiteInfoandsiteInfo.routesin one query — both work alone, together they trip complexity limits. Split into two POSTs. - Don't paginate routes with
first: 100even 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 emptyroutemeans the path doesn't exist or isn't published.
Related
content-sdk-playground-pattern— the workspace layout that consumesedge-snapshot/.content-sdk-debug-layout-probe— for capturing layout responses through the head app's/api/layout-debugroute (alternative to direct curl when the SDK's pre-processing matters).content-sdk-resolver-patterns— for interpretingitem.renderedonce 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.graphqlis aclient.mutate,xmc.preview.graphqlis aclient.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.graphqlbody (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.graphqlbody (read-only published-content access — Edge endpoint). - When the
.d.tsforxmc.*.graphqlshowsdata: [key: string]: unknownand 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
| Endpoint | URL pattern | Auth | Schema flavor | Use for |
|---|---|---|---|---|
| Authoring | https://<tenant>.sitecorecloud.io/sitecore/api/authoring/graphql/v1 | Authorization: Bearer <OAuth-JWT> | Generic — Item/ItemField/ItemTemplate work for any template | Read unpublished content, mutate items, manage versions, publishing, sites, roles, users |
| Edge / Preview / Live | https://<tenant>.sitecorecloud.io/sitecore/api/graph/edge | sc_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 vianode_modules/@sitecore-marketplace-sdk/xmc/dist/...client-authoring/types.gen.d.tsandclient-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. fieldsreturns[ItemField]!directly, not a Connection.ownFields: Booleanis 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'sitemId(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
| Endpoint | Header | Source |
|---|---|---|
| Authoring | Authorization: Bearer <OAuth2-JWT> | OAuth2 client-credentials grant (per sitecoreai-auth); Marketplace SDK manages this internally for xmc.authoring.graphql. |
| Edge / Preview / Live | sc_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
versionarg type differs. AuthoringInt!, EdgeString. Mismatched variable type → cryptic GraphQL validation error.where:is mandatory on Authoring. Noitem(path: ..., language: ...)shortcut — wrap inwhere: { ... }.- Authoring
fields(...)connection requires three args with no defaults.excludeStandardFields: Boolean!,ownFields: Boolean!,withLanguageFallback: Boolean!— all marked NON_NULL, so omitting them errors out. ItemField.valueis alwaysString!. 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.ItemPublishandItemAccessare nested objects, not booleans.Item.publish.published(or similar) — verify the exact subfield via introspection.xmc.authoring.graphqlis a MUTATION on the SDK. Single.dataunwrap, not double. The schema underneath has aQueryroot, but the SDK call signature isclient.mutate(...)because the SDK wraps both reads and writes through the same POST endpoint. Seemarketplace-sdk-xmc§ 8b for the unwrap matrix.- 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.
- Edge
Item.fields: [ItemField]!is plain list, not a Connection. No pagination, nonodeswrapper — just access the array. - The "
/ide/" suffix is a 404 on the Edge endpoint — drop it. The base URL is/sitecore/api/graph/edge(no trailing path). - 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. - A write is validated as a string, never as the field type (measured 2026-09-26 → 29).
updateItem/createItemaccept 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 thecontent-sdk-create-componentskill, section "Write-side wire formats" of its GraphQL sequence reference (installsitecore-content-sdkto get it). - 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 (uselanguageItem). Edge preview counts a literalfirst: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: 1001is a warning plus clamp on live and a hard error on preview. The Edgelanguageargument 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.graphqlcall signatures, module-vs-experimental modes, response unwrap matrix.marketplace-sdk-client—client.queryvsclient.mutate, params-wrapper behavior (Mode A wraps body underparams, 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 genericItem, 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:
| Instrument | Sees | Never use it as |
|---|---|---|
| Authoring GraphQL | master (and the search index) | proof of publication |
| Edge, live context | what is published | proof that master is fine |
| Edge, preview context | master in Edge shape | the "published" side of any join |
| Browser / unfollowed HTTP | what a visitor gets | a 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
mutationorsubscriptionanywhere is refused), theclient_credentialstoken mint, and the non-JSON/api/revalidateprobe with no credential header (it cannot revalidate); - any Edge Admin path outside
GET /webhooks,/webhooks/{id},/settings, and every/contentroute (the Edge administration client also holdsedge.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
| Scope | Flags | Runs |
|---|---|---|
| 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 /route | D1, 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) | Enables | Without it |
|---|---|---|
Org automation client SITECORE_DEPLOY_<LABEL>_ADMIN_CLIENT_ID/_SECRET (--org <label>) | X0, Deploy, Authoring, Monitoring logs, context ids | delivery-only run |
Edge administration client SITECORE_EDGE_<LABEL>_CLIENT_ID/_SECRET | D10 webhooks + settings | D10 SKIPPED |
| Tenant-scoped automation client | O6 Publishing jobs, E4 Sites API | SKIPPED (the org client gets 403 / 401 there) |
Access-gate cookie DOCTOR_GATE_COOKIE / --auth-cookie | authenticated robots + crawl on a private surface | those checks UNKNOWN |
Playwright (cwd or PLAYWRIGHT_MODULE) | hydrated crawl, console errors | crawl 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):
- X0 binding, X1 matrix.
- 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. - Census: R1 every live route's layout, D11 preview vs live.
- D8 sitemap, D14-D16.
- 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). - Crawl D5/D7/D9, media D6.
- 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
| Sev | Means | Examples |
|---|---|---|
| P0 | broken or invisible for everyone now | Disallow: / on a public site, live route route:null, app on the preview context, open revalidate endpoint, media from the CM |
| P1 | broken for some readers, or breaks the next publish | internal 404, missing datasource/reference, item whose template is gone, sitemap on the CM host, disabled webhook |
| P2 | degraded or risky | soft 404, no webhook, editing secret unset on a delivery-only app, unpublished pages |
| P3 | hygiene, candidates, info | unreferenced data items, preview-only routes, noisy log lines |
- Instrument error = UNKNOWN, never clean; UNKNOWN makes the exit code 1. Compare
totalwith what was received everywhere. - Assert the first status; a 3xx to
/sso-apimeans locked. --visibility privateinverts 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_intentionalmarks 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):
| Script | Gate |
|---|---|
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 andser pullto 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
| Layer | Holds | Write surface |
|---|---|---|
| Environment | /sitecore/system/Languages/<name> items: Iso, Regional Iso Code, Fallback Language, charset/codepage | AGQL addLanguage (org client OK); Sites POST/PATCH/DELETE /api/v1/languages (env client) |
| Site | supportedLanguages[] (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.
- Add the environment language. AGQL:
Read backmutation { addLanguage(input:{ languageCode:"de", regionCode:"DE", fallbackCode:"en" }){ successful } }languages{ nodes{ name } }andlanguageItem(name:"de-DE"){ fields(ownFields:true){ nodes{ name value } } }: expectRegional 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]. - Enable it on the site (
supportedLanguages) and set the host language settings. Env client or UI [probe-gated: G8]. - Assign an analytics identifier for the language on the host; a new language has none, so personalization and analytics are off for it (
sitecoreai-personalizationR2). - Create versions (§ 3) or AI-translate (§ 6). Compose layout per language:
__Final Renderingsis versioned, so a new version starts with an empty final layout; shared__Renderingsstays shared. - Version datasources in place (
update_content(language, createNewVersion:true)oraddItemVersion+updateItem(language)); never build a parallelData/tree per language. - Dictionary phrases (§ 5).
- Workflow per language version (shared fields bypass it).
- Publish every language once (§ 7), including
/Dictionarywith subitems or the site root. - Read back per locale on live with a known-bad locale as control (§ 8), then run the census.
- Keep the head app in step:
check-locale-drift.mjsin the i18n skill (routing.localesmust list the language with identical casing).
3. Creating language versions: what each surface does
[measured 2026-10-02]
| Call | Result |
|---|---|
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-DE | creates de-DE v1 with only the written fields |
MCP update_content without language | writes 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 version | error "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
| Need | Use | Requires |
|---|---|---|
| Regional variant (en-AU → en) | item-level fallback | Fallback 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 translated | field-level fallback | field-definition flag; not on shared, __Standard Values or __ system fields; never combined with item-level on one item |
| Genuinely different content | no fallback | missing version = 404 in the head app (honest) |
| "Show the default language if missing" in the app | not an SDK feature | fallback above, or custom getPage retry code |
- Edge delivery fallback is governed by the environment patch
ExperienceEdge.EnableItemLanguageFallback/EnableFieldLanguageFallback(both default false, a/platformconfig 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=1on the item → Edge previewlayout(language:"de-DE")null, and AGQLfields(withLanguageFallback:true)empty. Whether the hostitemLanguageFallbackflag 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 fallbackis 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 Domain0a2847e6-9885-450b-b61e-f9e6528480ef; the site propertydictionaryDomainpoints at it. Entries: template6d1cd897-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"}]}), thenaddItemVersion(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;
totalcounts 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
/Dictionaryitem 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 andtotal: 0on live. - Shared dictionaries:
Fallback Domainon the consuming domain → the shared domain; publish the shared site first [probe-gated: G4]. - Serialization:
/DictionaryasItemAndDescendants, push Create-only, so content edits are not overwritten.
6. AI translation
| Surface | Shape | Works 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 string | env client; return value [probe-gated: G6-REST] |
| Pages / Channels UI | adds "Keep workflow state" (UI-only) | author |
- One target language per call. Poll AGQL with
job(input:{handle})untildone(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 itemsShared/Unversioned). translateIfTargetVersionExists:falseon 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 exactlyAddVersionandSkipIfExists. - 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 }; pollpublishingStatus(publishingOperationId){ isDone isFailed state }[measured]. - Publishing REST: locales go per item or in
options.xmc.locales, never both (400).options.xmc.sitepublishes the whole environment; use item-rooted jobs (sitecoreai-publishing). - Unpublish one item without touching parents: set
__Hide version=1on each language version and publish the item again in those languages → livelayoutnull [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'slanguageargument is case-insensitive [measured]; the head app's is not. url.pathhas 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 onSiteInfo).- Dictionary:
siteInfo(site).dictionary(language:$l, first:$f, after:$a)withfirstas a variable. Live clampsfirst > 1000with a warning; preview errors on it, and preview rejects a literalfirst≥ 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
| Trap | Effect |
|---|---|
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 language | writes en silently [measured]; always pass it |
MCP update_fields_on_item | has 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 check | always non-null for a valid culture |
| New language, no analytics identifier | personalization/analytics off for it |
__Final Renderings versioned | new language starts with an empty layout |
| Shared fields | leak across languages, bypass workflow, are not translated |
| Edge dictionary untranslated | returns the key, never empty |
| Org automation client on Sites/Pages REST | 401 (host-addressed AGQL works) [measured] |
Sites GET /api/v1/languages/supported without a token | not 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/contentin 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/tokenwithgrant_type=client_credentialsandaudience=https://api.sitecorecloud.io. - Granted scope: the token response carries
xmcloud.cm:admin— a single admin-level scope, not granular per-endpoint:r/:wscopes. Accept: application/jsonheader 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/searchonly, 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}/livefor the page,GET /pages/{pageId}/live/variantsfor 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}/versioncopies the base version is still open (probe-gated), while AuthoringaddItemVersionand MCPadd_language_to_pagewere measured to create an EMPTY language version (2026-10-02).translatecovers 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)
POST /pages/{pageId}/duplicate→ get newpageId.PATCH /pages/{newId}→ set the fields that differ.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/jsonrequired. Missing header →406 Not Acceptable./pages/searchmatches 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}/layoutreplaces the whole layout, not a merge. Fetch → modify → write back. - JWT expires in 24 h. Cache. See the
sitecoreai-authskill. - 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 (theFieldNamesdisplay variant; seesitecoreai-content-composition§ Variants).set_component_variantis personalization / A/B only.
Mental model: four layers, written by different APIs
| Layer | Holds | Written by | Read by |
|---|---|---|---|
| Flow (embedded Personalize) | audience (condition groups), splits, status, friendlyId embedded_[scope_]<pageIdNoDashes>_<lang> | create_perso_version_multi / POST /api/v2/personalization/{pageId}/versions | list_page_flows, get_flow_definition |
| CM page layout | per-variant COPY / SWAP / HIDE on a rendering, per page version and language | set_component_variant / POST /api/v1/flows/{flowId}/variants/{variantId} | get_flow_variant_by_id, get_components_on_page(variantId) |
| Edge projection | personalization.variantIds, each rendering's experiences{} | publish | Edge GraphQL, Pages GET /pages/{id}/live/variants |
| Enablement | analytics identifier per site language; PAGES_PERSONALIZE_SCOPE | Sites API / Channels UI; Deploy env var | Sites 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 | |
|---|---|---|---|
| Decides | which page variant a visitor gets; each variant changes one or more components | which variant of one component; rows top-down, first match wins | random split |
| Hero options | COPY, SWAP, HIDE, per-variant layout/styling (UI only) | Duplicate / Hide / Swap | Copy / Swap / Hide |
| Limits | ≤ 10 variants per page, ≤ 5 conditions per audience, one embedded experience per page | undocumented | ≤ 6 variants, ≤ 6 concurrent tests per page |
| Versioning | per page version and language | shared across versions, including live (a draft edit changes production) | — |
| API / MCP | yes, end to end except publish | none | yes; no start/stop verb |
| Status | GA | phased rollout | GA |
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_pagehides it on the default page.
2. Prerequisites — check read-only before any write
| # | Check | How | Fails as |
|---|---|---|---|
| R1 | Personalization enabled on the tenant | get_perso_cond_tmpls returns 18 templates | error or empty |
| R2 | Analytics 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 ones | Sites API host analyticsIdentifiers (sitecoreai-sites), then the portal's Site hosts page shows no "missing analytics identifier" warning | that language never personalizes or tracks |
| R3 | Scope 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 rules | Deploy API env vars (read); head-app env | wrong friendlyId → 404 No experiences found for friendlyId … at the wire (measured P7); the SDK turns it into the default, silently |
| R4 | Head app serves variants: PersonalizeProxy in the chain, production build against LIVE Edge | ask, or check via content-sdk-personalization | default hero, silently |
| R5 | Consent narrows reach: visitors without consent get the default hero by design | head-app consent gate | expected; put it in the acceptance criteria |
| R6 | Publish path: neither the MCP nor the Agent API publishes | sitecoreai-publishing credentials | variant never reaches Edge |
| R7 | Binding 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 |
| R8 | Read 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 conflict | list_page_flows | duplicate variants |
| R9 | Every write below is a real-tenant mutation: get the user's go-ahead | user | — |
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.
- Locate.
list_sites→get_all_pages_by_site(siteName, language)→ the homepageId. - Find the hero.
get_components_on_page(pageId, language)→ note the hero'sid(instance uid),componentId(rendering definition), anddataSourceItem.path. - Pre-check (R8).
list_page_flows. ExistingEXPERIENCE→ reuse it (step 4 appends a variant; that is the only way to add one). ExistingEXPERIMENT→ stop and escalate. - 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_valueneedstype,compares to,UTM valueandUTM value(s)(both required). - Create.
create_perso_version_multi(pageId, name, variantName, audienceName, conditionGroups, language).conditionTemplateIdis the uuidref. The first group has nounionType; later groups needANDorOR. Do not usecreate_perso_version(flat v1 shape; the v1 create 400s onutm_value). AnaudienceNamewith parentheses → 400; plain text works. - Get the ids. The create response (or
list_page_flows/get_flow_definition) carries the flowrefand two variant ids. Use the template variant id: the 32-hex value insidetranspiledVariants[].tasks[0].input.template/traffic.splits[].template({"variantId": "7de9…"}). The dashedtranspiledVariants[].refis the "variant ref". Variant tools reject it:Requires template Variant Id, not variant ref (400). The 32-hex id is also what EdgevariantIds,_variantId_<v>andpageVariantIduse. The create ignores yournameand names the flow<page name> <lang> - <PAGEID>; variant and audience names are kept. - Give the hero its own content.
set_component_variant(flowId, pageId, componentId=<instance uid>, variantId, variantStrategy="COPY", language, pageVersion=0). The response'sdatasourceis 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. - Edit the copy.
get_content_item_by_path(<copy path>)→update_content(itemId, siteName, fields, language)(siteNameis required). Edit the copy, never the original. - Read back.
get_flow_variant_by_id→ herovariantStrategy: COPYand the newdatasourcePath;get_components_on_page(pageId, language, variantId)→ the copy's fields; the default page's hero still points at the original. - 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
| Strategy | Effect | Use when |
|---|---|---|
COPY | copies the component and its rendering parameters into the variant, creates and assigns a copy of the datasource; you then edit the copy | new hero copy for the audience (default) |
SWAP | replaces 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) |
HIDE | removes the component in that variant | the 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_variantdoes 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: rules:name= template variant id, condition{8E7426A4-…}s:VariantName=<v>, action{0F3C6BEC-…}s:DataSource=<copy path>(a path, not a GUID), plus aDefaultrule. 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
PRODUCTIONfrom the moment of create, and publish does not touch it. What gates visitors is only Edge LIVEvariantIds, 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 expectnull, not[], as the pre-publish control.
6. Change and undo
| Need | Tool | Note |
|---|---|---|
| Change the audience | update_perso_version | full replace: send variantName, audienceName, conditionGroups |
| Undo the hero setup in a variant | reset_component_variant(flowId, pageId, componentId, variantId) | omit variantId to reset the default page's component |
| Undo a whole REST sequence | POST /api/v1/jobs/{jobId}/revert with the sequence's x-sc-job-id | coverage [probe-gated: P23] |
| Delete / pause / schedule / archive the experience | no verb in the MCP or the Agent API. update_ab_test(archived:true) on an EXPERIENCE flow returns 500 and changes nothing | reset + 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 withlanguage: "de", its own datasource language version, and an analytics identifier on thedesite 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_SCOPEexists to separate them.
8. Verification ladder — each layer independent
| # | Layer | Check | Pass | Control |
|---|---|---|---|---|
| 1 | Flow | list_page_flows | one EXPERIENCE; audience as written | no duplicate variants (append trap) |
| 2 | Variant setup | get_flow_variant_by_id | hero variantStrategy: COPY, new datasourcePath | default hero still on the original datasource |
| 3 | Edge | Pages 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: {} |
| 4 | Decision | POST /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 … |
| 5 | Render | production build on LIVE Edge, real browser UA, consent set, e.g. ?utm_campaign=… | HTML shows the copy | without the input → original hero; a headless UA counts as a bot |
| 6 | Beacon | browser network POST …/v1/events/v1.2/events | 2xx, ext.pageVariantId ends _<v> | default visit ends _default |
| 7 | Analytics | Page builder Personalize analytics / dashboardLinks | variant views appear | human 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
dashboardLinksand 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-codeheaders, 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: uuidref, 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 group | Required scope (one of) |
|---|---|
Read — GET /jobs, GET /jobs/{id}, GET /jobs/filters, GET /jobs/summary | xmcpub.jobs.a:r, xmcpub.jobs.t:r, or xmcpub.jobs.t:rl |
Permissions — GET /jobs/permissions | No 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}/cancel | xmcpub.jobs.a:w, xmcpub.jobs.t:w, or xmcpub.jobs.t:wl |
- The
:rl/:wlsuffix 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 theSitecore Client Advanced PublishingorSitecore Client Publishingrole, or theadminflag set in SitecoreAI. - Application/client-credentials tokens additionally require the
xmcloud.cm:adminscope (spec note onPOST /jobsandPOST /jobs/{jobId}/cancel). Without it, calls return403.
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):
| Status | When |
|---|---|
400 | Invalid parameters / job ID / name / items / mode / locales / source / tenant. |
401 | Unauthorized request or invalid access token. |
403 | Authorization failed (missing scopes/roles, or xmcloud.cm:admin missing on an app token), or context tenant cannot be resolved. |
404 | Job not found (GET /jobs/{id}, POST /jobs/{jobId}/cancel). |
409 | Cancel rejected — job is not Queued/Running (POST /jobs/{jobId}/cancel). |
501 | Cancel 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 (namedsitefor 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.publishChildrenis job-wide, not per item. There is no exclude: an item with children on takes every descendant, so a siteHomewith 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 FLAToptions.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
GET /jobs/summaryon a timer (60 s is plenty) → counters.GET /jobs?status=in_progress→ live list, capped at page size.- Use
GET /jobs/filtersonce 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.
:wlusers can cancel only their own jobs. Surface clear error messaging when the principal lacks scope.xmcloud.cm:admingotcha. Application tokens (client_credentials) need this extra scope or every call returns403. This is the #1 setup mistake.- Job creation is async.
POST /jobsreturns 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
403here (no publishing scope). Use the environment's CM client token, or publish through Authoring GraphQLpublishItem, which worked with the CM client in the S5 probes (2026-10-02). - Statistics are eventually consistent.
/jobs/summarymay lag individual job-detail reads by a few seconds. - Rate limits undocumented. Back off on
429/5xx. - Nested create body is mandatory.
POST /jobsneedsoptions.xmc.site.{mode}+options.xmc.locales(see "Create-job request body"). The flatGETshape → 500. The #2 setup mistake after thexmcloud.cm:adminscope. itemsFailedis 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 withGET /jobs/permissions(canCreate: true); compareitemsProcessedvsitemsFailedinjob.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
Completedonly means the job ran; inspectstatistics.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)
| Surface | Endpoint | Credential | Status |
|---|---|---|---|
| Query | POST https://edge-platform.sitecorecloud.io/v1/search, /v1/search/suggest | Edge context id in x-sitecore-contextid (public) | [confirmed] reachable; every CM context of a test org was recognised (preview and live) |
| Config read | GET 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}/push | Authorization: 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)
- 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].
- 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].
- The search plane recognises the environment's context id: the probe-search script of
content-sdk-search(fake-context control → 404No sitecore context; your context + fake index → 404no search index found). A recognised context proves the plane, not that the Search sources UI is enabled or that any source exists. - A source id exists: from the source's Settings tab (field "ID"), or
scripts/search-config.mjswith a credential that carries the scope.
Choose the source type
| Content lives in… | Source | Caveat |
|---|---|---|
| Sitecore items of ONE template, simple field types | Content | published 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 site | Site (crawler) | crawler must reach the site; sitemap required; scheduled re-index |
| External system of record, or must be fresh in real time | Push | you own the full document set; no history kept |
| Sitecore items that must be fresh on publish | Content source + Edge webhook → push upsert, replayed after every reindex; or a push source fed only by the webhook | pushes 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 → pushupsertwithid = 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 withtenant 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 asSITECORE_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.actionreserved. - 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.mjsvalidates 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.--datasourceprints 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-testruns a fake-fetch suite plus a mutation sweep that disables each guard in turn and fails if nothing notices.
Hard rules
- 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.
- Never put the push ApiKey in client code, argv, logs or captures.
- After every reindex of a source that also receives pushes, replay the pushes.
- Treat 404
No sitecore contextas "wrong or dead context id", and 404no search index foundas "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
sitecore.json→modules: [globs]finds every*.module.json.serialization.defaultModuleRelativeSerializationPathsets where YAML lands when a module gives noitems.path.- A module =
namespace(unique) +items.includes[](+ optionalreferences,roles,users,excludedFields). - An include =
name(it is the on-disk folder name) +path+scope+allowedPushOperations+rules[]. - Rules are first-match-wins, relative to the include path; finish a selective include with
{ "path": "*", "scope": "Ignored" }. - A content item may be included only once across all modules.
Defaults that hurt
| Property | Default | Why it hurts |
|---|---|---|
scope | ItemAndDescendants | An include with no scope takes the whole subtree, including author content under it |
allowedPushOperations | CreateUpdateAndDelete | A push deletes every item in scope that is not on disk, author-created items included |
items.path | the shared default root | Sibling modules share one folder tree (§ Grain) |
-n (environment) | default | Resolves 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.
| Strategy | Site include | When |
|---|---|---|
| Full record (default here) | ItemAndDescendants, CreateAndUpdate, no "*" → Ignored | git 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, "*" → Ignored | authors 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 class | Push | Why |
|---|---|---|
Templates, branches, renderings, placeholder settings, /sitecore/system/Settings/Project/<C> | CreateUpdateAndDelete | Developer-owned: removals must propagate |
Site /Presentation (page and partial designs, headless variants) | CreateUpdateAndDelete | Structure the code depends on |
Tenant root /sitecore/content/<C> | CreateAndUpdate, SingleItem | The container only, never its sites |
| Pages, datasources, dictionary, media | CreateAndUpdate | A push must never delete an authored item |
/Settings/Site Grouping (hostnames, robots) | CreateOnly | Environment-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.
CreateOnlydoes 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 GroupingRenderingHostfield (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 atItemAndChildren. - 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/systemyou 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.jsonin its own directory and setitems.path: ".". A distinctitems.pathalone 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 reported0 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 validatelist the other collection's files as "EXTRA ITEM … > Fix will delete file", andser pullaborted. One--fixwould 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 unscopedser pull,ser validate --fixor--forceon 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-iffirst, then explain every[D]line before the real run. - Live tenant first, then pull. Write through the authoring API or MCP, then
ser pullthe 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,__Ownerand__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;--fixonly after you have read the delete list.--fixdeletes 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
.scindexstill maps the old paths.ser pullthen reports an item "on disk in more than one place", andvalidate --fixandpullundo each other on every run. Move that include's folders and its.scindexaside (a move, not a delete) and pull it fresh; a second pull must report 0 changes (measured 2026-10-28).
Deploy: IAR or database
| Mechanism | xmcloud.build.json | Effect |
|---|---|---|
| Items as resources | deployItems.modules (omitted = every module) | YAML → .dat at deploy; read-only, merged at runtime |
| Database push | postActions.actions.scsModules.modules | A 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
__Revisionand by value; a value-only compare missed 9 of 11. ser pushskips 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 pushalso wrote to the database survives the deployment that drops its YAML: three removed schema folders still listed on the CM afterwards. A scopedser pushof the module removes them where the include isCreateUpdateAndDelete; its--what-ifmust list exactly the removed subtree roots (measured 2026-10-28). Content includes areCreateAndUpdate, so a site goes through the Sites API delete instead. scsModuleswithCreateUpdateAndDeletedeletes 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 userpatternpushed 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 existstops at that item; everything after it in tree order is stranded.continueOnItemFailure: truedoes not help. Usual culprit: an empty, unreferenced SXA<site>/Data/Datasource Content Resolveritem 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. NonUniquePathExceptionaborts 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
scopeandallowedPushOperations; nothing authored isCreateUpdateAndDelete - 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$schemapath; 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/scsModuleschoice is deliberate for this environment
Related
sitecoreai-cli-cloud-workflow: login, connect, endpoints, push procedure, overlays, estate movecontent-sdk-website-build-flow: when in a build the pulls happencontent-sdk-create-component,content-sdk-list-component: the items a module must then carry- Docs: SCS configuration reference · Set up SCS · Build configuration · Items as resources
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 says | Build | Why |
|---|---|---|
| own hostname, own navigation or brand, separate microsite | site 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 site | page blueprint (build-blueprint) | Seconds for a marketer, no new site, host or deploy. |
| every new site of a template should offer such pages | blueprints 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 build | Round 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
-
Write the spec (
references/spec-format.md, exampleassets/example.spec.json): page types, pages, components, partials,renderingHost,thumbnail(ormake-thumbnail.mjs --primary #hex --accent #hex), optionalblueprints. -
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.
-
Run the same command without
--dry-runto build. -
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.
--keepkeeps 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
- Write the blueprint spec:
{ site, name, pageTemplate?, offerOn?, fields?, components }. build-blueprint.mjs --spec bp.json --component-map … --smoke --environment-id …. It lints, writes the branch, and offers it on theofferOntemplates' 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
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.- Read every
WARN. SetrenderingHostwhen the source binds toDefault, 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.
- Ids that point into the source site (Styles, NavigationRoot, …) become
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 collectionPage. At site creation the script creates collection types of the same name that inherit the module type and the collectionPage, which ownsTitleandContent. 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-Pathguards), not byAddItem. - Home insert options are set at item level, because the skeleton's item-level
Base Pagewould otherwise hide every page type. - Components:
-FinalLayouton pages and shared layout on partials. Datasources sit under<owner>/Dataaslocal:/Data/<name>, and each rendering gets aDynamicPlaceholderId. AContainerplaces 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), andFieldNamesis the variant item id. - Datasource rows:
datasource.childrencreates child items (gallery frames, list rows, nested to any depth) in array order with explicit__Sortorder.datasource.insertOptionswrites 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__Mastersread-back. Syntax:references/spec-format.md. - Dictionary and settings:
dictionary[]makes Dictionary entries andsettings{}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
DefaultPage Design maps the collectionPageand 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)
- 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 inNew-Item). Generated scripts use template IDs andmaster:paths. Have a human create one site through the dialog before calling a template done. - Scaffold failures are silent. The job ends
FINISHEDand the dialog shows success; onlyjob.status.exceptionshas the error. Always smoke-verify. - The collection decides page templates. The starter's scripts rewrite the collection
Pagebase. The dialog keeps one template family per collection, butcreateSiteover the API does not. - Home's item-level
__Masters(Base Page) overrides page-type insert options. - The rendering host is a literal name with no existence check. Sites from Basic bind to
Default. - 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.
- Site names are unique CM-wide.
Enabled=0shows greyed out. No thumbnail gives a skeleton card. - Captured layouts carry
?-prefixeds:par(Basic), site-local Styles and NavigationRoot ids, and site-created variants (Banneron Image). The extractor and scaffold handle all of them. - 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
availableRenderingsgroup 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/tokenwithgrant_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}plusAccept: application/jsonon every request. - Token lifetime: 24 h (
expires_in: 86400); cache and refresh on401.
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"] }).
| Status | Where it appears |
|---|---|
400 Bad Request | Validation failures — present on nearly every operation. |
401 Unauthorized | Editor-profile endpoints (and any expired/invalid token). |
403 Forbidden | Editor-profile endpoints (insufficient role). |
404 Not Found | Any {id}/{handle} lookup miss. |
409 Conflict | Host create / update (hostname collision). |
503 Service Unavailable | name/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
GET /sites/{siteId}/hierarchy→ root level.- Lazy-expand:
GET /sites/{siteId}/hierarchy/{pageId}/childrenon node click. - Breadcrumbs:
GET /sites/{siteId}/hierarchy/{pageId}/ancestors.
Create a new site
GET /sites/templates→ pick a template id.POST /sites/name/validatewith{ name }→ validate.POST /siteswith{ siteName, templateId, collectionId, language }(measured 2026-10-28;templateIdas a braced GUID) → returns a job handle.- Poll
GET /jobs/{jobHandle}/statusuntildone: truewitherrors: [].
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):
POST /sites/{id}/renamewith{ name }(notnewName: that is400 "The name field is required") → job. It renames the site root and its media folder.- It does not rename the Site Grouping item or its
SiteNamefield, which is what the runtime resolves the site by. Set both through Authoring GraphQL (updateItemonSiteName,renameItemon the grouping item) and read them back. - Republish each renamed site's
Settingssubtree and readsiteInfoCollectionon the live Edge context. After two renames plus one subtree republish, live Edge listed neither name whilelayout(site: …)still resolved and preview was correct. A Content SDK build reading the site list then failsIV-007 Site "<name>" does not exist. DELETE /sites/{id}?force=true→ job; it removes the site's content and media. It does not unpublish: live Edge keeps the site insiteInfoCollectionuntil 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:
POST /sites/{siteId}/upload-thumbnailwithmultipart/form-datafieldFile(PNG verified). The call returns200with 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.- Max 1 MB. A larger file returns
400 "Thumbnail size is more than 1MB"and nothing is written. - 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.
- Read back with
GET /sites/{siteId}. Expectthumbnail.autogenerated: falseand a url namingthumbnail_<siteId>. The media url is on the CM withdb=master: it answers302anonymously and200with the bearer token. - The custom thumbnail is sticky. A no-op
PATCH /sites/{siteId}leaves it in place.resetThumbnail: trueon 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
GET /languages/supported→ find the ISO code.POST /languageswith 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
aggregationendpoints this pattern relies on are not present in thev1Sites API spec (shaa26e933…) — neither/aggregation/pagesnor/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/validaterather than inventing your own regex. - Deprecated
renderinghosts. Already marked deprecated — migrate any integration toeditinghostsnow, not later. - Site creation is async.
POST /sitesreturns 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
PATCHtakesanalyticsIdentifiers: [{ 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 GroupingPOSfield and inGET /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