Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): give agents the Content Editor through the MCP and REST API (#1305)

Cihan9b9082a4b646
diff --git a/web/src/app/api/mcp/content-drafts/[id]/impact/route.ts b/web/src/app/api/mcp/content-drafts/[id]/impact/route.ts
new file mode 100644
index 000000000..35778dc8e
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/impact/route.ts
@@ -0,0 +1,38 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getContentImpactFor } from '@/lib/mcp/content';
+import { contentUuid, impactDays } from '@/lib/mcp/content-schemas';
+
+/**
+ * GET /api/mcp/content-drafts/[id]/impact?days=30 — REST mirror of the
+ * `get_content_impact` MCP tool (days: 7, 30, 90 or 365).
+ */
+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ const raw = new URL(req.url).searchParams.get('days');
+ const days = impactDays.safeParse(raw === null ? undefined : Number(raw));
+ if (!contentUuid.safeParse(id).success || !days.success) {
+ return NextResponse.json(
+ { error: 'id must be a draft UUID; days 7, 30, 90 or 365' },
+ { status: 400 },
+ );
+ }
+ try {
+ const impact = await getContentImpactFor(auth, id, days.data);
+ if (impact === 'no_page') {
+ return NextResponse.json(
+ { error: 'This draft is a new page, not live yet' },
+ { status: 409 },
+ );
+ }
+ if (!impact) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(impact);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts b/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts
new file mode 100644
index 000000000..fde39a1f2
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/ready/route.ts
@@ -0,0 +1,30 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { setContentDraftReadyFor } from '@/lib/mcp/content';
+import { contentUuid } from '@/lib/mcp/content-schemas';
+
+/** POST /api/mcp/content-drafts/[id]/ready — REST mirror of `set_content_draft_ready`. */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ if (!contentUuid.safeParse(id).success) {
+ return NextResponse.json({ error: 'id must be a draft UUID' }, { status: 400 });
+ }
+ try {
+ const result = await setContentDraftReadyFor(auth, id);
+ if (result === 'in_review') {
+ return NextResponse.json(
+ { error: 'The draft is in review: a person marks it ready in the editor' },
+ { status: 409 },
+ );
+ }
+ if (!result) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(result);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/app/api/mcp/content-drafts/[id]/route.ts b/web/src/app/api/mcp/content-drafts/[id]/route.ts
new file mode 100644
index 000000000..a143420d2
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getContentDraftFor } from '@/lib/mcp/content';
+import { contentUuid } from '@/lib/mcp/content-schemas';
+
+/** GET /api/mcp/content-drafts/[id] — REST mirror of the `get_content_draft` MCP tool. */
+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ if (!contentUuid.safeParse(id).success) {
+ return NextResponse.json({ error: 'id must be a draft UUID' }, { status: 400 });
+ }
+ try {
+ const draft = await getContentDraftFor(auth, id);
+ if (!draft) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(draft);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts b/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts
new file mode 100644
index 000000000..21afe6c62
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/sources/route.ts
@@ -0,0 +1,58 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { addContentSourceFor, getContentSourcesFor } from '@/lib/mcp/content';
+import { addSourceShape, contentUuid, sourceRefError } from '@/lib/mcp/content-schemas';
+
+/** GET /api/mcp/content-drafts/[id]/sources — REST mirror of `get_content_sources`. */
+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ if (!contentUuid.safeParse(id).success) {
+ return NextResponse.json({ error: 'id must be a draft UUID' }, { status: 400 });
+ }
+ try {
+ const sources = await getContentSourcesFor(auth, id);
+ if (!sources) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(sources);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
+
+/**
+ * POST /api/mcp/content-drafts/[id]/sources — REST mirror of
+ * `add_content_source`. Body: { kind: prompt | cited_page | gsc_query, ref }
+ */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ const parsed = z.object(addSourceShape).safeParse(await req.json().catch(() => null));
+ if (!contentUuid.safeParse(id).success || !parsed.success) {
+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ }
+ const { kind, ref } = parsed.data;
+ const refError = sourceRefError(kind, ref);
+ if (refError) return NextResponse.json({ error: refError }, { status: 400 });
+ try {
+ const result = await addContentSourceFor(
+ auth,
+ id,
+ kind === 'prompt' ? { kind, promptId: ref } : { kind, ref },
+ );
+ if (result === 'not_found')
+ return NextResponse.json({ error: 'Prompt not found' }, { status: 404 });
+ if (!result) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(result);
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts b/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts
new file mode 100644
index 000000000..4d5470994
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/suggestions/route.ts
@@ -0,0 +1,44 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { suggestContentChangesFor } from '@/lib/mcp/content';
+import { contentUuid, suggestionsShape } from '@/lib/mcp/content-schemas';
+
+/**
+ * POST /api/mcp/content-drafts/[id]/suggestions — REST mirror of the
+ * `suggest_content_changes` MCP tool. Body: { suggestions: [...] }
+ */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const { id } = await params;
+ const parsed = z.object(suggestionsShape).safeParse(await req.json().catch(() => null));
+ if (!contentUuid.safeParse(id).success || !parsed.success) {
+ return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ }
+ try {
+ const result = await suggestContentChangesFor(auth, id, parsed.data.suggestions);
+ if (result === 'published') {
+ return NextResponse.json(
+ { error: 'The draft is published; suggest on a new draft' },
+ { status: 409 },
+ );
+ }
+ if (result === 'open_suggestions') {
+ return NextResponse.json(
+ {
+ error:
+ 'A person still has open suggestions on this draft to accept or reject; suggest again once the draft lists none',
+ },
+ { status: 409 },
+ );
+ }
+ if (!result) return NextResponse.json({ error: 'Draft not found' }, { status: 404 });
+ return NextResponse.json(result, { status: result.kept ? 201 : 200 });
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/app/api/mcp/content-drafts/route.ts b/web/src/app/api/mcp/content-drafts/route.ts
new file mode 100644
index 000000000..a66f5972b
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/route.ts
@@ -0,0 +1,76 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { createContentDraftFor, listContentDraftsFor } from '@/lib/mcp/content';
+import { createDraftShape, listDraftsShape } from '@/lib/mcp/content-schemas';
+
+/**
+ * GET /api/mcp/content-drafts?brand_id=…&status=… — REST mirror of the
+ * `list_content_drafts` MCP tool.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const url = new URL(req.url);
+ const parsed = z.object(listDraftsShape).safeParse({
+ brand_id: url.searchParams.get('brand_id') ?? undefined,
+ status: url.searchParams.get('status') ?? undefined,
+ });
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: 'brand_id is required; status must be a draft status' },
+ { status: 400 },
+ );
+ }
+ try {
+ const drafts = await listContentDraftsFor(auth, parsed.data.brand_id, parsed.data.status);
+ if (!drafts) return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ return NextResponse.json({ drafts });
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
+
+/**
+ * POST /api/mcp/content-drafts — REST mirror of `create_content_draft`.
+ * Body: { brand_id, title, body_html, method?, page_type?, source_url?, prompt_ids? }
+ */
+export async function POST(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+ const parsed = z.object(createDraftShape).safeParse(await req.json().catch(() => null));
+ if (!parsed.success) {
+ return NextResponse.json(
+ { error: 'Invalid body', issues: parsed.error.issues },
+ { status: 400 },
+ );
+ }
+ const body = parsed.data;
+ try {
+ const created = await createContentDraftFor(auth, {
+ brandId: body.brand_id,
+ title: body.title,
+ bodyHtml: body.body_html,
+ method: body.method,
+ pageType: body.page_type,
+ sourceUrl: body.source_url,
+ promptIds: body.prompt_ids,
+ });
+ if (created === 'off_domain') {
+ return NextResponse.json(
+ { error: "source_url must be a page on one of the brand's domains" },
+ { status: 422 },
+ );
+ }
+ if (!created) return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ return NextResponse.json(created, { status: 201 });
+ } catch (err) {
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Failed' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/lib/content/agent-suggestions.test.ts b/web/src/lib/content/agent-suggestions.test.ts
new file mode 100644
index 000000000..8126a80f0
--- /dev/null
+++ b/web/src/lib/content/agent-suggestions.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import { passageKey } from './cited-passages';
+import { cleanInsertHtml, draftPassages, keepAgentSuggestions } from './agent-suggestions';
+
+const HTML =
+ '<h1>How to brew pour-over</h1><p>Use good coffee &amp; hot water.</p>' +
+ '<ul><li><p>A <strong>dripper</strong></p></li></ul>' +
+ '<table><tbody><tr><td><p>Ratio</p></td></tr></tbody></table>' +
+ '<div data-html-block="PHA+aGk8L3A+"></div><p>Pour&nbsp;slowly.</p>';
+
+describe('draftPassages', () => {
+ it('reads headings and paragraphs in order, with the text the editor has', () => {
+ expect(draftPassages(HTML)).toEqual([
+ { tag: 'h1', text: 'How to brew pour-over' },
+ { tag: 'p', text: 'Use good coffee & hot water.' },
+ { tag: 'p', text: 'A dripper' },
+ { tag: 'p', text: 'Ratio' },
+ // A non-breaking space, as the editor keeps it.
+ { tag: 'p', text: 'Pour\u00a0slowly.' },
+ ]);
+ });
+});
+
+describe('cleanInsertHtml', () => {
+ it('keeps simple blocks without attributes and drops scripts', () => {
+ expect(
+ cleanInsertHtml(
+ '<h2 class="x">FAQ</h2><p onclick="y()">How long? <a href="z">3 min</a></p><script>bad()</script><img src="a">',
+ ),
+ ).toBe('<h2>FAQ</h2><p>How long? 3 min</p>');
+ });
+});
+
+describe('keepAgentSuggestions', () => {
+ const passages = draftPassages(HTML);
+ const locked = new Set([passageKey('A dripper')]);
+ const replace = (over = {}) => ({
+ kind: 'replace' as const,
+ passage: 2,
+ before: 'good coffee',
+ after: '15 g of coffee',
+ reason: 'add a number (rule)',
+ rules: ['dated', 'dated'],
+ ...over,
+ });
+
+ it('keeps a replace found in its passage, and an insert cleaned', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [
+ replace(),
+ {
+ kind: 'insert',
+ passage: 3,
+ after: '<h2>FAQ</h2><p>Q? <em>A</em></p>',
+ reason: 'add FAQ block',
+ },
+ ],
+ passages,
+ locked,
+ );
+ expect(dropped).toEqual([]);
+ expect(kept).toEqual([
+ {
+ kind: 'replace',
+ block_text: 'Use good coffee & hot water.',
+ before_text: 'good coffee',
+ after_text: '15 g of coffee',
+ reason: 'add a number (rule)',
+ rule_keys: ['dated'],
+ },
+ {
+ kind: 'insert',
+ block_text: 'A dripper',
+ before_text: '',
+ after_text: '<h2>FAQ</h2><p>Q? <em>A</em></p>',
+ reason: 'add FAQ block',
+ rule_keys: [],
+ },
+ ]);
+ });
+
+ it('says why each one it drops was dropped', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [
+ replace({ passage: 9 }),
+ replace({ passage: 3, before: 'dripper', after: 'cone' }),
+ replace({ before: 'cold water' }),
+ replace({ after: 'good coffee' }),
+ replace({ after: '<p></p>' }),
+ replace(),
+ replace(),
+ ],
+ passages,
+ locked,
+ );
+ expect(kept).toHaveLength(1);
+ expect(dropped).toEqual([
+ { index: 0, reason: 'no_passage' },
+ { index: 1, reason: 'locked' },
+ { index: 2, reason: 'not_in_passage' },
+ { index: 3, reason: 'no_change' },
+ { index: 4, reason: 'empty' },
+ { index: 6, reason: 'duplicate' },
+ ]);
+ });
+});
diff --git a/web/src/lib/content/agent-suggestions.ts b/web/src/lib/content/agent-suggestions.ts
new file mode 100644
index 000000000..126c1228d
--- /dev/null
+++ b/web/src/lib/content/agent-suggestions.ts
@@ -0,0 +1,155 @@
+import sanitizeHtml from 'sanitize-html';
+import { passageKey } from './cited-passages';
+
+/**
+ * An agent's suggestions through the editor API (CE-022): the same contract
+ * the Content Agent keeps on the server (server/src/lib/content-agent.js):
+ * an agent reads the draft as numbered passages, then suggests a replace
+ * (words in one passage) or an insert (blocks after one). Only what the
+ * editor can apply is kept, and never a change to a locked passage.
+ */
+
+/** The most suggestions one call leaves. */
+export const MAX_API_SUGGESTIONS = 20;
+
+/** A passage of a draft, as the editor reads it: a heading or a paragraph. */
+export interface DraftPassage {
+ tag: string;
+ text: string;
+}
+
+const ENTITIES: Record<string, string> = {
+ amp: '&',
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ apos: "'",
+ '#39': "'",
+ // Written as an escape: the editor keeps a non-breaking space as one
+ // (U+00A0), and so must a passage's text, or a replace across it never
+ // matches there.
+ nbsp: '\u00a0',
+};
+
+function decodeEntities(text: string): string {
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+\d*|#39);/gi, (match, code: string) => {
+ const lower = code.toLowerCase();
+ if (lower in ENTITIES) return ENTITIES[lower];
+ if (lower.startsWith('#x')) return String.fromCodePoint(parseInt(lower.slice(2), 16));
+ if (lower.startsWith('#')) return String.fromCodePoint(Number(lower.slice(1)));
+ return match;
+ });
+}
+
+/**
+ * A draft's passages in order, with each one's text as the editor has it:
+ * the saved HTML is the editor's own, so headings and paragraphs (in lists
+ * and cells too) are plain elements, never nested.
+ */
+export function draftPassages(html: string): DraftPassage[] {
+ const passages: DraftPassage[] = [];
+ for (const match of (html ?? '').matchAll(/<(h[1-6]|p)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi)) {
+ const text = decodeEntities(match[2].replace(/<[^>]*>/g, ''));
+ if (text.trim()) passages.push({ tag: match[1].toLowerCase(), text });
+ }
+ return passages;
+}
+
+/** An insert's HTML, kept to the blocks the editor takes from an agent, with no attributes. */
+export function cleanInsertHtml(html: string): string {
+ return sanitizeHtml(html ?? '', {
+ allowedTags: ['h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'br'],
+ allowedAttributes: {},
+ nonTextTags: ['script', 'style', 'textarea', 'option', 'noscript', 'template', 'title'],
+ }).trim();
+}
+
+const textOf = (html: string) =>
+ decodeEntities(sanitizeHtml(html ?? '', { allowedTags: [], allowedAttributes: {} }));
+
+/** What an agent sends: passage numbers are 1-based, as get_content_draft lists them. */
+export interface AgentSuggestionInput {
+ kind: 'replace' | 'insert';
+ passage: number;
+ before?: string;
+ after: string;
+ reason: string;
+ rules?: string[];
+}
+
+export interface KeptSuggestion {
+ kind: 'replace' | 'insert';
+ block_text: string;
+ before_text: string;
+ after_text: string;
+ reason: string;
+ rule_keys: string[];
+}
+
+/** Why a suggestion wasn't kept, for the agent to correct it. */
+export type DroppedReason =
+ | 'no_passage'
+ | 'locked'
+ | 'not_in_passage'
+ | 'no_change'
+ | 'empty'
+ | 'duplicate'
+ | 'too_many';
+
+/**
+ * The suggestions the editor can apply: a passage that exists; a replace's
+ * words found in it as written, changed, and never on a locked passage; an
+ * insert's HTML cleaned and not empty; each change once.
+ */
+export function keepAgentSuggestions(
+ raw: AgentSuggestionInput[],
+ passages: DraftPassage[],
+ lockedKeys: Set<string>,
+): { kept: KeptSuggestion[]; dropped: { index: number; reason: DroppedReason }[] } {
+ const kept: KeptSuggestion[] = [];
+ const dropped: { index: number; reason: DroppedReason }[] = [];
+ const seen = new Set<string>();
+ raw.forEach((s, index) => {
+ const drop = (reason: DroppedReason) => dropped.push({ index, reason });
+ if (kept.length >= MAX_API_SUGGESTIONS) return drop('too_many');
+ const passage = passages[s.passage - 1];
+ if (!passage || passage.text.length > 5000) return drop('no_passage');
+ const reason = s.reason.trim().slice(0, 300);
+ if (!reason) return drop('empty');
+ const rules = [...new Set((s.rules ?? []).map((r) => r.trim()).filter(Boolean))].slice(0, 20);
+ if (s.kind === 'replace') {
+ if (lockedKeys.has(passageKey(passage.text))) return drop('locked');
+ const before = (s.before ?? '').trim();
+ const after = textOf(s.after).trim();
+ if (!before || !after) return drop('empty');
+ if (before === after || after.length > 2000) return drop('no_change');
+ if (!passage.text.includes(before)) return drop('not_in_passage');
+ const id = `replace:${passage.text}:${before}`;
+ if (seen.has(id)) return drop('duplicate');
+ seen.add(id);
+ kept.push({
+ kind: 'replace',
+ block_text: passage.text,
+ before_text: before,
+ after_text: after,
+ reason,
+ rule_keys: rules,
+ });
+ return;
+ }
+ const html = cleanInsertHtml(s.after);
+ if (!textOf(html).trim() || html.length > 20_000) return drop('empty');
+ const id = `insert:${passage.text}:${html}`;
+ if (seen.has(id)) return drop('duplicate');
+ seen.add(id);
+ kept.push({
+ kind: 'insert',
+ block_text: passage.text,
+ before_text: '',
+ after_text: html,
+ reason,
+ rule_keys: rules,
+ });
+ });
+ return { kept, dropped };
+}
diff --git a/web/src/lib/mcp/content-schemas.ts b/web/src/lib/mcp/content-schemas.ts
new file mode 100644
index 000000000..5cf05910e
--- /dev/null
+++ b/web/src/lib/mcp/content-schemas.ts
@@ -0,0 +1,95 @@
+import { z } from 'zod';
+import { MAX_API_SUGGESTIONS } from '@/lib/content/agent-suggestions';
+import { DRAFT_STATUSES, PAGE_TYPES } from '@/lib/content/drafts';
+
+/**
+ * The inputs of the Content Editor's agent API (CE-022), shared by the MCP
+ * tools (server.ts) and their REST mirrors under /api/mcp/content-drafts.
+ */
+
+/** Any 8-4-4-4-12 hex id: seeded ids aren't all RFC 4122 versions. */
+export const contentUuid = z
+ .string()
+ .regex(
+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,
+ 'Invalid UUID format',
+ );
+
+/** A page address the editor takes: http(s) only, as the web actions require. */
+export function isHttpUrl(value: string): boolean {
+ try {
+ return /^https?:$/.test(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+}
+
+export const listDraftsShape = {
+ brand_id: contentUuid.describe('Brand UUID, from list_brands.'),
+ status: z.enum(DRAFT_STATUSES).optional().describe('Only drafts with this status.'),
+};
+
+export const createDraftShape = {
+ brand_id: contentUuid.describe('Brand UUID, from list_brands.'),
+ title: z.string().min(1).max(300).describe('The page title (its H1).'),
+ body_html: z.string().min(1).max(500_000).describe('The page as HTML, starting with its H1.'),
+ method: z
+ .enum(['create', 'optimize'])
+ .default('create')
+ .describe('create: a new page; optimize: a new version of the live page at source_url.'),
+ page_type: z.enum(PAGE_TYPES).optional().describe('The page type; detected when omitted.'),
+ source_url: z
+ .string()
+ .trim()
+ .max(2048)
+ .refine(isHttpUrl, 'source_url must be an http(s) address')
+ .optional()
+ .describe('For optimize: the live page, on one of the brand domains.'),
+ prompt_ids: z
+ .array(contentUuid)
+ .max(100)
+ .optional()
+ .describe('Tracked prompts the page answers, from list_prompts.'),
+};
+
+export const impactDays = z
+ .union([z.literal(7), z.literal(30), z.literal(90), z.literal(365)])
+ .default(30)
+ .describe('The period: 7, 30, 90 or 365 days.');
+
+export const addSourceShape = {
+ kind: z.enum(['prompt', 'cited_page', 'gsc_query']),
+ ref: z
+ .string()
+ .trim()
+ .min(1)
+ .max(2048)
+ .describe('The prompt UUID, the page address (http or https), or the query.'),
+};
+
+/** Why an add_content_source ref can't be taken for its kind, or null when it can. */
+export function sourceRefError(kind: 'prompt' | 'cited_page' | 'gsc_query', ref: string) {
+ if (kind === 'prompt' && !contentUuid.safeParse(ref).success) return 'ref must be a prompt UUID';
+ if (kind === 'cited_page' && !isHttpUrl(ref)) return 'ref must be an http(s) page address';
+ return null;
+}
+
+export const suggestionsShape = {
+ suggestions: z
+ .array(
+ z.object({
+ kind: z.enum(['replace', 'insert']),
+ passage: z.number().int().min(1).describe('The passage number, from get_content_draft.'),
+ before: z.string().max(5000).optional().describe('replace: the exact words to change.'),
+ after: z.string().min(1).max(20_000).describe('replace: the new words; insert: the HTML.'),
+ reason: z
+ .string()
+ .min(1)
+ .max(300)
+ .describe('Why, in a few words: "answer the fan-out …", "add a dated data point".'),
+ rules: z.array(z.string().max(60)).max(20).optional().describe('Rule keys it fixes.'),
+ }),
+ )
+ .min(1)
+ .max(MAX_API_SUGGESTIONS),
+};
diff --git a/web/src/lib/mcp/content.test.ts b/web/src/lib/mcp/content.test.ts
new file mode 100644
index 000000000..5b06f9e6f
--- /dev/null
+++ b/web/src/lib/mcp/content.test.ts
@@ -0,0 +1,297 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * The Content Editor's agent API (CE-022): drafts read and written through
+ * the API key's organization only, an agent's draft going to In review, its
+ * suggestions never on a passage AI quotes, and Ready keeping a version.
+ */
+
+const db = vi.hoisted(() => ({
+ /** What each table answers: one row for single reads, a list for the rest. */
+ rows: {} as Record<string, unknown>,
+ rpc: {} as Record<string, unknown>,
+ rpcCalls: [] as [string, unknown][],
+ writes: [] as { table: string; op: string; value: unknown }[],
+ filters: [] as [string, string, unknown][],
+}));
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ rpc: async (name: string, args: unknown) => {
+ db.rpcCalls.push([name, args]);
+ return { data: db.rpc[name] ?? null, error: null };
+ },
+ from: (table: string) => {
+ const read = () => ({ data: db.rows[table] ?? null, error: null });
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: (col: string, v: unknown) => (db.filters.push([table, col, v]), chain),
+ in: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ insert: (value: unknown) => (db.writes.push({ table, op: 'insert', value }), chain),
+ update: (value: unknown) => (db.writes.push({ table, op: 'update', value }), chain),
+ upsert: async (value: unknown) => (
+ db.writes.push({ table, op: 'upsert', value }),
+ { error: null }
+ ),
+ maybeSingle: async () => read(),
+ single: async () => read(),
+ then: (resolve: (value: unknown) => unknown) => resolve(read()),
+ };
+ return chain;
+ },
+ },
+}));
+
+const brandInOrg = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/mcp/data', () => ({ brandInOrg }));
+
+const {
+ createContentDraftFor,
+ getContentDraftFor,
+ getContentImpactFor,
+ setContentDraftReadyFor,
+ suggestContentChangesFor,
+} = await import('./content');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+};
+
+const QUOTED =
+ 'Northwind forecasts each deal from real activity: emails, meetings and stage changes.';
+const draftRow = (over = {}) => ({
+ id: 'd1',
+ brand_id: 'b1',
+ title: 'Pipeline forecasting',
+ status: 'draft',
+ method: 'optimize',
+ page_type: 'feature_page',
+ author: 'user',
+ source_url: 'https://acme.example/forecasting',
+ body_html: `<h1>Pipeline forecasting</h1><p>${QUOTED}</p><p>Our forecasting is very accurate.</p>`,
+ action_id: 'act-1',
+ prompt_ids: [],
+ updated_at: '2026-10-21T10:00:00Z',
+ actions: { action_no: 214 },
+ ...over,
+});
+
+beforeEach(() => {
+ db.rows = {};
+ db.rpc = {};
+ db.rpcCalls = [];
+ db.writes = [];
+ db.filters = [];
+ brandInOrg.mockReset().mockResolvedValue(true);
+});
+
+describe('getContentDraftFor', () => {
+ it('numbers the passages, marks the ones AI quotes and lists the open batch', async () => {
+ db.rows.content_drafts = draftRow();
+ db.rpc.content_draft_cited_answers = [
+ { platform: 'chatgpt-web', response: `They say: ${QUOTED}` },
+ ];
+ // Newest first: an older batch's open one isn't the editor's to show.
+ db.rows.content_draft_suggestions = [
+ { id: 's3', kind: 'replace', reason: 'decided', batch_id: 'new', status: 'accepted' },
+ { id: 's2', kind: 'insert', reason: 'add FAQ', batch_id: 'new', status: 'open' },
+ { id: 's1', kind: 'replace', reason: 'old batch', batch_id: 'old', status: 'open' },
+ ];
+
+ const draft = await getContentDraftFor(auth, 'd1');
+
+ expect(db.filters).toContainEqual(['content_drafts', 'brands.organization_id', 'org-1']);
+ expect(draft).toMatchObject({
+ action: { id: 'act-1', number: 214 },
+ editor_path: '/dashboard/content/editor/d1',
+ passages: [
+ { n: 1, tag: 'h1', text: 'Pipeline forecasting', locked: false },
+ { n: 2, tag: 'p', text: QUOTED, locked: true },
+ { n: 3, tag: 'p', text: 'Our forecasting is very accurate.', locked: false },
+ ],
+ open_suggestions: [{ id: 's2', kind: 'insert', reason: 'add FAQ' }],
+ });
+ });
+
+ it('reads nothing of another organization’s draft', async () => {
+ await expect(getContentDraftFor(auth, 'd1')).resolves.toBeNull();
+ expect(db.rpcCalls).toEqual([]);
+ });
+});
+
+describe('createContentDraftFor', () => {
+ it('writes the agent’s draft for review, its HTML checked and its prompts the brand’s', async () => {
+ db.rows.brands = { site_type: 'b2b', industry: 'Software', shopping_mode_enabled: false };
+ db.rows.prompts = [{ id: 'p1' }];
+ db.rows.content_drafts = { id: 'd-new', status: 'in_review', page_type: 'guide' };
+
+ const created = await createContentDraftFor(auth, {
+ brandId: 'b1',
+ title: 'How to clean CRM data',
+ bodyHtml:
+ '<h1>How to clean CRM data</h1><p onclick="x()">Start here.</p><script>bad()</script>',
+ method: 'create',
+ promptIds: ['p1', 'p-other'],
+ });
+
+ // Through the prompt's set: a prompt without a topic is the brand's too.
+ expect(db.filters).toContainEqual(['prompts', 'prompt_sets.brand_id', 'b1']);
+ expect(created).toEqual({
+ id: 'd-new',
+ status: 'in_review',
+ page_type: 'guide',
+ editor_path: '/dashboard/content/editor/d-new',
+ });
+ const insert = db.writes.find((w) => w.table === 'content_drafts' && w.op === 'insert')!;
+ expect(insert.value).toMatchObject({
+ brand_id: 'b1',
+ author: 'agent',
+ created_by: null,
+ status: 'in_review',
+ page_type_source: 'detected',
+ prompt_ids: ['p1'],
+ body_html: '<h1>How to clean CRM data</h1><p>Start here.</p>',
+ });
+ });
+
+ it('takes a live page only on one of the brand’s domains', async () => {
+ db.rows.brands = { site_type: 'b2b', industry: 'Software', shopping_mode_enabled: false };
+ db.rows.brand_domains = [{ domain: 'https://www.Acme.example/' }];
+ db.rows.content_drafts = { id: 'd-new', status: 'in_review', page_type: 'feature_page' };
+ const optimize = (sourceUrl: string) =>
+ createContentDraftFor(auth, {
+ brandId: 'b1',
+ title: 'Pipeline forecasting',
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>x</p>',
+ method: 'optimize',
+ sourceUrl,
+ });
+
+ await expect(optimize('https://elsewhere.example/forecasting')).resolves.toBe('off_domain');
+ await expect(optimize('https://acme.example.evil.example/x')).resolves.toBe('off_domain');
+ expect(db.writes).toEqual([]);
+ await expect(optimize('https://docs.acme.example/forecasting')).resolves.toMatchObject({
+ id: 'd-new',
+ });
+ });
+
+ it('writes nothing for a brand outside the organization', async () => {
+ brandInOrg.mockResolvedValue(false);
+ await expect(
+ createContentDraftFor(auth, {
+ brandId: 'b9',
+ title: 'x',
+ bodyHtml: '<p>x</p>',
+ method: 'create',
+ }),
+ ).resolves.toBeNull();
+ expect(db.writes).toEqual([]);
+ });
+});
+
+describe('suggestContentChangesFor', () => {
+ it('keeps one batch for review, never on a locked passage', async () => {
+ db.rows.content_drafts = draftRow();
+ db.rpc.content_draft_cited_answers = [
+ { platform: 'perplexity-web', response: `Quote: ${QUOTED}` },
+ ];
+
+ const result = await suggestContentChangesFor(auth, 'd1', [
+ {
+ kind: 'replace',
+ passage: 2,
+ before: 'real activity',
+ after: 'activity',
+ reason: 'shorter',
+ },
+ {
+ kind: 'replace',
+ passage: 3,
+ before: 'very accurate',
+ after: 'shown per team, each week',
+ reason: 'answer a fan-out',
+ },
+ ]);
+
+ expect(result).toMatchObject({ kept: 1, dropped: [{ index: 0, reason: 'locked' }] });
+ const insert = db.writes.find((w) => w.table === 'content_draft_suggestions')!;
+ expect(insert.value).toEqual([
+ expect.objectContaining({
+ draft_id: 'd1',
+ action_id: 'act-1',
+ position: 0,
+ kind: 'replace',
+ block_text: 'Our forecasting is very accurate.',
+ before_text: 'very accurate',
+ }),
+ ]);
+ });
+
+ it('waits while a person still has the latest batch to decide', async () => {
+ db.rows.content_drafts = draftRow();
+ db.rows.content_draft_suggestions = [
+ { id: 's1', kind: 'replace', reason: 'x', batch_id: 'b1', status: 'open' },
+ ];
+ await expect(
+ suggestContentChangesFor(auth, 'd1', [
+ { kind: 'insert', passage: 1, after: '<p>x</p>', reason: 'y' },
+ ]),
+ ).resolves.toBe('open_suggestions');
+ expect(db.writes).toEqual([]);
+ });
+
+ it('leaves a published draft alone', async () => {
+ db.rows.content_drafts = draftRow({ status: 'published' });
+ await expect(
+ suggestContentChangesFor(auth, 'd1', [
+ { kind: 'insert', passage: 1, after: '<p>x</p>', reason: 'y' },
+ ]),
+ ).resolves.toBe('published');
+ expect(db.writes).toEqual([]);
+ });
+});
+
+describe('setContentDraftReadyFor', () => {
+ it('marks a draft ready and keeps the version, once', async () => {
+ db.rows.content_drafts = draftRow({ status: 'draft' });
+ // The update reads back the same row; its status is what the update set.
+ const result = await setContentDraftReadyFor(auth, 'd1');
+ expect(db.writes).toContainEqual({
+ table: 'content_drafts',
+ op: 'update',
+ value: { status: 'ready' },
+ });
+ expect(db.filters).toContainEqual(['content_drafts', 'status', 'draft']);
+ expect(result).toEqual({ status: 'draft' });
+ expect(db.rpcCalls).toContainEqual([
+ 'content_draft_snapshot',
+ { p_draft_id: 'd1', p_origin: 'ready' },
+ ]);
+
+ db.writes = [];
+ db.rows.content_drafts = draftRow({ status: 'published' });
+ await expect(setContentDraftReadyFor(auth, 'd1')).resolves.toEqual({ status: 'published' });
+ expect(db.writes).toEqual([]);
+ });
+
+ it('leaves an agent’s draft in review to a person', async () => {
+ db.rows.content_drafts = draftRow({ status: 'in_review', author: 'agent' });
+ await expect(setContentDraftReadyFor(auth, 'd1')).resolves.toBe('in_review');
+ expect(db.writes).toEqual([]);
+ expect(db.rpcCalls).toEqual([]);
+ });
+});
+
+describe('getContentImpactFor', () => {
+ it('says a new page has nothing to measure yet', async () => {
+ db.rows.content_drafts = draftRow({ source_url: null });
+ await expect(getContentImpactFor(auth, 'd1', 30)).resolves.toBe('no_page');
+ expect(db.rpcCalls).toEqual([]);
+ });
+});
diff --git a/web/src/lib/mcp/content.ts b/web/src/lib/mcp/content.ts
new file mode 100644
index 000000000..dc1877b54
--- /dev/null
+++ b/web/src/lib/mcp/content.ts
@@ -0,0 +1,473 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import { brandInOrg } from '@/lib/mcp/data';
+import {
+ draftPassages,
+ keepAgentSuggestions,
+ type AgentSuggestionInput,
+ type DroppedReason,
+} from '@/lib/content/agent-suggestions';
+import { classifyDomain, extractHostname, normalizeDomain } from '@/lib/citations/classify';
+import { CITED_DAYS, passageKey, quotedPassages } from '@/lib/content/cited-passages';
+import { contentEditorPath, isPageType, type PageType } from '@/lib/content/drafts';
+import { IMPACT_PERIODS } from '@/lib/content/impact';
+import { detectPageType, siteTypeOf } from '@/lib/content/page-types';
+import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
+import { SOURCES_DAYS } from '@/lib/content/sources';
+
+/**
+ * The Content Editor's API for agents (CE-022, spec §15): what a person does
+ * in the editor, an agent does through the same data — open or create a
+ * draft, read Impact and Sources, add a source, leave suggestions, set
+ * Ready. Agents never accept their own suggestions, publish, or change a
+ * passage AI answers quote (locked, CE-018).
+ *
+ * As the rest of the MCP layer: the service role, with an explicit check
+ * that the draft's brand is the API key's organization's. A draft outside
+ * it reads as not found.
+ */
+
+/** The most drafts list_content_drafts returns, the latest changed first. */
+const LIST_LIMIT = 100;
+
+const DRAFT_COLUMNS =
+ 'id, brand_id, title, status, method, page_type, author, source_url, body_html, action_id, prompt_ids, updated_at, brands!inner(organization_id, site_type, industry, shopping_mode_enabled), actions(action_no)';
+
+interface DraftRow {
+ id: string;
+ brand_id: string;
+ title: string;
+ status: string;
+ method: string;
+ page_type: string | null;
+ author: string;
+ source_url: string | null;
+ body_html: string;
+ action_id: string | null;
+ prompt_ids: string[] | null;
+ updated_at: string;
+ actions: { action_no: number } | { action_no: number }[] | null;
+}
+
+/** A draft in the caller's organization, or null. */
+async function draftFor(auth: McpAuthContext, draftId: string): Promise<DraftRow | null> {
+ if (!auth.organizationId) return null;
+ const { data, error } = await supabaseAdmin
+ .from('content_drafts')
+ .select(DRAFT_COLUMNS)
+ .eq('id', draftId)
+ .eq('brands.organization_id', auth.organizationId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return (data as unknown as DraftRow | null) ?? null;
+}
+
+const actionNo = (row: DraftRow) => {
+ const action = Array.isArray(row.actions) ? row.actions[0] : row.actions;
+ return action?.action_no ?? null;
+};
+
+/**
+ * The passages AI answers quote today, by key: from the answers citing the
+ * draft's page over 30 days (00216), matched as the editor matches them.
+ */
+async function lockedKeys(draft: DraftRow, texts: string[]): Promise<Set<string>> {
+ if (!draft.source_url) return new Set();
+ const { data, error } = await supabaseAdmin.rpc('content_draft_cited_answers', {
+ p_draft_id: draft.id,
+ p_days: CITED_DAYS,
+ });
+ if (error) throw new Error(error.message);
+ const answers = (data ?? []) as { platform: string; response: string }[];
+ return new Set(quotedPassages(texts, answers).map((p) => p.key));
+}
+
+/** How many of a draft's newest suggestions are read to find its latest batch. */
+const LATEST_BATCH_ROWS = 200;
+
+/**
+ * The draft's latest batch's suggestions still waiting for a person: the
+ * editor shows only that batch, so a new one would hide them (and Undo on
+ * the ones accepted).
+ */
+async function openSuggestionsOf(draftId: string) {
+ const { data, error } = await supabaseAdmin
+ .from('content_draft_suggestions')
+ .select('id, kind, reason, batch_id, status, created_at')
+ .eq('draft_id', draftId)
+ .order('created_at', { ascending: false })
+ .limit(LATEST_BATCH_ROWS);
+ if (error) throw new Error(error.message);
+ const batch = data?.[0]?.batch_id;
+ return (data ?? [])
+ .filter((s) => s.batch_id === batch && s.status === 'open')
+ .map((s) => ({ id: s.id, kind: s.kind, reason: s.reason }));
+}
+
+/** Whether the address is on one of the brand's domains, or a subdomain of one. */
+async function onBrandDomain(brandId: string, url: string): Promise<boolean> {
+ const { data, error } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ const host = extractHostname(url);
+ const brandDomains = (data ?? []).map((r) => normalizeDomain(r.domain)).filter(Boolean);
+ return !!host && classifyDomain(host, { brandDomains, competitorDomains: [] }) === 'you';
+}
+
+export interface McpDraftSummary {
+ id: string;
+ title: string;
+ status: string;
+ method: string;
+ page_type: string | null;
+ author: string;
+ source_url: string | null;
+ open_suggestions: number;
+ updated_at: string;
+ editor_path: string;
+}
+
+/** A brand's drafts, the latest changed first; null for a brand outside the organization. */
+export async function listContentDraftsFor(
+ auth: McpAuthContext,
+ brandId: string,
+ status?: string,
+): Promise<McpDraftSummary[] | null> {
+ if (!(await brandInOrg(auth, brandId))) return null;
+ let query = supabaseAdmin
+ .from('content_drafts')
+ .select('id, title, status, method, page_type, author, source_url, updated_at')
+ .eq('brand_id', brandId)
+ .order('updated_at', { ascending: false })
+ .limit(LIST_LIMIT);
+ if (status) query = query.eq('status', status);
+ const { data, error } = await query;
+ if (error) throw new Error(error.message);
+ const rows = data ?? [];
+
+ const open = new Map<string, number>();
+ if (rows.length) {
+ const { data: suggestions, error: suggestionsError } = await supabaseAdmin
+ .from('content_draft_suggestions')
+ .select('draft_id')
+ .in(
+ 'draft_id',
+ rows.map((r) => r.id),
+ )
+ .eq('status', 'open');
+ if (suggestionsError) throw new Error(suggestionsError.message);
+ for (const s of suggestions ?? []) open.set(s.draft_id, (open.get(s.draft_id) ?? 0) + 1);
+ }
+ return rows.map((row) => ({
+ ...row,
+ open_suggestions: open.get(row.id) ?? 0,
+ editor_path: contentEditorPath(row.id),
+ }));
+}
+
+export interface McpDraft {
+ id: string;
+ brand_id: string;
+ title: string;
+ status: string;
+ method: string;
+ page_type: string | null;
+ author: string;
+ source_url: string | null;
+ action: { id: string; number: number | null } | null;
+ editor_path: string;
+ body_html: string;
+ /** The page passage by passage, as suggest_content_changes numbers them. */
+ passages: { n: number; tag: string; text: string; locked: boolean }[];
+ /** The latest batch's suggestions still waiting for a person. */
+ open_suggestions: { id: string; kind: string; reason: string }[];
+}
+
+/** One draft, its passages numbered and the locked ones marked; null outside the organization. */
+export async function getContentDraftFor(
+ auth: McpAuthContext,
+ draftId: string,
+): Promise<McpDraft | null> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ const passages = draftPassages(draft.body_html);
+ const locked = await lockedKeys(
+ draft,
+ passages.map((p) => p.text),
+ );
+ const openSuggestions = await openSuggestionsOf(draft.id);
+
+ return {
+ id: draft.id,
+ brand_id: draft.brand_id,
+ title: draft.title,
+ status: draft.status,
+ method: draft.method,
+ page_type: draft.page_type,
+ author: draft.author,
+ source_url: draft.source_url,
+ action: draft.action_id ? { id: draft.action_id, number: actionNo(draft) } : null,
+ editor_path: contentEditorPath(draft.id),
+ body_html: draft.body_html,
+ passages: passages.map((p, i) => ({
+ n: i + 1,
+ tag: p.tag,
+ text: p.text,
+ locked: locked.has(passageKey(p.text)),
+ })),
+ open_suggestions: openSuggestions,
+ };
+}
+
+export interface CreateDraftInput {
+ brandId: string;
+ title: string;
+ bodyHtml: string;
+ method: 'create' | 'optimize';
+ pageType?: string;
+ sourceUrl?: string;
+ promptIds?: string[];
+}
+
+/**
+ * An agent's draft (spec §5, "Agent: drafts, I review"): written by the
+ * agent, so it goes to the Library's In review for a person. Its HTML is
+ * checked against the draft allow-list, as a save is; the page type is the
+ * one given, or the one the page shows; prompts are kept to the brand's.
+ * Null for a brand outside the organization; 'off_domain' for a source_url
+ * that isn't on one of the brand's domains.
+ */
+export async function createContentDraftFor(
+ auth: McpAuthContext,
+ input: CreateDraftInput,
+): Promise<
+ | { id: string; status: string; page_type: string | null; editor_path: string }
+ | 'off_domain'
+ | null
+> {
+ if (!(await brandInOrg(auth, input.brandId))) return null;
+ if (input.sourceUrl && !(await onBrandDomain(input.brandId, input.sourceUrl))) {
+ return 'off_domain';
+ }
+ const { data: brand, error: brandError } = await supabaseAdmin
+ .from('brands')
+ .select('site_type, industry, shopping_mode_enabled')
+ .eq('id', input.brandId)
+ .single();
+ if (brandError) throw new Error(brandError.message);
+
+ const bodyHtml = sanitizeDraftHtml(input.bodyHtml);
+ const title = input.title.trim().slice(0, 300);
+ const picked = input.pageType && isPageType(input.pageType) ? input.pageType : null;
+ const pageType: PageType | null =
+ picked ??
+ detectPageType(
+ { title, html: bodyHtml, url: input.sourceUrl },
+ siteTypeOf({
+ siteType: brand.site_type,
+ industry: brand.industry,
+ shoppingModeEnabled: brand.shopping_mode_enabled,
+ }),
+ );
+
+ let promptIds: string[] = [];
+ if (input.promptIds?.length) {
+ // Through the prompt's set, not its topic: a prompt may have no topic.
+ const { data: prompts, error: promptsError } = await supabaseAdmin
+ .from('prompts')
+ .select('id, prompt_sets!inner(brand_id)')
+ .in('id', input.promptIds)
+ .eq('prompt_sets.brand_id', input.brandId);
+ if (promptsError) throw new Error(promptsError.message);
+ promptIds = (prompts ?? []).map((p) => p.id);
+ }
+
+ const { data, error } = await supabaseAdmin
+ .from('content_drafts')
+ .insert({
+ brand_id: input.brandId,
+ author: 'agent',
+ created_by: null,
+ method: input.method,
+ title,
+ page_type: pageType,
+ page_type_source: picked ? 'user' : 'detected',
+ body_html: bodyHtml,
+ source_url: input.sourceUrl ?? null,
+ prompt_ids: promptIds,
+ status: 'in_review',
+ })
+ .select('id, status, page_type')
+ .single();
+ if (error) throw new Error(error.message);
+ return { ...data, editor_path: contentEditorPath(data.id) };
+}
+
+/**
+ * The draft's page in AI answers, AI visits and Google over the period
+ * (CE-016, 00209), as the Impact tab reads it. 'no_page' for a draft that
+ * isn't of a live page yet; null outside the organization.
+ */
+export async function getContentImpactFor(
+ auth: McpAuthContext,
+ draftId: string,
+ days: number,
+): Promise<Record<string, unknown> | 'no_page' | null> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ if (!draft.source_url) return 'no_page';
+ if (!(IMPACT_PERIODS as readonly number[]).includes(days))
+ throw new Error('days must be 7, 30, 90 or 365');
+ const { data, error } = await supabaseAdmin.rpc('content_page_impact', {
+ p_brand_id: draft.brand_id,
+ p_page: draft.source_url,
+ p_days: days,
+ });
+ if (error) throw new Error(error.message);
+ return (data as Record<string, unknown> | null) ?? {};
+}
+
+/**
+ * The brand's data the draft draws on over 30 days (CE-008, 00211), with the
+ * person's choices: a source left out (included false) or added by hand.
+ */
+export async function getContentSourcesFor(
+ auth: McpAuthContext,
+ draftId: string,
+): Promise<{ sources: unknown; choices: unknown[] } | null> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ const [sources, choices] = await Promise.all([
+ supabaseAdmin.rpc('content_draft_sources', { p_draft_id: draft.id, p_days: SOURCES_DAYS }),
+ supabaseAdmin
+ .from('content_draft_sources')
+ .select('kind, ref, included, added')
+ .eq('draft_id', draft.id),
+ ]);
+ if (sources.error) throw new Error(sources.error.message);
+ if (choices.error) throw new Error(choices.error.message);
+ return { sources: sources.data, choices: choices.data ?? [] };
+}
+
+export type AddSourceInput =
+ | { kind: 'prompt'; promptId: string }
+ | { kind: 'cited_page' | 'gsc_query'; ref: string };
+
+/**
+ * Adds a source, as the Sources tab's Add does: a prompt of the brand's
+ * joins the draft's prompts; a page address or a Search Console query is
+ * kept as added. 'not_found' for a prompt outside the brand; null for a draft
+ * outside the organization.
+ */
+export async function addContentSourceFor(
+ auth: McpAuthContext,
+ draftId: string,
+ source: AddSourceInput,
+): Promise<{ added: true } | 'not_found' | null> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ if (source.kind === 'prompt') {
+ const { data: prompt, error } = await supabaseAdmin
+ .from('prompts')
+ .select('id, prompt_sets!inner(brand_id)')
+ .eq('id', source.promptId)
+ .eq('prompt_sets.brand_id', draft.brand_id)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!prompt) return 'not_found';
+ const promptIds = [...new Set([...(draft.prompt_ids ?? []), prompt.id])].slice(0, 500);
+ const { error: updateError } = await supabaseAdmin
+ .from('content_drafts')
+ .update({ prompt_ids: promptIds })
+ .eq('id', draft.id);
+ if (updateError) throw new Error(updateError.message);
+ return { added: true };
+ }
+ const ref = source.kind === 'gsc_query' ? source.ref.trim().toLowerCase() : source.ref.trim();
+ const { error } = await supabaseAdmin
+ .from('content_draft_sources')
+ .upsert(
+ { draft_id: draft.id, kind: source.kind, ref, included: true, added: true },
+ { onConflict: 'draft_id,kind,ref' },
+ );
+ if (error) throw new Error(error.message);
+ return { added: true };
+}
+
+/**
+ * An agent's suggestions, left for a person to review in the page as one new
+ * batch (CE-018, 00217), linked to the draft's Action Center action. Passages
+ * are numbered as get_content_draft lists them; what the editor can't apply
+ * is dropped with the reason. Null outside the organization; 'published' for
+ * a draft that is live already; 'open_suggestions' while a person still has
+ * the latest batch's suggestions to decide.
+ */
+export async function suggestContentChangesFor(
+ auth: McpAuthContext,
+ draftId: string,
+ suggestions: AgentSuggestionInput[],
+): Promise<
+ | { kept: number; batch_id: string | null; dropped: { index: number; reason: DroppedReason }[] }
+ | 'published'
+ | 'open_suggestions'
+ | null
+> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ if (draft.status === 'published') return 'published';
+ if ((await openSuggestionsOf(draft.id)).length) return 'open_suggestions';
+ const passages = draftPassages(draft.body_html);
+ const locked = await lockedKeys(
+ draft,
+ passages.map((p) => p.text),
+ );
+ const { kept, dropped } = keepAgentSuggestions(suggestions, passages, locked);
+ if (!kept.length) return { kept: 0, batch_id: null, dropped };
+
+ const batchId = crypto.randomUUID();
+ const { error } = await supabaseAdmin.from('content_draft_suggestions').insert(
+ kept.map((row, position) => ({
+ ...row,
+ draft_id: draft.id,
+ batch_id: batchId,
+ action_id: draft.action_id,
+ position,
+ })),
+ );
+ if (error) throw new Error(error.message);
+ return { kept: kept.length, batch_id: batchId, dropped };
+}
+
+/**
+ * Ready (spec §6): a draft is ready to publish, and History keeps it as a
+ * version. An agent's draft in review waits for a person to mark it ready in
+ * the editor ('in_review'): the key that wrote it can't approve it. A draft
+ * already ready or published keeps its status. Null outside the organization.
+ */
+export async function setContentDraftReadyFor(
+ auth: McpAuthContext,
+ draftId: string,
+): Promise<{ status: string } | 'in_review' | null> {
+ const draft = await draftFor(auth, draftId);
+ if (!draft) return null;
+ if (draft.status === 'in_review') return 'in_review';
+ if (draft.status !== 'draft') return { status: draft.status };
+ const { data, error } = await supabaseAdmin
+ .from('content_drafts')
+ .update({ status: 'ready' })
+ .eq('id', draft.id)
+ .eq('status', 'draft')
+ .select('status')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (data) {
+ const { error: versionError } = await supabaseAdmin.rpc('content_draft_snapshot', {
+ p_draft_id: draft.id,
+ p_origin: 'ready',
+ });
+ if (versionError) console.error('Failed to keep the ready version:', versionError.message);
+ }
+ return { status: data?.status ?? draft.status };
+}
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 714a3ecd6..724187fdf 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -2758,7 +2758,7 @@ const UNCOUNTED_TASK_STATUSES = ['skipped', 'failed'];
const MCP_SIGNAL_COLUMNS =
'id, category, kind, impact, status, source, detected_at, last_detected_at, resolved_at, previous_value, current_value, change_value, payload, kpi_keys, action_id';
-async function brandInOrg(auth: McpAuthContext, brandId: string): Promise<boolean> {
+export async function brandInOrg(auth: McpAuthContext, brandId: string): Promise<boolean> {
if (!auth.organizationId) return false;
const { data } = await supabaseAdmin
.from('brands')
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 04975228e..703a94bdb 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -45,6 +45,25 @@ import {
createImproveActionFor,
} from './data';
import { exportActionFor } from './action-export';
+import {
+ addContentSourceFor,
+ createContentDraftFor,
+ getContentDraftFor,
+ getContentImpactFor,
+ getContentSourcesFor,
+ listContentDraftsFor,
+ setContentDraftReadyFor,
+ suggestContentChangesFor,
+} from './content';
+import { MAX_API_SUGGESTIONS } from '@/lib/content/agent-suggestions';
+import {
+ addSourceShape,
+ createDraftShape,
+ impactDays,
+ listDraftsShape,
+ sourceRefError,
+ suggestionsShape,
+} from './content-schemas';
/**
* Build a fresh MCP server bound to a single authenticated request.
@@ -1326,5 +1345,198 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ // ─── Content Editor (CE-022): drafts, read and written as a person would ───
+
+ const json = (value: unknown) => ({
+ content: [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }],
+ });
+ const notFound = (what: string) => ({
+ content: [{ type: 'text' as const, text: `${what} not found` }],
+ isError: true,
+ });
+
+ server.registerTool(
+ 'list_content_drafts',
+ {
+ description:
+ "List a brand's Content Editor drafts, the latest changed first (up to 100): title, status (draft, in_review, ready, published), method (create or optimize), page type, author (user or agent), the live page it optimizes, how many agent suggestions wait for review, and the editor path.",
+ inputSchema: listDraftsShape,
+ },
+ async (args) => {
+ const drafts = await listContentDraftsFor(auth, args.brand_id, args.status);
+ return drafts ? json(drafts) : notFound('Brand');
+ },
+ );
+
+ server.registerTool(
+ 'get_content_draft',
+ {
+ description:
+ 'Read one Content Editor draft: its HTML, and the page passage by passage (numbered, as suggest_content_changes refers to them). Passages marked locked are quoted by AI answers today: never suggest changing them. Also the action it belongs to and the agent suggestions still waiting for review.',
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID, from list_content_drafts.'),
+ },
+ },
+ async (args) => {
+ const draft = await getContentDraftFor(auth, args.draft_id);
+ return draft ? json(draft) : notFound('Draft');
+ },
+ );
+
+ server.registerTool(
+ 'create_content_draft',
+ {
+ description:
+ "Write a new Content Editor draft as the agent. It goes to the Library's In review for a person to read, edit and mark ready — the agent never publishes. The HTML is checked against the editor's allow-list (headings, paragraphs, lists, tables, links, schema JSON-LD). Without page_type, it is detected from the page. It is a write logged as the agent's — only on explicit user intent.",
+ inputSchema: createDraftShape,
+ },
+ async (args) => {
+ const created = await createContentDraftFor(auth, {
+ brandId: args.brand_id,
+ title: args.title,
+ bodyHtml: args.body_html,
+ method: args.method,
+ pageType: args.page_type,
+ sourceUrl: args.source_url,
+ promptIds: args.prompt_ids,
+ });
+ if (created === 'off_domain') {
+ return {
+ content: [
+ {
+ type: 'text' as const,
+ text: "source_url must be a page on one of the brand's domains",
+ },
+ ],
+ isError: true,
+ };
+ }
+ return created ? json(created) : notFound('Brand');
+ },
+ );
+
+ server.registerTool(
+ 'get_content_impact',
+ {
+ description:
+ "What the draft's live page earns, as the editor's Impact tab reads it: citations in AI answers, AI visits, Google clicks and the prompts citing it, against the period before. Only for a draft of a live page (method optimize, or published).",
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID.'),
+ days: impactDays,
+ },
+ },
+ async (args) => {
+ const impact = await getContentImpactFor(auth, args.draft_id, args.days);
+ if (impact === 'no_page') {
+ return {
+ content: [{ type: 'text' as const, text: 'This draft is a new page, not live yet' }],
+ isError: true,
+ };
+ }
+ return impact ? json(impact) : notFound('Draft');
+ },
+ );
+
+ server.registerTool(
+ 'get_content_sources',
+ {
+ description:
+ "The brand's data the draft draws on over 30 days, as the Sources tab shows it: its prompts, the AI searches (fan-outs) run for them, the pages AI cites, Search Console queries, and the person's choices (sources left out or added).",
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID.'),
+ },
+ },
+ async (args) => {
+ const sources = await getContentSourcesFor(auth, args.draft_id);
+ return sources ? json(sources) : notFound('Draft');
+ },
+ );
+
+ server.registerTool(
+ 'add_content_source',
+ {
+ description:
+ "Add a source to a draft, as the Sources tab's Add does: a tracked prompt (by id) joins the draft's prompts; a page address or a Search Console query is kept as added.",
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID.'),
+ ...addSourceShape,
+ },
+ },
+ async (args) => {
+ const ref = args.ref.trim();
+ const refError = sourceRefError(args.kind, ref);
+ if (refError) {
+ return { content: [{ type: 'text' as const, text: refError }], isError: true };
+ }
+ const result = await addContentSourceFor(
+ auth,
+ args.draft_id,
+ args.kind === 'prompt' ? { kind: 'prompt', promptId: ref } : { kind: args.kind, ref },
+ );
+ if (result === 'not_found') return notFound('Prompt');
+ return result ? json(result) : notFound('Draft');
+ },
+ );
+
+ server.registerTool(
+ 'suggest_content_changes',
+ {
+ description: `Leave changes on a draft for a person to accept or reject in the editor — never applied by the agent. Read the draft with get_content_draft first: each suggestion names a passage by its number. A replace changes words in that passage ("before" copied exactly as the passage has it, "after" as plain text); an insert adds blocks after it ("after" as simple HTML: h2, h3, p, ul, ol, li, strong, em). Never change a locked passage. While a person still has the draft's open suggestions to decide, no new ones are taken: wait until get_content_draft lists none. At most ${MAX_API_SUGGESTIONS}; ones the editor can't apply come back in "dropped" with the reason (no_passage, locked, not_in_passage, no_change, empty, duplicate, too_many).`,
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID.'),
+ ...suggestionsShape,
+ },
+ },
+ async (args) => {
+ const result = await suggestContentChangesFor(auth, args.draft_id, args.suggestions);
+ if (result === 'published') {
+ return {
+ content: [
+ { type: 'text' as const, text: 'The draft is published; suggest on a new draft' },
+ ],
+ isError: true,
+ };
+ }
+ if (result === 'open_suggestions') {
+ return {
+ content: [
+ {
+ type: 'text' as const,
+ text: 'A person still has open suggestions on this draft to accept or reject; suggest again once get_content_draft lists none',
+ },
+ ],
+ isError: true,
+ };
+ }
+ return result ? json(result) : notFound('Draft');
+ },
+ );
+
+ server.registerTool(
+ 'set_content_draft_ready',
+ {
+ description:
+ "Mark a draft ready to publish, as the editor's Mark ready does: from draft only — an agent's draft in review waits for a person to mark it ready in the editor. History keeps the page as a version. Ansvisor never publishes — a person does. Only on explicit user intent.",
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID.'),
+ },
+ },
+ async (args) => {
+ const result = await setContentDraftReadyFor(auth, args.draft_id);
+ if (result === 'in_review') {
+ return {
+ content: [
+ {
+ type: 'text' as const,
+ text: 'The draft is in review: a person marks it ready in the editor',
+ },
+ ],
+ isError: true,
+ };
+ }
+ return result ? json(result) : notFound('Draft');
+ },
+ );
+
return server;
}