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(mcp): give a draft as a page ready for a CMS, as Send to CMS makes it (#1728)

Cihan45492d1bcf24
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 95d00d286..9f63d26d7 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -220,7 +220,7 @@ instead.
## Available tools
-The MCP server exposes **61 tools**. Descriptions below match
+The MCP server exposes **62 tools**. Descriptions below match
[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).
Tools that change data are marked **writes** — only call them on explicit user
intent, not during exploratory queries. A write that needs a particular role
@@ -323,7 +323,7 @@ The plan is also available over REST with the same `ans_` key: `GET /api/mcp/con
Drafts are read and written as a person would in the editor. Ansvisor never puts a page on your site, and a suggestion isn't applied until a person accepts it. None of these tools calls an LLM: the assistant writes the drafts and suggestions itself.
-The MCP never sends a page to a CMS: Ansvisor's own **Send to CMS** stays in the product. To publish from your assistant, put the page on your CMS with the assistant's own CMS connector, then call `mark_content_draft_published` with the address it went live at, so Ansvisor measures it. Over REST: `POST /api/mcp/content-drafts/<id>/published` with `{ "url": "…" }`.
+The MCP never sends a page to a CMS: Ansvisor's own **Send to CMS** stays in the product. To publish from your assistant, read the draft with `get_content_draft_package` (the page as **Send to CMS** would send it), put it on your CMS with the assistant's own CMS connector, then call `mark_content_draft_published` with the address it went live at, so Ansvisor measures it. Over REST: `GET /api/mcp/content-drafts/<id>/package`, then `POST /api/mcp/content-drafts/<id>/published` with `{ "url": "…" }`.
| Tool | What it does | Writes |
| --- | --- | --- |
@@ -334,6 +334,7 @@ The MCP never sends a page to a CMS: Ansvisor's own **Send to CMS** stays in the
| `create_content_draft` | Write a new draft as the agent (`create`, or `optimize` a page on the brand's domains); it goes to the Library's In review. | **yes** |
| `add_content_source` | Add a prompt, a cited page or a Search Console query to the draft's sources. | **yes** |
| `suggest_content_changes` | Leave up to 20 suggestions (replace or insert, each with a reason) for a person to accept or reject. Refused on a published draft, while open suggestions wait, or while the Content Agent writes it. | **yes** |
+| `get_content_draft_package` | A draft as a page ready for a CMS, exactly as **Send to CMS** would send it: title, slug, meta title and description, the HTML ready to paste (as **Copy HTML** gives it, with the byline line and no H1; HTML blocks are passed as written, scripts and iframes included, as Copy HTML and Send to CMS pass them), its JSON-LD, the author and the featured image. Ansvisor doesn't send it: put it on your CMS with your assistant's own CMS connector, then call `mark_content_draft_published`. A page that can't go yet says why. | |
| `mark_content_draft_published` | Mark a draft Published at the address it went live at, as the editor's **Mark published** does, once your own CMS connector has put it there. Ansvisor then measures that address, and a linked action's Publish task completes once every page it names is live. | **yes** |
| `set_content_draft_ready` | Set a draft ready, as the editor's Mark ready does, without its Before you publish check; a linked action's writing task completes once every page it names has a ready draft. A draft in review waits for a person. | **yes** |
diff --git a/web/package.json b/web/package.json
index 885fcb2b3..7d903d954 100644
--- a/web/package.json
+++ b/web/package.json
@@ -47,6 +47,7 @@
"docx": "9.7.0",
"dompurify": "3.4.16",
"fflate": "^0.8.3",
+ "jsdom": "^26.0.0",
"lucide-react": "^0.577.0",
"mammoth": "1.13.0",
"marked": "^18.0.0",
@@ -83,7 +84,6 @@
"eslint": "^9",
"eslint-config-next": "16.1.6",
"eslint-config-prettier": "^10.1.8",
- "jsdom": "^26.0.0",
"prettier": "^3.8.3",
"tailwindcss": "^4",
"typescript": "^5",
diff --git a/web/src/app/api/mcp/content-drafts/[id]/package/route.test.ts b/web/src/app/api/mcp/content-drafts/[id]/package/route.test.ts
new file mode 100644
index 000000000..e938a0c62
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/package/route.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** GET /api/mcp/content-drafts/[id]/package: the REST mirror of get_content_draft_package. */
+
+const { getContentDraftPackageFor } = vi.hoisted(() => ({ getContentDraftPackageFor: vi.fn() }));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ })),
+}));
+vi.mock('@/lib/mcp/content-package', () => ({ getContentDraftPackageFor }));
+
+const { GET, runtime } = await import('./route');
+
+const DRAFT = '11111111-2222-3333-4444-555555555555';
+const get = (id = DRAFT) =>
+ GET(new Request(`http://localhost/api/mcp/content-drafts/${id}/package`), {
+ params: Promise.resolve({ id }),
+ });
+
+beforeEach(() => {
+ getContentDraftPackageFor.mockReset();
+});
+
+describe('GET /api/mcp/content-drafts/[id]/package', () => {
+ it('runs on Node, where jsdom reads the page, and answers the package', async () => {
+ expect(runtime).toBe('nodejs');
+ getContentDraftPackageFor.mockResolvedValue({ draft_id: DRAFT, html: '<p>x</p>' });
+ const res = await get();
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ draft_id: DRAFT, html: '<p>x</p>' });
+ });
+
+ it('says why a page can’t go yet (409), or that it isn’t there (404)', async () => {
+ getContentDraftPackageFor.mockResolvedValueOnce({
+ error: 'not_ready',
+ problem: 'placeholders',
+ message: 'Fill them',
+ });
+ const notReady = await get();
+ expect(notReady.status).toBe(409);
+ expect(await notReady.json()).toEqual({
+ error: 'Fill them',
+ code: 'not_ready',
+ problem: 'placeholders',
+ });
+ getContentDraftPackageFor.mockResolvedValueOnce({ error: 'not_found', message: 'No' });
+ expect((await get()).status).toBe(404);
+ expect((await get('not-a-draft')).status).toBe(400);
+ });
+});
diff --git a/web/src/app/api/mcp/content-drafts/[id]/package/route.ts b/web/src/app/api/mcp/content-drafts/[id]/package/route.ts
new file mode 100644
index 000000000..25c6b96c7
--- /dev/null
+++ b/web/src/app/api/mcp/content-drafts/[id]/package/route.ts
@@ -0,0 +1,32 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getContentDraftPackageFor } from '@/lib/mcp/content-package';
+import { contentUuid } from '@/lib/mcp/content-schemas';
+
+// Node, not the edge: the package is read with jsdom.
+export const runtime = 'nodejs';
+
+/** GET /api/mcp/content-drafts/[id]/package — REST mirror of `get_content_draft_package`. */
+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 result = await getContentDraftPackageFor(auth, id);
+ if ('error' in result) {
+ return NextResponse.json(
+ { error: result.message, code: result.error, problem: result.problem ?? null },
+ { status: result.error === 'not_found' ? 404 : 409 },
+ );
+ }
+ 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/route.ts b/web/src/app/api/mcp/route.ts
index edb835893..8e11116d8 100644
--- a/web/src/app/api/mcp/route.ts
+++ b/web/src/app/api/mcp/route.ts
@@ -5,6 +5,8 @@ import { authenticateMcpRequest } from '@/lib/mcp-auth';
import { createMcpServer } from '@/lib/mcp/server';
export const dynamic = 'force-dynamic';
+// Node, not the edge: get_content_draft_package reads pages with jsdom.
+export const runtime = 'nodejs';
/**
* Streamable HTTP entry point for the Ansvisor MCP server. Claude Desktop,
diff --git a/web/src/lib/actions/content-authors.ts b/web/src/lib/actions/content-authors.ts
index 0807345a3..94c7f432a 100644
--- a/web/src/lib/actions/content-authors.ts
+++ b/web/src/lib/actions/content-authors.ts
@@ -2,6 +2,7 @@
import { z } from 'zod';
import { authorInput, type AuthorInput, type AuthorsRead } from '@/lib/content/authors';
+import { readContentAuthors } from '@/lib/content/authors-read';
import { createClient } from '@/lib/supabase/server';
import { assertWritable } from '@/lib/subscription-guard';
@@ -16,8 +17,6 @@ import { assertWritable } from '@/lib/subscription-guard';
/** The member is another author already (content_authors_member, a unique violation). */
const ALREADY_AUTHOR = '23505';
-const AUTHOR_COLUMNS = 'id, name, title, bio, photo_url, same_as, user_id, created_by';
-
/**
* The workspace's authors, its brands and the member reading; null when
* signed out. `pages` counts each author's pages (Settings' column); the
@@ -37,59 +36,10 @@ export async function getContentAuthors(
if (profileError) throw new Error(profileError.message);
if (!profile?.organization_id) return null;
- const [authorsRes, brandsRes, defaultsRes] = await Promise.all([
- supabase
- .from('content_authors')
- .select(AUTHOR_COLUMNS)
- .eq('organization_id', profile.organization_id)
- .order('name'),
- supabase
- .from('brands')
- .select('id, name, content_byline')
- .eq('organization_id', profile.organization_id)
- .order('name'),
- supabase.from('content_author_defaults').select('brand_id, author_id'),
- ]);
- for (const res of [authorsRes, brandsRes, defaultsRes]) {
- if (res.error) throw new Error(res.error.message);
- }
- const defaults = (defaultsRes.data ?? []) as { brand_id: string; author_id: string }[];
- const rows = authorsRes.data ?? [];
- // A workspace has a few authors: one count each, on content_drafts_author,
- // of the pages the Library shows (not archived).
- const pages = options.pages
- ? await Promise.all(
- rows.map(async (row) => {
- const { count, error } = await supabase
- .from('content_drafts')
- .select('id', { count: 'exact', head: true })
- .eq('author_id', row.id)
- .is('archived_at', null);
- if (error) throw new Error(error.message);
- return count ?? 0;
- }),
- )
- : null;
- return {
- authors: rows.map((row, i) => ({
- id: row.id,
- name: row.name,
- title: row.title,
- bio: row.bio,
- photoUrl: row.photo_url,
- sameAs: row.same_as ?? [],
- userId: row.user_id,
- createdBy: row.created_by,
- defaultFor: defaults.filter((d) => d.author_id === row.id).map((d) => d.brand_id),
- pages: pages?.[i] ?? null,
- })),
- brands: (brandsRes.data ?? []).map((b) => ({
- id: b.id,
- name: b.name,
- bylineInContent: !!b.content_byline,
- })),
+ return readContentAuthors(supabase, profile.organization_id, {
me: { id: auth.user.id, role: profile.role ?? 'analyst' },
- };
+ pages: options.pages,
+ });
}
/**
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index bc58190ff..fbe02b743 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -51,6 +51,7 @@ import { MAX_SOURCE_SITES, type AiSourceClass } from '@/lib/content/source-class
import { draftShopping } from '@/lib/content/shopping-check';
import {
NO_DRAFT_RULES,
+ draftLanguage,
draftRulesFit,
draftRulesSchema,
ruleSetFits,
@@ -341,13 +342,6 @@ export interface DraftPage {
language: string | null;
}
-/** The language a draft's own Language rule names, when it is on and set. */
-function draftLanguage(rules: unknown): string | null {
- const language = draftRulesSchema.safeParse(rules).data?.overrides.language;
- const value = language?.on === false ? '' : (language?.value?.trim() ?? '');
- return value || null;
-}
-
/**
* A call's pages stop at about this many characters, well inside a
* serverless response's 4.5 MB: fifty pages can each be up to 500 KB.
diff --git a/web/src/lib/content/authors-read.test.ts b/web/src/lib/content/authors-read.test.ts
new file mode 100644
index 000000000..263d2b113
--- /dev/null
+++ b/web/src/lib/content/authors-read.test.ts
@@ -0,0 +1,89 @@
+import type { SupabaseClient } from '@supabase/supabase-js';
+import { describe, expect, it } from 'vitest';
+import { readContentAuthors } from './authors-read';
+
+/**
+ * The authors read: with the service role (the MCP's get_content_draft_package),
+ * which reads every row, each table keeps to the organization's.
+ */
+
+interface Query {
+ table: string;
+ columns: string;
+ filters: [string, unknown][];
+}
+
+/** A client answering each table with its rows, and keeping what each query asked. */
+function client(rows: Record<string, unknown[]>) {
+ const queries: Query[] = [];
+ const supabase = {
+ from(table: string) {
+ const query: Query = { table, columns: '', filters: [] };
+ queries.push(query);
+ const chain = {
+ select: (columns: string) => ((query.columns = columns), chain),
+ eq: (column: string, value: unknown) => (query.filters.push([column, value]), chain),
+ is: (column: string, value: unknown) => (query.filters.push([column, value]), chain),
+ order: () => chain,
+ then: (resolve: (result: { data: unknown[]; error: null }) => unknown) =>
+ resolve({ data: rows[table] ?? [], error: null }),
+ };
+ return chain;
+ },
+ };
+ return { supabase: supabase as unknown as SupabaseClient, queries };
+}
+
+describe('readContentAuthors', () => {
+ it("reads the organization's authors, brands and only its brands' defaults", async () => {
+ const { supabase, queries } = client({
+ content_authors: [
+ {
+ id: 'author-1',
+ name: 'Ada Lovelace',
+ title: 'Head barista',
+ bio: null,
+ photo_url: null,
+ same_as: null,
+ user_id: null,
+ created_by: 'user-1',
+ },
+ ],
+ brands: [{ id: 'brand-1', name: 'Acme Coffee', content_byline: true }],
+ content_author_defaults: [{ brand_id: 'brand-1', author_id: 'author-1' }],
+ });
+ const read = await readContentAuthors(supabase, 'org-1', {
+ me: { id: 'user-1', role: 'analyst' },
+ });
+
+ const byTable = Object.fromEntries(queries.map((q) => [q.table, q]));
+ expect(byTable.content_authors.filters).toContainEqual(['organization_id', 'org-1']);
+ expect(byTable.brands.filters).toContainEqual(['organization_id', 'org-1']);
+ expect(byTable.content_author_defaults.columns).toContain('brands!inner(organization_id)');
+ expect(byTable.content_author_defaults.filters).toContainEqual([
+ 'brands.organization_id',
+ 'org-1',
+ ]);
+ // No page counts unless asked (Settings' column).
+ expect(queries.some((q) => q.table === 'content_drafts')).toBe(false);
+
+ expect(read).toEqual({
+ authors: [
+ {
+ id: 'author-1',
+ name: 'Ada Lovelace',
+ title: 'Head barista',
+ bio: null,
+ photoUrl: null,
+ sameAs: [],
+ userId: null,
+ createdBy: 'user-1',
+ defaultFor: ['brand-1'],
+ pages: null,
+ },
+ ],
+ brands: [{ id: 'brand-1', name: 'Acme Coffee', bylineInContent: true }],
+ me: { id: 'user-1', role: 'analyst' },
+ });
+ });
+});
diff --git a/web/src/lib/content/authors-read.ts b/web/src/lib/content/authors-read.ts
new file mode 100644
index 000000000..e4fd56a4f
--- /dev/null
+++ b/web/src/lib/content/authors-read.ts
@@ -0,0 +1,76 @@
+import type { SupabaseClient } from '@supabase/supabase-js';
+import type { AuthorsRead } from '@/lib/content/authors';
+
+/**
+ * The workspace's authors and its brands (content_authors, 00256; the
+ * brands' byline setting, 00261), read through the client given: the
+ * member's session for Settings and the editor (getContentAuthors), the
+ * service role for the MCP's get_content_draft_package once the draft is the
+ * key's. `pages` counts each author's pages (Settings' column).
+ */
+
+const AUTHOR_COLUMNS = 'id, name, title, bio, photo_url, same_as, user_id, created_by';
+
+export async function readContentAuthors(
+ supabase: SupabaseClient,
+ organizationId: string,
+ { me, pages: pagesToo = false }: { me: AuthorsRead['me']; pages?: boolean },
+): Promise<AuthorsRead> {
+ const [authorsRes, brandsRes, defaultsRes] = await Promise.all([
+ supabase
+ .from('content_authors')
+ .select(AUTHOR_COLUMNS)
+ .eq('organization_id', organizationId)
+ .order('name'),
+ supabase
+ .from('brands')
+ .select('id, name, content_byline')
+ .eq('organization_id', organizationId)
+ .order('name'),
+ // The organization's brands' defaults only: the service role reads every row.
+ supabase
+ .from('content_author_defaults')
+ .select('brand_id, author_id, brands!inner(organization_id)')
+ .eq('brands.organization_id', organizationId),
+ ]);
+ for (const res of [authorsRes, brandsRes, defaultsRes]) {
+ if (res.error) throw new Error(res.error.message);
+ }
+ const defaults = (defaultsRes.data ?? []) as { brand_id: string; author_id: string }[];
+ const rows = authorsRes.data ?? [];
+ // A workspace has a few authors: one count each, on content_drafts_author,
+ // of the pages the Library shows (not archived).
+ const pages = pagesToo
+ ? await Promise.all(
+ rows.map(async (row) => {
+ const { count, error } = await supabase
+ .from('content_drafts')
+ .select('id', { count: 'exact', head: true })
+ .eq('author_id', row.id)
+ .is('archived_at', null);
+ if (error) throw new Error(error.message);
+ return count ?? 0;
+ }),
+ )
+ : null;
+ return {
+ authors: rows.map((row, i) => ({
+ id: row.id,
+ name: row.name,
+ title: row.title,
+ bio: row.bio,
+ photoUrl: row.photo_url,
+ sameAs: row.same_as ?? [],
+ userId: row.user_id,
+ createdBy: row.created_by,
+ defaultFor: defaults.filter((d) => d.author_id === row.id).map((d) => d.brand_id),
+ pages: pages?.[i] ?? null,
+ })),
+ brands: (brandsRes.data ?? []).map((b) => ({
+ id: b.id,
+ name: b.name,
+ bylineInContent: !!b.content_byline,
+ })),
+ me,
+ };
+}
diff --git a/web/src/lib/content/clean-html.ts b/web/src/lib/content/clean-html.ts
index c042a90ff..8372d2974 100644
--- a/web/src/lib/content/clean-html.ts
+++ b/web/src/lib/content/clean-html.ts
@@ -1,4 +1,5 @@
import DOMPurify from 'dompurify';
+import { contentDom, parseHtml } from './dom';
import {
ALLOWED_ATTRIBUTES,
ALLOWED_TAGS,
@@ -58,16 +59,16 @@ function keepStyledEmphasis(root: HTMLElement) {
!el.closest('h1, h2, h3, h4, h5, h6');
const italic = el.style.fontStyle === 'italic';
if (!bold && !italic) continue;
- const inner = document.createElement('span');
+ const inner = root.ownerDocument.createElement('span');
inner.append(...el.childNodes);
let wrapped: HTMLElement = inner;
if (italic) {
- const em = document.createElement('em');
+ const em = root.ownerDocument.createElement('em');
em.append(wrapped);
wrapped = em;
}
if (bold) {
- const strong = document.createElement('strong');
+ const strong = root.ownerDocument.createElement('strong');
strong.append(wrapped);
wrapped = strong;
}
@@ -78,7 +79,7 @@ function keepStyledEmphasis(root: HTMLElement) {
function demoteHeadings(root: HTMLElement) {
for (const tag of DEMOTED_HEADINGS) {
for (const heading of root.querySelectorAll(tag)) {
- const h3 = document.createElement('h3');
+ const h3 = root.ownerDocument.createElement('h3');
h3.append(...heading.childNodes);
heading.replaceWith(h3);
}
@@ -95,14 +96,14 @@ export function cleanHtml(
{ keepImages, keepHtmlBlocks = false }: { keepImages: boolean; keepHtmlBlocks?: boolean },
): CleanedHtml {
const { html, kept } = extractKeptBlocks(input, { htmlBlocks: keepHtmlBlocks });
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
// Counted in the whole document: a script before any text parses into <head>.
const unsafeRemoved = doc.querySelectorAll(UNSAFE_TAGS.join(',')).length;
keepStyledEmphasis(doc.body);
demoteHeadings(doc.body);
// A purifier of its own, so these hooks don't touch other uses of DOMPurify.
- const purify = DOMPurify(window);
+ const purify = DOMPurify(contentDom());
let imagesRemoved = 0;
purify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'A') {
diff --git a/web/src/lib/content/dom.ts b/web/src/lib/content/dom.ts
new file mode 100644
index 000000000..e9a4e144c
--- /dev/null
+++ b/web/src/lib/content/dom.ts
@@ -0,0 +1,32 @@
+/**
+ * The DOM the Content Editor's HTML helpers read and clean pages with
+ * (clean-html, ready-to-publish, page-schema, placeholders, readability):
+ * the browser's own, or one the server gives with setContentDom. The MCP's
+ * get_content_draft_package gives a jsdom window, so the page it hands an
+ * assistant is the one the editor's Copy HTML and Send to CMS make. Nothing
+ * here imports a DOM library: the browser's bundle never carries one.
+ */
+
+/** A window, as the browser's: its document, DOMParser, nodes and elements. */
+export type ContentWindow = Window & typeof globalThis;
+
+let given: ContentWindow | null = null;
+
+/** The window the helpers read with on the server; null goes back to the browser's. */
+export function setContentDom(win: ContentWindow | null): void {
+ given = win;
+}
+
+/** The window the helpers read with: the one given, else the browser's. */
+export function contentDom(): ContentWindow {
+ return given ?? window;
+}
+
+/** HTML as a document of its own, as DOMParser reads it. */
+export function parseHtml(html: string): Document {
+ return new (contentDom().DOMParser)().parseFromString(html, 'text/html');
+}
+
+/** Node types, as the DOM numbers them: no Node global on the server. */
+export const ELEMENT_NODE = 1;
+export const TEXT_NODE = 3;
diff --git a/web/src/lib/content/page-schema.ts b/web/src/lib/content/page-schema.ts
index bee3af9b4..40b737977 100644
--- a/web/src/lib/content/page-schema.ts
+++ b/web/src/lib/content/page-schema.ts
@@ -1,6 +1,7 @@
import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';
import type { ContentAuthor } from './authors';
import { factValueText, pagePrices, priceRanges } from './brand-facts';
+import { TEXT_NODE, parseHtml } from './dom';
import type { PageType } from './drafts';
import { PLACEHOLDER } from './placeholders';
import { cleanHref, decodeHtmlBlock } from './html-allowlist';
@@ -47,7 +48,7 @@ export const pageName = (title: string) =>
/** The page's first image with a full https address, as JSON-LD's image. */
export function firstImage(html: string): string | null {
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
for (const img of doc.querySelectorAll('img[src]')) {
const src = img.getAttribute('src') ?? '';
if (/^https:\/\/[^\s"'<>]+$/i.test(src)) return src;
@@ -311,7 +312,7 @@ export function offerText(offer: PageOffer): string {
/** The page's opening paragraph (past a byline or a date), as Product's description: up to 500 characters. */
export function openingParagraph(html: string): string | null {
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
for (const p of doc.body.querySelectorAll('p')) {
const text = (p.textContent ?? '').replace(/\s+/g, ' ').trim();
if (!text || isByline(text)) continue;
@@ -398,7 +399,7 @@ export const MAX_LISTED = 100;
function linkName(a: Element): string | null {
const words: string[] = [];
const walk = (node: Node) => {
- if (node.nodeType === Node.TEXT_NODE) words.push(node.textContent ?? '');
+ if (node.nodeType === TEXT_NODE) words.push(node.textContent ?? '');
else node.childNodes.forEach(walk);
};
walk(a);
@@ -430,7 +431,7 @@ export function listedProducts(
): ListedProduct[] {
const own = brandDomains.map(normalizeDomain).filter(Boolean);
const root = base ?? (own[0] ? `https://${own[0]}` : null);
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
const links: Element[] = [];
for (const el of doc.body.querySelectorAll('a[href], [data-html-block]')) {
if (el.tagName === 'A') {
@@ -439,9 +440,7 @@ export function listedProducts(
}
const inner = decodeHtmlBlock(el.getAttribute('data-html-block') ?? '');
if (inner) {
- links.push(
- ...new DOMParser().parseFromString(inner, 'text/html').body.querySelectorAll('a[href]'),
- );
+ links.push(...parseHtml(inner).body.querySelectorAll('a[href]'));
}
}
const byKey = new Map<string, ListedProduct>();
diff --git a/web/src/lib/content/placeholders.ts b/web/src/lib/content/placeholders.ts
index 540cf5952..f64d4b590 100644
--- a/web/src/lib/content/placeholders.ts
+++ b/web/src/lib/content/placeholders.ts
@@ -1,3 +1,5 @@
+import { ELEMENT_NODE, TEXT_NODE, parseHtml } from './dom';
+
/**
* Placeholders in a page (Content Editor Quality spec §4, §9, CE-044): words
* in square brackets where a real name, quote or number goes — what the
@@ -38,8 +40,9 @@ const INLINE = /^(A|STRONG|EM|B|I|U|S|SPAN|CODE|MARK|SUB|SUP|SMALL|BR)$/;
function itemOwnText(li: Element): string {
let text = '';
for (const node of li.childNodes) {
- if (node.nodeType === Node.TEXT_NODE) text += node.textContent ?? '';
- else if (node instanceof Element && INLINE.test(node.tagName)) text += node.textContent ?? '';
+ if (node.nodeType === TEXT_NODE) text += node.textContent ?? '';
+ else if (node.nodeType === ELEMENT_NODE && INLINE.test((node as Element).tagName))
+ text += node.textContent ?? '';
}
return text;
}
@@ -51,7 +54,7 @@ function itemOwnText(li: Element): string {
* by its own words.
*/
export function pagePlaceholders(html: string): PagePlaceholders {
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
let count = 0;
for (const el of doc.body.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li')) {
const text = el.tagName === 'LI' ? itemOwnText(el) : (el.textContent ?? '');
diff --git a/web/src/lib/content/readability.ts b/web/src/lib/content/readability.ts
index e2c34fc42..c24c32577 100644
--- a/web/src/lib/content/readability.ts
+++ b/web/src/lib/content/readability.ts
@@ -1,4 +1,5 @@
import { LANGUAGES } from '@/config/prompt-options';
+import { parseHtml } from './dom';
/**
* Readability, one of the Quality scores (Content Editor Quality spec §2.3,
@@ -136,7 +137,7 @@ export function ownText(el: Element): string {
/** The page's headings and prose, in order: a quote once, each list item on its own. */
export function readBlocks(html: string): ReadBlock[] {
- const doc = new DOMParser().parseFromString(html, 'text/html');
+ const doc = parseHtml(html);
const blocks: ReadBlock[] = [];
for (const el of doc.body.querySelectorAll('h1, h2, h3, p, li, blockquote')) {
const tag = el.tagName.toLowerCase() as ReadBlock['tag'];
diff --git a/web/src/lib/content/ready-to-publish.ts b/web/src/lib/content/ready-to-publish.ts
index 193ab0293..d58557a81 100644
--- a/web/src/lib/content/ready-to-publish.ts
+++ b/web/src/lib/content/ready-to-publish.ts
@@ -1,5 +1,6 @@
import { slugify } from '@/lib/slug';
import type { ContentAuthor } from './authors';
+import { ELEMENT_NODE, TEXT_NODE, contentDom } from './dom';
import { cleanHref, jsonLdText } from './html-allowlist';
import { firstImage } from './page-schema';
import { AGENT_PLACEHOLDER, PLACEHOLDER, placeholderIn } from './placeholders';
@@ -21,7 +22,7 @@ import { languageCode } from './readability';
* it is (DOMParser's body would move it).
*/
export function fragment(html: string): HTMLElement {
- const doc = document.implementation.createHTMLDocument('');
+ const doc = contentDom().document.implementation.createHTMLDocument('');
const root = doc.createElement('div');
root.innerHTML = html;
return root;
@@ -35,8 +36,8 @@ function textNodes(root: Node): Text[] {
const out: Text[] = [];
const walk = (node: Node) => {
for (const child of Array.from(node.childNodes)) {
- if (child.nodeType === Node.TEXT_NODE) out.push(child as Text);
- else if (child.nodeType === Node.ELEMENT_NODE) {
+ if (child.nodeType === TEXT_NODE) out.push(child as Text);
+ else if (child.nodeType === ELEMENT_NODE) {
const tag = (child as Element).tagName.toLowerCase();
if (tag !== 'script' && tag !== 'style' && tag !== 'template') walk(child);
}
diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.ts
index dacc6bb39..bc8e6c4e4 100644
--- a/web/src/lib/content/rules.ts
+++ b/web/src/lib/content/rules.ts
@@ -1558,3 +1558,10 @@ export function rulesMet(statuses: { rule: ActiveRule; status: RuleStatus }[]):
const counted = statuses.filter((s) => s.rule.on && s.status.state !== 'info');
return { met: counted.filter((s) => s.status.state === 'ok').length, total: counted.length };
}
+
+/** The language a draft's own Language rule names, when it is on and set. */
+export function draftLanguage(rules: unknown): string | null {
+ const language = draftRulesSchema.safeParse(rules).data?.overrides.language;
+ const value = language?.on === false ? '' : (language?.value?.trim() ?? '');
+ return value || null;
+}
diff --git a/web/src/lib/mcp/__fixtures__/package-draft.ts b/web/src/lib/mcp/__fixtures__/package-draft.ts
new file mode 100644
index 000000000..fef2634de
--- /dev/null
+++ b/web/src/lib/mcp/__fixtures__/package-draft.ts
@@ -0,0 +1,121 @@
+import type { AuthorsRead } from '@/lib/content/authors';
+import { htmlBlockElement } from '@/lib/content/html-allowlist';
+
+/**
+ * One draft for get_content_draft_package's tests: the editor's own Send to
+ * CMS (in the browser) and the MCP's (on the server, with jsdom) must make
+ * the same page of it.
+ */
+
+export const BRAND_ID = '22222222-0000-4000-8000-000000000001';
+export const DRAFT_ID = '33333333-0000-4000-8000-000000000001';
+export const AUTHOR_ID = '44444444-0000-4000-8000-000000000001';
+
+const JSON_LD =
+ '{"@context":"https://schema.org","@type":"Article","headline":"Cold brew at home"}';
+
+/** An HTML block's code (a call to action), with text past ASCII. */
+const HTML_BLOCK =
+ '<div class="acme-cta">\n <a href="https://acme.example/shop">Kaffeebohnen kaufen – café</a>\n</div>';
+
+/** The draft's row as the MCP reads it. */
+export const DRAFT_ROW = {
+ id: DRAFT_ID,
+ brand_id: BRAND_ID,
+ title: 'Cold brew at home: a slow, smooth coffee',
+ body_html: [
+ '<h1>Cold brew at home: a slow, smooth coffee</h1>',
+ '<p>Cold brew is coffee steeped in cold water for twelve to eighteen hours. It tastes smoother and less bitter than coffee brewed hot, and it keeps for a week in the fridge.</p>',
+ '<h2>What you need</h2>',
+ '<ul><li><p>Coarsely ground coffee</p></li><li><p>A large jar and a filter</p></li></ul>',
+ '<p><span style="font-weight:700">Tip:</span> grind it coarse, or the brew turns muddy.</p>',
+ '<h4>Ratios in Zürich — çok güzel</h4>',
+ '<table><colgroup><col style="width: 120px"><col></colgroup><tbody>',
+ '<tr><th colspan="1" rowspan="1"><p>Coffee</p></th><th colspan="1" rowspan="1"><p>Water</p></th></tr>',
+ '<tr><td colspan="1" rowspan="1"><p>100 g</p></td><td colspan="1" rowspan="1"><p>1 l</p></td></tr>',
+ '</tbody></table>',
+ '<p>Read <a target="_blank" rel="noopener noreferrer nofollow" href="https://acme.example/guides/grind">our grind guide</a> before you buy a naïve café blend.</p>',
+ '<img src="https://acme.example/cold-brew.jpg" alt="A jar of cold brew">',
+ htmlBlockElement(HTML_BLOCK),
+ `<script type="application/ld+json">${JSON_LD}</script>`,
+ ].join(''),
+ source_url: null,
+ author_id: AUTHOR_ID,
+ author_real_at: null,
+ rules: null,
+ slug: 'cold-brew-at-home',
+ meta_title: null,
+ meta_description: null,
+ archived_at: null,
+ brands: { organization_id: 'org-1', name: 'Acme Coffee', language: 'en' },
+};
+
+/** The workspace's authors and its brand, which puts the byline in the content. */
+export const AUTHORS: AuthorsRead = {
+ authors: [
+ {
+ id: AUTHOR_ID,
+ name: 'Ada Lovelace',
+ title: 'Head barista',
+ bio: null,
+ photoUrl: null,
+ sameAs: [],
+ userId: null,
+ createdBy: null,
+ defaultFor: [],
+ pages: null,
+ },
+ ],
+ brands: [{ id: BRAND_ID, name: 'Acme Coffee', bylineInContent: true }],
+ me: { id: 'user-1', role: 'analyst' },
+};
+
+/** The JSON-LD the page carries, parsed. */
+export const JSON_LD_PARSED = JSON.parse(JSON_LD);
+
+/**
+ * The page's HTML as the editor's Send to CMS sends it (in the browser): the
+ * byline line first, no H1, the styled bold kept as <strong>, the H4 an H3,
+ * the table without its column widths, the link with its address only, the
+ * text past ASCII as written, and the image, the HTML block's code and the
+ * JSON-LD as they are.
+ */
+export const EXPECTED_HTML = [
+ '<p>By Ada Lovelace</p>',
+ '<p>Cold brew is coffee steeped in cold water for twelve to eighteen hours. It tastes smoother and less bitter than coffee brewed hot, and it keeps for a week in the fridge.</p>',
+ '<h2>What you need</h2>',
+ '<ul>',
+ '<li>',
+ '<p>Coarsely ground coffee</p>',
+ '</li>',
+ '<li>',
+ '<p>A large jar and a filter</p>',
+ '</li>',
+ '</ul>',
+ '<p><strong>Tip:</strong> grind it coarse, or the brew turns muddy.</p>',
+ '<h3>Ratios in Zürich — çok güzel</h3>',
+ '<table>',
+ '<tbody>',
+ '<tr>',
+ '<th colspan="1" rowspan="1">',
+ '<p>Coffee</p>',
+ '</th>',
+ '<th colspan="1" rowspan="1">',
+ '<p>Water</p>',
+ '</th>',
+ '</tr>',
+ '<tr>',
+ '<td colspan="1" rowspan="1">',
+ '<p>100 g</p>',
+ '</td>',
+ '<td colspan="1" rowspan="1">',
+ '<p>1 l</p>',
+ '</td>',
+ '</tr>',
+ '</tbody>',
+ '</table>',
+ '<p>Read <a href="https://acme.example/guides/grind">our grind guide</a> before you buy a naïve café blend.</p>',
+ // An image and an HTML block aren't blocks the HTML view puts on lines of their own.
+ `<img src="https://acme.example/cold-brew.jpg" alt="A jar of cold brew">${HTML_BLOCK}`,
+ `<script type="application/ld+json">${JSON_LD}</script>`,
+].join('\n');
diff --git a/web/src/lib/mcp/content-package.editor.test.ts b/web/src/lib/mcp/content-package.editor.test.ts
new file mode 100644
index 000000000..f6ac7aa91
--- /dev/null
+++ b/web/src/lib/mcp/content-package.editor.test.ts
@@ -0,0 +1,61 @@
+import { JSDOM } from 'jsdom';
+import { afterEach, describe, expect, it } from 'vitest';
+import { bulkCmsItems, cmsSource } from '@/lib/content/cms-send';
+import { setContentDom } from '@/lib/content/dom';
+import {
+ AUTHORS,
+ BRAND_ID,
+ DRAFT_ID,
+ DRAFT_ROW,
+ EXPECTED_HTML,
+} from './__fixtures__/package-draft';
+
+/**
+ * get_content_draft_package's page is the editor's own (B5): the Library's
+ * Send to CMS, in the browser, makes EXPECTED_HTML of the fixture, and the
+ * same helpers given another window (as the server gives jsdom's) make the
+ * same page. content-package.test.ts runs the MCP's on the server.
+ */
+
+/** The fixture's page as the Library's Send to CMS makes it. */
+function sendPage() {
+ const source = cmsSource({
+ page: {
+ id: DRAFT_ID,
+ title: DRAFT_ROW.title,
+ bodyHtml: DRAFT_ROW.body_html,
+ sourceUrl: DRAFT_ROW.source_url,
+ authorId: DRAFT_ROW.author_id,
+ authorConfirmed: false,
+ language: null,
+ },
+ authors: AUTHORS,
+ brandId: BRAND_ID,
+ brandName: 'Acme Coffee',
+ brandLanguage: 'en',
+ });
+ const [item] = bulkCmsItems([source], new Map([[DRAFT_ID, { slug: DRAFT_ROW.slug }]]));
+ return item.page!;
+}
+
+afterEach(() => {
+ setContentDom(null);
+});
+
+describe("the editor's Send to CMS page", () => {
+ it('is the page the MCP gives, made with the browser’s window', () => {
+ const page = sendPage();
+ expect(page.html).toBe(EXPECTED_HTML);
+ expect(page).toMatchObject({
+ slug: 'cold-brew-at-home',
+ author: 'Ada Lovelace',
+ featuredImage: { src: 'https://acme.example/cold-brew.jpg', alt: 'A jar of cold brew' },
+ });
+ });
+
+ it('is the same made with a window of its own, as the server gives jsdom’s', () => {
+ const browser = sendPage();
+ setContentDom(new JSDOM('<!doctype html><html><head></head><body></body></html>').window);
+ expect(sendPage()).toEqual(browser);
+ });
+});
diff --git a/web/src/lib/mcp/content-package.test.ts b/web/src/lib/mcp/content-package.test.ts
new file mode 100644
index 000000000..35e760e98
--- /dev/null
+++ b/web/src/lib/mcp/content-package.test.ts
@@ -0,0 +1,196 @@
+// @vitest-environment node
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import {
+ AUTHORS,
+ DRAFT_ID,
+ DRAFT_ROW,
+ EXPECTED_HTML,
+ JSON_LD_PARSED,
+} from './__fixtures__/package-draft';
+import { htmlBlockElement } from '@/lib/content/html-allowlist';
+
+/**
+ * get_content_draft_package (B5) on the server, where there is no browser
+ * window: the editor's helpers read the page with jsdom's, and the page is
+ * the one the editor's Send to CMS makes (content-package.editor.test.ts).
+ */
+
+let draft: Record<string, unknown> | null;
+const draftFilters: [string, unknown][] = [];
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: (column: string, value: unknown) => (draftFilters.push([column, value]), chain),
+ maybeSingle: async () => ({ data: draft, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+const readContentAuthors = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/content/authors-read', () => ({ readContentAuthors }));
+
+const { getContentDraftPackageFor } = await import('./content-package');
+const { createMcpServer } = await import('./server');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ role: 'admin',
+};
+
+beforeEach(() => {
+ draft = { ...DRAFT_ROW };
+ draftFilters.length = 0;
+ readContentAuthors.mockReset().mockResolvedValue(AUTHORS);
+ // The authors, and so the byline, are read once Quality is live.
+ vi.stubEnv('NEXT_PUBLIC_CONTENT_QUALITY_PHASE', '1');
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('getContentDraftPackageFor', () => {
+ it('gives the page the editor’s Send to CMS makes, read with jsdom on the server', async () => {
+ expect(typeof window).toBe('undefined');
+ const result = await getContentDraftPackageFor(auth, DRAFT_ID);
+ expect(result).toEqual({
+ draft_id: DRAFT_ID,
+ title: 'Cold brew at home: a slow, smooth coffee',
+ slug: 'cold-brew-at-home',
+ meta_title: 'Cold brew at home: a slow, smooth coffee',
+ meta_description: 'Cold brew is coffee steeped in cold water for twelve to eighteen hours.',
+ html: EXPECTED_HTML,
+ json_ld: [JSON_LD_PARSED],
+ author: 'Ada Lovelace',
+ featured_image: { src: 'https://acme.example/cold-brew.jpg', alt: 'A jar of cold brew' },
+ source_url: null,
+ });
+ expect(draftFilters).toContainEqual(['brands.organization_id', 'org-1']);
+ expect(readContentAuthors).toHaveBeenCalledWith(expect.anything(), 'org-1', expect.anything());
+ });
+
+ it('cleans what a CMS mustn’t run, as the editor does', async () => {
+ draft = {
+ ...DRAFT_ROW,
+ body_html:
+ '<h1>Cold brew</h1><p onclick="steal()">Steep it slowly.<script>steal()</script></p>',
+ };
+ const result = await getContentDraftPackageFor(auth, DRAFT_ID);
+ expect('html' in result && result.html).not.toMatch(/onclick|steal/);
+ });
+
+ it('passes an HTML block as written, as Copy HTML and Send to CMS do', async () => {
+ // A block's code is the user's own: a CMS gets it as it is, script and all.
+ const code =
+ '<script src="https://widgets.example/w.js"></script><iframe src="https://video.example/embed/1"></iframe><a href="javascript:openChat()">Chat</a>';
+ draft = {
+ ...DRAFT_ROW,
+ body_html: `<h1>Cold brew</h1><p onclick="steal()">Steep it slowly.</p>${htmlBlockElement(code)}`,
+ };
+ const result = await getContentDraftPackageFor(auth, DRAFT_ID);
+ const html = 'html' in result ? result.html : '';
+ expect(html).toContain(code);
+ // The page's own content is still cleaned.
+ expect(html).not.toMatch(/onclick|steal/);
+ });
+
+ it('says why a page can’t go yet', async () => {
+ draft = {
+ ...DRAFT_ROW,
+ body_html: '<h1>Cold brew</h1><p>It steeps for [number] hours.</p>',
+ };
+ expect(await getContentDraftPackageFor(auth, DRAFT_ID)).toMatchObject({
+ error: 'not_ready',
+ problem: 'placeholders',
+ });
+ });
+
+ it('finds no draft of another organization, nor an archived one', async () => {
+ draft = null;
+ expect(await getContentDraftPackageFor(auth, DRAFT_ID)).toMatchObject({ error: 'not_found' });
+ draft = { ...DRAFT_ROW, archived_at: '2026-10-20T10:00:00Z' };
+ expect(await getContentDraftPackageFor(auth, DRAFT_ID)).toMatchObject({ error: 'not_found' });
+ expect(
+ await getContentDraftPackageFor({ ...auth, organizationId: null }, DRAFT_ID),
+ ).toMatchObject({ error: 'not_found' });
+ });
+});
+
+describe('the get_content_draft_package tool', () => {
+ it('lists as a read-only tool and answers a page that can’t go yet as the REST route does', async () => {
+ const server = createMcpServer(auth);
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: 'test', version: '1.0.0' });
+ await client.connect(clientTransport);
+ const text = (result: Awaited<ReturnType<Client['callTool']>>) =>
+ JSON.parse((result.content as { text: string }[])[0].text);
+
+ const { tools } = await client.listTools();
+ const tool = tools.find((t) => t.name === 'get_content_draft_package');
+ expect(tool).toMatchObject({
+ title: 'Draft as a CMS-ready page',
+ annotations: { readOnlyHint: true, openWorldHint: false },
+ });
+ // It says HTML blocks come as written, so a client expects their code.
+ expect(tool?.description).toContain('HTML blocks are passed as written');
+ expect(tool?.description).not.toMatch(/cleaned/);
+
+ const ready = await client.callTool({
+ name: 'get_content_draft_package',
+ arguments: { draft_id: DRAFT_ID },
+ });
+ expect(ready.isError).toBeFalsy();
+ expect(text(ready)).toMatchObject({ draft_id: DRAFT_ID, html: EXPECTED_HTML });
+
+ draft = { ...DRAFT_ROW, body_html: '<h1>Cold brew</h1><p>It steeps for [number] hours.</p>' };
+ const notReady = await client.callTool({
+ name: 'get_content_draft_package',
+ arguments: { draft_id: DRAFT_ID },
+ });
+ expect(notReady.isError).toBe(true);
+ expect(text(notReady)).toEqual({
+ error: expect.stringContaining('[placeholders]'),
+ code: 'not_ready',
+ problem: 'placeholders',
+ });
+ });
+});
+
+describe('jsdom’s window', () => {
+ afterEach(() => {
+ vi.doUnmock('jsdom');
+ vi.resetModules();
+ });
+
+ it('is made again on the next call when the first try fails', async () => {
+ vi.resetModules();
+ const made = vi.fn();
+ vi.doMock('jsdom', async () => {
+ const real = await vi.importActual<typeof import('jsdom')>('jsdom');
+ return {
+ JSDOM: class extends real.JSDOM {
+ constructor(html?: string) {
+ made();
+ if (made.mock.calls.length === 1) throw new Error('jsdom failed to load');
+ super(html);
+ }
+ },
+ };
+ });
+ const { getContentDraftPackageFor: fresh } = await import('./content-package');
+ await expect(fresh(auth, DRAFT_ID)).rejects.toThrow('jsdom failed to load');
+ expect(await fresh(auth, DRAFT_ID)).toMatchObject({ draft_id: DRAFT_ID, html: EXPECTED_HTML });
+ expect(made).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/web/src/lib/mcp/content-package.ts b/web/src/lib/mcp/content-package.ts
new file mode 100644
index 000000000..fac066c6f
--- /dev/null
+++ b/web/src/lib/mcp/content-package.ts
@@ -0,0 +1,171 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import { readContentAuthors } from '@/lib/content/authors-read';
+import { bulkCmsItems, cmsSource, type BulkProblem } from '@/lib/content/cms-send';
+import { setContentDom } from '@/lib/content/dom';
+import { qualityPhase } from '@/lib/content/quality';
+import { fragment } from '@/lib/content/ready-to-publish';
+import { draftLanguage } from '@/lib/content/rules';
+
+/**
+ * A draft as a page ready for a CMS, for the MCP tool
+ * get_content_draft_package (MCP plan B5): what the Content Library's Send to
+ * CMS sends (bulkCmsItems), so the user's own AI tool can put it on their CMS
+ * with its own connector. Ansvisor's MCP never sends it.
+ *
+ * The editor's helpers read HTML with a DOM, which the server has none of:
+ * jsdom's window is given to them (setContentDom), made on the first call
+ * and kept, and imported here alone, so no other tool waits for it and the
+ * browser's bundle never carries it. The MCP server imports this module on
+ * the tool's first call too.
+ */
+
+let dom: Promise<void> | null = null;
+
+/** jsdom's window for the editor's helpers, made once; a failed load is tried again. */
+function withContentDom(): Promise<void> {
+ dom ??= import('jsdom')
+ .then(({ JSDOM }) => {
+ const { window } = new JSDOM('<!doctype html><html><head></head><body></body></html>');
+ setContentDom(window);
+ })
+ .catch((err: unknown) => {
+ dom = null;
+ throw err;
+ });
+ return dom;
+}
+
+/** The page as the CMS takes it. */
+export interface McpCmsPackage {
+ draft_id: string;
+ title: string;
+ /** The page's address part, as the draft kept it from its last send, else its title's. */
+ slug: string;
+ meta_title: string;
+ meta_description: string;
+ /**
+ * The page's HTML ready to paste, as the editor's Copy HTML gives it: HTML
+ * blocks are passed as written (their scripts, iframes and links too), as
+ * Copy HTML and Send to CMS pass them; no placeholders left, with the
+ * brand's byline line when it puts one in the content, and without its H1,
+ * which the CMS's title field carries.
+ */
+ html: string;
+ /** The JSON-LD blocks the HTML carries, parsed, for a CMS that takes them apart. */
+ json_ld: unknown[];
+ /** The author's name for the CMS's author field; null to keep the CMS's own. */
+ author: string | null;
+ featured_image: { src: string; alt: string } | null;
+ /** The live page it optimizes; null for a new page. */
+ source_url: string | null;
+}
+
+export type McpPackageError = {
+ error: 'not_found' | 'not_ready';
+ problem?: BulkProblem;
+ message: string;
+};
+
+/** What a page that can't go yet needs, as the Library's Send says it. */
+const PROBLEMS: Record<BulkProblem, string> = {
+ noTitle: 'The page has no title.',
+ longTitle: 'The title is longer than 300 characters.',
+ empty: 'The page has nothing under its H1 to publish.',
+ tooLong: 'The page is longer than a million characters.',
+ placeholders:
+ 'The page still has [placeholders] to fill: fill them in the editor (or with suggest_content_changes) first.',
+ slug: "The slug the draft kept isn't one a CMS takes: letters, digits, '-', '_' and single dots, up to 200.",
+ metaTitle: 'The meta title the draft kept is longer than 300 characters.',
+ metaDescription: 'The meta description the draft kept is longer than 500 characters.',
+};
+
+/** The JSON-LD blocks of a page's HTML, each parsed; one that doesn't parse is left out. */
+function jsonLdOf(html: string): unknown[] {
+ return Array.from(fragment(html).querySelectorAll('script[type="application/ld+json"]')).flatMap(
+ (script) => {
+ try {
+ return [JSON.parse(script.textContent ?? '')];
+ } catch {
+ return [];
+ }
+ },
+ );
+}
+
+/**
+ * The draft as Send to CMS would send it unchanged; why it can't go yet when
+ * it can't (fill it in the editor). Not found for a draft outside the key's
+ * organization, or archived.
+ */
+export async function getContentDraftPackageFor(
+ auth: McpAuthContext,
+ draftId: string,
+): Promise<McpCmsPackage | McpPackageError> {
+ const notFound: McpPackageError = { error: 'not_found', message: 'Draft not found' };
+ if (!auth.organizationId) return notFound;
+ const { data: draft, error } = await supabaseAdmin
+ .from('content_drafts')
+ .select(
+ 'id, brand_id, title, body_html, source_url, author_id, author_real_at, rules, slug, meta_title, meta_description, archived_at, brands!inner(organization_id, name, language)',
+ )
+ .eq('id', draftId)
+ .eq('brands.organization_id', auth.organizationId)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!draft || draft.archived_at) return notFound;
+ const brand = (Array.isArray(draft.brands) ? draft.brands[0] : draft.brands) as {
+ name: string;
+ language: string | null;
+ };
+
+ // As the Library reads them: the authors once Quality is live (its phase 1).
+ const [authors] = await Promise.all([
+ qualityPhase() >= 1
+ ? readContentAuthors(supabaseAdmin, auth.organizationId, {
+ // Who reads them: cmsSource doesn't use it, so the key's role isn't looked up.
+ me: { id: auth.userId, role: 'analyst' },
+ })
+ : Promise.resolve(null),
+ withContentDom(),
+ ]);
+ const name = authors?.brands.find((b) => b.id === draft.brand_id)?.name ?? brand.name;
+ const source = cmsSource({
+ page: {
+ id: draft.id,
+ title: draft.title,
+ bodyHtml: draft.body_html,
+ sourceUrl: draft.source_url,
+ authorId: draft.author_id,
+ authorConfirmed: draft.author_real_at !== null,
+ language: draftLanguage(draft.rules),
+ },
+ authors,
+ brandId: draft.brand_id,
+ brandName: name,
+ brandLanguage: brand.language,
+ });
+ const kept = {
+ slug: draft.slug ?? undefined,
+ metaTitle: draft.meta_title ?? undefined,
+ metaDescription: draft.meta_description ?? undefined,
+ };
+ const [item] = bulkCmsItems([source], new Map([[draft.id, kept]]));
+ if (!item.page) {
+ const problem = item.problem ?? 'empty';
+ return { error: 'not_ready', problem, message: PROBLEMS[problem] };
+ }
+ const page = item.page;
+ return {
+ draft_id: draft.id,
+ title: page.title,
+ slug: page.slug,
+ meta_title: page.metaTitle,
+ meta_description: page.metaDescription,
+ html: page.html,
+ json_ld: jsonLdOf(page.html),
+ author: page.author,
+ featured_image: page.featuredImage,
+ source_url: draft.source_url,
+ };
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index e4ca9685e..1347d49c1 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -2069,6 +2069,31 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ server.registerTool(
+ 'get_content_draft_package',
+ {
+ title: 'Draft as a CMS-ready page',
+ description:
+ "A Content Editor draft as a page ready for a CMS, exactly as Ansvisor's own Send to CMS would send it: title, slug and meta title/description (as the draft kept them from its last send, else from the page), the HTML ready to paste (as the editor's Copy HTML gives it: HTML blocks are passed as written, as Copy HTML and Send to CMS pass them, with any script, iframe or link they hold; no placeholders left, the brand's byline line when it puts one in the content, and no H1: the CMS's title field carries it), its JSON-LD blocks parsed (json_ld), the author for the CMS's author field (null to keep the CMS's own) and the featured image with its alt text. Ansvisor never sends it: put it on the user's CMS with your own CMS connector, then call mark_content_draft_published with the address it went live at. A draft that can't go yet answers why, as an error with code not_ready, its problem (placeholders, noTitle, longTitle, empty, tooLong, slug, metaTitle or metaDescription) and what to do.",
+ inputSchema: {
+ draft_id: relaxedUuid.describe('Draft UUID, from list_content_drafts.'),
+ },
+ annotations: { readOnlyHint: true, openWorldHint: false },
+ },
+ async (args) => {
+ // Loaded on the tool's first call, with jsdom: no other tool loads the editor's page code.
+ const { getContentDraftPackageFor } = await import('./content-package');
+ const result = await getContentDraftPackageFor(auth, args.draft_id);
+ if ('error' in result) {
+ if (result.error === 'not_found') return notFound('Draft');
+ // As the REST route's 409 answers it.
+ const why = { error: result.message, code: result.error, problem: result.problem ?? null };
+ return { ...json(why), isError: true };
+ }
+ return json(result);
+ },
+ );
+
server.registerTool(
'mark_content_draft_published',
{
diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.ts
index 65e711b70..cac1e3e05 100644
--- a/web/src/lib/mcp/subscription-gate.test.ts
+++ b/web/src/lib/mcp/subscription-gate.test.ts
@@ -79,7 +79,7 @@ describe('the MCP tools on a read-only workspace', () => {
const client = await connect();
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
- expect(names.filter(isReadTool)).toHaveLength(46);
+ expect(names.filter(isReadTool)).toHaveLength(47);
expect(names.filter((name) => !isReadTool(name)).sort()).toEqual([
'accept_prompt_suggestion',
'accept_topic_suggestion',
diff --git a/web/src/types/jsdom.d.ts b/web/src/types/jsdom.d.ts
new file mode 100644
index 000000000..893ce835f
--- /dev/null
+++ b/web/src/types/jsdom.d.ts
@@ -0,0 +1,11 @@
+/**
+ * The part of jsdom the server uses (lib/mcp/content-package.ts): a window
+ * for the Content Editor's HTML helpers. jsdom ships no types, and this is
+ * all of it the app reads.
+ */
+declare module 'jsdom' {
+ export class JSDOM {
+ constructor(html?: string);
+ readonly window: Window & typeof globalThis;
+ }
+}