Part 4: Surviving Partial Failures in Bulk Agentic Sitecore Operations: Idempotency, Rollback, and the Plan-First Pattern
Why turn-by-turn MCP execution breaks on multi-market rollouts—and how to design idempotent, recoverable agent workflows in XM Cloud
Previously on the blog: In Part 1, we looked at why Model Context Protocol (MCP) turns AI from a passive reader into a governed collaborator in Sitecore XM Cloud. In Part 2, we wired up Marketer MCP and the open-source community server to create and publish a landing page from a prompt. And in Part 3, we put security guardrails in place—tool risk tiers, scoped service accounts, prompt-injection boundaries, and workflow gates.
Even with all those guardrails active, real-world usage exposes a quieter failure mode that has nothing to do with security and everything to do with distributed systems: partial failure mid-chain.
When an agent executes twelve sequential MCP tool calls to build five localized campaign pages and their datasource components, what happens when call #8 hits an API rate limit, a template validation error, or an LLM context timeout? Unlike a SQL database transaction, MCP tool calls against Sitecore do not automatically roll back when step #8 throws an error. You are left with three completed market pages, one half-configured page missing its Hero datasource, one untouched market, and an operator wondering whether hitting “Retry” will fix the gap or create duplicate items across the content tree.
Anatomy of a Mid-Chain Failure: The 12-Call Campaign Rollout
Return to the multi-market launch from Part 3: creating localized landing pages for en-GB, de-DE, fr-FR, es-ES, and it-IT under /sitecore/content/Campaigns/Campaign X, each with a Hero datasource item and a Promo card datasource item. That single request expands into at least 15 discrete tool calls (5 page creations + 10 datasource creations and presentation bindings).
Campaign X_1 or duplicate datasources for UK and DE while leaving FR in a broken state.
If the user simply tells the AI client “That failed, please retry,” an unguarded agent faces three traps:
- Duplicate Item Sprawl: Naive
create-itemwrappers either fail with “Item already exists” on UK/DE or—worse—auto-append suffixes likeHero Banner 1, leaving orphaned datasources. - Context Window Drift: By call #12, the model’s conversation history is filled with verbose JSON responses from earlier tool calls, increasing the chance it forgets an item GUID or mixes up locale codes.
- No Atomic Undo: Because Tier 4 delete permissions are rightly stripped from the agent’s service account (see Part 3), the agent cannot simply wipe its own half-finished folder and start clean.
Pattern 1: Make Every Write Tool Idempotent (Upsert by Deterministic Key)
In distributed engineering, an operation is idempotent if running it once or running it five times produces the exact same end state. Most out-of-the-box CMS create endpoints are not idempotent—calling create twice creates two items or throws an error.
When wrapping Sitecore’s Authoring GraphQL or Item Service in custom MCP tools, replace blind create operations with deterministic ensure (upsert) semantics:
- Compute a deterministic item path and name from the business key (for example,
/sitecore/content/Campaigns/Campaign-X/fr-FR/Data/Hero-Primaryrather than a timestamp or LLM-invented name). - Query before creating: Inside the tool handler itself—not left to LLM prompt instructions—check whether an item already exists at that path.
- Create or patch cleanly: If missing, create the item in the
Awaiting Reviewworkflow state. If it already exists and matches the expected template, update only the changed fields and return the existingitemIdwith"status": "already_exists_updated".
export const ensureContentItem = {
name: "ensure-content-item",
description: "Idempotently creates or updates a Sitecore item at a deterministic path.",
inputSchema: {
type: "object",
properties: {
parentPath: { type: "string" },
itemName: { type: "string" },
templateId: { type: "string" },
language: { type: "string" },
correlationId: { type: "string" },
fields: { type: "object" }
},
required: ["parentPath", "itemName", "templateId", "language", "correlationId"]
},
handler: async (input) => {
const targetPath = `${input.parentPath}/${input.itemName}`;
const existing = await sitecoreClient.getItemByPath(targetPath, input.language);
if (existing) {
if (existing.templateId !== input.templateId) {
throw new Error(`Template conflict at ${targetPath}: expected ${input.templateId}`);
}
await sitecoreClient.updateItemFields(existing.id, input.language, {
...input.fields,
__AgentCorrelationId: input.correlationId
});
return { itemId: existing.id, path: targetPath, action: "reused_and_updated" };
}
const created = await sitecoreClient.createItem({
parentPath: input.parentPath,
name: input.itemName,
templateId: input.templateId,
language: input.language,
fields: {
...input.fields,
__AgentCorrelationId: input.correlationId
}
});
return { itemId: created.id, path: targetPath, action: "created" };
}
};
With ensure-content-item in place, re-running the 12-call rollout after a failure on call #8 safely reconciles calls 1–7 in milliseconds and picks up creating calls 8–15 without a single duplicate item.
Pattern 2: Tag Every Run with a Correlation ID for Surgical Rollback
Even with idempotent upserts, sometimes a bulk rollout needs to be aborted entirely—for example, when a stakeholder realizes the wrong campaign template or copy deck was used halfway through execution.
Include a correlationId (such as run-2026-11-campaignx-04) in your MCP tool schema and stamp it onto a dedicated tracking field (or workflow comment) on every touched item. That single field gives operators two superpowers:
- Instant Blast-Radius Query: One GraphQL or PowerShell query (
__AgentCorrelationId eq 'run-2026-11-campaignx-04') lists every page and datasource created or modified during that specific agent session. - Human-Triggered Cleanup: Because the agent lacks Tier 4 delete permissions, a human administrator can inspect that filtered list and run a single deterministic cleanup script if the run is rejected.
Pattern 3: Switch from Turn-by-Turn Calls to the “Plan-First” Pattern
The biggest architectural mistake teams make with MCP is forcing the LLM to act as a live loop runner for large batch jobs. Every tool call round-trip burns tokens, adds network latency, and increases the probability of a mid-chain failure.
| Criteria | Turn-by-Turn MCP Execution | Plan-First (Manifest / Script) Pattern |
|---|---|---|
| Best For | Exploratory tasks, single-page edits, 1–4 tool calls | Bulk migrations, multi-market rollouts, 5+ mutations |
| Where the Loop Runs | Inside the LLM chat context (slow, token-heavy) | Inside a deterministic Node.js / Sitecore CLI / SPE runner |
| Pre-Execution Review | Operator approves each tool call piecemeal | Human reviews the complete JSON manifest or diff up front |
| Failure Recovery | Requires re-prompting the LLM to inspect and resume | Deterministic retry from checkpoint with backoff |
In the Plan-First pattern, you split the agent’s job into two distinct phases:
- Phase 1 — Read & Plan (Tier 1 Only): The agent uses read-only MCP tools to inspect existing templates, language codes, and target paths, then outputs a structured Execution Manifest (JSON) describing all 15 planned operations. No mutations happen yet.
-
Phase 2 — Validate & Execute Deterministically: A human (or automated schema validator) reviews the manifest. Once approved, a single MCP tool—
execute-bulk-manifest—or a Sitecore CLI / Node runner processes the manifest sequentially with exponential backoff, checkpoint logging, and idempotent upserts.
{
"correlationId": "run-2026-11-campaignx-04",
"targetRoot": "/sitecore/content/Campaigns/Campaign X",
"workflowState": "Awaiting Review",
"operations": [
{
"step": 1,
"op": "ensure-content-item",
"path": "/sitecore/content/Campaigns/Campaign X/fr-FR",
"template": "Campaign Landing",
"language": "fr-FR",
"fields": { "Title": "Campagne X" }
},
{
"step": 2,
"op": "ensure-content-item",
"path": "/sitecore/content/Campaigns/Campaign X/fr-FR/Data/Hero-Primary",
"template": "Hero Banner",
"language": "fr-FR",
"fields": { "Headline": "Découvrez notre nouvelle gamme" }
}
]
}
Production Readiness Checklist for Bulk Agentic Workflows
- Idempotent Tool Contracts: Write tools accept deterministic paths/keys and perform read-before-write checks inside the handler rather than relying on prompt instructions.
- Correlation Tracking: Every item created or updated in a batch carries a shared
correlationIdfor audit queries and surgical rollback. - Retry with Backoff on Transient Errors: Wrap Authoring GraphQL and Item Service calls with bounded retries (e.g., 3 attempts with jitter) for HTTP
429and503responses before surfacing a failure. - Plan-First Threshold: Bulk operations affecting 5+ items generate a reviewable JSON manifest before any write tool is invoked.
- Separated Publish Step: Even after a batch manifest succeeds 100%, items remain in
Awaiting Reviewuntil a human triggers publishing through Sitecore’s standard workflow.
Wrapping Up
Across these four articles, the progression mirrors how every serious Sitecore engineering team matures with AI: starting with protocol fundamentals (Part 1), proving end-to-end creation with MCP (Part 2), locking down blast radius and permissions (Part 3), and finally engineering for deterministic recovery when multi-step workflows hit real-world failure modes (Part 4).
Treating LLM agents as plan generators backed by idempotent, correlation-tagged MCP tools gives you the speed of natural-language orchestration without sacrificing the predictability your XM Cloud content tree depends on.