SitecoreAI · Agent API · Next.js 15 · MCP

Your agent doesn't
know your components.

Marketer MCP knows Sitecore's primitives perfectly. It has no idea your component library exists — and on a mature project, neither do you. A complete build, in twelve steps.

Teja VallabhaneniSenior Sitecore Developer & Technical Lead~32 min read

Here's a thing that will happen to you within ten minutes of connecting Marketer MCP to Cursor.

You type: "Create a landing page for the summer promo under /Campaigns. Use our promo split component with a headline and a CTA."

The agent thinks. It calls the Agent API. It creates a page. And then it adds a Promo component with a Text field and a Link field — because that's a component it knows about, while your actual PromoSplit sits in src/components/PromoSplit.tsx with six fields and a rendering parameter.

The agent didn't fail. It did exactly what it was designed to do. It just doesn't know your component library exists.

And here's the part that makes it worse: on a mature project, you don't fully know your component library either. By year three you have Promo, PromoSplit, PromoBanner, PromoSplitV2, HeroPromo, and CampaignPromo — six components, four of them near-identical, each added by a different developer under a different deadline because finding the existing one was harder than writing a new one.

This article fixes both problems with the same piece of infrastructure. We're going to build an MCP server that reads your JSS component library, reconciles it against what Sitecore actually has, surfaces the duplication you've accumulated, and refuses to let an agent compose an invalid page.

Twelve steps. Every file complete — no // ... elisions.

What Marketer MCP knows, and what it structurally can't

Worth being precise, because this isn't a criticism of the platform.

The Agent API abstracts low-level endpoints into business-level actions like create_page, add_component_on_page, and create_personalization_version. It covers Sites, Pages, Content, Components, Assets, Environments, Personalization, Jobs, Brand kits, Briefs, Experiments, and Flow definitions. It's a well-designed surface, and it knows Sitecore primitives perfectly.

What it can't know is the layer you own:

The agent knowsThe agent doesn't know
A rendering called PromoSplit existsThat Heading is required and Eyebrow isn't
Its datasource template IDThat Heading clamps at two lines, so ~60 chars
Pages have placeholdersThat it's only legal in main, never header
Fields have typesThat variant accepts exactly three values
It can create datasourcesThat PromoSplit and PromoBanner are the same component with different names

That last row is the one nobody talks about, and it's the one that compounds.

The real problem underneath: component sprawl

Every headless Sitecore project I've worked on follows the same curve.

Year one: 20 components. Everyone knows all of them. Code review catches duplicates.

Year two: 60 components across three site collections. Two developers independently build a "promo with an image on the left." Both ship. Neither knows about the other.

Year three: 140 components. Onboarding a developer takes three weeks. Nobody can answer "do we already have something for this?" without grepping. So the answer is always build a new one, and the curve steepens.

Watch out

The duplication tax isn't the disk space. It's that every near-duplicate multiplies your test surface, your design QA, your Experience Editor confusion, and your migration cost — while the answer to "which one should I use?" gets harder every sprint.

Now put an agent on top of that.

An agent asked for "a promo component" facing six near-identical options will pick one essentially at random — usually the one whose name best matches the prompt string, which is the worst possible heuristic. PromoBanner wins over PromoSplit because the marketer said "banner." Six months later you have content authored across all six, and consolidating is no longer possible.

Don't

Agents don't just suffer from component sprawl. They accelerate it. Every ambiguous choice gets made, silently, at machine speed, and lands as real content in your tree.

So the manifest we're about to build does double duty. It's what makes the agent correct — and it's the first machine-readable inventory of your component library you've ever had. Once every component's field signature is in one JSON file, duplication stops being a feeling and becomes a query.

That's Step 8, and it's the step I'd run first on an existing project even if you never wire up the agent.

The architecture

┌──────────────────┐
│  Cursor / Claude │   "Build a summer promo landing page"
└────────┬─────────┘
         │  MCP · Streamable HTTP
         ▼
┌──────────────────────────────────────────────────┐
│  Your MCP server — Next.js 15 App Router        │
│  app/api/[transport]/route.ts                   │
│                                                 │
│  list_components          get_component_contract│
│  find_duplicate_components ◄── the audit tool   │
│  validate_page_plan        ◄── the guard rail   │
│  build_page                revert_job           │
└──────┬────────────────────────────┬─────────────┘
       │                            │
       ▼                            ▼
┌───────────────────┐    ┌──────────────────────┐
│ Contract manifest │    │  SitecoreAI          │
│ generated from    │    │  Agent API           │
│ your JSS source   │    │  (deployed reality)  │
│ at build time     │    │                      │
└───────────────────┘    └──────────────────────┘

Two sources of truth, deliberately. Your source tree says what should exist. The Agent API says what does. Every interesting bug on a mature project lives in the gap between those two, and reconciling them is how you find it.

Step 1 — Scaffold

01Scaffold the server
terminalbash
1234567
npx create-next-app@latest sitecore-component-mcp \
  --typescript --app --no-tailwind --eslint

cd sitecore-component-mcp

npm install mcp-handler@^2 @modelcontextprotocol/server@^2 zod@^4
npm install -D ts-morph tsx

mcp-handler 2.x requires the MCP SDK v2 packages, zod ^4.2.0, and Node.js 20+. If you're still on @modelcontextprotocol/sdk 1.x, use mcp-handler 1.x instead — mixing them produces a confusing "server.registerTool is not a function" at runtime.

Why Next.js for an MCP server? Streamable HTTP transport, Vercel deployment, env var management, and route-level auth without writing an Express server. createMcpHandler returns a Web-standard request handler, so nothing here is Vercel-specific.

.env.localbash
1234567891011121314151617
# SitecoreAI Deploy → Credentials → Environment →
# Create credentials → Automation
SITECORE_CLIENT_ID=
SITECORE_CLIENT_SECRET=

# SitecoreAI Deploy → Projects → [project] →
# Authoring environments → Details → Environment host name
SITECORE_ENV_HOST=your-environment.sitecorecloud.io

# Absolute or relative path to your JSS components folder
JSS_COMPONENTS_PATH=../my-jss-app/src/components

# Shared secret for the /api/mcp route
MCP_SHARED_SECRET=

# Safety: refuse to write unless this is explicitly "true"
ALLOW_PRODUCTION_WRITES=false
Tip

That last flag is worth adding on day one. Point the server at a non-production environment by default and make production writes an explicit, deliberate act.

Step 2 — The contract schema

This is the actual product of the exercise. Everything else is plumbing around it.

02Define the contract
lib/contract.tsts
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
import { z } from "zod";

/** The Sitecore field types we know how to map from JSS. */
export const SitecoreFieldType = z.enum([
  "Single-Line Text",
  "Multi-Line Text",
  "Rich Text",
  "Image",
  "General Link",
  "Checkbox",
  "Droplink",
  "Droptree",
  "Multilist",
  "Treelist",
  "Date",
  "Datetime",
  "Number",
  "Integer",
]);
export type SitecoreFieldType = z.infer<typeof SitecoreFieldType>;

export const FieldContract = z.object({
  /** Exact Sitecore field name. Case matters. */
  name: z.string(),
  type: SitecoreFieldType,
  required: z.boolean(),
  /**
   * Soft limit. Sitecore does not enforce this — your layout does.
   * Violations are warnings, never errors.
   */
  maxLength: z.number().int().positive().optional(),
  /** Free text the model reads and respects. Write it for a human. */
  guidance: z.string().optional(),
  /** For Droplink / constrained fields. */
  allowedValues: z.array(z.string()).optional(),
});
export type FieldContract = z.infer<typeof FieldContract>;

export const ComponentContract = z.object({
  name: z.string(),
  description: z.string(),
  /** Resolved from the Agent API at runtime, not from source. */
  renderingId: z.string().optional(),
  datasourceTemplate: z.string().optional(),
  /** Empty array means "nowhere" — treat as a config error. */
  allowedPlaceholders: z.array(z.string()),
  maxPerPage: z.number().int().positive().optional(),
  fields: z.array(FieldContract),
  /** Rendering parameters with constrained values. */
  params: z.record(z.string(), z.array(z.string())).optional(),
  /** Relative path in the repo. Used by the duplicate report. */
  sourcePath: z.string().optional(),
  /** A known-good example — few-shot prompting via tool response. */
  example: z.record(z.string(), z.unknown()).optional(),
});
export type ComponentContract = z.infer<typeof ComponentContract>;

/**
 * A stable, order-independent signature of a component's shape.
 * Two components with the same signature are structurally identical
 * regardless of what they're called. This is what Step 8 compares.
 */
export function fieldSignature(c: ComponentContract): string {
  return c.fields
    .map((f) => `${f.name.toLowerCase()}:${f.type}:${f.required ? 1 : 0}`)
    .sort()
    .join("|");
}

guidance does more work than it looks like. "Renders in a two-line clamp on mobile — keep under 60 characters" is the kind of instruction a model follows reliably and a human forgets by Thursday.

fieldSignature is the quiet one. It's four lines, and it's what turns "I think we have too many promo components" into a number.

Step 3 — Annotate your components

Your components already declare their shape in TypeScript. We add intent on top, in the place developers already look.

03Annotate once, in source
src/components/PromoSplit.tsxtsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445
import {
  Field,
  ImageField,
  LinkField,
  RichTextField,
  withDatasourceCheck,
} from "@sitecore-jss/sitecore-jss-nextjs";
import type { ComponentProps } from "lib/component-props";

/**
 * Two-column promotional block: image on one side, copy on the other.
 * Use for campaign landing pages and mid-page conversion moments.
 *
 * @placeholder main
 * @placeholder promo-zone
 * @maxPerPage 3
 * @param variant image-left | image-right | stacked
 */
export type PromoSplitFields = {
  /** Small label above the heading. All caps in the design. @maxLength 24 */
  Eyebrow?: Field<string>;

  /** Two-line clamp on mobile — keep it tight. @maxLength 60 */
  Heading: Field<string>;

  /** Body copy. Inline links fine, no headings. @maxLength 220 */
  Body: RichTextField;

  /** 16:9. Alt text required for AA compliance. */
  Image: ImageField;

  PrimaryCta: LinkField;

  /** Omit unless there's a genuine secondary action. */
  SecondaryCta?: LinkField;
};

type PromoSplitProps = ComponentProps & { fields: PromoSplitFields };

const PromoSplit = ({ fields, params }: PromoSplitProps) => {
  const variant = params?.variant ?? "image-left";
  return <section className={`promo-split promo-split--${variant}`}>{/* … */}</section>;
};

export default withDatasourceCheck()<PromoSplitProps>(PromoSplit);

The convention: a type alias named <ComponentName>Fields, with JSDoc on the type for component-level tags and JSDoc on each property for field-level guidance. That's it. Nothing to maintain separately, nothing to fall out of sync.

Step 4 — The extractor

The complete file this time, including the tag helpers I usually see hand-waved.

04Read the types
scripts/generate-manifest.tsts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
import { Project, SyntaxKind, JSDoc, SourceFile } from "ts-morph";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { ComponentContract, SitecoreFieldType } from "../lib/contract";

/** JSS field type → Sitecore field type. Extend as your library grows. */
const TYPE_MAP: Record<string, SitecoreFieldType> = {
  "Field<string>": "Single-Line Text",
  "Field<boolean>": "Checkbox",
  "Field<number>": "Number",
  "Field<Date>": "Date",
  TextField: "Single-Line Text",
  RichTextField: "Rich Text",
  RichText: "Rich Text",
  ImageField: "Image",
  LinkField: "General Link",
  DateField: "Date",
  NumberField: "Number",
  CheckboxField: "Checkbox",
};

/** Read a single @tag value as a number, e.g. `@maxLength 60`. */
function numberTag(doc: JSDoc | undefined, tag: string): number | undefined {
  const raw = doc
    ?.getTags()
    .find((t) => t.getTagName() === tag)
    ?.getCommentText()
    ?.trim();
  const n = raw ? Number.parseInt(raw, 10) : NaN;
  return Number.isFinite(n) ? n : undefined;
}

/** Read every occurrence of a repeatable @tag, e.g. `@placeholder main`. */
function tagValues(doc: JSDoc | undefined, tag: string): string[] {
  return (doc?.getTags() ?? [])
    .filter((t) => t.getTagName() === tag)
    .map((t) => t.getCommentText()?.trim())
    .filter((v): v is string => Boolean(v));
}

/** Parse `@param variant a | b | c` into { variant: ["a","b","c"] }. */
function paramTags(doc: JSDoc | undefined): Record<string, string[]> {
  const out: Record<string, string[]> = {};
  for (const raw of tagValues(doc, "param")) {
    const [name, ...rest] = raw.split(/\s+/);
    const values = rest.join(" ").split("|").map((v) => v.trim()).filter(Boolean);
    if (name && values.length) out[name] = values;
  }
  return out;
}

/** Strip @tags from a JSDoc comment so descriptions stay clean. */
function describe(doc: JSDoc | undefined, fallback: string): string {
  const text = doc?.getCommentText()?.replace(/\s+/g, " ").trim();
  return text && text.length > 0 ? text : fallback;
}

function extract(file: SourceFile): ComponentContract | null {
  const componentName = path.basename(file.getFilePath(), ".tsx");

  const fieldsType =
    file.getTypeAlias(`${componentName}Fields`) ??
    file.getInterface(`${componentName}Fields`);
  if (!fieldsType) return null;

  const typeDoc = fieldsType.getJsDocs()[0];

  const fields = fieldsType
    .getDescendantsOfKind(SyntaxKind.PropertySignature)
    .map((prop) => {
      const raw = prop.getTypeNode()?.getText().replace(/\s/g, "") ?? "";
      const doc = prop.getJsDocs()[0];
      const mapped = TYPE_MAP[raw];

      if (!mapped) {
        console.warn(
          `  ! ${componentName}.${prop.getName()}: unmapped type "${raw}" ` +
            `— defaulting to Single-Line Text`
        );
      }

      return {
        name: prop.getName(),
        type: mapped ?? ("Single-Line Text" as SitecoreFieldType),
        required: !prop.hasQuestionToken(),
        maxLength: numberTag(doc, "maxLength"),
        guidance: describe(doc, "") || undefined,
      };
    });

  const placeholders = tagValues(typeDoc, "placeholder");
  if (placeholders.length === 0) {
    console.warn(`  ! ${componentName}: no @placeholder tag — defaulting to "main"`);
  }

  return {
    name: componentName,
    description: describe(typeDoc, `${componentName} component`),
    allowedPlaceholders: placeholders.length ? placeholders : ["main"],
    maxPerPage: numberTag(typeDoc, "maxPerPage"),
    params: Object.keys(paramTags(typeDoc)).length ? paramTags(typeDoc) : undefined,
    fields,
    sourcePath: path.relative(process.cwd(), file.getFilePath()),
  };
}

function main() {
  const componentsPath = process.env.JSS_COMPONENTS_PATH;
  if (!componentsPath) throw new Error("JSS_COMPONENTS_PATH is not set");

  const project = new Project({
    tsConfigFilePath: path.join(componentsPath, "../../tsconfig.json"),
    skipAddingFilesFromTsConfig: true,
  });
  project.addSourceFilesAtPaths(`${componentsPath}/**/*.tsx`);

  const contracts = project
    .getSourceFiles()
    .map(extract)
    .filter((c): c is ComponentContract => c !== null)
    .sort((a, b) => a.name.localeCompare(b.name));

  mkdirSync(path.join(process.cwd(), "generated"), { recursive: true });
  writeFileSync(
    path.join(process.cwd(), "generated/manifest.json"),
    JSON.stringify(contracts, null, 2) + "\n"
  );

  console.log(`✓ Extracted ${contracts.length} component contracts`);
}

main();
package.jsonjson
12345678
{
  "scripts": {
    "prebuild": "tsx scripts/generate-manifest.ts",
    "dev": "npm run prebuild && next dev",
    "manifest": "tsx scripts/generate-manifest.ts",
    "manifest:check": "npm run manifest && git diff --exit-code generated/manifest.json"
  }
}
Tip

Run manifest:check in CI. If someone adds a field and doesn't regenerate, the build fails instead of the manifest quietly lying to your agent for three weeks.

Note the two console.warn calls. On a real codebase the first run is noisy, and that noise is a to-do list: unmapped field types and components with no placeholder declared. Work through it once and it stays clean.

Step 5 — Authenticate

05Cache the token
lib/sitecore/auth.tsts
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
const TOKEN_URL = "https://auth.sitecorecloud.io/oauth/token";
const AUDIENCE = "https://api.sitecorecloud.io";

type TokenResponse = {
  access_token: string;
  expires_in: number;
  token_type: string;
  scope: string;
};

let cached: { token: string; expiresAt: number } | null = null;
let inFlight: Promise<string> | null = null;

async function request(): Promise<string> {
  const res = await fetch(TOKEN_URL, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      client_id: process.env.SITECORE_CLIENT_ID!,
      client_secret: process.env.SITECORE_CLIENT_SECRET!,
      grant_type: "client_credentials",
      audience: AUDIENCE,
    }),
  });

  if (!res.ok) {
    throw new Error(`Sitecore auth failed: ${res.status} ${await res.text()}`);
  }

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

export async function getSitecoreToken(): Promise<string> {
  // 5-minute safety buffer before actual expiry
  if (cached && Date.now() < cached.expiresAt - 300_000) return cached.token;

  // Collapse concurrent refreshes into one request
  if (!inFlight) {
    inFlight = request().finally(() => {
      inFlight = null;
    });
  }
  return inFlight;
}

The JWT lives 24 hours. Cache it. The inFlight promise matters more than it looks — without it, three simultaneous tool calls on a cold start fire three token requests, and you'll meet the rate limiter.

Watch out

To create the automation client you need Organization Admin or Owner. Cloud Portal → SitecoreAI Deploy → Credentials → Environment → Create credentials → Automation. Copy the ID and secret immediately; you cannot view them again.

Watch out

Registering a full OAuth app instead? You must email Sitecore Support and request the scopes explicitly: xmcloud.cm:admin, personalize.exp:mng, personalize.tmpl:r, personalize.pos:mng, ai.org.bri:r, co.briefs:r, co.briefs:w, ai.org.brd:r, ai.org.bri:w, cmp.sites:read, platform.tenants:list.

Step 6 — The Agent API client

06One place for every path
lib/sitecore/agent-api.tsts
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
import { getSitecoreToken } from "./auth";

const BASE = `https://${process.env.SITECORE_ENV_HOST}`;

/**
 * Agent API v2.0 changed paths in May 2026 and removed the
 * personalization v1.0 endpoints in August. Keep every path here so a
 * version bump is a one-file diff instead of a grep across the repo.
 *
 * Verify against the OpenAPI definition — don't trust this table:
 * https://api-docs.sitecore.com/sai/agent-api
 */
export const ENDPOINTS = {
  listComponents: "/agent/v2/components",
  getComponent: (id: string) => `/agent/v2/components/${id}`,
  createDatasource: "/agent/v2/components/datasources",
  listSites: "/agent/v2/sites",
  createPage: "/agent/v2/pages",
  getPage: (id: string) => `/agent/v2/pages/${id}`,
  addComponent: (pageId: string) => `/agent/v2/pages/${pageId}/components`,
  getJob: (jobId: string) => `/agent/v2/jobs/${jobId}`,
  revertJob: (jobId: string) => `/agent/v2/jobs/${jobId}/revert`,
} as const;

export class AgentApiError extends Error {
  constructor(
    readonly status: number,
    readonly endpoint: string,
    readonly body: string
  ) {
    super(`Agent API ${status} on ${endpoint}: ${body.slice(0, 400)}`);
    this.name = "AgentApiError";
  }
}

export async function agentApi<T>(
  endpoint: string,
  init: RequestInit = {}
): Promise<T> {
  const token = await getSitecoreToken();

  const res = await fetch(`${BASE}${endpoint}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      Accept: "application/json",
      ...init.headers,
    },
  });

  if (!res.ok) {
    throw new AgentApiError(res.status, endpoint, await res.text());
  }

  // 204 on some revert responses
  if (res.status === 204) return undefined as T;
  return (await res.json()) as T;
}
Don't

Don't hand-type endpoint shapes. Download the OpenAPI definition from the API catalog and run openapi-typescript over it. Guessing request bodies is how you spend an evening debugging a 400 that turns out to be a casing difference.

Step 7 — Reconcile source against reality

07Find the drift
lib/manifest.tsts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
import rawManifest from "@/generated/manifest.json";
import { agentApi, ENDPOINTS } from "./sitecore/agent-api";
import type { ComponentContract } from "./contract";

type SitecoreRendering = {
  id: string;
  name: string;
  datasourceTemplateId?: string;
};

export type ResolvedContract = ComponentContract & {
  /** Present in source AND deployed to this environment. */
  deployed: boolean;
};

let cache: { data: ResolvedContract[]; at: number } | null = null;
const TTL_MS = 5 * 60_000;

export async function getContracts(): Promise<ResolvedContract[]> {
  if (cache && Date.now() - cache.at < TTL_MS) return cache.data;

  const { components } = await agentApi<{ components: SitecoreRendering[] }>(
    ENDPOINTS.listComponents
  );
  const byName = new Map(components.map((c) => [c.name, c]));

  const data = (rawManifest as ComponentContract[]).map((contract) => {
    const rendering = byName.get(contract.name);
    return {
      ...contract,
      renderingId: rendering?.id,
      datasourceTemplate: rendering?.datasourceTemplateId,
      deployed: Boolean(rendering),
      description: rendering
        ? contract.description
        : `${contract.description} [NOT DEPLOYED to this environment — do not use]`,
    };
  });

  cache = { data, at: Date.now() };
  return data;
}

/** Renderings Sitecore has that your repo has never heard of. */
export async function getOrphanedRenderings(): Promise<string[]> {
  const { components } = await agentApi<{ components: SitecoreRendering[] }>(
    ENDPOINTS.listComponents
  );
  const known = new Set((rawManifest as ComponentContract[]).map((c) => c.name));
  return components.map((c) => c.name).filter((n) => !known.has(n));
}

Two directions of drift, and both matter:

In source, not deployed. Someone built a component, merged it, and the serialization never made it to this environment. The agent would otherwise pick it and fail deep inside add_component_on_page with an unhelpful error.

Deployed, not in source. Renderings that exist in Sitecore with no corresponding component file. On a project with any history you will find these — leftovers from a migration, or components deleted from the repo but never from the tree. Every one is either a cleanup task or a missing file.

Tip

getOrphanedRenderings on a five-year-old project is uncomfortable reading. Run it anyway. It's the cheapest audit in this article.

Step 8 — Find your duplicate components

This is the step that addresses sprawl directly, and it's the one I'd run first on any existing project.

08Make duplication a number
lib/duplicates.tsts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
import { getContracts, type ResolvedContract } from "./manifest";
import { fieldSignature } from "./contract";

export type DuplicateGroup = {
  kind: "identical" | "near-identical" | "subset";
  similarity: number;
  components: {
    name: string;
    sourcePath?: string;
    deployed: boolean;
    fieldCount: number;
  }[];
  sharedFields: string[];
  differingFields: string[];
  recommendation: string;
};

/** Jaccard similarity over the set of "name:type" pairs. */
function similarity(a: ResolvedContract, b: ResolvedContract): number {
  const sa = new Set(a.fields.map((f) => `${f.name.toLowerCase()}:${f.type}`));
  const sb = new Set(b.fields.map((f) => `${f.name.toLowerCase()}:${f.type}`));
  if (sa.size === 0 && sb.size === 0) return 1;
  let shared = 0;
  for (const x of sa) if (sb.has(x)) shared += 1;
  return shared / (sa.size + sb.size - shared);
}

function fieldNames(c: ResolvedContract): Set<string> {
  return new Set(c.fields.map((f) => f.name.toLowerCase()));
}

function isSubset(a: ResolvedContract, b: ResolvedContract): boolean {
  const [sa, sb] = [fieldNames(a), fieldNames(b)];
  if (sa.size === 0 || sa.size >= sb.size) return false;
  for (const x of sa) if (!sb.has(x)) return false;
  return true;
}

export async function findDuplicates(threshold = 0.7): Promise<DuplicateGroup[]> {
  const contracts = await getContracts();
  const groups: DuplicateGroup[] = [];
  const seen = new Set<string>();

  // Pass 1 — exact structural matches, grouped by signature
  const bySignature = new Map<string, ResolvedContract[]>();
  for (const c of contracts) {
    const sig = fieldSignature(c);
    bySignature.set(sig, [...(bySignature.get(sig) ?? []), c]);
  }

  for (const [, group] of bySignature) {
    if (group.length < 2) continue;
    group.forEach((c) => seen.add(c.name));
    groups.push({
      kind: "identical",
      similarity: 1,
      components: group.map(summarise),
      sharedFields: group[0].fields.map((f) => f.name),
      differingFields: [],
      recommendation:
        `${group.length} components with an identical field signature. ` +
        `These are the same component. Keep the most-used one, migrate ` +
        `datasources, and delete the rest.`,
    });
  }

  // Pass 2 — near-identical and subset pairs
  for (let i = 0; i < contracts.length; i++) {
    for (let j = i + 1; j < contracts.length; j++) {
      const [a, b] = [contracts[i], contracts[j]];
      if (seen.has(a.name) && seen.has(b.name)) continue;

      const score = similarity(a, b);
      const subset = isSubset(a, b) || isSubset(b, a);
      if (score < threshold && !subset) continue;

      const na = fieldNames(a);
      const nb = fieldNames(b);
      const shared = [...na].filter((x) => nb.has(x));
      const differing = [
        ...[...na].filter((x) => !nb.has(x)),
        ...[...nb].filter((x) => !na.has(x)),
      ];

      groups.push({
        kind: subset ? "subset" : "near-identical",
        similarity: Number(score.toFixed(2)),
        components: [summarise(a), summarise(b)],
        sharedFields: shared,
        differingFields: differing,
        recommendation: subset
          ? `One component's fields are a strict subset of the other. ` +
            `Consider a single component with optional fields, or a ` +
            `rendering variant, instead of two renderings.`
          : `${Math.round(score * 100)}% field overlap, differing only in ` +
            `[${differing.join(", ")}]. Usually one component with optional ` +
            `fields plus a rendering parameter.`,
      });
    }
  }

  return groups.sort((x, y) => y.similarity - x.similarity);
}

function summarise(c: ResolvedContract) {
  return {
    name: c.name,
    sourcePath: c.sourcePath,
    deployed: c.deployed,
    fieldCount: c.fields.length,
  };
}

Run this against a real library and the output looks like this:

find_duplicate_components — outputtext
1234567891011121314151617181920
IDENTICAL (1.00)
  PromoSplit        src/components/PromoSplit.tsx        6 fields  deployed
  PromoBanner       src/components/PromoBanner.tsx       6 fields  deployed
  CampaignPromo     src/components/promo/Campaign.tsx    6 fields  NOT deployed
  → 3 components with an identical field signature. These are the same
    component. Keep the most-used one, migrate datasources, delete the rest.

NEAR-IDENTICAL (0.86)
  HeroBanner        src/components/HeroBanner.tsx        7 fields  deployed
  HeroBannerVideo   src/components/HeroBannerVideo.tsx   8 fields  deployed
  shared:    Eyebrow, Heading, Body, Image, PrimaryCta, Theme, Alignment
  differing: VideoUrl
  → 86% field overlap, differing only in [VideoUrl]. Usually one component
    with optional fields plus a rendering parameter.

SUBSET (0.71)
  TextBlock         src/components/TextBlock.tsx         2 fields  deployed
  TextBlockWithCta  src/components/TextBlockWithCta.tsx  4 fields  deployed
  → One component's fields are a strict subset of the other. Consider a
    single component with optional fields, or a rendering variant.

Three things this gives you that a grep can't.

It's evidence, not opinion. "We have too many promo components" is a hallway complaint that never gets prioritised. "Three components share an identical field signature, one of which isn't even deployed" is a ticket.

It's ordered by how safe the consolidation is. Identical signatures are near-zero-risk merges. Subsets are usually one optional field away from being the same component. Near-identical pairs need a design conversation. Work top-down.

It runs in CI. Fail the build when a new identical-signature pair appears. You won't fix the existing 140 overnight, but you can stop the curve steepening — which is the only intervention that actually compounds.

Watch out

Threshold tuning matters. At 0.7 you'll get useful signal with some noise on genuinely different components that happen to share Heading and Image. Start at 0.8 to build trust in the output, then lower it once the obvious cases are cleared.

And the agent-facing benefit: once duplicates are consolidated, list_components returns one obvious answer per intent instead of six ambiguous ones. The dedup work makes the agent correct and makes onboarding faster. Same effort, two payoffs.

Step 9 — Register the tools

09Expose the surface
app/api/[transport]/route.tsts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
import { createMcpHandler } from "mcp-handler";
import { z } from "zod";
import { getContracts, getOrphanedRenderings } from "@/lib/manifest";
import { findDuplicates } from "@/lib/duplicates";
import { validatePlan, PlannedComponentSchema } from "@/lib/validate";
import { buildPage } from "@/lib/build";
import { agentApi, ENDPOINTS } from "@/lib/sitecore/agent-api";

const text = (t: string, isError = false) => ({
  content: [{ type: "text" as const, text: t }],
  ...(isError ? { isError: true } : {}),
});

const handler = createMcpHandler(
  (server) => {
    server.registerTool(
      "list_components",
      {
        title: "List available components",
        description:
          "Returns every component in this project's library with a " +
          "one-line description and its allowed placeholders. ALWAYS call " +
          "this before planning a page. Never invent a component name.",
        inputSchema: z.object({
          placeholder: z
            .string()
            .optional()
            .describe("Filter to components legal in this placeholder"),
        }),
      },
      async ({ placeholder }) => {
        const all = await getContracts();
        const list = placeholder
          ? all.filter((c) => c.allowedPlaceholders.includes(placeholder))
          : all;

        if (list.length === 0) {
          return text(`No components are allowed in "${placeholder}".`, true);
        }

        return text(
          list
            .filter((c) => c.deployed)
            .map(
              (c) =>
                `${c.name} — ${c.description} ` +
                `[placeholders: ${c.allowedPlaceholders.join(", ")}]`
            )
            .join("\n")
        );
      }
    );

    server.registerTool(
      "get_component_contract",
      {
        title: "Get a component's full field contract",
        description:
          "Returns exact field names, Sitecore field types, which fields " +
          "are required, length guidance, and allowed parameter values. " +
          "Call this for every component you intend to use, before " +
          "writing any content.",
        inputSchema: z.object({ name: z.string() }),
      },
      async ({ name }) => {
        const all = await getContracts();
        const found = all.find(
          (c) => c.name.toLowerCase() === name.toLowerCase()
        );
        if (!found) {
          return text(
            `No component named "${name}". Available: ` +
              all.map((c) => c.name).join(", "),
            true
          );
        }
        return {
          content: [{ type: "text", text: JSON.stringify(found, null, 2) }],
          structuredContent: found,
        };
      }
    );

    server.registerTool(
      "find_duplicate_components",
      {
        title: "Audit the library for duplicate components",
        description:
          "Groups components by field signature to surface identical, " +
          "near-identical, and subset duplicates. Use when asked to audit " +
          "the component library, before adding a new component, or when " +
          "unsure which of several similar components to use.",
        inputSchema: z.object({
          threshold: z.number().min(0).max(1).default(0.7),
        }),
      },
      async ({ threshold }) => {
        const groups = await findDuplicates(threshold);
        if (groups.length === 0) {
          return text(`No duplicates above ${threshold} similarity.`);
        }
        return {
          content: [{ type: "text", text: JSON.stringify(groups, null, 2) }],
          structuredContent: { groups },
        };
      }
    );

    server.registerTool(
      "find_orphaned_renderings",
      {
        title: "Renderings in Sitecore with no source component",
        description:
          "Lists renderings deployed to the environment that have no " +
          "matching component file in the repo. Cleanup candidates.",
        inputSchema: z.object({}),
      },
      async () => {
        const orphans = await getOrphanedRenderings();
        return text(
          orphans.length
            ? `${orphans.length} orphaned:\n${orphans.join("\n")}`
            : "No orphaned renderings."
        );
      }
    );

    // validate_page_plan and build_page — Steps 10 and 11
  },
  {},
  { basePath: "/api", maxDuration: 60, verboseLogs: true }
);

export { handler as GET, handler as POST, handler as DELETE };
Tip

Read those description strings again. "ALWAYS call this before planning a page. Never invent a component name." Tool descriptions are prompt-engineering surface and most people leave them as bare noun phrases. This is where you encode the workflow you actually want, and it costs nothing.

Note list_components filters to deployed components. The agent should never see something it can't use. get_component_contract still returns undeployed ones, with the warning in the description — so if the agent does ask by name, it gets a useful answer rather than a dead end.

Step 10 — The validation tool

Everything before this was plumbing. This is the piece that changes behaviour.

10Let it fail cheaply
lib/validate.tsts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
import { z } from "zod";
import { getContracts } from "./manifest";

export const PlannedComponentSchema = z.object({
  component: z.string(),
  placeholder: z.string(),
  fields: z.record(z.string(), z.string()),
  params: z.record(z.string(), z.string()).optional(),
});
export type PlannedComponent = z.infer<typeof PlannedComponentSchema>;

export type ValidationIssue = {
  severity: "error" | "warning";
  component: string;
  message: string;
  /** What "valid" looks like. This is what lets the agent self-correct. */
  fix?: string;
};

export async function validatePlan(
  plan: PlannedComponent[]
): Promise<ValidationIssue[]> {
  const contracts = await getContracts();
  const issues: ValidationIssue[] = [];
  const counts = new Map<string, number>();

  if (plan.length === 0) {
    return [{ severity: "error", component: "-", message: "Plan is empty." }];
  }

  for (const item of plan) {
    const contract = contracts.find((c) => c.name === item.component);

    // 1 — does it exist at all?
    if (!contract) {
      const near = contracts
        .map((c) => c.name)
        .filter((n) => n.toLowerCase().includes(item.component.toLowerCase().slice(0, 5)));
      issues.push({
        severity: "error",
        component: item.component,
        message: `Component "${item.component}" does not exist.`,
        fix: near.length
          ? `Did you mean: ${near.join(", ")}? Call list_components.`
          : `Call list_components and choose a real one.`,
      });
      continue;
    }

    // 2 — is it deployed here?
    if (!contract.deployed) {
      issues.push({
        severity: "error",
        component: item.component,
        message: `"${item.component}" exists in source but is not deployed to this environment.`,
        fix: `Choose a deployed component, or deploy this one first.`,
      });
    }

    // 3 — legal placeholder?
    if (!contract.allowedPlaceholders.includes(item.placeholder)) {
      issues.push({
        severity: "error",
        component: item.component,
        message: `Not allowed in placeholder "${item.placeholder}".`,
        fix: `Allowed placeholders: ${contract.allowedPlaceholders.join(", ")}`,
      });
    }

    // 4 — design guidance on repetition
    counts.set(item.component, (counts.get(item.component) ?? 0) + 1);
    const used = counts.get(item.component)!;
    if (contract.maxPerPage && used > contract.maxPerPage) {
      issues.push({
        severity: "warning",
        component: item.component,
        message: `Used ${used} times; design guidance is max ${contract.maxPerPage}.`,
      });
    }

    // 5 — required fields present and non-empty
    for (const field of contract.fields.filter((f) => f.required)) {
      if (!item.fields[field.name]?.trim()) {
        issues.push({
          severity: "error",
          component: item.component,
          message: `Missing required field "${field.name}" (${field.type}).`,
          fix: field.guidance ?? `Provide a ${field.type} value.`,
        });
      }
    }

    // 6 — no invented field names
    const known = new Set(contract.fields.map((f) => f.name));
    for (const supplied of Object.keys(item.fields)) {
      if (!known.has(supplied)) {
        issues.push({
          severity: "error",
          component: item.component,
          message: `Field "${supplied}" does not exist on ${contract.name}.`,
          fix: `Valid fields: ${[...known].join(", ")}`,
        });
      }
    }

    // 7 — soft length limits
    for (const field of contract.fields) {
      const value = item.fields[field.name];
      if (field.maxLength && value && value.length > field.maxLength) {
        issues.push({
          severity: "warning",
          component: item.component,
          message: `"${field.name}" is ${value.length} chars, guidance is ${field.maxLength}.`,
          fix: field.guidance,
        });
      }
    }

    // 8 — constrained rendering parameters
    for (const [key, value] of Object.entries(item.params ?? {})) {
      const allowed = contract.params?.[key];
      if (allowed && !allowed.includes(value)) {
        issues.push({
          severity: "error",
          component: item.component,
          message: `Param "${key}" = "${value}" is invalid.`,
          fix: `Allowed: ${allowed.join(" | ")}`,
        });
      }
    }
  }

  return issues;
}

export function formatIssues(issues: ValidationIssue[]): string {
  const errors = issues.filter((i) => i.severity === "error");
  const header = errors.length
    ? `${errors.length} error(s) — you MUST fix these and re-validate:`
    : `Warnings only. Safe to proceed, but review:`;

  return [
    header,
    ...issues.map(
      (i) =>
        `[${i.severity.toUpperCase()}] ${i.component}: ${i.message}` +
        (i.fix ? `\n  → ${i.fix}` : "")
    ),
  ].join("\n");
}

Register it, and make the description carry the workflow:

app/api/[transport]/route.ts (continued)ts
123456789101112131415161718192021
server.registerTool(
  "validate_page_plan",
  {
    title: "Validate a page plan before building",
    description:
      "MANDATORY before build_page. Checks that components exist, are " +
      "deployed, sit in legal placeholders, have all required fields, " +
      "use only real field names, and respect length and parameter " +
      "constraints. Returns structured issues with fixes. Fix every " +
      "error and call this again before building.",
    inputSchema: z.object({ plan: z.array(PlannedComponentSchema) }),
  },
  async ({ plan }) => {
    const issues = await validatePlan(plan);
    if (issues.length === 0) {
      return text("Plan is valid. Proceed to build_page.");
    }
    const hasErrors = issues.some((i) => i.severity === "error");
    return text(formatIssues(issues), hasErrors);
  }
);

Why the fix field is the whole thing

Compare two responses to the same failed check.

a bare errortext
1
[ERROR] PromoSplit: Invalid field.
an actionable errortext
12
[ERROR] PromoSplit: Field "Title" does not exist on PromoSplit.
  → Valid fields: Eyebrow, Heading, Body, Image, PrimaryCta, SecondaryCta

The first ends the conversation — the agent guesses, guesses wrong, and eventually asks you. The second closes the loop: it rewrites the plan, re-validates, and passes without you touching anything.

Tip

If you take one thing from this article, take this. When an agent writes into a real system, your error strings are an interface. Design them like one. Severity says whether to stop, message says what's wrong, fix says what to do next — and only the third one closes the loop.

Step 11 — Build, and keep the receipts

11Never write without an undo
lib/build.tsts
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
import { agentApi, ENDPOINTS } from "./sitecore/agent-api";
import { validatePlan, type PlannedComponent } from "./validate";

export type BuildResult = {
  pageId: string;
  path: string;
  jobIds: string[];
};

export async function buildPage(input: {
  name: string;
  parentPath: string;
  plan: PlannedComponent[];
}): Promise<BuildResult> {
  if (process.env.ALLOW_PRODUCTION_WRITES !== "true") {
    const host = process.env.SITECORE_ENV_HOST ?? "";
    if (!/dev|qa|uat|staging/i.test(host)) {
      throw new Error(
        `Refusing to write to "${host}". Set ALLOW_PRODUCTION_WRITES=true ` +
          `if this is intentional.`
      );
    }
  }

  // Belt and braces — never trust that the agent called validate first
  const issues = await validatePlan(input.plan);
  const errors = issues.filter((i) => i.severity === "error");
  if (errors.length) {
    throw new Error(
      `Refusing to build — ${errors.length} validation error(s):\n` +
        errors.map((e) => `${e.component}: ${e.message}`).join("\n")
    );
  }

  const page = await agentApi<{ id: string; path: string; jobId: string }>(
    ENDPOINTS.createPage,
    {
      method: "POST",
      body: JSON.stringify({
        name: input.name,
        parentPath: input.parentPath,
      }),
    }
  );

  const jobIds = [page.jobId];

  for (const item of input.plan) {
    const res = await agentApi<{ jobId: string }>(
      ENDPOINTS.addComponent(page.id),
      {
        method: "POST",
        body: JSON.stringify({
          componentName: item.component,
          placeholder: item.placeholder,
          fields: item.fields,
          parameters: item.params,
        }),
      }
    );
    jobIds.push(res.jobId);
  }

  return { pageId: page.id, path: page.path, jobIds };
}

Return the job IDs to the agent and tell it what they're for:

app/api/[transport]/route.ts (continued)ts
1234567891011121314151617181920212223242526272829303132333435363738
server.registerTool(
  "build_page",
  {
    title: "Create a page from a validated plan",
    description:
      "Creates the page and adds every component. Only call after " +
      "validate_page_plan returns no errors. Returns job IDs — keep " +
      "them; revert_job undoes any operation.",
    inputSchema: z.object({
      name: z.string(),
      parentPath: z.string(),
      plan: z.array(PlannedComponentSchema),
    }),
  },
  async (input) => {
    const r = await buildPage(input);
    return text(
      `Created ${r.path}\n\n` +
        `Job IDs — revert newest first:\n` +
        r.jobIds.slice().reverse().map((id) => `  ${id}`).join("\n")
    );
  }
);

server.registerTool(
  "revert_job",
  {
    title: "Undo an Agent API operation",
    description:
      "Reverts a previously executed job by ID. When undoing a page " +
      "build, revert in reverse order — components before the page.",
    inputSchema: z.object({ jobId: z.string() }),
  },
  async ({ jobId }) => {
    await agentApi(ENDPOINTS.revertJob(jobId), { method: "POST" });
    return text(`Reverted job ${jobId}.`);
  }
);

Every Agent API operation is tracked with a job ID you can revert. Most people building on this API never surface it. An undo stack for AI-generated content is the difference between letting an agent near staging and letting it near production.

Step 12 — Connect and lock down

12Wire it up
.cursor/mcp.jsonjson
1234567
{
  "mcpServers": {
    "sitecore-components": {
      "url": "http://localhost:3000/api/mcp"
    }
  }
}
terminal — Claude Codebash
12
claude mcp add sitecore-components --url http://localhost:3000/api/mcp
claude mcp list
middleware.tsts
1234567891011
import { NextResponse, type NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const auth = req.headers.get("authorization");
  if (auth !== `Bearer ${process.env.MCP_SHARED_SECRET}`) {
    return new NextResponse("Unauthorized", { status: 401 });
  }
  return NextResponse.next();
}

export const config = { matcher: "/api/:path*" };
Don't

A shared bearer secret is the minimum floor for an internal tool. For anything leaving your team, the MCP 2025-11-25 spec requires OAuth 2.1 with PKCE and a Protected Resource Metadata document at /.well-known/oauth-protected-resource — plain PKCE is explicitly forbidden. mcp-handler ships withMcpAuth for this. An MCP endpoint with CMS write access and no auth is how you end up in an incident review.

Now run the original prompt again. You'll see list_components, then get_component_contract, then validate_page_plan — usually twice — and only then build_page. It writes Heading, not Title. It keeps the headline under 60 characters. It puts the component in main.

When it goes wrong: a debugging guide

Everything above is the happy path. Here's what actually breaks, in the order you'll hit it.

SymptomCause and fix
server.registerTool is not a functionmcp-handler 2.x with SDK 1.x. Match major versions.
Agent never calls your toolsTool descriptions too vague. Put the workflow in the description: "ALWAYS call this before…"
401 from the Agent API on the second callYou're not caching the JWT, or you're caching past expiry. Check the 5-minute buffer.
403 on every callAutomation client lacks scope, or you created it at the wrong level. It must be an environment automation client.
Manifest is emptyYour type alias isn't named <ComponentName>Fields, or JSS_COMPONENTS_PATH is wrong. The extractor silently skips files it can't match — check the file count in the log.
Every field comes out Single-Line TextYour TYPE_MAP keys don't match the source text. The extractor strips whitespace, so Field<string> not Field< string >. Watch the unmapped type warnings.
Agent picks the wrong componentSprawl. Run find_duplicate_components — you almost certainly have near-identical options and the agent is coin-flipping.
Validation passes, build_page 400sYour ENDPOINTS bodies don't match the OpenAPI spec. Generate types from the spec.
First tool call takes 8 secondsCold start + OAuth + component fetch. Expected on serverless. Warm the cache or move to a long-lived host.
Tool response truncatedYou're returning all contracts in one response. That's why list_components returns one line each.

Reading what the agent actually did

When behaviour is confusing, look at the tool call sequence rather than the final output. In Cursor, the MCP panel shows each call and response. In Claude Code, --verbose prints them.

The three patterns worth recognising:

It skipped validation. The description isn't forceful enough, or build_page looks callable on its own. Fix: strengthen the description, and keep the server-side check in buildPage so skipping fails loudly.

It validated, got errors, and gave up. Your fix strings are missing or unhelpful. An error without a fix is a dead end.

It looped on the same error. Usually a contradiction — a field marked required that the agent has no way to source, like an Image with no asset available. Either make it optional in the contract or give the agent an asset tool.

What will bite you at scale

Stale manifests. Someone adds a field, forgets the generator. Gate it in CI with manifest:check.

Cold starts. First call is cold start plus OAuth plus component fetch. Cache in module scope with a TTL, as above. Consider revalidating on a schedule rather than on demand.

Datasource strategy. One datasource per component, or shared per campaign folder? The agent has no opinion. Encode yours in the build_page description, or you'll get a content tree that looks like a landfill.

Multi-site and multi-language. Across dozens of locales, component availability genuinely differs per site collection. list_components needs a site parameter. Add it early — retrofitting is miserable.

Rendering parameters. SXA standard values, parameter templates, and styles don't map cleanly onto a flat params record. Start with the constrained-enum subset here and expand deliberately.

Token budget. Fifty components with full contracts is a lot of tokens burned before the agent does anything. One line each in list_components, full detail only in get_component_contract.

Why this matters more than it looks

Marketer MCP is built for marketers, and lets them manage pages and content through natural language instead of API calls. That's the right design for its audience.

But the same protocol pointed at your code becomes something else: a way to make your architectural decisions legible to a machine. Which components go where, what's required, how long copy can run, which of your six promo components is the real one — that's always been tribal knowledge, enforced by code review and hope.

An MCP server turns it into a contract that gets checked automatically, every time, by whoever or whatever is composing the page. And the manifest that makes the agent correct is the same artifact that finally lets you measure the sprawl you've been complaining about for three years.

The component library was always the interesting part of a headless Sitecore build. It just never had an API before.

The full file tree

sitecore-component-mcp/
├── app/
│   └── api/
│       └── [transport]/
│           └── route.ts          # MCP server + tool registration
├── lib/
│   ├── contract.ts               # Zod schema + fieldSignature()
│   ├── manifest.ts               # source ⟷ Sitecore reconciliation
│   ├── duplicates.ts             # the sprawl audit
│   ├── validate.ts               # the guard rail
│   ├── build.ts                  # Agent API orchestration
│   └── sitecore/
│       ├── auth.ts               # cached JWT, single-flight
│       └── agent-api.ts          # typed client + ENDPOINTS
├── scripts/
│   └── generate-manifest.ts      # ts-morph extraction
├── generated/
│   └── manifest.json             # build artifact, committed
├── middleware.ts                 # bearer gate
└── .env.local